Skip to content

Commit a0eff62

Browse files
authored
fix(commands): give option groups values only when a command lists them (#6221)
An option group looked its values up by spelling, so one the typed command did not list could read another option's value, of another type. It reads as its defaults now, and in a process that uses the CLI as a library too. Groups are told apart by the group itself, and a command cannot list two that share a spelling. The hooks of a parent command, such as before-run-ios, can read the groups of the subcommand the user typed. Adds agent skills with guidelines for dependency injection, options and commands in .agents/skills, linked from .claude/skills.
1 parent 341e227 commit a0eff62

25 files changed

Lines changed: 920 additions & 147 deletions
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
---
2+
name: cli-commands
3+
description: Guidelines for NativeScript CLI commands. Use whenever adding or editing an `ns` command, its options, params, providers, help page, registration or tests, and when reviewing such a change. Covers defineCommand, `extends Command(...)` and running one command from another.
4+
---
5+
6+
# Commands
7+
8+
`defining-commands.md` is the authority. Read the section for whatever you use.
9+
Built-in commands have all been migrated: do not add an `ICommand` class. When editing
10+
a command, apply these rules to what you change and leave the rest.
11+
12+
## 1. Choose the form
13+
14+
- **`defineCommand({ … })`** by default: a few services and a short handler.
15+
- **`class X extends Command({ … })`** when the command has internal structure:
16+
state shared by `canExecute` and `run`, several private steps, or enough
17+
collaborators that fields read better. Converting an existing command needs a
18+
reason of that kind; both forms are supported and behave the same. Do not
19+
convert one because you are nearby.
20+
21+
Where a sibling command disagrees with the rules below, follow the rules. Look at a
22+
command of the same shape before writing one: `lib/commands/clean.ts`,
23+
`lib/commands/platform-clean.ts` (class), `lib/commands/install.ts` (process-level
24+
options), `lib/commands/run.ts` (several platforms).
25+
26+
## 2. Rules
27+
28+
- **Options**: declare with `booleanOption()`, `stringOption()` and the rest, and
29+
read them from `ctx.options` or `this.options`, never from `$options`. Extract a
30+
shared schema with `satisfies CommandOptionsSchema`, not a type annotation.
31+
- **Process-level options** (`--path`, `--log`, …) are not redeclared. List
32+
`CliOptions`: `options: [CliOptions, { … }]`.
33+
- **Options a service also reads** belong in an option group, which the command lists; see
34+
the cli-options skill.
35+
- **Services**: `inject(Token)` at the top of the handler, or in fields in the class
36+
form. After an `await`, use `ctx.injector.get(Token)`. Never build a shared
37+
"services" object, and do not pass one to helpers: each helper injects or receives
38+
what it uses.
39+
- **A project**: `providers: [provideProject()]` instead of checking by hand.
40+
- **Arguments**: declare `params`. `canExecute` adds checks; it does not replace
41+
the `params` policy.
42+
- **Failing**: `ctx.fail(message)` or `this.context.fail(message)`.
43+
- **Another command**: `CommandsService.runCommand(...)`, awaited. It parses the
44+
same command line; it takes no options of its own, so pass data to services
45+
directly when their values must differ.
46+
- **Platform families**: one definition registered per platform with a provider for
47+
the platform, not subclasses.
48+
- **Help** lives in `docs/man_pages/<area>/`, in a file named after the command with
49+
`|` as `-` (`config|get` is `config/config-get.md`). Copy a sibling's layout, header
50+
included, and add the command to the area's other "Related Commands" tables. A
51+
definition's `description` is not shown there. Pages are copied by the build. Do
52+
not rename a command without moving its page.
53+
- **`--json`**: declare `json: booleanOption()`, print one JSON document and nothing
54+
else, through the same logger the command's other output uses.
55+
- Hooks fire as `before-<name>` and `after-<name>`, so a name is public behaviour.
56+
57+
## 3. Register
58+
59+
In `lib/bootstrap.ts`, with the type argument and a lazy `require`:
60+
61+
```ts
62+
registerBuiltInCommand<
63+
typeof import("./commands/clean").cleanCommandDefinition
64+
>("clean", () => require("./commands/clean").cleanCommandDefinition);
65+
```
66+
67+
Never import the command module at the top of the bootstrap except as a type.
68+
69+
## 4. Test
70+
71+
Build the command with `createCommandFromDefinition(definition, injector)` and stub
72+
its services on a `Yok` test injector (see `test/commands/provide-project.ts`). Option
73+
values come from the stub: `injector.register("options", { json: true })`. Cover the
74+
arguments policy, a refused `canExecute` and each option that changes behaviour.
75+
76+
```sh
77+
npx tsc --noEmit -p tsconfig.json
78+
npm run build && npx vitest run
79+
node bin/ns <command> --help
80+
node bin/ns <command> --path <project> --profileDir <scratch dir> --disableAnalytics
81+
```
82+
83+
Also run it outside a project when it needs one, and with a stray argument.
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
---
2+
name: cli-dependency-injection
3+
description: Guidelines for dependency injection in the NativeScript CLI. Use whenever adding or editing a class, service, controller or helper under lib/ that takes dependencies, registers with the injector, declares a contract or token, or is resolved by name, and when reviewing such a change. Covers inject(), @Contract, @LegacyContract, InjectionToken, providers and how far to modernize code you are already touching.
4+
---
5+
6+
# Dependency injection
7+
8+
`dependency-injection.md` at the repository root is the authority on the API. These
9+
are the rules for using it here.
10+
11+
The CLI is moving from string-based injection (`$name` parameters, `resolve("name")`) to
12+
typed tokens, **a little at a time, in code that is being changed anyway**. Both reach the
13+
same instance, so a class may mix them for as long as it needs to.
14+
15+
## New code
16+
17+
- Depend on a token: `private fs = inject(FileSystem)`, or
18+
`inject(Token)` at the top of a command handler. Add no `$` parameter and no string
19+
lookup for a service that has a token.
20+
- A new service declares `@Contract()` in `lib/contracts/internal/`, with no name, an
21+
implementation called `*Impl`, and a lazy registration in the bootstrap:
22+
`injector.register(provideLazy(Thing, () => require("./path").ThingImpl))`.
23+
- A value that is not a class takes an `InjectionToken`; give it a `factory` if it can
24+
provide itself.
25+
- Do not bundle services into one object that is passed around.
26+
27+
## Internal and public contracts
28+
29+
| | Internal | Public |
30+
|---|---|---|
31+
| Lives in | `lib/contracts/internal/` | `lib/contracts/`, exported from `index.ts` |
32+
| For | the CLI's own plumbing | extension and hook authors |
33+
| Its shape | may change in any release | covered by semver |
34+
| Changing a member | change it, and its callers | additive only; deprecate before removing |
35+
| Documentation | optional | JSDoc on every member, and a row in `dependency-injection.md` |
36+
| Mentions in signatures | anything | public contracts and published types only |
37+
38+
- **Internal is the default.** Making a contract public, or exporting anything new from
39+
`nativescript/contracts`, is a maintainer's decision: ask first, with the author's use
40+
case. Expose the smallest useful shape. Moving an internal contract out later is easy;
41+
taking a public one back is a breaking change.
42+
- `lib/common/contracts/` holds the injector facade's own contracts. Those exported
43+
through `lib/contracts/index.ts` are public; the rest are internal.
44+
- **A name does not make a contract public.** `@LegacyContract({ name })` keeps a string
45+
spelling working. Hooks may still resolve an internal service by that string, so do not
46+
drop or change the name, but its members carry no promise.
47+
- A public contract is named today, because an extension with its own copy of the CLI
48+
cannot resolve one without a name.
49+
- Changing the interface of an internal service is the moment to give it a contract.
50+
Changing a public contract is an API change: say so in the pull request.
51+
52+
## Code you are already changing
53+
54+
| You are | Do |
55+
|---|---|
56+
| adding a dependency to a class | `inject()` the new one; leave the others |
57+
| changing a class whose dependencies have tokens | move them if every condition below holds |
58+
| changing a service's interface | give it an internal contract, if it has none |
59+
| changing a public contract | additive changes only, or ask |
60+
| fixing a bug, or touching one line | leave the injection alone |
61+
| not otherwise changing a file | leave it alone |
62+
63+
Move dependencies only when all of these hold:
64+
65+
- the class is constructed by the injector everywhere: no `new X(...)`, no
66+
`resolve(X, { $name })`, no subclass that calls `super($name)`
67+
- tests cover what you touch, or you add them
68+
- no open pull request changes the same lines
69+
- the move is small next to your change; put it in its own commit and mention it in
70+
the pull request
71+
72+
When one does not hold, leave the class as it is and finish your change. Do not widen it.
73+
74+
## Traps
75+
76+
- `provide(Token, Impl)` while `Impl` still takes `$` parameters builds it with
77+
`undefined`, silently. Keep `register("name", Impl)` until none are left.
78+
- `inject()` ignores `resolve(X, { $name: stub })` overrides, silently.
79+
- `inject()` throws outside a field initializer, constructor or factory, and after an
80+
`await`. For a late lookup hold `inject(Injector)`.
81+
- Parameter names of `@hook` methods are the hook's payload. Never rename them, and keep
82+
`$hooksService` on such a class.
83+
- A registered string name is public: hooks resolve it, and `@exported` methods do on
84+
every call. Keep it, with `@LegacyContract({ name })`.
85+
- A class with `@performanceLog` methods keeps its class name.
86+
- Importing an implementation in the bootstrap or a contract defeats lazy loading.
87+
88+
## Recipes
89+
90+
- [Moving a class to tokens](references/moving-a-class-to-tokens.md)
91+
- [Giving a service a contract](references/giving-a-service-a-contract.md)
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
# Giving a service a contract
2+
3+
Read the "Tokens", "Internal contracts" and "Registering"
4+
sections of `dependency-injection.md` first. The worked example is
5+
`lib/contracts/internal/os-info.ts` with `lib/common/os-info.ts`.
6+
7+
## 1. Survey
8+
9+
For a service registered as `thing`:
10+
11+
```sh
12+
rg -n '"\$?thing"|\$thing\b' lib test # registration, lookups, stubs
13+
rg -n 'interface IThing\b' lib # the declared shape
14+
rg -n '\bThing\b' lib test # imports, subclasses, new Thing()
15+
```
16+
17+
List the open pull requests that touch a file:
18+
19+
```sh
20+
R=NativeScript/nativescript-cli
21+
for n in $(gh pr list -R $R --state open --limit 200 --json number -q '.[].number'); do
22+
gh api --paginate "repos/$R/pulls/$n/files" -q ".[].filename" | sed "s|^|$n |"
23+
done | grep -F lib/services/thing.ts
24+
```
25+
26+
If one changes the service's shape, pick another service or ask.
27+
28+
## 2. Classify
29+
30+
| Kind | What to do |
31+
|---|---|
32+
| Class with one interface | this recipe |
33+
| Interface shared by several registrations (package managers, platform services, log filters) | one token class per registration, merged with the interface: `@LegacyContract({ name }) export abstract class X {}` plus `export interface X extends IShared {}`; leave the interface alone |
34+
| Value that is not a class (a module, a function) | `InjectionToken`, not a contract |
35+
| `shared: false` registration | keep it transient: `{ provide: Token, useClass: Impl, shared: false }` |
36+
| Class that does not satisfy its interface | stop and report; fix conformance in its own change |
37+
| Nothing uses it | stop and report; hooks can still resolve it by name |
38+
39+
## 3. Choose the decorator and the place
40+
41+
- **`@LegacyContract({ name })`** when the service already has a string name. Hooks
42+
and `$` parameters resolve it, so the name stays exactly as registered.
43+
- **`@Contract()`** when it never had one, and for new services. Without a name it
44+
cannot be resolved by string, or through an extension's own copy of the CLI.
45+
- **`lib/contracts/internal/`** is the default; the skill says what separates it from a
46+
public contract. A test fails if a class in it is exported from
47+
`nativescript/contracts`.
48+
49+
A contract file imports only the decorator and types. It must stay free of side
50+
effects, so it never imports `lib/common/yok` or an implementation.
51+
52+
## 4. Edit
53+
54+
1. Declare the contract with the members of the interface, moving their JSDoc.
55+
Correct JSDoc that does not describe the member. For an inherited interface
56+
such as `EventEmitter`, merge it:
57+
`export interface Thing extends NodeJS.EventEmitter {}` next to the class.
58+
2. Make the interface an alias:
59+
`/** @deprecated Kept so existing annotations compile; use the {@link Thing} contract. */`
60+
`interface IThing extends Thing {}`, with an `import type` at the top of the
61+
declaration file. A `.d.ts` without any `import` or `export` is ambient, and
62+
the import turns it into a module: wrap **everything** in it in
63+
`declare global { … }`, as `lib/definitions/prompter.d.ts` does.
64+
3. Rename the class to `ThingImpl implements Thing` and fix imports of the class,
65+
tests included. A class with `@performanceLog` methods keeps its name: the
66+
decorator reports it. The old class export disappears for deep `require()`s;
67+
say so in the pull request.
68+
4. Register it:
69+
- no `$` constructor parameters left: `injector.register(provide(Thing, ThingImpl))`
70+
- any left: keep `injector.register("thing", ThingImpl)`. With `provide()` they
71+
are **silently `undefined`**, because the class is built with no arguments.
72+
5. Leave the `injector.require("thing", "./path")` line in the bootstrap. Never
73+
import an implementation there: modules must stay lazy. A service with no
74+
string name is registered there with
75+
`injector.register(provideLazy(Thing, () => require("./path").ThingImpl))`,
76+
and its module registers nothing.
77+
6. Leave the service's own `$` parameters, and its consumers, unless you are
78+
changing them anyway; then see
79+
[moving a class to tokens](moving-a-class-to-tokens.md). Both spellings reach the same instance, so
80+
consumers can move before or after.
81+
82+
Keep `@exported` and `@hook` usages and their names unchanged.
83+
84+
## 5. Verify
85+
86+
```sh
87+
npx tsc --noEmit -p tsconfig.json
88+
npx tsc -p tsconfig.release.json --noEmit
89+
npm run build && npx vitest run
90+
```
91+
92+
Add a test to `test/contracts.ts`: for a service registered with `provide()`, that the
93+
class, the name and the `$`-spelling resolve to one instance, as `OsInfo` does. With
94+
a by-name registration that needs stubs, assert `getContractName(Thing)` instead.
95+
96+
Check the real registration, and that it is still lazy (both lines must print as
97+
shown):
98+
99+
```sh
100+
node -e '
101+
require("./dist/lib/bootstrap");
102+
const { injector } = require("./dist/lib/common/yok");
103+
const { Thing } = require("./dist/lib/contracts/internal/thing");
104+
const loaded = () => Object.keys(require.cache).some((k) => k.endsWith("services/thing.js"));
105+
console.log(loaded()); // false
106+
const a = injector.get(Thing);
107+
console.log(loaded(), a === injector.resolve("$thing")); // true true
108+
process.exit();'
109+
```
110+
111+
Report the decorator and folder you chose and why, the consumers left on strings,
112+
and any open pull request that overlaps.
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# Moving a class to tokens
2+
3+
For a class you are already changing. Uses tokens that exist; see
4+
[giving a service a contract](giving-a-service-a-contract.md) for a missing one.
5+
6+
## 1. Pick the replacements
7+
8+
For every dependency of the file:
9+
10+
| Today | Replacement |
11+
|---|---|
12+
| `private $fs: IFileSystem` and a contract exists | field `private fs = inject(FileSystem)` |
13+
| `$injector` | `inject(Injector)` |
14+
| `inject("logger")` | `inject(Logger)` |
15+
| `injector.get("logger")`, `injector.resolve("logger")` | `.get(Logger)` on the same injector: do not turn it into `inject()`, it may run after an `await` |
16+
| `$x`, `inject("x")` or `get("x")` with no contract for `x` | leave it, or give `x` a contract first |
17+
| `$options` | leave it; see the cli-options skill |
18+
| a runtime value (`device`, `identifier`) | leave it as a constructor parameter |
19+
20+
Find the tokens with
21+
`rg -A1 'Contract\(|new InjectionToken' lib/contracts lib/common/contracts`. Import
22+
a token from the module that declares it, never through `lib/contracts/index.ts`.
23+
Check the file against the open pull requests, as the contract recipe shows.
24+
25+
A partly migrated class is fine: `$` parameters and `inject()` fields reach the
26+
same instance.
27+
28+
## 2. Check for these before editing
29+
30+
1. **`new X(...)`**: `rg 'new X\(' lib test`. `inject()` throws outside an injection
31+
context, so such a call has to become `injector.resolve(X)` or
32+
`runInInjectionContext(injector, () => new X(...))`.
33+
2. **Per-call overrides**: search `rg 'resolve\(X,' lib test`. `resolve(X, { $logger: stub })`
34+
reaches `$` parameters only. `inject()` ignores it *silently* and gets the registered service. Change
35+
it to `createInstance(X, [{ provide: Logger, useValue: stub }])`, or leave that
36+
dependency as a parameter. A runtime value passed this way keeps working.
37+
3. **Subclasses**: `rg 'extends X\b' lib test`, and the class's own base. When a base
38+
constructor loses a parameter, every `super(...)` call changes in the same
39+
commit.
40+
4. **Use after an `await`, or later in a method**: `inject()` is valid only in field
41+
initializers, constructors and factories. For a late or conditional lookup,
42+
hold `inject(Injector)` and call `get()`. A cycle between two services is
43+
broken the same way; keep an existing late `$injector.resolve` late.
44+
5. **`@hook` methods**: never rename a parameter of the method. Parameter names are
45+
the hook's payload. Keep `$hooksService` (or `$injector`) as it is: without
46+
it the decorator falls back to the process-wide injector and the test's stub
47+
is bypassed.
48+
6. **`@exported` classes**: the registered name must not change. It is resolved on
49+
every public API call.
50+
7. **Tests that assign `service.$x = stub`**: they stop having an effect. Register
51+
the stub on the test injector instead.
52+
53+
## 3. Edit
54+
55+
- Field initializers run before the constructor body, so a field can be used there.
56+
- In services the field has no `$`: `private osInfo = inject(OsInfo)`. In commands
57+
keep the `$` the file already uses.
58+
- Delete the interface import the parameter used, if nothing else needs it.
59+
- Do not touch registrations, do not rename the class, and do not reformat lines
60+
you did not change.
61+
- Fields resolve after `$` parameters. If a constructor has side effects, check that
62+
the order in which its dependencies are built does not matter.
63+
- `service.$x` is gone for anyone reading it from outside: search for it.
64+
- Behaviour must not change. Bugs noticed on the way are reported, not fixed.
65+
66+
## 4. Verify
67+
68+
```sh
69+
npx tsc --noEmit -p tsconfig.json
70+
npm run build && npx vitest run
71+
```
72+
73+
Tests run from `dist/`, so always build first. Then check the class itself: resolve it
74+
from `dist/lib/bootstrap` and call what you touched, or run a command that reaches
75+
it with `node bin/ns`. If it has no tests and needs a device, add a small unit test
76+
of the method you touched, and say what was not exercised.
77+
78+
Report what moved, what stayed on strings and why.

0 commit comments

Comments
 (0)