@starci/eslint-canon-be 3.21.1 → 3.23.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # Changelog
2
2
 
3
+ ## 3.23.3 - 2026-11-12
4
+
5
+ - Added: `cli-client-boundary` (R398 `BE_CLI_CLIENT_BOUNDARY`): a client cli (slots `be.app.client-cli`, `be.client-cli`) imports no domain, events, queues or projections module, nothing of the database capability or of a persistence folder, and no `typeorm`, `@nestjs/typeorm` or `pg`.
6
+ - Changed: `cli-bootstrap`, `cli-command-shape` and `cli-owner` judge every cli app and cli feature root, the ops cli (`apps/cli`, `src/features/cli/`) and a client cli (`apps/<app>`, `src/features/client-cli/<app>/`) alike.
7
+ - Changed: a unit role names its slots as a list (`ruleParams.be.unitRoles[].slots`, manifest 3.37.0), so a `.cli.ts` command of a client cli owes its `.cli.spec.ts` like an ops command; the client cli slots and that list are in `@starci/hfs` 6.8.6.
8
+
9
+ ## 3.23.2 - 2026-11-12
10
+
11
+ - Changed: the hfs 6.8 line (`@starci/hfs` 6.8.5) merged with `pkg/canon-fe-status-view-types`, `pkg/claude-work-concepts` and `pkg/claude-grammar-meter-foreground-fill`, so one installable set carries all of them: the 3.21.2 and 3.21.3 changes (the `todo-tag` fix of R235) join the 3.23 line; peer `@starci/hfs ~6.8.0`.
12
+
13
+ ## 3.23.1 - 2026-11-12
14
+
15
+ - Fixed (R78): `user-copy-through-catalog` no longer reports the `summary`, `description` or `title` of an object literal handed to an `@nestjs/swagger` export (`@ApiOperation`, `@ApiProperty`, `@ApiResponse`, directly or inside `applyDecorators`, through nested object and array literals): that text documents a REST contract for its clients' developers and R396 judges the emitted document. A same-named local helper and another package's decorator (`@Field({ description })`) are still response copy.
16
+ - Specs: `src/user-copy.spec.ts` (swagger operation, property and response documentation valid; a local `ApiOperation` and a GraphQL `@Field` description still report).
17
+ - Fixed (R88, BE-TRANSPORT-1): `rest-route-declared` reports nothing in a back end whose api apps declare `contract: "rest"`, like `rest-door-needs-a-reason` (one predicate, `servesRest` in `lib/transport-slots.ts`): the controllers are that back end's declared contract, judged by R396. Spec: `src/transport.spec.ts`.
18
+ - Fixed (R85): `injector-type-match` accepts a parameter typed exactly as a nullable injector's `T` (`VectorIndex | null`); it compared the injected type with the parameter's type stripped of null, so such an injector never matched. A parameter that drops the injector's null is still a mismatch, and `@Optional()`'s added undefined still matches. Spec: `src/injection.spec.ts`.
19
+ - Fixed (R38): `throw-domain-error` takes the rejection handler of `.then(onFulfilled, onRejected)` as it takes a `.catch` handler: its parameter is a caught value, rethrown as it is (`isCaughtValue`). The fulfilment handler's value is still judged. Spec: `src/error-handling.spec.ts`.
20
+ - Added (R47, BE-TEST-1): a unit spec over its line budget splits by facet, `<name>.<role>.<facet>.spec.ts` beside the main `<name>.<role>.spec.ts` and the same subject (`mainSpecOfSplit`, `lib/unit-spec.ts`); `unit-test-colocated` accepts it with both beside it and reports it `orphan` otherwise. Spec: `src/testing.spec.ts`.
21
+ - Specs (R281, BE-TEST-2): `spec-infra-double-from-kit` keeps refusing a function of another module inside the subject object of a function-only policy or mapper (`{ pad, shout, doubled }` with `doubled` from another file); the form is now written in BE-TEST-2. Spec: `src/unit-spec.spec.ts`.
22
+ - Fixed (R71): `no-secret-in-log` skips a credential-sounding name whose value is a number or a boolean (`usage.promptTokens`): a count is never the credential, which travels as text. Spec: `src/log-safety.spec.ts`.
23
+
24
+ ## 3.23.0 - 2026-11-11
25
+
26
+ - Changed (R278): `rest-door-needs-a-reason` reports nothing in a back end whose api apps declare `contract: "rest"` in hfs.json (the controller is that back end's default door); a graphql back end is judged as before. `HfsApp` carries the optional `contract`. Peer `@starci/hfs ~6.8.0`, the release whose view carries it.
27
+ - Specs: `src/transport.spec.ts` (a rest back end serves a plain controller; the same controller in the default back end still reports).
28
+
29
+ ## 3.21.3 - 2026-11-11
30
+
31
+ - Fixed (R235): `starci-be/todo-tag` (S1135) replaces `sonarjs/todo-tag` in the Sonar way block, the one rule both canons publish from the shared runtime copy (`scripts/lib/sonar-syntax-rules.mjs`): it refuses a leftover marker (`TODO`, `TODO:`, `TODO(name)`, `todo:`) and not the noun in prose or a name such as `guide.todo`.
32
+
33
+ ## 3.21.2 - 2026-11-09
34
+
35
+ - Changed: peer `@starci/hfs ~6.7.0` (hfs 6.7.0: the per-screen gallery and its explain.md gates, R395); no lint rule of this package changed.
36
+
3
37
  ## 3.21.1 - 2026-11-09
4
38
 
5
39
  - Changed: peer `@starci/hfs ~6.6.0`; no lint rule of this package changed.
package/README.md CHANGED
@@ -43,7 +43,7 @@ A sample, not the list:
43
43
  | **Model calls** (R326, R327, R344) | Every model call goes through the `@starci/ai-router` gateway: an upstream provider key variable (`PROVIDER_KEY_VARIABLES` of `src/ai-gateway.ts`, with its `_FILE` twin) is named only in the gateway's custody owner `integrations/ai-gateway`, specs and the test world included; code builds only `ChatOpenAI` and `OpenAIEmbeddings` of `@langchain/openai`, each from an inline options object whose `configuration.baseURL` is read from a `<c>.options.ts` type and whose `apiKey` is a `platform/config` `Secret` revealed; `integrations/ai` reads exactly `STARCI_AI_KEY`, the one virtual key of every client, and the custody owner passes the gateway no `adminToken`. Which owner may import LangChain, `openai`, a provider SDK or an agent framework is the infrastructure table (`provider-key-custody`, `ai-client-through-gateway`, `ai-virtual-key-name`, `infra-import-owner`) |
44
44
  | **Ambient ids** (R142) | `randomUUID` of Node's crypto (named, namespace or global), the `v1`, `v4`, `v6` and `v7` generators of `uuid`, `nanoid` and `ulid` are used only inside `platform/ids`, specs included: code asks the injected `Ids` port and a spec provides `fakeIds()`; the generators are found by the module they are imported from, never by a local name (`no-ambient-id`) |
45
45
  | **App composition** (R245, R246) | `apps/<app>/src/<app>.env.ts` exports an explicit typed `<App>Env` interface and `read<App>Env(env: EnvSource): <App>Env` (for example `ApiEnv` and `readApiEnv`). The interface declares its own readonly parsed members, such as `readonly server: ReturnType<typeof parseServerConfig>`, structurally compatible with the app's options. The role name stays `<app>.env.ts`, never `env.ts`; capability `<capability>.config.ts` files stay unchanged. `main.ts` creates `EnvSource` once, imports and calls the reader, builds options and boots. The env file holds fail-fast parsing only, with no localhost or default host fallback, logic, module composition, business code or feature imports; `<app>.options.ts` holds env-derived options and port bindings only, with no parsing. Both refuse an array listing `*Module` classes, module or queue registrations (`register`, `forRoot`, `registerQueue`) or scheduler entries, and an `imports`, `modules`, `schedulers` or `processors` list; the env file also refuses standalone module or queue registration calls. Composition belongs in a `compose/<area>.ts` group that `app.module.ts` spreads (`app-options-composition-free`, `BE_APP_OPTIONS_COMPOSITION`). Each app file stays within its slot's line budget: `main.ts` 80, env 150, options 200, group 120, root 250 (`app-file-budget`, `BE_APP_COMPOSITION_BUDGET`). The interface and reader exports are a documented scaffold contract; they need no new lint rule |
46
- | **Sonar parity** (R235) | The smells SonarCloud measures that a lint rule can decide: no `await` inside a loop (`no-await-in-loop`, S9382; `for (;;)` and `while (true)` are spared), no `charCodeAt`/`fromCharCode` (`prefer-code-point`), no string that only escapes backslashes (`prefer-string-raw`), no nested conditional (`no-nested-conditional`), `void` only on a call (`no-void-operator`), no unused import (`no-unused-import`), `export ... from` for an import that is only handed on (`prefer-export-from`), no raw U+2028, U+2029 or U+0085 in any file, specs included (`no-line-separator-literal`: the scanner counts them as line breaks and aborts; the finding names the escape), no raw bidirectional control character (`no-bidirectional-character`), one import per module with `--fix` merging a value and a type import (`no-duplicate-import`); the Sonar way block also maps the unicorn, core and typescript-eslint rules of `scripts/lib/sonar-way.mjs`, and the specs run the test-scoped rules of the profile; the factory also turns on typescript-eslint `no-deprecated`, `no-base-to-string` and `require-await`. The files `*.spec.ts` and `*.e2e-spec.ts` are outside the scan, so outside these rules |
46
+ | **Sonar parity** (R235) | The smells SonarCloud measures that a lint rule can decide: no `await` inside a loop (`no-await-in-loop`, S9382; `for (;;)` and `while (true)` are spared), no `charCodeAt`/`fromCharCode` (`prefer-code-point`), no string that only escapes backslashes (`prefer-string-raw`), no nested conditional (`no-nested-conditional`), `void` only on a call (`no-void-operator`), no unused import (`no-unused-import`), `export ... from` for an import that is only handed on (`prefer-export-from`), no raw U+2028, U+2029 or U+0085 in any file, specs included (`no-line-separator-literal`: the scanner counts them as line breaks and aborts; the finding names the escape), no raw bidirectional control character (`no-bidirectional-character`), no leftover `TODO` marker comment (`todo-tag`, S1135: the upper-case word `TODO`, or `todo:` and `todo(`; the noun in prose or a name such as `guide.todo` is no marker), one import per module with `--fix` merging a value and a type import (`no-duplicate-import`); the Sonar way block also maps the unicorn, core and typescript-eslint rules of `scripts/lib/sonar-way.mjs`, and the specs run the test-scoped rules of the profile; the factory also turns on typescript-eslint `no-deprecated`, `no-base-to-string` and `require-await`. The files `*.spec.ts` and `*.e2e-spec.ts` are outside the scan, so outside these rules |
47
47
  | **Cookies** (R141) | A cookie a door writes through the response of Express or Fastify (`cookie`, `setCookie`) states `httpOnly: true`, `secure: true` and `sameSite` `lax` or `strict` in options typed with those literals, and `Set-Cookie` is never written as a header; the call is recognised by where its signature is declared (`response-cookie-attributes`). A secret-derived value is compared with `timingSafeEqual`: a `Secret` of `platform/config` and the `.digest()` of a `Hash` or `Hmac` of Node's crypto are recognised by type (`secret-compare-timing-safe`) |
48
48
  | **Default deny** | Typed bodies and arguments, no `GraphQLJSON` tunnel, no `switch (operation)`, `@Public` carries a `PublicReason` member of `domain/identity`, no `@UseGuards` (the global `APP_GUARD` chain decides) and no guard injected into another guard (`no-untyped-body`, `public-needs-reason`, `no-auth-use-guards`, `no-guard-injects-guard`) |
49
49
  | **Module shape** | No `@Global()`; `isGlobal: true` only in an app's `app.module.ts`; no import of another owner's module; typed `ConfigurableModuleBuilder`; `static register` is the only factory; every module (capability, sub-module, feature, transport, cli group) has a sibling `<x>.module-definition.ts` and `<x>.options.ts`, extends its own `ConfigurableModuleClass` and is listed only as `X.register(...)` (`module-definition-required`); only a capability's representative module keeps `.setExtras({ isGlobal: false })` and the `register` override (`capability-module-shape`); one module per file; no `new` of a provider; no module-level `let` (`no-global-decorator`, `is-global-only-in-app`, `no-cross-owner-module-import`, `static-module-register`) |
@@ -69,7 +69,7 @@ A sample, not the list:
69
69
  | **Infrastructure owners** | Each raw library (HTTP, cache, queue, scheduler, logger, date, config, events) is imported or reached as a global only inside the capability the manifest names for it (`ruleParams.be.infraOwners`); `@nestjs/config`, `dotenv` and `@nestjs/event-emitter` nowhere; the `HttpClient` port of `platform/http` (found by the receiver's type) is called only in an `integrations` owner, `platform/http` and the test world (`infra-import-owner`, `http-client-only-in-integrations`) |
70
70
  | **Observability** | Logs leave through the `Logger` port of `platform/logging`, never the framework's `Logger`; a log call's first argument is a member of an owner's `<owner>.log-events.ts` enum; a failure log carries the exception's identity, not only its wording (`no-framework-logger`, `no-interpolated-log-message`, `no-error-wording-as-log-identity`) |
71
71
  | **Testing** | A unit spec is `<name>.<role>.spec.ts` beside its subject: REQUIRED beside every file of a spec-required role of `ruleParams.be.unitRoles` (every `<name>.service.ts` its `<name>.service.spec.ts`, every `<name>.cli.ts` of `src/features/cli/` its `<name>.cli.spec.ts`) and beside a webhook or realtime door that has no service of its own; OPTIONAL beside any other file of a `ruleParams.be.logicRoles` role inside a slot whose `coverage` is `required` (the file owes 100 per file, not a spec of its own); any other `*.spec.ts` outside `src/tests/{e2e,integration,contract,world}` (handler, resolver, controller, consumer, entity, module, composition) is a finding; there is no `.test.ts`, `int-spec` or `harness-spec`; a spec asserts a result or a state, not only a call; an e2e reads persisted state back through a typeorm `EntityManager` and reaches no model provider outside `src/tests/e2e/live/` (`unit-test-colocated`, `no-call-only-spec`, `e2e-asserts-persisted-state`, `no-model-call-in-e2e`, `no-api-shaped-e2e-filename`, `no-marker-model-stub`) |
72
- | **Command line** | Every one-off action is a nest-commander command of the one cli app: `apps/cli/src/main.ts` boots with `CommandFactory.run` and never serves (`cli-bootstrap`); a `@Command` or `@SubCommand` is declared only in `src/features/cli/` as `<group>/<group>.cli.ts` or `<group>/subs/<name>.cli.ts`, one per file, each with its `<name>.cli.spec.ts` beside it (`cli-command-shape`, `unit-test-colocated`); `nest-commander` is imported only by the cli, and `process.argv`, `commander`, `yargs` and `minimist` nowhere (`cli-owner`) |
72
+ | **Command line** | A command line is a nest-commander cli app with its own feature root: the one ops cli `apps/cli` with `src/features/cli/` (every one-off action), and a client cli `apps/<app>` with `src/features/client-cli/<app>/` (a command line a user installs from npm). Its `main.ts` boots with `CommandFactory.run` and never serves (`cli-bootstrap`); a `@Command` or `@SubCommand` is declared only in a cli feature root as `<group>/<group>.cli.ts` or `<group>/subs/<name>.cli.ts`, one per file, each with its `<name>.cli.spec.ts` beside it (`cli-command-shape`, `unit-test-colocated`); `nest-commander` is imported only by the cli apps and their feature roots, and `process.argv`, `commander`, `yargs` and `minimist` nowhere (`cli-owner`); a client cli imports no domain, events, queues or projections module, nothing of the database capability or of a persistence folder, and no database library (`cli-client-boundary`) |
73
73
  | **End-to-end flows** | One file, one flow, named steps; the flow enters through transport (a `CommandBus`, `QueryBus` or a handler, consumer or job is never called), boots through `src/tests/e2e/setup` (no `Test.createTestingModule`), **never sleeps** — it polls with `waitFor` until the state settles, with a deadline — and takes no branch inside a step (`e2e-uses-production-transport`, `no-wiring-in-flow-spec`, `no-sleep-in-flow`, `no-branch-in-flow-step`) |
74
74
  | **CDC · event delivery** | Projections and events follow the declared delivery contract |
75
75
  | **Service dependencies · source form** | Production source declares no `Mock*`, `Fake*` or `Stub*` class, function or constant: the marker is a whole PascalCase or camelCase word of the identifier, a double lives in a spec or `src/tests`, and an offline driver is an options-driven adapter named for what it does (`no-test-double-in-source`); the provider, repository-class and connection rules of this law are listed under Dependency injection and Data access |
package/dist/cli.d.ts CHANGED
@@ -1,13 +1,16 @@
1
1
  import type { Recommended, RuleModule } from "./lib/rule.js";
2
- /** The cli app boots with CommandFactory.run and never serves HTTP or a microservice. */
2
+ /** A cli app boots with CommandFactory.run and never serves HTTP or a microservice. */
3
3
  export declare const cliBootstrap: RuleModule;
4
- /** A nest-commander command is declared only where the cli feature root keeps it, one per file, a sub-command a CommandRunner. */
4
+ /** A nest-commander command is declared only where a cli feature root keeps it, one per file, a sub-command a CommandRunner. */
5
5
  export declare const cliCommandShape: RuleModule;
6
- /** nest-commander belongs to the cli app and the cli feature root; nothing else parses arguments or opens an action door. */
6
+ /** nest-commander belongs to the cli apps and the cli feature roots; nothing else parses arguments or opens an action door. */
7
7
  export declare const cliOwner: RuleModule;
8
+ /** A client cli imports nothing of the server: no domain or messaging module, no database capability or persistence, no database library. */
9
+ export declare const cliClientBoundary: RuleModule;
8
10
  /** The rules this law contributes to the plugin. */
9
11
  export declare const rules: {
10
12
  "cli-bootstrap": RuleModule;
13
+ "cli-client-boundary": RuleModule;
11
14
  "cli-command-shape": RuleModule;
12
15
  "cli-owner": RuleModule;
13
16
  };
package/dist/cli.js CHANGED
@@ -1,40 +1,50 @@
1
1
  /**
2
- * The rules of the one-off actions of a back end (catalog R148 `BE_CLI_BOOTSTRAP`, R149 `BE_CLI_COMMAND_SHAPE`, R150
3
- * `BE_CLI_OWNER`). Every one-off action (migrate, seed, sync, backup, any operator command)
4
- * lives in ONE app, `be/apps/cli` (slot `be.app.cli`), built on nest-commander, and its commands live in the cli feature root
5
- * `src/features/cli/` (slot `be.cli`):
2
+ * The rules of the command lines of a back end (catalog R148 `BE_CLI_BOOTSTRAP`, R149 `BE_CLI_COMMAND_SHAPE`, R150
3
+ * `BE_CLI_OWNER`, R398 `BE_CLI_CLIENT_BOUNDARY`). A cli app is built on nest-commander and its commands live in its own feature
4
+ * root: the ops cli `be/apps/cli` (slot `be.app.cli`: every one-off action, migrate, seed, sync, backup, any operator command)
5
+ * with `src/features/cli/` (slot `be.cli`), and a client cli `be/apps/<app>` (slot `be.app.client-cli`: a command line a user
6
+ * installs from npm) with `src/features/client-cli/<app>/` (slot `be.client-cli`):
6
7
  *
7
- * - `cli-bootstrap`: the cli app boots with `CommandFactory.run(...)` of nest-commander in its `main.ts`; it never creates an HTTP
8
+ * - `cli-bootstrap`: a cli app boots with `CommandFactory.run(...)` of nest-commander in its `main.ts`; it never creates an HTTP
8
9
  * application or a microservice (`NestFactory.create*` of `@nestjs/core`, `.listen()` on what it built, an HTTP platform adapter
9
10
  * or `@nestjs/microservices`);
10
11
  * - `cli-command-shape`: a nest-commander command class (`@Command` or `@SubCommand`, by the import that binds the decorator) is
11
- * declared only in the cli feature root: a group `@Command` in `<group>/<group>.cli.ts`, a `@SubCommand` in
12
+ * declared only in a cli feature root: a group `@Command` in `<group>/<group>.cli.ts`, a `@SubCommand` in
12
13
  * `<group>/subs/<name>.cli.ts`, one class per file, and a sub-command extends `CommandRunner`. Its unit spec beside it
13
- * (`<name>.cli.spec.ts`) is required by `starci app check` (scripts/hfs/rules/cli.mjs);
14
- * - `cli-owner`: `nest-commander` is imported only by the cli app and the cli feature root; no back-end source parses the process
14
+ * (`<name>.cli.spec.ts`) is required by `unit-test-colocated`;
15
+ * - `cli-owner`: `nest-commander` is imported only by the cli apps and the cli feature roots; no back-end source parses the process
15
16
  * arguments itself (`process.argv`) or imports another argument parser (commander, yargs, minimist): an action door anywhere
16
- * else is refused.
17
+ * else is refused;
18
+ * - `cli-client-boundary`: a client cli runs on a user's machine, so its app and its feature root import no domain, events,
19
+ * queues or projections module, nothing of the database capability or of a persistence folder, and no database library.
17
20
  *
18
21
  * Where a file lives is asked of the slot view; what a name IS comes from the import that binds it. No path pattern is spelled here.
19
22
  */
23
+ import { posix } from "node:path";
20
24
  import { hfsOf } from "./lib/hfs.js";
21
25
  import { decoratorCallee, importOf, isImportedFrom, moduleReferences } from "./lib/import-source.js";
22
- /** The slot of the cli app and of the cli feature root. */
23
- const CLI_APP_SLOT = "be.app.cli";
24
- const CLI_FEATURE_SLOT = "be.cli";
26
+ import { normalizePath } from "./lib/path.js";
27
+ import { resolveAlias } from "./lib/specifier.js";
28
+ /** The slots of the client cli: its app and its feature root. */
29
+ const CLIENT_APP_SLOT = "be.app.client-cli";
30
+ const CLIENT_FEATURE_SLOT = "be.client-cli";
31
+ /** The slots of a cli app (the ops cli, a client cli) and of a cli feature root (of the ops cli, of a client cli). */
32
+ const CLI_APP_SLOTS = new Set(["be.app.cli", CLIENT_APP_SLOT]);
33
+ const CLI_FEATURE_SLOTS = new Set(["be.cli", CLIENT_FEATURE_SLOT]);
25
34
  const COMMANDER = "nest-commander";
26
35
  /** The argument parsers no back-end source imports: nest-commander (in the cli app and feature only) parses the arguments. */
27
36
  const FOREIGN_PARSERS = new Set(["commander", "yargs", "yargs/yargs", "yargs/helpers", "minimist"]);
28
37
  /** The entry file of an app (the slot's first requirement): where the cli app boots. */
29
38
  const ENTRY = "main.ts";
30
39
  const relativeIn = (hfs, file) => hfs.allows(file)?.relative ?? null;
31
- const isCliApp = (hfs, file) => hfs.slotOf(file) === CLI_APP_SLOT;
32
- const isCliFeature = (hfs, file) => hfs.slotOf(file) === CLI_FEATURE_SLOT;
33
- /** The cli app boots with CommandFactory.run and never serves HTTP or a microservice. */
40
+ const isCliApp = (hfs, file) => CLI_APP_SLOTS.has(hfs.slotOf(file) ?? "");
41
+ const isCliFeature = (hfs, file) => CLI_FEATURE_SLOTS.has(hfs.slotOf(file) ?? "");
42
+ const isClientCli = (hfs, file) => hfs.slotOf(file) === CLIENT_APP_SLOT || hfs.slotOf(file) === CLIENT_FEATURE_SLOT;
43
+ /** A cli app boots with CommandFactory.run and never serves HTTP or a microservice. */
34
44
  export const cliBootstrap = {
35
45
  meta: {
36
46
  type: "problem",
37
- docs: { description: "The cli app boots with `CommandFactory.run` of nest-commander and never creates an HTTP application or a microservice." },
47
+ docs: { description: "A cli app boots with `CommandFactory.run` of nest-commander and never creates an HTTP application or a microservice." },
38
48
  schema: [],
39
49
  messages: {
40
50
  missing: "The cli app's `main.ts` never calls `CommandFactory.run(AppModule, ...)` of nest-commander. The cli app is the command line of the back end: boot it with CommandFactory.run, which parses the arguments and runs the command.",
@@ -84,7 +94,7 @@ const commanderDecorator = (context, klass) => {
84
94
  }
85
95
  return null;
86
96
  };
87
- /** Where a command of each kind is declared in the cli feature root: `<group>/<group>.cli.ts` or `<group>/subs/<name>.cli.ts`. */
97
+ /** Where a command of each kind is declared in a cli feature root: `<group>/<group>.cli.ts` or `<group>/subs/<name>.cli.ts`. */
88
98
  const placeOf = (relative) => {
89
99
  const parts = String(relative ?? "").split("/");
90
100
  if (parts.length === 2 && parts[1] === `${parts[0]}.cli.ts`)
@@ -94,15 +104,15 @@ const placeOf = (relative) => {
94
104
  return "SubCommand";
95
105
  return null;
96
106
  };
97
- /** A nest-commander command is declared only where the cli feature root keeps it, one per file, a sub-command a CommandRunner. */
107
+ /** A nest-commander command is declared only where a cli feature root keeps it, one per file, a sub-command a CommandRunner. */
98
108
  export const cliCommandShape = {
99
109
  meta: {
100
110
  type: "problem",
101
- docs: { description: "A nest-commander command is a group `@Command` in `src/features/cli/<group>/<group>.cli.ts` or a `@SubCommand` extending `CommandRunner` in `src/features/cli/<group>/subs/<name>.cli.ts`, one per file." },
111
+ docs: { description: "A nest-commander command is a group `@Command` in `<group>/<group>.cli.ts` or a `@SubCommand` extending `CommandRunner` in `<group>/subs/<name>.cli.ts` of a cli feature root (`src/features/cli/`, `src/features/client-cli/<app>/`), one per file." },
102
112
  schema: [],
103
113
  messages: {
104
- outside: "`@{{kind}}` declares a command outside the cli feature root (this file is in slot `{{slot}}`). Every one-off action is a command of `src/features/cli/`: a group in `<group>/<group>.cli.ts`, a sub-command in `<group>/subs/<name>.cli.ts`, compiled only into apps/cli.",
105
- misplaced: "`@{{kind}}` sits in `{{relative}}`. A group `@Command` lives in `<group>/<group>.cli.ts` and a `@SubCommand` in `<group>/subs/<name>.cli.ts` of the cli feature root.",
114
+ outside: "`@{{kind}}` declares a command outside a cli feature root (this file is in slot `{{slot}}`). A one-off action is a command of `src/features/cli/`, compiled only into apps/cli; a command a user runs is one of `src/features/client-cli/<app>/`, compiled only into that client cli: a group in `<group>/<group>.cli.ts`, a sub-command in `<group>/subs/<name>.cli.ts`.",
115
+ misplaced: "`@{{kind}}` sits in `{{relative}}`. A group `@Command` lives in `<group>/<group>.cli.ts` and a `@SubCommand` in `<group>/subs/<name>.cli.ts` of its cli feature root.",
106
116
  second: "This file declares a second command. One command per file: move it to its own `<name>.cli.ts`.",
107
117
  runner: "`@SubCommand` class `{{name}}` does not extend `CommandRunner` of nest-commander. A sub-command is a CommandRunner whose `run(...)` performs the action.",
108
118
  },
@@ -149,16 +159,16 @@ const isProcessArgv = (context, node) => {
149
159
  return true;
150
160
  return object.type === "MemberExpression" && !object.computed && object.object.type === "Identifier" && object.object.name === "globalThis" && object.property.type === "Identifier" && object.property.name === "process";
151
161
  };
152
- /** nest-commander belongs to the cli app and the cli feature root; nothing else parses arguments or opens an action door. */
162
+ /** nest-commander belongs to the cli apps and the cli feature roots; nothing else parses arguments or opens an action door. */
153
163
  export const cliOwner = {
154
164
  meta: {
155
165
  type: "problem",
156
- docs: { description: "nest-commander is imported only by the cli app and the cli feature root; no back-end source reads `process.argv` or imports another argument parser." },
166
+ docs: { description: "nest-commander is imported only by the cli apps and the cli feature roots; no back-end source reads `process.argv` or imports another argument parser." },
157
167
  schema: [],
158
168
  messages: {
159
- commander: "`nest-commander` is imported outside the cli app and the cli feature root (this file is in slot `{{slot}}`). A one-off action is a command of `src/features/cli/` run by apps/cli; no other app or source opens an action door.",
160
- parser: "`{{name}}` parses command-line arguments. The back end has one command line, apps/cli on nest-commander: write the action as a command of `src/features/cli/<group>/subs/<name>.cli.ts`.",
161
- argv: "`process.argv` is read here. No back-end process parses its own arguments: a one-off action is a command of `src/features/cli/` that apps/cli runs through nest-commander.",
169
+ commander: "`nest-commander` is imported outside a cli app and a cli feature root (this file is in slot `{{slot}}`). A one-off action is a command of `src/features/cli/` run by apps/cli, and a command a user runs is one of a client cli's `src/features/client-cli/<app>/`; no other app or source opens an action door.",
170
+ parser: "`{{name}}` parses command-line arguments. A command line of the back end is a cli app on nest-commander: write the action as a command `<group>/subs/<name>.cli.ts` of its feature root.",
171
+ argv: "`process.argv` is read here. No back-end process parses its own arguments: an action is a command of a cli feature root that its cli app runs through nest-commander.",
162
172
  },
163
173
  },
164
174
  create(context) {
@@ -182,15 +192,67 @@ export const cliOwner = {
182
192
  };
183
193
  },
184
194
  };
195
+ /** The tiers a client cli never imports: the business of the server and its messaging. */
196
+ const SERVER_TIERS = new Set(["domain", "events", "queues", "projections"]);
197
+ /** The libraries that talk to the database: a client cli holds no connection. */
198
+ const DATABASE_LIBRARIES = ["typeorm", "@nestjs/typeorm", "pg"];
199
+ const DATABASE_CAPABILITY = "database";
200
+ const PERSISTENCE_SLOT = "be.persistence";
201
+ /** The file an import of a relative or aliased specifier names, as its two candidate paths (a folder entry, a file); none for a package. */
202
+ const targetsOf = (context, specifier) => {
203
+ const base = specifier.startsWith(".") ? posix.join(posix.dirname(normalizePath(context.filename)), specifier) : resolveAlias(context, specifier)?.target;
204
+ return base === undefined ? [] : [`${base}/index.ts`, `${base}.ts`];
205
+ };
206
+ /** Why a client cli may not import a file of the back end, or null when it may. */
207
+ const serverSideOf = (hfs, file) => {
208
+ const tier = hfs.tierOf(file);
209
+ if (tier !== null && SERVER_TIERS.has(tier))
210
+ return `a ${tier} module`;
211
+ const found = hfs.classify(file);
212
+ if (found.slot === PERSISTENCE_SLOT)
213
+ return "a persistence folder";
214
+ if (found.bindings?.["capability"] === DATABASE_CAPABILITY && tier === "platform")
215
+ return "the database capability";
216
+ return null;
217
+ };
218
+ /** A client cli imports nothing of the server: no domain or messaging module, no database capability or persistence, no database library. */
219
+ export const cliClientBoundary = {
220
+ meta: {
221
+ type: "problem",
222
+ docs: { description: "A client cli (its app and its feature root) imports no domain, events, queues or projections module, nothing of the database capability or of a persistence folder, and no database library." },
223
+ schema: [],
224
+ messages: {
225
+ server: "`{{name}}` is {{what}}. A client cli runs on a user's machine and holds nothing of the server: it calls the server through an integration client (`modules/integrations/<provider>`) and composes platform capabilities only.",
226
+ library: "`{{name}}` is a database library. A client cli holds no database connection: what it needs from the data it asks the server for, through an integration client.",
227
+ },
228
+ },
229
+ create(context) {
230
+ const hfs = hfsOf(context);
231
+ if (!isClientCli(hfs, context.filename))
232
+ return {};
233
+ return moduleReferences(({ source, value }) => {
234
+ if (DATABASE_LIBRARIES.some((name) => value === name || value.startsWith(`${name}/`)))
235
+ return context.report({ node: source, messageId: "library", data: { name: value } });
236
+ for (const target of targetsOf(context, value)) {
237
+ const what = serverSideOf(hfs, target);
238
+ if (what === null)
239
+ continue;
240
+ return context.report({ node: source, messageId: "server", data: { name: value, what } });
241
+ }
242
+ });
243
+ },
244
+ };
185
245
  /** The rules this law contributes to the plugin. */
186
246
  export const rules = {
187
247
  "cli-bootstrap": cliBootstrap,
248
+ "cli-client-boundary": cliClientBoundary,
188
249
  "cli-command-shape": cliCommandShape,
189
250
  "cli-owner": cliOwner,
190
251
  };
191
252
  /** Every rule is an error from the start: HFS keeps no baseline. */
192
253
  export const recommended = {
193
254
  "starci-be/cli-bootstrap": "error",
255
+ "starci-be/cli-client-boundary": "error",
194
256
  "starci-be/cli-command-shape": "error",
195
257
  "starci-be/cli-owner": "error",
196
258
  };
@@ -18,7 +18,7 @@
18
18
  * `HttpException` family, a thrown string or object), and a domain owner that throws a platform error outward. A rejection is
19
19
  * a throw: `Promise.reject(value)` and the `reject(value)` of a `new Promise((resolve, reject) => ...)` executor are judged
20
20
  * the same way, so the one form that also satisfies Sonar S7746 (`throw` in an async function) and S6671 (an Error rejects)
21
- * is `throw new <C>Error(...)`.
21
+ * is `throw new <C>Error(...)`. A value caught by a `catch` clause or by the rejection handler of `.catch(onRejected)` or `.then(onFulfilled, onRejected)` is rethrown as it is.
22
22
  *
23
23
  * The error base of every file is `DomainError` as `@starci/common` declares it: both rules ask the type checker where the class is declared,
24
24
  * so a family of an app (which imports it through the re-export of `platform/errors`), of a root workspace package and of a `@starci` package
@@ -291,13 +291,12 @@ const isCaughtValue = (context, identifier) => {
291
291
  return false;
292
292
  const fn = definition.node;
293
293
  const call = fn.parent;
294
+ // The rejection handler of a promise: the one argument of `.catch(onRejected)`, or the second of `.then(onFulfilled, onRejected)`.
295
+ const handler = (method) => call?.type === "CallExpression" && call.callee.type === "MemberExpression" && !call.callee.computed
296
+ && call.callee.property.type === "Identifier" && call.callee.property.name === method
297
+ && call.arguments[method === "catch" ? 0 : 1] === fn;
294
298
  return ((fn.type === "ArrowFunctionExpression" || fn.type === "FunctionExpression") &&
295
- call?.type === "CallExpression" &&
296
- call.arguments[0] === fn &&
297
- call.callee.type === "MemberExpression" &&
298
- !call.callee.computed &&
299
- call.callee.property.type === "Identifier" &&
300
- call.callee.property.name === "catch" &&
299
+ (handler("catch") || handler("then")) &&
301
300
  fn.params[0] === definition.name);
302
301
  });
303
302
  }
package/dist/injection.js CHANGED
@@ -426,15 +426,17 @@ const check = (context, decorator, call, target, injected) => {
426
426
  // every type annotation maps to a TypeScript type node; the guard only tells the compiler so
427
427
  if (!tsAnnotation || !ts.isTypeNode(tsAnnotation))
428
428
  return;
429
- const declared = checker.getNonNullableType(checker.getTypeFromTypeNode(tsAnnotation));
430
- const declaredName = checker.typeToString(declared);
429
+ // The parameter is the injected type exactly, or that type made optional (`@Optional() x?: T` adds undefined): an injector of `T | null`
430
+ // matches a parameter of `T | null`, and a parameter of `T` alone still refuses a `T | null` injector, whose null it would not handle.
431
+ const annotated = checker.getTypeFromTypeNode(tsAnnotation);
432
+ const declared = checker.getNonNullableType(annotated);
433
+ const declaredName = checker.typeToString(annotated);
431
434
  if (injected.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
432
435
  context.report({ node: decorator, messageId: "unresolved", data: { injector, declared: declaredName } });
433
436
  return;
434
437
  }
435
- if (injected === declared)
436
- return;
437
- if (checker.isTypeAssignableTo(injected, declared) && checker.isTypeAssignableTo(declared, injected))
438
+ const same = (type) => injected === type || (checker.isTypeAssignableTo(injected, type) && checker.isTypeAssignableTo(type, injected));
439
+ if (same(annotated) || same(declared))
438
440
  return;
439
441
  context.report({ node: annotation, messageId: "mismatch", data: { injector, injected: injectedName, declared: declaredName } });
440
442
  };
@@ -8,6 +8,12 @@
8
8
  export interface HfsApp {
9
9
  readonly name: string;
10
10
  readonly kind: string;
11
+ /** The contract an api app declares, `graphql` or `rest`; absent means graphql. */
12
+ readonly contract?: string;
13
+ /** The npm package a client cli is published as. */
14
+ readonly package?: string;
15
+ /** The command a client cli installs. */
16
+ readonly bin?: string;
11
17
  }
12
18
  /** One declared database connection (`hfs.json` sides.be.connections). */
13
19
  export interface HfsConnection {
@@ -62,7 +68,8 @@ export interface HfsSlot {
62
68
  export interface HfsUnitRole {
63
69
  readonly role: string;
64
70
  readonly spec: string;
65
- readonly slot?: string;
71
+ /** The slots the role is unit-tested in; absent, every slot. */
72
+ readonly slots?: readonly string[];
66
73
  readonly exempt?: readonly string[];
67
74
  }
68
75
  /** A parameter-name rule (`ruleParams.be.paramNames`). */
@@ -15,3 +15,11 @@ export declare const KIND_DOOR_SLOTS: readonly string[];
15
15
  * @returns {boolean} Whether files of that slot are transport files.
16
16
  */
17
17
  export declare const isTransportSlot: (slot: unknown) => boolean;
18
+ /**
19
+ * True for a back end whose api apps all declare `contract: "rest"` (hfs.json, BE-TRANSPORT-1): its controllers are its default doors, so the
20
+ * rules that ask a REST route for GraphQL's evidence (a door reason, a declared operation table) do not judge it.
21
+ */
22
+ export declare const servesRest: (apps: ReadonlyArray<{
23
+ readonly kind: string;
24
+ readonly contract?: string;
25
+ }>) => boolean;
@@ -15,3 +15,11 @@ export const KIND_DOOR_SLOTS = Object.freeze(["be.feature.webhooks.http", "be.fe
15
15
  * @returns {boolean} Whether files of that slot are transport files.
16
16
  */
17
17
  export const isTransportSlot = (slot) => typeof slot === "string" && (slot.startsWith("be.transport.") || KIND_DOOR_SLOTS.includes(slot));
18
+ /**
19
+ * True for a back end whose api apps all declare `contract: "rest"` (hfs.json, BE-TRANSPORT-1): its controllers are its default doors, so the
20
+ * rules that ask a REST route for GraphQL's evidence (a door reason, a declared operation table) do not judge it.
21
+ */
22
+ export const servesRest = (apps) => {
23
+ const apis = apps.filter((app) => app.kind === "api");
24
+ return apis.length > 0 && apis.every((app) => app.contract === "rest");
25
+ };
@@ -3,10 +3,17 @@ import type { HfsUnitRole, HfsView } from "./hfs.js";
3
3
  export interface SpecRole {
4
4
  readonly role: string;
5
5
  readonly spec: string;
6
- readonly slot?: string;
6
+ readonly slots?: readonly string[];
7
7
  readonly exempt?: readonly string[];
8
8
  readonly optional?: boolean;
9
+ /** The spec is a size split, `<name>.<role>.<facet>.spec.ts`, of the main spec `<name>.<role>.spec.ts` (BE-TEST-1). */
10
+ readonly split?: boolean;
9
11
  }
12
+ /**
13
+ * The main spec a size split stands beside: `orders.service.refunds.spec.ts` -> `orders.service.spec.ts` (one kebab facet before
14
+ * `.spec.ts`), or null for a name with no facet segment. A split carries further cases of the same subject when one spec outgrows its line budget.
15
+ */
16
+ export declare const mainSpecOfSplit: (name: string) => string | null;
10
17
  /** The file name of a linted path. */
11
18
  export declare const baseOf: (filename: string) => string;
12
19
  /**
@@ -20,10 +27,10 @@ export declare const isUnitSpecFile: (hfs: HfsView, filename: string) => boolean
20
27
  /** Whether a file is a `<name>.service.spec.ts` unit spec. */
21
28
  export declare const isServiceSpecFile: (hfs: HfsView, filename: string) => boolean;
22
29
  /**
23
- * The unit-tested roles of the back end: `ruleParams.be.unitRoles` of the slot manifest, the ONE list (`[{ role, spec, slot? }]`).
30
+ * The unit-tested roles of the back end: `ruleParams.be.unitRoles` of the slot manifest, the ONE list (`[{ role, spec, slots? }]`).
24
31
  *
25
32
  * @param {object} hfs - The HFS view.
26
- * @returns {ReadonlyArray<{ role: string, spec: string, slot?: string }>} The roles.
33
+ * @returns {ReadonlyArray<{ role: string, spec: string, slots?: string[] }>} The roles.
27
34
  */
28
35
  export declare const unitRoles: (hfs: HfsView) => readonly HfsUnitRole[];
29
36
  /**
@@ -11,6 +11,14 @@
11
11
  * the quality rules of R48 judge the service specs.
12
12
  */
13
13
  import { basename } from "node:path";
14
+ /**
15
+ * The main spec a size split stands beside: `orders.service.refunds.spec.ts` -> `orders.service.spec.ts` (one kebab facet before
16
+ * `.spec.ts`), or null for a name with no facet segment. A split carries further cases of the same subject when one spec outgrows its line budget.
17
+ */
18
+ export const mainSpecOfSplit = (name) => {
19
+ const match = /^(.+\.[a-z][a-z0-9-]*)\.[a-z][a-z0-9-]*\.spec\.([cm]?ts)$/.exec(name);
20
+ return match ? `${match[1]}.spec.${match[2]}` : null;
21
+ };
14
22
  /** The slots whose `*.spec.ts` files are not unit specs: the other test kinds and world infrastructure. */
15
23
  const OTHER_KIND_SLOTS = new Set(["be.tests.e2e", "be.tests.integration", "be.tests.contract", "be.tests.world", "be.tests.world.kit"]);
16
24
  /** The file name of a linted path. */
@@ -31,10 +39,10 @@ export const isUnitSpecFile = (hfs, filename) => {
31
39
  /** Whether a file is a `<name>.service.spec.ts` unit spec. */
32
40
  export const isServiceSpecFile = (hfs, filename) => /\.service\.spec\.ts$/.test(baseOf(filename)) && isUnitSpecFile(hfs, filename);
33
41
  /**
34
- * The unit-tested roles of the back end: `ruleParams.be.unitRoles` of the slot manifest, the ONE list (`[{ role, spec, slot? }]`).
42
+ * The unit-tested roles of the back end: `ruleParams.be.unitRoles` of the slot manifest, the ONE list (`[{ role, spec, slots? }]`).
35
43
  *
36
44
  * @param {object} hfs - The HFS view.
37
- * @returns {ReadonlyArray<{ role: string, spec: string, slot?: string }>} The roles.
45
+ * @returns {ReadonlyArray<{ role: string, spec: string, slots?: string[] }>} The roles.
38
46
  */
39
47
  export const unitRoles = (hfs) => hfs.ruleParams.unitRoles ?? [];
40
48
  /** Whether the slot that owns a file is measured at 100 per file (`coverage: required`): the home of the optional specs of the logic roles. */
@@ -44,8 +52,8 @@ const inCoverageSlot = (hfs, filename) => {
44
52
  };
45
53
  /** The roles whose spec is legal but not required: every logic role that is not a spec-required unit role. */
46
54
  const optionalRoles = (hfs) => (hfs.ruleParams.logicRoles ?? []).filter((role) => !unitRoles(hfs).some((unit) => unit.role === role)).map((role) => ({ role, spec: `${role}.spec`, optional: true }));
47
- /** Whether a role admits a file by its slot (a role with no slot admits any slot; an optional logic role only a coverage-required slot). */
48
- const inRoleSlot = (hfs, role, filename) => (role.optional === true ? inCoverageSlot(hfs, filename) : role.slot === undefined || hfs.slotOf(filename) === role.slot);
55
+ /** Whether a role admits a file by its slot (a role with no slots admits any slot; an optional logic role only a coverage-required slot). */
56
+ const inRoleSlot = (hfs, role, filename) => (role.optional === true ? inCoverageSlot(hfs, filename) : role.slots === undefined || role.slots.includes(hfs.slotOf(filename) ?? ""));
49
57
  /** The path of a classified file below the instance root of its slot. */
50
58
  const slotRelative = (found) => (found.root !== undefined && found.path.startsWith(`${found.root}/`) ? found.path.slice(found.root.length + 1) : baseOf(found.path));
51
59
  /**
@@ -73,7 +81,15 @@ export const unitRoleOfSpec = (hfs, filename) => {
73
81
  if (!isUnitSpecFile(hfs, filename))
74
82
  return null;
75
83
  const name = baseOf(filename);
76
- return [...unitRoles(hfs), ...optionalRoles(hfs)].find((role) => name.endsWith(`.${role.spec}.ts`) && inRoleSlot(hfs, role, filename)) ?? declaredLogicRole(hfs, filename);
84
+ const roles = [...unitRoles(hfs), ...optionalRoles(hfs)];
85
+ const direct = roles.find((role) => name.endsWith(`.${role.spec}.ts`) && inRoleSlot(hfs, role, filename)) ?? declaredLogicRole(hfs, filename);
86
+ if (direct)
87
+ return direct;
88
+ const main = mainSpecOfSplit(name);
89
+ // The split stands where its main spec stands, so the main spec's path answers the slot question.
90
+ const mainPath = main === null ? "" : `${String(filename).replace(/\\/g, "/").slice(0, -name.length)}${main}`;
91
+ const split = main === null ? undefined : roles.find((role) => main.endsWith(`.${role.spec}.ts`) && inRoleSlot(hfs, role, mainPath));
92
+ return split === undefined ? null : { ...split, split: true };
77
93
  };
78
94
  /** Whether a file is the spec of a value role (`ruleParams.be.valueRoles`: a zod schema): its subject is a declared value, so the spec parses it and builds no testing module. */
79
95
  export const isValueRoleSpec = (hfs, filename) => {
@@ -10,7 +10,8 @@
10
10
  * 2. a value whose NAME says it is a credential (`password`, `secret`, `apiKey`, `accessToken`, `authorization`,
11
11
  * `cookie`, `otp`) or a personal identifier (`email`, `phone`, `fullName`, `idCard`, `birthDate`). This is the
12
12
  * second half the convention keeps for values that never carried a brand; a name that says it MEASURES a
13
- * credential (`tokenCount`, `tokenType`, `secretName`) is not the credential, so those endings are exempt.
13
+ * credential (`tokenCount`, `tokenType`, `secretName`) is not the credential, so those endings are exempt, and neither is a
14
+ * value whose type is a number or a boolean (`usage.promptTokens`), since a credential travels as text.
14
15
  *
15
16
  * A log line outlives the request, is copied to a vendor, and is read by people who never had the credential or the
16
17
  * consent. Log an id, a count, or a masked form instead.
@@ -198,6 +199,9 @@ export const noSecretInLog = {
198
199
  const words = wordsOf(name);
199
200
  if (reported.has(name))
200
201
  continue;
202
+ // A number or a flag is never the credential its name mentions: `promptTokens` counts model tokens (a credential travels as text).
203
+ if (isSecretName(words) && isCountOrFlag(context, at))
204
+ continue;
201
205
  if (isSecretName(words)) {
202
206
  reported.add(name);
203
207
  context.report({ node: at, messageId: "secret", data: { name } });
@@ -218,6 +222,12 @@ const isText = (context, node) => {
218
222
  const parts = presentParts(typeOf(context, node));
219
223
  return parts.length > 0 && parts.every((part) => (part.flags & STRINGY) && !(part.flags & ts.TypeFlags.EnumLiteral));
220
224
  };
225
+ const COUNT_OR_FLAG = ts.TypeFlags.NumberLike | ts.TypeFlags.BigIntLike | ts.TypeFlags.BooleanLike;
226
+ /** Whether a node's type is a number or a boolean (with `null`/`undefined` removed): a measure of something, never a credential's text. */
227
+ const isCountOrFlag = (context, node) => {
228
+ const parts = presentParts(typeOf(context, node));
229
+ return parts.length > 0 && parts.every((part) => Boolean(part.flags & COUNT_OR_FLAG));
230
+ };
221
231
  /** The last name a value expression ends in (`token`, `request.headers.authorization`), or null. */
222
232
  const ownNameOf = (node) => {
223
233
  if (node.type === "Identifier")
@@ -14,7 +14,7 @@ import ts from "typescript";
14
14
  import { keyName, walk } from "./lib/ast.js";
15
15
  import { hfsOf } from "./lib/hfs.js";
16
16
  import { decoratorArguments, decoratorCallee, isImportedFrom } from "./lib/import-source.js";
17
- import { isTransportSlot } from "./lib/transport-slots.js";
17
+ import { isTransportSlot, servesRest } from "./lib/transport-slots.js";
18
18
  import { isTsNode, typed } from "./lib/types.js";
19
19
  /** The HTTP route decorators of `@nestjs/common` (`Sse` is a route too: a `text/event-stream` GET that needs its own evidence). */
20
20
  const HTTP_ROUTES = ["Get", "Post", "Put", "Patch", "Delete", "All", "Options", "Head", "Sse"];
@@ -544,7 +544,8 @@ export const restRouteDeclared = {
544
544
  },
545
545
  create(context) {
546
546
  const hfs = hfsOf(context);
547
- if (!isTransportSlot(hfs.slotOf(context.filename)))
547
+ // A rest back end's controllers are its declared contract (BE-TRANSPORT-1, -4): R396 judges them in the emitted document, not a table.
548
+ if (!isTransportSlot(hfs.slotOf(context.filename)) || servesRest(hfs.apps))
548
549
  return {};
549
550
  const declared = operationRouteEvidence(context);
550
551
  return {
@@ -3,14 +3,14 @@
3
3
  *
4
4
  * Each rule is the syntax-tree form of one Sonar rule, shared with the front-end canon (scripts/lib/sonar-syntax-rules.mjs,
5
5
  * bundled under `runtime/`): `no-await-in-loop` (S9382), `prefer-code-point` (S7758), `prefer-string-raw` (S7780),
6
- * `no-nested-conditional` (S3358), `no-void-operator` (S3735), `no-unused-import` (S1128) and `prefer-export-from` (S7763), `no-duplicate-import` (S3863, fixable) and `no-bidirectional-character` (text:S6389); the rest of
6
+ * `no-nested-conditional` (S3358), `no-void-operator` (S3735), `no-unused-import` (S1128) and `prefer-export-from` (S7763), `no-duplicate-import` (S3863, fixable) `todo-tag` (S1135) and `no-bidirectional-character` (text:S6389); the rest of
7
7
  * Sonar way is the factory's Sonar way block (scripts/lib/sonar-way.mjs).
8
8
  * The three Sonar rules that need the type checker, S1874 (a deprecated API), S6551 (an object turned into text) and S7503 (an `async`
9
9
  * function that never awaits and returns no promise), are the typescript-eslint rules `no-deprecated`, `no-base-to-string` and
10
10
  * `require-await` the factory turns on.
11
11
  */
12
12
  import { SONAR_SYNTAX_RULES } from "../runtime/scripts/lib/sonar-syntax-rules.mjs";
13
- const NAMES = ["no-await-in-loop", "prefer-code-point", "prefer-string-raw", "no-nested-conditional", "no-void-operator", "no-unused-import", "prefer-export-from", "max-params", "no-line-separator-literal", "no-bidirectional-character", "no-duplicate-import"];
13
+ const NAMES = ["no-await-in-loop", "prefer-code-point", "prefer-string-raw", "no-nested-conditional", "no-void-operator", "no-unused-import", "prefer-export-from", "max-params", "no-line-separator-literal", "no-bidirectional-character", "no-duplicate-import", "todo-tag"];
14
14
  /** The rules this law contributes to the plugin. */
15
15
  export const rules = Object.fromEntries(NAMES.flatMap((name) => {
16
16
  const rule = SONAR_SYNTAX_RULES[name];
package/dist/testing.js CHANGED
@@ -25,7 +25,7 @@ import { statSync } from "node:fs";
25
25
  import { basename, dirname, join } from "node:path";
26
26
  import { hfsOf, inTestWorld } from "./lib/hfs.js";
27
27
  import { isPackageType, typeOrigins } from "./lib/types.js";
28
- import { doorOfSpec, isUnitSpecFile, unitRoleOfSpec, unitRoleOfSubject } from "./lib/unit-spec.js";
28
+ import { doorOfSpec, isUnitSpecFile, mainSpecOfSplit, unitRoleOfSpec, unitRoleOfSubject } from "./lib/unit-spec.js";
29
29
  /** The file name of a linted path, in forward-slash form. */
30
30
  const baseOf = (filename) => basename(String(filename || "").replace(/\\/g, "/"));
31
31
  /** Test kind `spec`: a unit spec, `<name>.service.spec.ts` beside its service. */
@@ -151,8 +151,10 @@ export const unitTestColocated = {
151
151
  const role = unitRoleOfSpec(hfs, filename);
152
152
  if (!role)
153
153
  return { Program(node) { context.report({ node, messageId: "notService", data: { name } }); } };
154
- const subject = `${name.slice(0, -`.${role.spec}.ts`.length)}.${role.role}.ts`;
155
- if (exists(join(dirname(filename), subject)))
154
+ // A size split `<name>.<role>.<facet>.spec.ts` stands beside its main spec `<name>.<role>.spec.ts` and the subject they test.
155
+ const main = role.split === true ? mainSpecOfSplit(name) : name;
156
+ const subject = main === null ? null : `${main.slice(0, -`.${role.spec}.ts`.length)}.${role.role}.ts`;
157
+ if (subject !== null && main !== null && exists(join(dirname(filename), subject)) && (role.split !== true || exists(join(dirname(filename), main))))
156
158
  return {};
157
159
  return { Program(node) { context.report({ node, messageId: "orphan", data: { name } }); } };
158
160
  }
package/dist/transport.js CHANGED
@@ -13,7 +13,7 @@ import ts from "typescript";
13
13
  import { walk } from "./lib/ast.js";
14
14
  import { hfsOf } from "./lib/hfs.js";
15
15
  import { decoratorArguments, decoratorCallee, importOf, isImportedFrom, moduleReferences } from "./lib/import-source.js";
16
- import { isTransportSlot, KIND_DOOR_SLOTS } from "./lib/transport-slots.js";
16
+ import { isTransportSlot, KIND_DOOR_SLOTS, servesRest } from "./lib/transport-slots.js";
17
17
  import { isPackageType, typeOrigins, typed } from "./lib/types.js";
18
18
  import { operationRouteEvidence, restExceptionEvidence } from "./operations.js";
19
19
  /** The HTTP route decorators of `@nestjs/common` (`Sse` is a route too: a `text/event-stream` GET that needs its own evidence). */
@@ -441,14 +441,17 @@ export const noCapabilityImportsFeatures = {
441
441
  export const restDoorNeedsAReason = {
442
442
  meta: {
443
443
  type: "problem",
444
- docs: { description: "Every REST route shows its own public reason (Health, AuthHandshake, SignedWebhook), byte transfer, redirect or declared operation table." },
444
+ docs: { description: "In a back end whose contract is graphql, every REST route shows its own public reason (Health, AuthHandshake, SignedWebhook), byte transfer, redirect or declared operation table." },
445
445
  schema: [],
446
446
  messages: {
447
447
  unjustified: "[BE_REST_DOOR_EVIDENCE] This REST route shows none of the reasons a door may not be GraphQL: a route-level probe, auth handshake or signed webhook (`@Public({ reason: PublicReason.X })`), a byte transfer, an OAuth redirect, an event stream (`@Sse` in the sse slot of a realtime channel) or a declared public v1 operation table. A plain JSON read belongs in the GraphQL schema, where the client already is.",
448
448
  },
449
449
  },
450
450
  create(context) {
451
- hfsOf(context);
451
+ const hfs = hfsOf(context);
452
+ // A back end whose api apps declare contract rest serves controllers by default: the evidence is GraphQL's door rule (BE-TRANSPORT-1).
453
+ if (servesRest(hfs.apps))
454
+ return {};
452
455
  const declared = operationRouteEvidence(context);
453
456
  return {
454
457
  ClassDeclaration(node) {
package/dist/user-copy.js CHANGED
@@ -13,7 +13,9 @@
13
13
  * 2. a `subject`/`title`/`body`/`text`/`message` property of an object handed to an outbound port - a call on a
14
14
  * receiver whose type is declared by an `integrations` owner or by `platform/event-bus` or `platform/queue` (the receiver's type
15
15
  * decides, not a method name such as `send`);
16
- * 3. a `message`/`description`/`title` property of an object literal built in a transport slot.
16
+ * 3. a `message`/`description`/`title` property of an object literal built in a transport slot, except one the object literal
17
+ * hands to an `@nestjs/swagger` export (`@ApiOperation`, `@ApiProperty`, `@ApiResponse`, ...): that is the operation and field
18
+ * documentation of the REST contract, read by the developers of its clients, and R396 judges the emitted document, not this rule.
17
19
  *
18
20
  * A short, code-shaped literal (`UPPER_SNAKE`, or a single bare word with no space or punctuation - `"PLAN_NOT_FOUND"`,
19
21
  * `"pending"`) is a key or an enum value, not copy, and is left alone; so is a template literal, which this reads one
@@ -57,6 +59,18 @@ const isCustomError = (program, checker, type) => {
57
59
  };
58
60
  /** Whether a receiver's type is declared by an `integrations` owner or by `platform/event-bus` or `platform/queue`: an outbound port. */
59
61
  const isOutboundPort = (context, hfs, node) => typeOrigins(context, node).some((origin) => origin.module === null && (hfs.tierOf(origin.file) === "integrations" || (hfs.tierOf(origin.file) === "platform" && ["event-bus", "queue"].includes(ownerNameOf(hfs, origin.file) ?? ""))));
62
+ /** The package whose decorators describe a REST contract: their text is API documentation for developers, not user copy. */
63
+ const SWAGGER = "@nestjs/swagger";
64
+ /**
65
+ * Whether a property sits in the object-literal argument of a call of an `@nestjs/swagger` export (`@ApiOperation({ description })`,
66
+ * `@ApiProperty({ description })`, `ApiResponse({ description })` inside `applyDecorators`), through nested object and array literals.
67
+ */
68
+ const inSwaggerCall = (property, swagger) => {
69
+ let node = property.parent;
70
+ while (node?.type === "ObjectExpression" || node?.type === "ArrayExpression" || node?.type === "Property")
71
+ node = node.parent;
72
+ return node?.type === "CallExpression" && node.callee.type === "Identifier" && swagger.has(node.callee.name);
73
+ };
60
74
  /** User-facing text is looked up in the catalog by key, never written where it is used. */
61
75
  export const userCopyThroughCatalog = {
62
76
  meta: {
@@ -78,7 +92,16 @@ export const userCopyThroughCatalog = {
78
92
  const inTransport = isTransportSlot(slot);
79
93
  const { program, checker, toTs } = typed(context);
80
94
  const isOutboundCall = (node) => node?.type === "CallExpression" && node.callee.type === "MemberExpression" && !node.callee.computed && isOutboundPort(context, hfs, node.callee.object);
95
+ // The local names this file binds to `@nestjs/swagger` (ApiOperation, ApiProperty, ApiResponse, ...): a call of one documents the contract.
96
+ const swagger = new Set();
81
97
  return {
98
+ ImportDeclaration(node) {
99
+ if (node.source.value !== SWAGGER)
100
+ return;
101
+ for (const specifier of node.specifiers)
102
+ if (specifier.type === "ImportSpecifier")
103
+ swagger.add(specifier.local.name);
104
+ },
82
105
  NewExpression(node) {
83
106
  const first = node.arguments[0];
84
107
  if (!first)
@@ -120,6 +143,8 @@ export const userCopyThroughCatalog = {
120
143
  return;
121
144
  if (isOutboundCall(node.parent?.parent))
122
145
  return; // already judged as notification copy
146
+ if (inSwaggerCall(node, swagger))
147
+ return; // contract text for developers, judged with the document (R396)
123
148
  context.report({ node: node.value, messageId: "response", data: { property: key } });
124
149
  },
125
150
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@starci/eslint-canon-be",
3
- "version": "3.21.1",
3
+ "version": "3.23.3",
4
4
  "description": "The StarCi back-end lint canon: every rule its laws publish, gathered as one flat-config plugin.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -40,7 +40,7 @@
40
40
  "node": ">=22.13.0"
41
41
  },
42
42
  "peerDependencies": {
43
- "@starci/hfs": "~6.6.0",
43
+ "@starci/hfs": "~6.8.0",
44
44
  "eslint": ">=9",
45
45
  "typescript": ">=5.9"
46
46
  },
@@ -74,6 +74,6 @@
74
74
  "typescript": "^6.0.3"
75
75
  },
76
76
  "types": "./dist/index.d.ts",
77
- "gitHead": "4f9def1b0a7af7ec2149a7bd3756cb77c963d288",
78
- "starciSource": "1bb5154e9e5ed2f50d3558964bbb3dfd938348a2f83ad72cea50dda64bb80603"
77
+ "gitHead": "bf397f2b69c82c3014caeb2f71158c91624ecf47",
78
+ "starciSource": "7f9bdbb61e27765ad89d6c933b87e5a53635d5145420e6cbdf01616c6513835e"
79
79
  }
@@ -515,6 +515,32 @@ const noBidirectionalCharacter = {
515
515
  }),
516
516
  };
517
517
 
518
+ /**
519
+ * S1135: a leftover `TODO` marker comment. A marker is the upper-case word `TODO` standing alone, or the word in any case written straight into a
520
+ * tag (`todo:`, `todo(owner)`), with no letter, digit, underscore or dot touching it on the left; a marker followed by an issue key (`TODO PROJ-12`)
521
+ * is a tracked task and passes. The plain word as a noun of prose or a name (`a todo can be`, `the todo list`, `guide.todo`, `GuideTodoKey`) is no
522
+ * marker: the sonarjs port of S1135 reads a `todo` after the dot of a member path as the start of a sentence and reports it.
523
+ */
524
+ const TODO_MARKER = /(?<![\p{L}\p{N}_.])(?:TODO(?![\p{L}\p{N}_])|[Tt][Oo][Dd][Oo](?=[:(]))/u;
525
+ const TODO_ISSUE_KEY = /\b[A-Z][A-Z0-9]+-\d+\b/u;
526
+ const todoTag = {
527
+ meta: { type: 'suggestion', schema: [], messages: { todo: 'S1135: Complete the task associated to this "TODO" comment.' } },
528
+ create: (context) => ({
529
+ 'Program:exit': () => {
530
+ for (const comment of context.sourceCode.getAllComments()) {
531
+ if (comment.value.trim().startsWith('eslint-disable')) continue;
532
+ comment.value.split(/\r\n?|\n/).forEach((line, lineIdx) => {
533
+ const found = TODO_MARKER.exec(line);
534
+ if (!found || TODO_ISSUE_KEY.test(line.slice(found.index + 4))) return;
535
+ const row = comment.loc.start.line + lineIdx;
536
+ const column = (lineIdx === 0 ? comment.loc.start.column + 2 : 0) + found.index;
537
+ context.report({ messageId: 'todo', loc: { start: { line: row, column }, end: { line: row, column: column + 4 } } });
538
+ });
539
+ }
540
+ },
541
+ }),
542
+ };
543
+
518
544
  /** The files the example scans leave out: a unit spec and an end-to-end spec (the regex, and the flat-config globs of the same set). */
519
545
  const OUTSIDE_THE_SCAN = /\.(?:e2e-)?spec\.[cm]?[jt]sx?$/;
520
546
  export const OUTSIDE_THE_SCAN_FILES = Object.freeze(['**/*.spec.{js,mjs,cjs,ts,mts,cts,jsx,tsx}', '**/*.e2e-spec.{js,mjs,cjs,ts,mts,cts,jsx,tsx}']);
@@ -536,6 +562,7 @@ export const SONAR_SYNTAX_RULES = Object.freeze({
536
562
  'max-params': scanned(maxParams),
537
563
  'no-line-separator-literal': noLineSeparatorLiteral,
538
564
  'no-bidirectional-character': noBidirectionalCharacter,
565
+ 'todo-tag': scanned(todoTag),
539
566
  'no-duplicate-import': scanned(noDuplicateImport),
540
567
  'no-useless-fragment': scanned(noUselessFragment),
541
568
  'no-nested-component': scanned(noNestedComponent),
@@ -19,6 +19,7 @@ const SONAR_WAY_OWNED = Object.freeze({
19
19
  'sonarjs/no-nested-conditional': 'S3358, the canon syntax rule no-nested-conditional',
20
20
  'sonarjs/unused-import': 'S1128, the canon syntax rule no-unused-import',
21
21
  'sonarjs/void-use': 'S3735, the canon syntax rule no-void-operator',
22
+ 'sonarjs/todo-tag': 'S1135, the canon syntax rule todo-tag (the marker word, not the noun)',
22
23
  'sonarjs/deprecation': 'S1874, the borrowed @typescript-eslint/no-deprecated',
23
24
  'sonarjs/no-unused-vars': 'S1481, the TypeScript compiler (noUnusedLocals and noUnusedParameters in @starci/tsconfig)',
24
25
  });