Skip to content

Commit aa74307

Browse files
committed
feat(di): internal contracts, with osInfo as the first
Contracts for the CLI's own plumbing live in lib/contracts/internal and are never exported from nativescript/contracts, so they carry no compatibility promise. A test fails when one is exported. osInfo is the worked example: the interface becomes an alias, the implementation is renamed, and two consumers move to inject().
1 parent 661cf04 commit aa74307

8 files changed

Lines changed: 144 additions & 57 deletions

File tree

‎dependency-injection.md‎

Lines changed: 71 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,31 @@ Tokens: `@Contract`
3737
-------------------
3838

3939
A token is an abstract class annotated with `@Contract`. The class is both the
40-
compile-time type and the runtime lookup key; the decorator records the token's
41-
canonical string name:
40+
compile-time type and the runtime lookup key:
4241

4342
```ts
4443
import { Contract } from "nativescript/contracts";
4544

46-
@Contract({ name: "doctorService" }) // canonical form, no `$`
45+
@Contract()
46+
export abstract class ReportWriter {
47+
abstract write(report: string): Promise<void>;
48+
}
49+
```
50+
51+
Such a token resolves by the class and nothing else: it has no string spelling,
52+
and a duplicated copy of the class is a different token.
53+
54+
Implementations do not become tokens by extending or implementing a contract;
55+
only the decorated class itself is a token.
56+
57+
### Named contracts: `@LegacyContract`
58+
59+
`@LegacyContract` adds a canonical string name, which the token also answers to:
60+
61+
```ts
62+
import { LegacyContract } from "nativescript/contracts";
63+
64+
@LegacyContract({ name: "doctorService" }) // canonical form, no `$`
4765
export abstract class DoctorService {
4866
abstract canExecuteLocalBuild(configuration?: {
4967
platform?: string;
@@ -52,6 +70,15 @@ export abstract class DoctorService {
5270
}
5371
```
5472

73+
A name exists for compatibility. Use one only when the service has to stay
74+
reachable by callers that cannot hold the class:
75+
76+
- code that resolves it by string — hook parameters, `$`-prefixed constructor
77+
parameters, `resolve("name")`, string registrations;
78+
- an extension whose dependency tree carries its own copy of the contract. This
79+
is why the contracts exported from `nativescript/contracts` are named, the
80+
recent ones included: without a name, such a copy cannot be resolved.
81+
5582
Rules:
5683

5784
- **The name is an explicit string literal** — never derived from `class.name`,
@@ -60,8 +87,34 @@ Rules:
6087
same name **throws at load time**, because a duplicate would silently alias
6188
two tokens.
6289
- The options object leaves room for future fields without changing call sites.
63-
- Implementations do not become tokens by extending or implementing a contract;
64-
only the decorated class itself is a token.
90+
91+
`@Contract({ name })` is the deprecated spelling of `@LegacyContract({ name })`
92+
and behaves identically.
93+
94+
### Internal contracts
95+
96+
Only what `nativescript/contracts` exports is a supported API. Contracts for the
97+
CLI's own plumbing live in `lib/contracts/internal` and are never exported from
98+
it: they may change or disappear in any release, even where a name keeps them
99+
resolvable by string or a deep `require()` reaches the file. A public contract's
100+
signature must not mention an internal one.
101+
102+
To move an existing service onto an internal contract:
103+
104+
1. Declare the contract in `lib/contracts/internal`, as a `@LegacyContract`
105+
under the name the service is registered with.
106+
2. Turn the ambient interface into an alias of it
107+
(`interface IOsInfo extends OsInfo {}`).
108+
3. Rename the implementation to `*Impl` and register it with
109+
`injector.register(provide(OsInfo, OsInfoImpl))` — or by its name, while it
110+
still takes `$`-prefixed constructor parameters. The `injector.require()`
111+
entry in the bootstrap stays as it is.
112+
4. Move consumers from `$osInfo` parameters to `inject(OsInfo)` fields, in as
113+
many steps as convenient: both reach the same instance.
114+
115+
`lib/contracts/internal/os-info.ts` is the worked example. A service that never
116+
had a string name takes a plain `@Contract()` and a `provideLazy()` registration
117+
instead.
65118

