Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions .agents/skills/cli-commands/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
---
name: cli-commands
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.
---

# Commands

`defining-commands.md` is the authority. Read the section for whatever you use.
Built-in commands have all been migrated: do not add an `ICommand` class. When editing
a command, apply these rules to what you change and leave the rest.

## 1. Choose the form

- **`defineCommand({ … })`** by default: a few services and a short handler.
- **`class X extends Command({ … })`** when the command has internal structure:
state shared by `canExecute` and `run`, several private steps, or enough
collaborators that fields read better. Converting an existing command needs a
reason of that kind; both forms are supported and behave the same. Do not
convert one because you are nearby.

Where a sibling command disagrees with the rules below, follow the rules. Look at a
command of the same shape before writing one: `lib/commands/clean.ts`,
`lib/commands/platform-clean.ts` (class), `lib/commands/install.ts` (process-level
options), `lib/commands/run.ts` (several platforms).

## 2. Rules

- **Options**: declare with `booleanOption()`, `stringOption()` and the rest, and
read them from `ctx.options` or `this.options`, never from `$options`. Extract a
shared schema with `satisfies CommandOptionsSchema`, not a type annotation.
- **Process-level options** (`--path`, `--log`, …) are not redeclared. List
`CliOptions`: `options: [CliOptions, { … }]`.
- **Options a service also reads** belong in an option group, which the command lists; see
the cli-options skill.
- **Services**: `inject(Token)` at the top of the handler, or in fields in the class
form. After an `await`, use `ctx.injector.get(Token)`. Never build a shared
"services" object, and do not pass one to helpers: each helper injects or receives
what it uses.
- **A project**: `providers: [provideProject()]` instead of checking by hand.
- **Arguments**: declare `params`. `canExecute` adds checks; it does not replace
the `params` policy.
- **Failing**: `ctx.fail(message)` or `this.context.fail(message)`.
- **Another command**: `CommandsService.runCommand(...)`, awaited. It parses the
same command line; it takes no options of its own, so pass data to services
directly when their values must differ.
- **Platform families**: one definition registered per platform with a provider for
the platform, not subclasses.
- **Help** lives in `docs/man_pages/<area>/`, in a file named after the command with
`|` as `-` (`config|get` is `config/config-get.md`). Copy a sibling's layout, header
included, and add the command to the area's other "Related Commands" tables. A
definition's `description` is not shown there. Pages are copied by the build. Do
not rename a command without moving its page.
- **`--json`**: declare `json: booleanOption()`, print one JSON document and nothing
else, through the same logger the command's other output uses.
- Hooks fire as `before-<name>` and `after-<name>`, so a name is public behaviour.

## 3. Register

In `lib/bootstrap.ts`, with the type argument and a lazy `require`:

```ts
registerBuiltInCommand<
typeof import("./commands/clean").cleanCommandDefinition
>("clean", () => require("./commands/clean").cleanCommandDefinition);
```

Never import the command module at the top of the bootstrap except as a type.

## 4. Test

Build the command with `createCommandFromDefinition(definition, injector)` and stub
its services on a `Yok` test injector (see `test/commands/provide-project.ts`). Option
values come from the stub: `injector.register("options", { json: true })`. Cover the
arguments policy, a refused `canExecute` and each option that changes behaviour.

```sh
npx tsc --noEmit -p tsconfig.json
npm run build && npx vitest run
node bin/ns <command> --help
node bin/ns <command> --path <project> --profileDir <scratch dir> --disableAnalytics
```

Also run it outside a project when it needs one, and with a stray argument.
91 changes: 91 additions & 0 deletions .agents/skills/cli-dependency-injection/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
---
name: cli-dependency-injection
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.
---

# Dependency injection

`dependency-injection.md` at the repository root is the authority on the API. These
are the rules for using it here.

The CLI is moving from string-based injection (`$name` parameters, `resolve("name")`) to
typed tokens, **a little at a time, in code that is being changed anyway**. Both reach the
same instance, so a class may mix them for as long as it needs to.

