@domain-first/project-structure 4.1.0 → 4.2.1

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/dist/lint.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { parseArgs } from "node:util";
3
3
  import node_fs from "node:fs";
4
4
  import node_path from "node:path";
5
- import { ConfigFile, canDependOn, ProjectRoot, findWiredModules, compilerOption, wiredDependencyNames } from "./533.js";
5
+ import { defaultDependencyRules, fileModuleKind, canDependOn, moduleKindOf, findWiredModules, configuredDependencyRules, ConfigFile, ProjectRoot, compilerOption, wiredDependencyNames } from "./201.js";
6
6
  const readAliases = (projectRoot)=>{
7
7
  const tsconfig = node_path.join(projectRoot, 'tsconfig.json');
8
8
  const paths = compilerOption(tsconfig, 'paths');
@@ -67,12 +67,9 @@ const layerImportRules = {
67
67
  rule: 'presentation imports infrastructure (only wiring knows concrete classes):'
68
68
  }
69
69
  };
70
- const isKindFile = (segments, kind)=>Boolean(segments && [
71
- 'application',
72
- 'infrastructure',
73
- 'wiring'
74
- ].includes(segments[0]) && segments[1] === kind);
75
- const importViolations = (projectRoot, rootFolder)=>{
70
+ const baseName = (file)=>node_path.basename(file).replace(/\.[^.]+$/, '');
71
+ const isOwnContract = (file, target)=>baseName(file).endsWith(`-${baseName(target)}`);
72
+ const importViolations = (projectRoot, rootFolder, rules)=>{
76
73
  const root = node_path.resolve(projectRoot, rootFolder);
77
74
  const contextsFolder = node_path.join(root, 'bounded-contexts');
78
75
  const sharedFolder = node_path.join(root, 'shared');
@@ -120,7 +117,8 @@ const importViolations = (projectRoot, rootFolder)=>{
120
117
  const source = node_fs.readFileSync(file, 'utf8');
121
118
  const from = locate(file);
122
119
  const ownContext = inside(contextsFolder, file)?.[0];
123
- const report = (rule, imported)=>violations.push({
120
+ const report = (check, rule, imported)=>violations.push({
121
+ check,
124
122
  rule,
125
123
  file,
126
124
  line: imported.line,
@@ -132,10 +130,10 @@ const importViolations = (projectRoot, rootFolder)=>{
132
130
  const to = locate(target);
133
131
  const targetContext = inside(contextsFolder, target)?.[0];
134
132
  if (ownContext) {
135
- if (targetContext && targetContext !== ownContext) report(`[${ownContext}] imports another context:`, imported);
133
+ if (targetContext && targetContext !== ownContext) report('context-isolation', `[${ownContext}] imports another context:`, imported);
136
134
  } else if (inside(sharedFolder, file)) {
137
135
  const allowed = !to || 'shared' === to.owner || 'domain' === to.segments[0] && 'errors' === to.segments[1] || file === inMemoryDbFile && isDomainModel(to.segments, target);
138
- if (!allowed) report('[shared] imports a bounded context outside its domain/errors (and domain models for the in-memory DB):', imported);
136
+ if (!allowed) report('shared-layer', '[shared] imports a bounded context outside its domain/errors (and domain models for the in-memory DB):', imported);
139
137
  } else if (inside(uiKitFolder, file) || inside(hooksFolder, file)) {
140
138
  const [area] = inside(reactFolder, target) ?? [];
141
139
  const forbidden = inside(uiKitFolder, file) ? [
@@ -146,20 +144,26 @@ const importViolations = (projectRoot, rootFolder)=>{
146
144
  'widgets',
147
145
  'pages'
148
146
  ];
149
- if (targetContext || forbidden.includes(area)) report(inside(uiKitFolder, file) ? '[presentation/react/ui-kit] imports a bounded context, widget or page:' : '[presentation/react/hooks] a shared hook imports a bounded context, UI-kit, widget or page:', imported);
150
- } else if (targetContext && !(imported.typeOnly && to?.segments[0] === 'presentation' && 'rest' === to.segments[1])) report('[presentation/react] imports a context other than `import type` from presentation/rest:', imported);
147
+ if (targetContext || forbidden.includes(area)) report('react', inside(uiKitFolder, file) ? '[presentation/react/ui-kit] imports a bounded context, widget or page:' : '[presentation/react/hooks] a shared hook imports a bounded context, UI-kit, widget or page:', imported);
148
+ } else if (targetContext && !(imported.typeOnly && to?.segments[0] === 'presentation' && 'rest' === to.segments[1])) report('react', '[presentation/react] imports a context other than `import type` from presentation/rest:', imported);
151
149
  const ownWidget = widgetOf(file);
152
150
  const targetWidget = widgetOf(target);
153
- if (ownWidget && targetWidget && targetWidget !== ownWidget) report('[presentation/react/widgets] a widget imports another widget:', imported);
151
+ if (ownWidget && targetWidget && targetWidget !== ownWidget) report('react', '[presentation/react/widgets] a widget imports another widget:', imported);
154
152
  if (!from || !to) continue;
155
- if (to.owner === from.owner && isKindFile(from.segments, 'queries') && isKindFile(to.segments, 'commands')) report(`[${from.owner}] a query imports a command (queries only read):`, imported);
153
+ if (isSpec(file)) continue;
154
+ const fromKind = fileModuleKind(from.segments);
155
+ const toKind = fileModuleKind(to.segments);
156
+ if (fromKind && toKind) {
157
+ if (!rules[fromKind].has(toKind) && !(fromKind === toKind && isOwnContract(file, target))) report('dependencies', `[${from.owner}] ${fromKind} may not use ${toKind} (dependency rules):`, imported);
158
+ if ('infrastructure' !== to.segments[0]) continue;
159
+ }
156
160
  const layerRule = layerImportRules[from.segments[0]];
157
- if (layerRule && !isSpec(file) && !layerRule.allows(to.segments)) report(`[${from.owner}] ${layerRule.rule}`, imported);
161
+ if (layerRule && !layerRule.allows(to.segments)) report('layers', `[${from.owner}] ${layerRule.rule}`, imported);
158
162
  }
159
163
  }
160
164
  return violations;
161
165
  };
162
- const wiringViolations = (projectRoot, rootFolder)=>{
166
+ const wiringViolations = (projectRoot, rootFolder, rules)=>{
163
167
  const root = node_path.resolve(projectRoot, rootFolder);
164
168
  const sharedFolder = node_path.join(root, 'shared');
165
169
  const contextsFolder = node_path.join(root, 'bounded-contexts');
@@ -197,13 +201,14 @@ const wiringViolations = (projectRoot, rootFolder)=>{
197
201
  const listStart = source.search(new RegExp(`wireClass\\(\\s*${implementation.className}\\b`));
198
202
  for (const dependency of dependencies){
199
203
  const candidate = visible.get(dependency);
200
- if (!candidate || canDependOn(consumer, candidate)) continue;
204
+ if (!candidate || canDependOn(consumer, candidate, rules)) continue;
201
205
  const index = source.indexOf(dependency, listStart);
202
206
  violations.push({
203
- rule: `[${name}] wiring: a dependency the CLI never offers (layer or kind rules):`,
207
+ check: 'dependencies',
208
+ rule: `[${name}] wiring: a dependency the dependency rules don't allow:`,
204
209
  file: consumer.wireFile,
205
210
  line: lineAt(source, index),
206
- text: `${implementation.className} ← ${candidate.typeName} (${candidate.kind})`
211
+ text: `${implementation.className} (${moduleKindOf(consumer) ?? consumer.kind}) ← ${candidate.typeName} (${moduleKindOf(candidate) ?? candidate.kind})`
207
212
  });
208
213
  }
209
214
  }
@@ -225,6 +230,7 @@ const clockViolations = (projectRoot, rootFolder)=>{
225
230
  return [
226
231
  ...source.matchAll(/\bnew\s+Date\s*\(\s*\)|\bDate\.now\s*\(/g)
227
232
  ].map((match)=>({
233
+ check: 'clock',
228
234
  rule: 'domain or application reads the current time directly (use the clock port):',
229
235
  file,
230
236
  line: lineAt(source, match.index),
@@ -232,11 +238,11 @@ const clockViolations = (projectRoot, rootFolder)=>{
232
238
  }));
233
239
  });
234
240
  };
235
- const lintProject = (projectRoot, rootFolder)=>[
236
- ...importViolations(projectRoot, rootFolder),
237
- ...wiringViolations(projectRoot, rootFolder),
241
+ const lintProject = (projectRoot, rootFolder, { rules = defaultDependencyRules, checks = {} } = {})=>[
242
+ ...importViolations(projectRoot, rootFolder, rules),
243
+ ...wiringViolations(projectRoot, rootFolder, rules),
238
244
  ...clockViolations(projectRoot, rootFolder)
239
- ];
245
+ ].filter((x)=>false !== checks[x.check]);
240
246
  const formatViolations = (violations, projectRoot)=>{
241
247
  const groups = new Map();
242
248
  for (const { rule, file, line, text } of violations)groups.set(rule, [
@@ -253,9 +259,10 @@ const formatViolations = (violations, projectRoot)=>{
253
259
  const help = `Usage: df-lint [rootFolder]
254
260
 
255
261
  Reports what breaks the Domain-First rules in the project:
256
- bounded context isolation, layers, wiring dependencies, React modules,
257
- queries using commands, and reading the time without the clock port.
258
- rootFolder defaults to the one in domain-first.project-structure.config.json.
262
+ bounded context isolation, layers, dependency rules (imports and wiring),
263
+ React modules, and reading the time without the clock port.
264
+ rootFolder defaults to the one in domain-first.project-structure.config.json,
265
+ whose optional \`rules\` change the dependency rules and turn checks off.
259
266
  Exits with 1 when something is found.
260
267
 
261
268
  Options:
@@ -275,8 +282,12 @@ if (values.help) {
275
282
  process.exit(0);
276
283
  }
277
284
  const lint_projectRoot = new ProjectRoot().path;
278
- const lint_rootFolder = positionals[0] ?? (ConfigFile.exists ? ConfigFile.Instance.data.rootFolder : 'src');
279
- const lint_violations = lintProject(lint_projectRoot, lint_rootFolder);
285
+ const config = ConfigFile.exists ? ConfigFile.Instance.data : void 0;
286
+ const lint_rootFolder = positionals[0] ?? config?.rootFolder ?? 'src';
287
+ const lint_violations = lintProject(lint_projectRoot, lint_rootFolder, {
288
+ rules: configuredDependencyRules(),
289
+ checks: config?.rules?.lint
290
+ });
280
291
  if (lint_violations.length) {
281
292
  console.log(formatViolations(lint_violations, lint_projectRoot));
282
293
  console.log(`\n${lint_violations.length} problem(s) found.`);
@@ -1,4 +1,10 @@
1
+ import type { LintCheck } from './config-file';
2
+ import { type DependencyRules } from './dependency-rules';
1
3
  export type Violation = {
4
+ /**
5
+ * The check that found it, which `rules.lint` can turn off.
6
+ */
7
+ check: LintCheck;
2
8
  /**
3
9
  * The broken rule, as printed above its violations.
4
10
  */
@@ -7,7 +13,14 @@ export type Violation = {
7
13
  line: number;
8
14
  text: string;
9
15
  };
10
- export declare const lintProject: (projectRoot: string, rootFolder: string) => Violation[];
16
+ export type LintOptions = {
17
+ rules?: DependencyRules;
18
+ /**
19
+ * Checks turned off with `false`; the others run.
20
+ */
21
+ checks?: Partial<Record<LintCheck, boolean>>;
22
+ };
23
+ export declare const lintProject: (projectRoot: string, rootFolder: string, { rules, checks }?: LintOptions) => Violation[];
11
24
  /**
12
25
  * Violations grouped under their rules, with paths from the project root.
13
26
  */
package/dist/wiring.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type DependencyRules } from './dependency-rules';
1
2
  export declare const layers: readonly ["domain", "application", "infrastructure", "presentation"];
2
3
  export type Layer = (typeof layers)[number];
3
4
  /**
@@ -43,6 +44,10 @@ export type WiredModule = {
43
44
  };
44
45
  export declare const readWiredModule: (wireFile: string, contextPath: string) => WiredModule | undefined;
45
46
  export declare const findWiredModules: (contextPath: string) => WiredModule[];
47
+ /**
48
+ * The kind a module has in the dependency rules.
49
+ */
50
+ export declare const moduleKindOf: (module: WiredModule) => "repositories" | "domain-services" | "application-ports" | "application-services" | "use-cases" | "execution-commands" | "execution-queries" | "orchestration-commands" | "orchestration-queries" | "infrastructure-services" | "presentation-services" | undefined;
46
51
  /**
47
52
  * The implementation label of a branched wire's class, taken from its
48
53
  * folder: `infrastructure/repositories/prisma/…` → `prisma`.
@@ -53,13 +58,13 @@ export declare const implementationType: (consumer: WiredModule, implementation:
53
58
  * as whole words: `in-memory-db-infrastructure-service` for `in-memory`.
54
59
  */
55
60
  export declare const isSuggestedFor: (candidate: WiredModule, implementation: string) => boolean;
56
- export declare const canDependOn: (consumer: WiredModule, candidate: WiredModule) => boolean;
61
+ export declare const canDependOn: (consumer: WiredModule, candidate: WiredModule, rules?: DependencyRules) => boolean;
57
62
  /**
58
- * What an implementation of the consumer can depend on: modules of the
59
- * visible layers, except the consumer and what this implementation
60
- * already depends on.
63
+ * What an implementation of the consumer can depend on by the project's
64
+ * rules, except the consumer and what this implementation already
65
+ * depends on.
61
66
  */
62
- export declare const availableDependencies: (consumer: WiredModule, implementation: WiredClass, candidates: WiredModule[]) => WiredModule[];
67
+ export declare const availableDependencies: (consumer: WiredModule, implementation: WiredClass, candidates: WiredModule[], rules?: DependencyRules) => WiredModule[];
63
68
  /**
64
69
  * Import path without extension, always starting with `./` or `../`.
65
70
  */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@domain-first/project-structure",
3
3
  "description": "Build and manage your Domain-First project structure with CLI",
4
- "version": "4.1.0",
4
+ "version": "4.2.1",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -15,6 +15,7 @@ Generated files contain placeholders: empty classes, `{}` schemas, `[]` dependen
15
15
  - Constructors take abstractions (`OrderRepository`, abstract `PlaceOrderCommand`, port `PaymentGateway`), never `PrismaOrderRepository`.
16
16
  - Implementation order: domain → application → schema tool runs (migrations, only if infrastructure needs data the database lacks) → infrastructure (repositories, execution commands/queries, adapters) → endpoints → other tool runs (OpenAPI, API client) → React. Widgets need the regenerated client. How to run tools and handle their output: the project's scripts skill (`project-scripts`), if there is one.
17
17
  - Run the project's tsc/lint/tests after each component.
18
+ - What each kind of module may use follows the defaults in these skills unless `rules.dependencies` in the config changes them; then follow the config, in imports as well as in wiring.
18
19
 
19
20
  ## Bounded context isolation
20
21
 
@@ -38,12 +39,11 @@ Run it from the project root; `rootFolder` defaults to the config's. It resolves
38
39
 
39
40
  - imports across contexts, and from `shared/` or React outside the exceptions above;
40
41
  - imports against the layers ("Ground rules"; specs excluded);
42
+ - module files importing kinds the project's dependency rules don't allow (a use case importing a use case, a query importing a command, …), and wired dependencies they don't allow ("Wiring" below, `df-ps-scaffold` rule 3); an implementation importing its own contract is fine;
41
43
  - a widget importing another widget (a widget = the nearest folder under `presentation/react/widgets/` with a `*-widget.tsx`, nested widgets included), UI-kit importing widgets, pages or contexts, shared hooks importing UI-kit, widgets, pages or contexts;
42
- - a query importing a command of its context (`application/`, `infrastructure/` or `wiring/` `queries/` → `commands/`);
43
- - wired dependencies the CLI would never offer ("Wiring" below, `df-ps-scaffold` rule 3);
44
44
  - `new Date()` / `Date.now()` in domain or application (use the `clock` port).
45
45
 
46
- It exits with 1 when anything is found.
46
+ It exits with 1 when anything is found. Checks turned off in the config (`rules.lint`) aren't reported; don't turn checks off yourself.
47
47
 
48
48
  ## Domain
49
49
 
@@ -86,7 +86,7 @@ export const wirePlaceOrderUseCase = wireClass(PlaceOrderUseCase, [wireOrderRepo
86
86
 
87
87
  ## REST endpoints ({handlers-rest})
88
88
 
89
- 1. Generator: initialization creates `RestEndpointGeneratorPresentationService` in `<rootFolder>/shared/presentation/services/`; every endpoint uses it. Set the module-level `const adapter` above the class (`undefined` until set) to the HTTP framework's adapter; the class reads it through closure. If initialization connected the Next adapter, the file already imports `nextAdapter` from `@domain-first/handlers-next` and passes it instead; just make sure that package is installed. The default `400` mapping lives in the private `defaultClientRequestErrors` getter (`ErrorMapping[]`); extend it with `errors: [httpError(MyError, 404), ...this.defaultClientRequestErrors]`. Map domain errors to statuses in the generator's `errors` with `httpError(ErrorClass, status, { description, message, details: { schema, map } })` (one class) or `httpStatus(status, { code, match })` (many errors, one code); the first match wins, so put specific mappings first, importing them from the contexts' `domain/errors` (the only thing `shared/` may import from a context, besides domain models in the in-memory DB). A new kind of endpoint (auth, other context) is a new getter returning `createEndpoint({ context, errors })(adapter) as EndpointGenerator` (`nextAdapter` with the Next adapter), next to `withoutGuards`. Generate the exposed handler before the endpoint: with wire, the `Handler:` pick fills its type and the wire (`[wireRestEndpointGeneratorPresentationService, wireGetRecentOrdersUseCase]`).
89
+ 1. Generator: initialization creates `RestEndpointGeneratorPresentationService` in `<rootFolder>/shared/presentation/services/`; every endpoint uses it. Set the module-level `const adapter` above the class (`undefined` until set) to the HTTP framework's adapter; the class reads it through closure. If initialization connected the Next adapter, the file already imports `nextAdapter` from `@domain-first/handlers-next` and passes it instead; just make sure that package is installed. Invalid requests (`400`) are answered by `invalidRequest()` of `@domain-first/handlers-rest` in `errors`; don't map `RequestParsingError` / `InputMappingError` by hand, add your own mappings next to it: `errors: [httpError(MyError, 404), invalidRequest()]`. Map domain errors to statuses in the generator's `errors` with `httpError(ErrorClass, status, { description, message, details: { schema, map } })` (one class) or `httpStatus(status, { code, match })` (many errors, one code); the first match wins, so put specific mappings first, importing them from the contexts' `domain/errors` (the only thing `shared/` may import from a context, besides domain models in the in-memory DB). A new kind of endpoint (auth, other context) is a new getter returning `createEndpoint({ context, errors: [..., invalidRequest()] })(adapter) as EndpointGenerator` (`nextAdapter` with the Next adapter), next to `withoutGuards`. Generate the exposed handler before the endpoint: with wire, the `Handler:` pick fills its type and the wire (`[wireRestEndpointGeneratorPresentationService, wireGetRecentOrdersUseCase]`).
90
90
  2. If `handler: never` is left (no handler existed at generation), re-run the endpoint generator as an approved overwrite to pick it (rule 3); don't replace it by hand.
91
91
  3. Complete `get handle()`: the generated `this.endpointGenerator(...)` doesn't compile on purpose. Pick the generating getter that fits the endpoint (`this.endpointGenerator.withoutGuards(...)`, or one with the needed guards), then `.input(...)`, `.mapInput(...)`, optional `.output(...)`, `.mapOutput(...)`.
92
92
  4. Register `restHandlers` from `<rootFolder>/presentation/rest/index.ts` in the server bootstrap (rule 2, exception 5).
@@ -9,7 +9,7 @@ description: Generate Domain-First components with the `df-ps` CLI (@domain-firs
9
9
 
10
10
  Follow this order for every request:
11
11
 
12
- 1. Read `domain-first.project-structure.config.json` (beside the nearest `package.json`). If missing, stop and tell the user to initialize the project with `npx df-ps` first.
12
+ 1. Read `domain-first.project-structure.config.json` (beside the nearest `package.json`). If missing, stop and tell the user to initialize the project with `npx df-ps` first. Its optional `rules.dependencies` changes what each kind of module may depend on; where it differs from the defaults in these skills, the config wins.
13
13
  2. Feature request without named contexts/components → `df-ps-plan-feature` (it covers steps 3–5).
14
14
  3. Choose a component for each piece of logic with `references/choosing-components.md`.
15
15
  4. Prepare the run details ("Preparing runs" below).
@@ -82,7 +82,7 @@ Moving or renaming a page or widget is a df-ps run too (`Move or rename page` /
82
82
  With `@domain-first/wire`, every new dependency of a wired class (a constructor parameter plus its wire) is added by `df-ps`: the generator's `Dependencies:` step for a new module, `Wire dependency` for an existing one, and the `Handler:` pick for an endpoint (its generator is added automatically). Don't add constructor parameters or wire entries by hand, and don't reorder or remove the ones `df-ps` added.
83
83
 
84
84
  - List each module's dependencies in the plan as run options (`deps: OrderRepository`), with a `Wire dependency` run for existing modules.
85
- - A dependency the CLI doesn't offer is forbidden by the wiring rules (layer, kind, or another context): change the design (a port, an execution query or command, an infrastructure service) instead of adding it by hand.
85
+ - A dependency the CLI doesn't offer is forbidden by the project's dependency rules (the defaults, changed by `rules.dependencies` in the config) or by context isolation: change the design (a port, an execution query or command, an infrastructure service) instead of adding it by hand.
86
86
  - A value that isn't a wired module (a database or SDK client, a config value) lives in an infrastructure service named after the implementation label (`prisma`, `in-memory-db`, `stripe`): the service creates or reads it itself (`readonly client = new PrismaClient()`), with no constructor parameter for it. Implementations get the service through `df-ps`, where it shows up under `Suggested`. Wrap the service's wire in `memoWire(...)` when one instance must be shared (a connection pool, an in-memory store). No `wireValue(...)`. A domain or application module never gets such a value directly: it depends on a port whose adapter uses the service.
87
87
  - An endpoint generated with `handler: never` gets its handler by re-running the endpoint generator once the handler exists, as an approved overwrite.
88
88
 
@@ -1,6 +1,6 @@
1
1
  # Choosing the component for a piece of logic
2
2
 
3
- The only place where these rules live.
3
+ The only place where these rules live. What each kind of module may depend on is the default; `rules.dependencies` in the project's config can change it (e.g. let use cases call each other), and then the config wins.
4
4
 
5
5
  Split the request into pieces of logic (one responsibility each). For each piece, go through the steps **in order**: the first "yes" decides. A name the user used ("service", "gateway") is not a decision.
6
6
 
@@ -21,7 +21,7 @@ Split the request into pieces of logic (one responsibility each). For each piece
21
21
  | 11 | One read/write on this context's own storage that isn't "load/save one aggregate" (read model, report, bulk update)? | **Execution command** (write) / **query** (read) |
22
22
  | 12 | A reusable read/write composed of other commands/queries? | **Orchestrator command** (execution commands and queries) / **query** (execution queries and repositories only, calling only their reading methods) |
23
23
  | 13 | A rule at the junction of several entities / value objects not all belonging to one aggregate (a discount from purchase history and the current discount), no I/O? | **Domain service**, always |
24
- | 14 | Application logic reused by 2+ use cases, with any external interaction delegated to injected ports? | **Application service** |
24
+ | 14 | Application logic reused by 2+ use cases, with any external interaction or storage access delegated to injected ports, commands or queries? | **Application service** |
25
25
  | 15 | A technical helper used only by infrastructure code? | **Infrastructure service** |
26
26
  | 16 | A helper used only by presentation code? | **Presentation service** |
27
27
  | — | None of the above | A method or function in an existing file |
@@ -36,7 +36,7 @@ Split the request into pieces of logic (one responsibility each). For each piece
36
36
  ## Port or service?
37
37
 
38
38
  - A **port** describes a capability at the boundary: an external system or time. Its adapter performs the actual interaction. Own storage still follows the repository / execution command / query rules above. Another context is not a port: it's an execution query/command (step 9).
39
- - An **application service** contains reusable application logic and may call injected ports. It does not call external SDKs, HTTP clients, or another context directly. A domain service remains pure: no I/O, ports, or repositories.
39
+ - An **application service** contains reusable application logic and may call injected ports, commands and queries. It does not call external SDKs, HTTP clients, or another context directly. A domain service remains pure: no I/O, ports, or repositories.
40
40
  - Wanting to mock a class or imagining multiple implementations is not enough to make it a port. Identify the boundary capability first. Ports get swappable adapters and a test implementation under `NODE_ENV=test`; test a service's logic with fake dependencies.
41
41
 
42
42
  Example: `order-confirmation` prepares a message and calls the injected `mailer` port. It stays an application service; the mailer adapter calls the email provider. Tests use a fake mailer and exercise the real service.
@@ -52,6 +52,7 @@ Example: `order-confirmation` prepares a message and calls the injected `mailer`
52
52
  | Domain / application service | Stated without requests, permissions, responses, scenarios → domain. Otherwise application. |
53
53
  | Use case / application service | Use case = one action with `handle`. Application service = helper used by use cases. |
54
54
  | Use case / orchestrator | Use case = action exposed outside. Orchestrator = reusable operation called by use cases. |
55
+ | Orchestrator / application service | Only composes commands/queries into one reusable storage operation → orchestrator. Also needs ports or application logic beyond that composition → application service (it may call commands and queries, orchestrators included). |
55
56
  | Application / infrastructure service | Used by use cases → application. Only by adapters/repositories → infrastructure. |
56
57
  | Logic infrastructure needs from an application service | Infrastructure never sees application services. Pure logic without ports → domain service. Logic over ports → infrastructure calls the ports directly. Technical (mapping, retries, external API formats) → infrastructure service. |
57
58
  | Clock | Always a port (`clock`, usually in Shared Layer). |
@@ -6,7 +6,7 @@ Every step list starts with `"pick:Bounded Context: <ctx>"` or `"pick:Shared Lay
6
6
 
7
7
  Any generator: if the run would replace existing files, the last prompt is the confirm `Overwrite them?` (the files are listed above it). Without it, nothing extra is asked. Added lines (barrels, errors, wiring indexes) never trigger it.
8
8
 
9
- {wire} Generators that create a wire (all below except endpoints, which ask their own two selects) then ask the checkbox `Dependencies:`, before `Overwrite them?`. It lists wired modules of `<C>` and of the Shared Layer (`(shared)` suffix), grouped under headers in this order: Repositories, Domain services, Ports, Application services, Queries, Commands, Use cases, Infrastructure services, Presentation services. Inside a group: by type name, `<C>` first. Headers are not counted: `toggle:<n,..>` numbers only modules, top to bottom. Answer `toggle:<n,..>` or `none`. It is skipped when nothing fits, so check `<C>/wiring/` and `<rootFolder>/shared/wiring/` before counting steps. What fits depends on the layer of the class the wire builds: domain → domain; application → domain, application; infrastructure (repository, execution command/query, and port implementations, infrastructure services) → domain, application ports (of `<C>` and the Shared Layer; no other application modules), infrastructure; presentation → application, presentation. On top of that, application services see only ports from application, use cases never see use cases, repository implementations never see repositories, execution command/query implementations never see commands or queries, orchestration commands see only execution commands and queries from application, and orchestration queries only execution queries (repositories from domain stay available; they call only reading methods). Endpoints are never listed. Each chosen module goes into the wire (`wireClass(X, [wireUserRepository])`) and the constructor (`private readonly userRepository: UserRepository`, with `import type`), in the same order. An env-branched wire (repository, execution command/query, port) wires each implementation in isolation: instead of `Dependencies:` it asks `Dependencies for <Implementation>:` once per implementation, in the order of the wire (main, then test). Each list leaves out only what that implementation already has, and a list with nothing to choose is skipped. It may start with a `Suggested` group: infrastructure modules whose file name has the implementation label (its folder, e.g. `prisma`, `in-memory`) as whole words, such as `in-memory-db-infrastructure-service` for `in-memory`. They are listed there only, so numbering starts with them, and they are **checked**: `none` keeps them, `toggle:<n>` on one of them unchecks it.
9
+ {wire} Generators that create a wire (all below except endpoints, which ask their own two selects) then ask the checkbox `Dependencies:`, before `Overwrite them?`. It lists wired modules of `<C>` and of the Shared Layer (`(shared)` suffix), grouped under headers in this order: Repositories, Domain services, Ports, Application services, Queries, Commands, Use cases, Infrastructure services, Presentation services. Inside a group: by type name, `<C>` first. Headers are not counted: `toggle:<n,..>` numbers only modules, top to bottom. Answer `toggle:<n,..>` or `none`. It is skipped when nothing fits, so check `<C>/wiring/` and `<rootFolder>/shared/wiring/` before counting steps. What fits depends on the layer of the class the wire builds: domain → domain; application → domain, application; infrastructure (repository, execution command/query, and port implementations, infrastructure services) → domain, application ports (of `<C>` and the Shared Layer; no other application modules), infrastructure; presentation → application, presentation. On top of that, application services see only ports, commands and queries from application, use cases never see use cases, repository implementations never see repositories, execution command/query implementations never see commands or queries, orchestration commands see only execution commands and queries from application, and orchestration queries only execution queries (repositories from domain stay available; they call only reading methods). These are the defaults: `rules.dependencies` in the config changes them per kind (`use-cases`, `orchestration-queries`, …), so count items from what the project's rules allow. Endpoints are never listed. Each chosen module goes into the wire (`wireClass(X, [wireUserRepository])`) and the constructor (`private readonly userRepository: UserRepository`, with `import type`), in the same order. An env-branched wire (repository, execution command/query, port) wires each implementation in isolation: instead of `Dependencies:` it asks `Dependencies for <Implementation>:` once per implementation, in the order of the wire (main, then test). Each list leaves out only what that implementation already has, and a list with nothing to choose is skipped. It may start with a `Suggested` group: infrastructure modules whose file name has the implementation label (its folder, e.g. `prisma`, `in-memory`) as whole words, such as `in-memory-db-infrastructure-service` for `in-memory`. They are listed there only, so numbering starts with them, and they are **checked**: `none` keeps them, `toggle:<n>` on one of them unchecks it.
10
10
 
11
11
  ## Bounded context
12
12