66119
Tokens for non-classes: `InjectionToken`
67120
----------------------------------------
@@ -81,12 +134,12 @@ class ProjectPatcher {
81134
}
82135
```
83136

84-
The description **is** the registry name, exactly as a contract's name is, so a
137+
The description **is** the registry name, exactly as a named contract's is, so a
85138
token is a typed alias onto an existing registration and nothing has to change
86139
where the value is registered — `injector.register("xcode", xcode)` keeps
87140
serving `inject(XCODE)`. A leading `$` in the description is stripped.
88141

89-
Names are minted in the same registry `@Contract` uses, so a token and a
142+
Names are minted in the same registry `@LegacyContract` uses, so a token and a
90143
contract cannot claim the same name: the second one **throws at load time**,
91144
rather than silently aliasing one registration under two tokens.
92145

@@ -193,7 +246,7 @@ instance. Transient instances are still retained by the container so
193246

194247
String keys are accepted anywhere a token is (`{ provide: "logger", useValue }`)
195248
— that is how the legacy facade registers, and how per-call overrides address
196-
not-yet-migrated dependencies. New registrations should mint a `@Contract`
249+
not-yet-migrated dependencies. New registrations should declare a `@Contract`
197250
class, or an `InjectionToken` when there is no class to decorate, instead of a
198251
new string name.
199252

@@ -217,13 +270,15 @@ Resolution semantics
217270
injector level before delegating to the parent. Both keys index the same
218271
provider record, so re-registering a service by its string name (as plugins
219272
are documented to do with `$logger`) stays visible to `inject(Logger)`
220-
consumers. This holds for `@Contract` classes and `InjectionToken`s alike.
273+
consumers. This holds for `@LegacyContract` classes and `InjectionToken`s
274+
alike; a `@Contract` class has no name and resolves by identity only.
221275
- A leading `$` is stripped from string tokens: `get("$fs")` and `get("fs")`
222276
are the same registration.
223-
- The name fallback also makes **duplicated token copies interchangeable**: if
224-
an extension's dependency tree carries its own copy of a contract class or
225-
injection token, that copy resolves to the same provider by name. "Works
226-
locally, breaks when installed" is not a failure mode of this design.
277+
- The name fallback also makes **duplicated copies of a named token
278+
interchangeable**: if an extension's dependency tree carries its own copy of a
279+
`@LegacyContract` class or injection token, that copy resolves to the same
280+
provider by name. "Works locally, breaks when installed" is not a failure mode
281+
of the tokens `nativescript/contracts` exports.
227282
- Cyclic dependencies fail with the full resolution path
228283
(`Cyclic dependency detected on dependency 'a'. Resolution path: a -> b -> a`).
229284

@@ -267,9 +322,9 @@ $injector.register(provide(DoctorService, DoctorServiceImpl));
267322
runInInjectionContext($injector, () => inject(DoctorService));
268323
```
269324