## New code

- Depend on a token: `private fs = inject(FileSystem)`, or
`inject(Token)` at the top of a command handler. Add no `$` parameter and no string
lookup for a service that has a token.
- A new service declares `@Contract()` in `lib/contracts/internal/`, with no name, an
implementation called `*Impl`, and a lazy registration in the bootstrap:
`injector.register(provideLazy(Thing, () => require("./path").ThingImpl))`.
- A value that is not a class takes an `InjectionToken`; give it a `factory` if it can
provide itself.
- Do not bundle services into one object that is passed around.

## Internal and public contracts

| | Internal | Public |
|---|---|---|
| Lives in | `lib/contracts/internal/` | `lib/contracts/`, exported from `index.ts` |
| For | the CLI's own plumbing | extension and hook authors |
| Its shape | may change in any release | covered by semver |
| Changing a member | change it, and its callers | additive only; deprecate before removing |
| Documentation | optional | JSDoc on every member, and a row in `dependency-injection.md` |
| Mentions in signatures | anything | public contracts and published types only |

- **Internal is the default.** Making a contract public, or exporting anything new from
`nativescript/contracts`, is a maintainer's decision: ask first, with the author's use
case. Expose the smallest useful shape. Moving an internal contract out later is easy;
taking a public one back is a breaking change.
- `lib/common/contracts/` holds the injector facade's own contracts. Those exported
through `lib/contracts/index.ts` are public; the rest are internal.
- **A name does not make a contract public.** `@LegacyContract({ name })` keeps a string
spelling working. Hooks may still resolve an internal service by that string, so do not
drop or change the name, but its members carry no promise.
- A public contract is named today, because an extension with its own copy of the CLI
cannot resolve one without a name.
- Changing the interface of an internal service is the moment to give it a contract.
Changing a public contract is an API change: say so in the pull request.

## Code you are already changing

| You are | Do |
|---|---|
| adding a dependency to a class | `inject()` the new one; leave the others |
| changing a class whose dependencies have tokens | move them if every condition below holds |
| changing a service's interface | give it an internal contract, if it has none |
| changing a public contract | additive changes only, or ask |
| fixing a bug, or touching one line | leave the injection alone |
| not otherwise changing a file | leave it alone |

Move dependencies only when all of these hold:

- the class is constructed by the injector everywhere: no `new X(...)`, no
`resolve(X, { $name })`, no subclass that calls `super($name)`
- tests cover what you touch, or you add them
- no open pull request changes the same lines
- the move is small next to your change; put it in its own commit and mention it in
the pull request

When one does not hold, leave the class as it is and finish your change. Do not widen it.

## Traps

- `provide(Token, Impl)` while `Impl` still takes `$` parameters builds it with
`undefined`, silently. Keep `register("name", Impl)` until none are left.
- `inject()` ignores `resolve(X, { $name: stub })` overrides, silently.
- `inject()` throws outside a field initializer, constructor or factory, and after an
`await`. For a late lookup hold `inject(Injector)`.
- Parameter names of `@hook` methods are the hook's payload. Never rename them, and keep
`$hooksService` on such a class.
- A registered string name is public: hooks resolve it, and `@exported` methods do on
every call. Keep it, with `@LegacyContract({ name })`.
- A class with `@performanceLog` methods keeps its class name.
- Importing an implementation in the bootstrap or a contract defeats lazy loading.

## Recipes

- [Moving a class to tokens](references/moving-a-class-to-tokens.md)
- [Giving a service a contract](references/giving-a-service-a-contract.md)
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# Giving a service a contract

Read the "Tokens", "Internal contracts" and "Registering"
sections of `dependency-injection.md` first. The worked example is
`lib/contracts/internal/os-info.ts` with `lib/common/os-info.ts`.

## 1. Survey

For a service registered as `thing`:

```sh
rg -n '"\$?thing"|\$thing\b' lib test # registration, lookups, stubs
rg -n 'interface IThing\b' lib # the declared shape
rg -n '\bThing\b' lib test # imports, subclasses, new Thing()
```

List the open pull requests that touch a file:

```sh
R=NativeScript/nativescript-cli
for n in $(gh pr list -R $R --state open --limit 200 --json number -q '.[].number'); do
gh api --paginate "repos/$R/pulls/$n/files" -q ".[].filename" | sed "s|^|$n |"
done | grep -F lib/services/thing.ts
```

If one changes the service's shape, pick another service or ask.

## 2. Classify

| Kind | What to do |
|---|---|
| Class with one interface | this recipe |
| 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 |
| Value that is not a class (a module, a function) | `InjectionToken`, not a contract |
| `shared: false` registration | keep it transient: `{ provide: Token, useClass: Impl, shared: false }` |
| Class that does not satisfy its interface | stop and report; fix conformance in its own change |
| Nothing uses it | stop and report; hooks can still resolve it by name |

## 3. Choose the decorator and the place

- **`@LegacyContract({ name })`** when the service already has a string name. Hooks
and `$` parameters resolve it, so the name stays exactly as registered.
- **`@Contract()`** when it never had one, and for new services. Without a name it
cannot be resolved by string, or through an extension's own copy of the CLI.
- **`lib/contracts/internal/`** is the default; the skill says what separates it from a
public contract. A test fails if a class in it is exported from
`nativescript/contracts`.

A contract file imports only the decorator and types. It must stay free of side
effects, so it never imports `lib/common/yok` or an implementation.

## 4. Edit

1. Declare the contract with the members of the interface, moving their JSDoc.
Correct JSDoc that does not describe the member. For an inherited interface
such as `EventEmitter`, merge it:
`export interface Thing extends NodeJS.EventEmitter {}` next to the class.
2. Make the interface an alias:
`/** @deprecated Kept so existing annotations compile; use the {@link Thing} contract. */`
`interface IThing extends Thing {}`, with an `import type` at the top of the
declaration file. A `.d.ts` without any `import` or `export` is ambient, and
the import turns it into a module: wrap **everything** in it in
`declare global { … }`, as `lib/definitions/prompter.d.ts` does.
3. Rename the class to `ThingImpl implements Thing` and fix imports of the class,
tests included. A class with `@performanceLog` methods keeps its name: the
decorator reports it. The old class export disappears for deep `require()`s;
say so in the pull request.
4. Register it:
- no `$` constructor parameters left: `injector.register(provide(Thing, ThingImpl))`
- any left: keep `injector.register("thing", ThingImpl)`. With `provide()` they
are **silently `undefined`**, because the class is built with no arguments.
5. Leave the `injector.require("thing", "./path")` line in the bootstrap. Never
import an implementation there: modules must stay lazy. A service with no
string name is registered there with
`injector.register(provideLazy(Thing, () => require("./path").ThingImpl))`,
and its module registers nothing.
6. Leave the service's own `$` parameters, and its consumers, unless you are
changing them anyway; then see
[moving a class to tokens](moving-a-class-to-tokens.md). Both spellings reach the same instance, so
consumers can move before or after.

Keep `@exported` and `@hook` usages and their names unchanged.

## 5. Verify

```sh
npx tsc --noEmit -p tsconfig.json
npx tsc -p tsconfig.release.json --noEmit
npm run build && npx vitest run
```

Add a test to `test/contracts.ts`: for a service registered with `provide()`, that the
class, the name and the `$`-spelling resolve to one instance, as `OsInfo` does. With
a by-name registration that needs stubs, assert `getContractName(Thing)` instead.

Check the real registration, and that it is still lazy (both lines must print as
shown):

```sh
node -e '
require("./dist/lib/bootstrap");
const { injector } = require("./dist/lib/common/yok");
const { Thing } = require("./dist/lib/contracts/internal/thing");
const loaded = () => Object.keys(require.cache).some((k) => k.endsWith("services/thing.js"));
console.log(loaded()); // false
const a = injector.get(Thing);
console.log(loaded(), a === injector.resolve("$thing")); // true true
process.exit();'
```