270-
- Legacy string names are permanent: a contract's token name is its interop
271-
identity, used by hooks, plugins, and the public API. Nothing is deleted
272-
per-service.
325+
- Legacy string names stay while published plugins and hooks depend on them: a
326+
named contract's name is its interop identity, used by hooks, plugins, and the
327+
public API. Nothing is deleted per-service.
273328
- Every legacy member (`resolve`, `register`, `require*`, the command-registry
274329
surface) carries `@deprecated` JSDoc naming its replacement.
275330
- Legacy usage at the external entry points (param-name hooks, require-time

‎lib/common/declarations.d.ts‎

Lines changed: 3 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import type { Errors } from "../contracts/errors";
1010
import type { FileSystem } from "../contracts/file-system";
1111
import type { HostInfo } from "../contracts/host-info";
1212
import type { HttpClient } from "../contracts/http-client";
13+
import type { OsInfo } from "../contracts/internal/os-info";
1314

1415
// tslint:disable-next-line:interface-name
1516
interface Object {
@@ -1132,34 +1133,8 @@ interface IDependencyInformation {
11321133
saveInDependencies?: boolean;
11331134
}
11341135

1135-
/**
1136-
* Describes operating system-related utility methods
1137-
*/
1138-
interface IOsInfo {
1139-
/**
1140-
* Returns a string identifying the operating system name.
1141-
* @return {string} A string identifying the operating system name.
1142-
*/
1143-
type(): string;
1144-
1145-
/**
1146-
* Returns a string identifying the operating system release.
1147-
* @return {string} A string identifying the operating system release.
1148-
*/
1149-
release(): string;
1150-
1151-
/**
1152-
* Returns a string identifying the operating system bitness.
1153-
* @return {string} A string identifying the operating system bitness.
1154-
*/
1155-
arch(): string;
1156-
1157-
/**
1158-
* Returns a string identifying the operating system platform.
1159-
* @return {string} A string identifying the operating system platform.
1160-
*/
1161-
platform(): string;
1162-
}
1136+
/** @deprecated Kept so existing annotations compile; use the {@link OsInfo} contract. */
1137+
interface IOsInfo extends OsInfo {}
11631138

11641139
interface IPromiseActions<T> {
11651140
resolve(value?: T | PromiseLike<T>): void;

‎lib/common/os-info.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import * as os from "os";
2-
import { IOsInfo } from "./declarations";
2+
import { OsInfo } from "../contracts/internal/os-info";
3+
import { provide } from "./di";
34
import { injector } from "./yok";
45

5-
export class OsInfo implements IOsInfo {
6+
export class OsInfoImpl implements OsInfo {
67
public type(): string {
78
return os.type();
89
}
@@ -20,4 +21,4 @@ export class OsInfo implements IOsInfo {
2021
}
2122
}
2223

23-
injector.register("osInfo", OsInfo);
24+
injector.register(provide(OsInfo, OsInfoImpl));

‎lib/common/services/net-service.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,22 @@ import {
55
IErrors,
66
INet,
77
IChildProcess,
8-
IOsInfo,
98
IWaitForPortListenData,
109
IDictionary,
1110
} from "../declarations";
11+
import { OsInfo } from "../../contracts/internal/os-info";
12+
import { inject } from "../di";
1213
import { injector } from "../yok";
1314

1415
export class Net implements INet {
1516
private static DEFAULT_INTERVAL = 1000;
1617

18+
private osInfo = inject(OsInfo);
19+
1720
constructor(
1821
private $errors: IErrors,
1922
private $childProcess: IChildProcess,
2023
private $logger: ILogger,
21-
private $osInfo: IOsInfo,
2224
) {}
2325

2426
public async getFreePort(): Promise<number> {
@@ -118,7 +120,7 @@ export class Net implements INet {
118120
},
119121
};
120122

121-
const platform = this.$osInfo.platform();
123+
const platform = this.osInfo.platform();
122124
const currentPlatformData = platformData[platform];
123125
if (!currentPlatformData) {
124126
this.$errors.fail(

‎lib/common/test/unit-tests/analytics-service.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { Yok } from "../../yok";
33
import { AnalyticsService } from "../../../services/analytics/analytics-service";
44
import { setIsInteractive } from "../../helpers";
55
import { HostInfo } from "../../host-info";
6-
import { OsInfo } from "../../os-info";
6+
import { OsInfoImpl } from "../../os-info";
77
import { IInjector } from "../../definitions/yok";
88
import { IAnalyticsService } from "../../declarations";
99
import { assert } from "chai";
@@ -87,7 +87,7 @@ function createTestInjector(testScenario: ITestScenario): IInjector {
8787
ANALYTICS_EXCEPTIONS_API_KEY: "AnalyticsExceptionsAPIKey",
8888
});
8989
testInjector.register("hostInfo", HostInfo);
90-
testInjector.register("osInfo", OsInfo);
90+
testInjector.register("osInfo", OsInfoImpl);
9191
testInjector.register(
9292
"userSettingsService",
9393
new UserSettingsServiceStub(

‎lib/contracts/internal/os-info.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { LegacyContract } from "../../common/di/contract";
2+
3+
/**
4+
* Describes operating system-related utility methods.
5+
*/
6+
@LegacyContract({ name: "osInfo" })
7+
export abstract class OsInfo {
8+
/** The operating system name. */
9+
abstract type(): string;
10+
11+
/** The operating system release. */
12+
abstract release(): string;
13+
14+
/** The operating system bitness. */
15+
abstract arch(): string;
16+
17+
/** The operating system platform. */
18+
abstract platform(): string;
19+
}

‎lib/services/analytics-settings-service.ts‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,22 @@ import {
55
IAnalyticsSettingsService,
66
IUserSettingsService,
77
IHostInfo,
8-
IOsInfo,
98
} from "../common/declarations";
109
import * as _ from "lodash";
10+
import { inject } from "../common/di";
1111
import { injector } from "../common/yok";
12+
import { OsInfo } from "../contracts/internal/os-info";
1213
import { color } from "../color";
1314

1415
class AnalyticsSettingsService implements IAnalyticsSettingsService {
1516
private static SESSIONS_STARTED_KEY_PREFIX = "SESSIONS_STARTED_";
1617

18+
private osInfo = inject(OsInfo);
19+
1720
constructor(
1821
private $userSettingsService: IUserSettingsService,
1922
private $staticConfig: IStaticConfig,
2023
private $hostInfo: IHostInfo,
21-
private $osInfo: IOsInfo,
2224
private $logger: ILogger,
2325
) {}
2426

@@ -65,7 +67,7 @@ class AnalyticsSettingsService implements IAnalyticsSettingsService {
6567
@exported("analyticsSettingsService")
6668
public getUserAgentString(identifier: string): string {
6769
let osString = "";
68-
const osRelease = this.$osInfo.release();
70+
const osRelease = this.osInfo.release();
6971

7072
if (this.$hostInfo.isWindows) {
7173
osString = `Windows NT ${osRelease}`;
@@ -77,12 +79,12 @@ class AnalyticsSettingsService implements IAnalyticsSettingsService {
7779
}
7880
} else {
7981
osString = `Linux x86`;
80-
if (this.$osInfo.arch() === "x64") {
82+
if (this.osInfo.arch() === "x64") {
8183
osString += "_64";
8284
}
8385
}
8486

85-
const userAgent = `${identifier} (${osString}; ${this.$osInfo.arch()})`;
87+
const userAgent = `${identifier} (${osString}; ${this.osInfo.arch()})`;
8688

8789
return userAgent;
8890
}

‎test/contracts.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import { assert } from "chai";
2+
import * as fs from "fs";
3+
import * as path from "path";
24
import { getContractName, Injector, provide } from "../lib/common/di";
35
import type { InjectionToken, ProviderToken } from "../lib/common/di";
46
import {
@@ -20,10 +22,13 @@ import {
2022
PBXPROJ_DOM_XCODE,
2123
XCODE,
2224
} from "../lib/contracts";
25+
import * as publicContracts from "../lib/contracts";
26+
import { OsInfo } from "../lib/contracts/internal/os-info";
2327
import { Yok } from "../lib/common/yok";
2428
import { Logger as LoggerImpl } from "../lib/common/logger/logger";
2529
import { Errors as ErrorsImpl } from "../lib/common/errors";
2630
import { FileSystem as FileSystemImpl } from "../lib/common/file-system";
31+
import { injector as globalInjector } from "../lib/common/yok";
2732
import type { ISpawnResult } from "../lib/common/declarations";
2833

2934
const tranche: [ProviderToken<any>, string][] = [
@@ -115,6 +120,34 @@ describe("contracts tranche", () => {
115120
}
116121
});
117122

123+
describe("internal contracts", () => {
124+
it("are not exported from the public entry point", () => {
125+
const internalDir = path.join(__dirname, "../lib/contracts/internal");
126+
const modules = fs
127+
.readdirSync(internalDir)
128+
.filter((file) => file.endsWith(".js"));
129+
const internal = modules.flatMap((file) =>
130+
Object.values(require(path.join(internalDir, file))),
131+
);
132+
assert.isNotEmpty(internal);
133+
134+
const published = new Set<unknown>(Object.values(publicContracts));
135+
assert.deepEqual(
136+
internal.filter((value) => published.has(value)),
137+
[],
138+
);
139+
});
140+
141+
it("resolve to one instance by class, by name and by $-spelling", () => {
142+
const { OsInfoImpl } = require("../lib/common/os-info");
143+
const byToken = globalInjector.get(OsInfo);
144+
145+
assert.instanceOf(byToken, OsInfoImpl);
146+
assert.strictEqual(globalInjector.resolve("osInfo"), byToken);
147+
assert.strictEqual(globalInjector.resolve("$osInfo"), byToken);
148+
});
149+
});
150+
118151
describe("against a real Yok container", () => {
119152
it("resolves the token and the legacy name to the same instance", () => {
120153
const injector = new Yok();

0 commit comments

Comments
 (0)