Report the decorator and folder you chose and why, the consumers left on strings,
and any open pull request that overlaps.
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Moving a class to tokens

For a class you are already changing. Uses tokens that exist; see
[giving a service a contract](giving-a-service-a-contract.md) for a missing one.

## 1. Pick the replacements

For every dependency of the file:

| Today | Replacement |
|---|---|
| `private $fs: IFileSystem` and a contract exists | field `private fs = inject(FileSystem)` |
| `$injector` | `inject(Injector)` |
| `inject("logger")` | `inject(Logger)` |
| `injector.get("logger")`, `injector.resolve("logger")` | `.get(Logger)` on the same injector: do not turn it into `inject()`, it may run after an `await` |
| `$x`, `inject("x")` or `get("x")` with no contract for `x` | leave it, or give `x` a contract first |
| `$options` | leave it; see the cli-options skill |
| a runtime value (`device`, `identifier`) | leave it as a constructor parameter |

Find the tokens with
`rg -A1 'Contract\(|new InjectionToken' lib/contracts lib/common/contracts`. Import
a token from the module that declares it, never through `lib/contracts/index.ts`.
Check the file against the open pull requests, as the contract recipe shows.

A partly migrated class is fine: `$` parameters and `inject()` fields reach the
same instance.

## 2. Check for these before editing

1. **`new X(...)`**: `rg 'new X\(' lib test`. `inject()` throws outside an injection
context, so such a call has to become `injector.resolve(X)` or
`runInInjectionContext(injector, () => new X(...))`.
2. **Per-call overrides**: search `rg 'resolve\(X,' lib test`. `resolve(X, { $logger: stub })`
reaches `$` parameters only. `inject()` ignores it *silently* and gets the registered service. Change
it to `createInstance(X, [{ provide: Logger, useValue: stub }])`, or leave that
dependency as a parameter. A runtime value passed this way keeps working.
3. **Subclasses**: `rg 'extends X\b' lib test`, and the class's own base. When a base
constructor loses a parameter, every `super(...)` call changes in the same
commit.
4. **Use after an `await`, or later in a method**: `inject()` is valid only in field
initializers, constructors and factories. For a late or conditional lookup,
hold `inject(Injector)` and call `get()`. A cycle between two services is
broken the same way; keep an existing late `$injector.resolve` late.
5. **`@hook` methods**: never rename a parameter of the method. Parameter names are
the hook's payload. Keep `$hooksService` (or `$injector`) as it is: without
it the decorator falls back to the process-wide injector and the test's stub
is bypassed.
6. **`@exported` classes**: the registered name must not change. It is resolved on
every public API call.
7. **Tests that assign `service.$x = stub`**: they stop having an effect. Register
the stub on the test injector instead.

## 3. Edit

- Field initializers run before the constructor body, so a field can be used there.
- In services the field has no `$`: `private osInfo = inject(OsInfo)`. In commands
keep the `$` the file already uses.
- Delete the interface import the parameter used, if nothing else needs it.
- Do not touch registrations, do not rename the class, and do not reformat lines
you did not change.
- Fields resolve after `$` parameters. If a constructor has side effects, check that
the order in which its dependencies are built does not matter.
- `service.$x` is gone for anyone reading it from outside: search for it.
- Behaviour must not change. Bugs noticed on the way are reported, not fixed.

## 4. Verify

```sh
npx tsc --noEmit -p tsconfig.json
npm run build && npx vitest run
```

Tests run from `dist/`, so always build first. Then check the class itself: resolve it
from `dist/lib/bootstrap` and call what you touched, or run a command that reaches
it with `node bin/ns`. If it has no tests and needs a device, add a small unit test
of the method you touched, and say what was not exercised.

Report what moved, what stayed on strings and why.
Loading
Loading