@domain-first/project-structure 4.0.0 → 4.1.0

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.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/lint.js ADDED
@@ -0,0 +1,285 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from "node:util";
3
+ import node_fs from "node:fs";
4
+ import node_path from "node:path";
5
+ import { ConfigFile, canDependOn, ProjectRoot, findWiredModules, compilerOption, wiredDependencyNames } from "./533.js";
6
+ const readAliases = (projectRoot)=>{
7
+ const tsconfig = node_path.join(projectRoot, 'tsconfig.json');
8
+ const paths = compilerOption(tsconfig, 'paths');
9
+ if (!paths || 'object' != typeof paths) return [];
10
+ const baseUrl = compilerOption(tsconfig, 'baseUrl');
11
+ const base = node_path.resolve(projectRoot, 'string' == typeof baseUrl ? baseUrl : '.');
12
+ return Object.entries(paths).filter(([, targets])=>targets.length).map(([key, [target]])=>{
13
+ const wildcard = key.endsWith('*');
14
+ return {
15
+ prefix: wildcard ? key.slice(0, -1) : key,
16
+ wildcard,
17
+ target: node_path.resolve(base, wildcard ? target.replace(/\*$/, '') : target)
18
+ };
19
+ }).sort((a, b)=>b.prefix.length - a.prefix.length);
20
+ };
21
+ const resolveSpecifier = (specifier, fromFile, aliases)=>{
22
+ if (specifier.startsWith('.')) return node_path.resolve(node_path.dirname(fromFile), specifier);
23
+ for (const { prefix, wildcard, target } of aliases)if (wildcard ? specifier.startsWith(prefix) : specifier === prefix) return node_path.join(target, wildcard ? specifier.slice(prefix.length) : '');
24
+ };
25
+ const inside = (folder, file)=>{
26
+ const relativePath = node_path.relative(folder, file);
27
+ return !relativePath || relativePath.startsWith('..') || node_path.isAbsolute(relativePath) ? void 0 : relativePath.split(node_path.sep);
28
+ };
29
+ const sourceFiles = (folder)=>{
30
+ if (!node_fs.existsSync(folder)) return [];
31
+ return node_fs.readdirSync(folder, {
32
+ withFileTypes: true
33
+ }).flatMap((entry)=>{
34
+ const entryPath = node_path.join(folder, entry.name);
35
+ if (entry.isDirectory()) return 'node_modules' === entry.name ? [] : sourceFiles(entryPath);
36
+ return /\.(c|m)?tsx?$/.test(entry.name) && !entry.name.endsWith('.d.ts') ? [
37
+ entryPath
38
+ ] : [];
39
+ });
40
+ };
41
+ const importPattern = /\b(?:(import|export)\s+(type\s+)?(?:(?!\b(?:import|export)\b)[\w*{}\s,$])*?\s*from\s*|import\s*\(\s*|require\s*\(\s*|import\s*)(['"])([^'"\n]+)\3/g;
42
+ const lineAt = (source, index)=>source.slice(0, index).split('\n').length;
43
+ const importsOf = (source, file, aliases)=>[
44
+ ...source.matchAll(importPattern)
45
+ ].map((match)=>({
46
+ typeOnly: 'import' === match[1] && Boolean(match[2]),
47
+ target: resolveSpecifier(match[4], file, aliases),
48
+ line: lineAt(source, match.index),
49
+ statement: match[0].replace(/\s+/g, ' ')
50
+ }));
51
+ const isSpec = (file)=>/\.(spec|test)\.(c|m)?tsx?$/.test(file);
52
+ const layerImportRules = {
53
+ domain: {
54
+ allows: ([layer])=>'domain' === layer,
55
+ rule: 'domain imports outside the domain layer:'
56
+ },
57
+ application: {
58
+ allows: ([layer])=>'domain' === layer || 'application' === layer,
59
+ rule: 'application imports outside domain and application:'
60
+ },
61
+ infrastructure: {
62
+ allows: ([layer, part, mode])=>'domain' === layer || 'infrastructure' === layer || 'application' === layer && ('ports' === part || ('commands' === part || 'queries' === part) && 'execution' === mode),
63
+ rule: 'infrastructure imports outside domain, infrastructure, application ports and execution contracts:'
64
+ },
65
+ presentation: {
66
+ allows: ([layer])=>'infrastructure' !== layer,
67
+ rule: 'presentation imports infrastructure (only wiring knows concrete classes):'
68
+ }
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)=>{
76
+ const root = node_path.resolve(projectRoot, rootFolder);
77
+ const contextsFolder = node_path.join(root, 'bounded-contexts');
78
+ const sharedFolder = node_path.join(root, 'shared');
79
+ const reactFolder = node_path.join(root, 'presentation', 'react');
80
+ const uiKitFolder = node_path.join(reactFolder, 'ui-kit');
81
+ const widgetsFolder = node_path.join(reactFolder, 'widgets');
82
+ const hooksFolder = node_path.join(reactFolder, 'hooks');
83
+ const inMemoryDbFile = node_path.join(sharedFolder, 'infrastructure', 'services', 'in-memory-db-infrastructure-service.ts');
84
+ const aliases = readAliases(projectRoot);
85
+ const violations = [];
86
+ const locate = (file)=>{
87
+ const inContext = inside(contextsFolder, file);
88
+ if (inContext && inContext.length > 1) {
89
+ const [owner, ...segments] = inContext;
90
+ return {
91
+ owner,
92
+ segments
93
+ };
94
+ }
95
+ const inShared = inside(sharedFolder, file);
96
+ return inShared && {
97
+ owner: 'shared',
98
+ segments: inShared
99
+ };
100
+ };
101
+ const isDomainModel = ([layer, part], target)=>'domain' === layer && [
102
+ 'aggregates',
103
+ 'entities',
104
+ 'value-objects'
105
+ ].includes(part) && !/-repository(\.tsx?)?$/.test(node_path.basename(target));
106
+ const widgetFolders = new Map();
107
+ const isWidgetFolder = (folder)=>{
108
+ if (!widgetFolders.has(folder)) widgetFolders.set(folder, node_fs.existsSync(folder) && node_fs.statSync(folder).isDirectory() && node_fs.readdirSync(folder).some((name)=>name.endsWith('-widget.tsx')));
109
+ return widgetFolders.get(folder);
110
+ };
111
+ const widgetOf = (file)=>{
112
+ for(let folder = file; inside(widgetsFolder, folder); folder = node_path.dirname(folder))if (isWidgetFolder(folder)) return folder;
113
+ };
114
+ const files = [
115
+ contextsFolder,
116
+ sharedFolder,
117
+ reactFolder
118
+ ].flatMap(sourceFiles);
119
+ for (const file of files){
120
+ const source = node_fs.readFileSync(file, 'utf8');
121
+ const from = locate(file);
122
+ const ownContext = inside(contextsFolder, file)?.[0];
123
+ const report = (rule, imported)=>violations.push({
124
+ rule,
125
+ file,
126
+ line: imported.line,
127
+ text: imported.statement
128
+ });
129
+ for (const imported of importsOf(source, file, aliases)){
130
+ const target = imported.target;
131
+ if (!target) continue;
132
+ const to = locate(target);
133
+ const targetContext = inside(contextsFolder, target)?.[0];
134
+ if (ownContext) {
135
+ if (targetContext && targetContext !== ownContext) report(`[${ownContext}] imports another context:`, imported);
136
+ } else if (inside(sharedFolder, file)) {
137
+ 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);
139
+ } else if (inside(uiKitFolder, file) || inside(hooksFolder, file)) {
140
+ const [area] = inside(reactFolder, target) ?? [];
141
+ const forbidden = inside(uiKitFolder, file) ? [
142
+ 'widgets',
143
+ 'pages'
144
+ ] : [
145
+ 'ui-kit',
146
+ 'widgets',
147
+ 'pages'
148
+ ];
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);
151
+ const ownWidget = widgetOf(file);
152
+ const targetWidget = widgetOf(target);
153
+ if (ownWidget && targetWidget && targetWidget !== ownWidget) report('[presentation/react/widgets] a widget imports another widget:', imported);
154
+ 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);
156
+ const layerRule = layerImportRules[from.segments[0]];
157
+ if (layerRule && !isSpec(file) && !layerRule.allows(to.segments)) report(`[${from.owner}] ${layerRule.rule}`, imported);
158
+ }
159
+ }
160
+ return violations;
161
+ };
162
+ const wiringViolations = (projectRoot, rootFolder)=>{
163
+ const root = node_path.resolve(projectRoot, rootFolder);
164
+ const sharedFolder = node_path.join(root, 'shared');
165
+ const contextsFolder = node_path.join(root, 'bounded-contexts');
166
+ const sharedModules = findWiredModules(sharedFolder);
167
+ const owners = [
168
+ {
169
+ name: 'shared',
170
+ modules: sharedModules
171
+ },
172
+ ...node_fs.existsSync(contextsFolder) ? node_fs.readdirSync(contextsFolder, {
173
+ withFileTypes: true
174
+ }).filter((entry)=>entry.isDirectory()).map((entry)=>({
175
+ name: entry.name,
176
+ modules: findWiredModules(node_path.join(contextsFolder, entry.name))
177
+ })) : []
178
+ ];
179
+ const violations = [];
180
+ for (const { name, modules } of owners){
181
+ const visible = new Map([
182
+ ...sharedModules,
183
+ ...modules
184
+ ].map((x)=>[
185
+ x.wireName,
186
+ x
187
+ ]));
188
+ for (const consumer of modules){
189
+ const source = node_fs.readFileSync(consumer.wireFile, 'utf8');
190
+ for (const implementation of consumer.implementations){
191
+ let dependencies;
192
+ try {
193
+ dependencies = wiredDependencyNames(source, implementation.className);
194
+ } catch {
195
+ continue;
196
+ }
197
+ const listStart = source.search(new RegExp(`wireClass\\(\\s*${implementation.className}\\b`));
198
+ for (const dependency of dependencies){
199
+ const candidate = visible.get(dependency);
200
+ if (!candidate || canDependOn(consumer, candidate)) continue;
201
+ const index = source.indexOf(dependency, listStart);
202
+ violations.push({
203
+ rule: `[${name}] wiring: a dependency the CLI never offers (layer or kind rules):`,
204
+ file: consumer.wireFile,
205
+ line: lineAt(source, index),
206
+ text: `${implementation.className} ← ${candidate.typeName} (${candidate.kind})`
207
+ });
208
+ }
209
+ }
210
+ }
211
+ }
212
+ return violations;
213
+ };
214
+ const clockViolations = (projectRoot, rootFolder)=>{
215
+ const root = node_path.resolve(projectRoot, rootFolder);
216
+ const folders = [
217
+ node_path.join(root, 'shared'),
218
+ ...node_fs.existsSync(node_path.join(root, 'bounded-contexts')) ? node_fs.readdirSync(node_path.join(root, 'bounded-contexts')).map((name)=>node_path.join(root, 'bounded-contexts', name)) : []
219
+ ].flatMap((folder)=>[
220
+ node_path.join(folder, 'domain'),
221
+ node_path.join(folder, 'application')
222
+ ]);
223
+ return folders.flatMap(sourceFiles).filter((file)=>!isSpec(file)).flatMap((file)=>{
224
+ const source = node_fs.readFileSync(file, 'utf8');
225
+ return [
226
+ ...source.matchAll(/\bnew\s+Date\s*\(\s*\)|\bDate\.now\s*\(/g)
227
+ ].map((match)=>({
228
+ rule: 'domain or application reads the current time directly (use the clock port):',
229
+ file,
230
+ line: lineAt(source, match.index),
231
+ text: match[0]
232
+ }));
233
+ });
234
+ };
235
+ const lintProject = (projectRoot, rootFolder)=>[
236
+ ...importViolations(projectRoot, rootFolder),
237
+ ...wiringViolations(projectRoot, rootFolder),
238
+ ...clockViolations(projectRoot, rootFolder)
239
+ ];
240
+ const formatViolations = (violations, projectRoot)=>{
241
+ const groups = new Map();
242
+ for (const { rule, file, line, text } of violations)groups.set(rule, [
243
+ ...groups.get(rule) ?? [],
244
+ ` ${node_path.relative(projectRoot, file)}:${line}: ${text}`
245
+ ]);
246
+ return [
247
+ ...groups
248
+ ].map(([rule, lines])=>[
249
+ rule,
250
+ ...lines
251
+ ].join('\n')).join('\n\n');
252
+ };
253
+ const help = `Usage: df-lint [rootFolder]
254
+
255
+ 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.
259
+ Exits with 1 when something is found.
260
+
261
+ Options:
262
+ -h, --help show this help`;
263
+ const { values: values, positionals: positionals } = parseArgs({
264
+ allowPositionals: true,
265
+ options: {
266
+ help: {
267
+ type: 'boolean',
268
+ short: 'h',
269
+ default: false
270
+ }
271
+ }
272
+ });
273
+ if (values.help) {
274
+ console.log(help);
275
+ process.exit(0);
276
+ }
277
+ 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);
280
+ if (lint_violations.length) {
281
+ console.log(formatViolations(lint_violations, lint_projectRoot));
282
+ console.log(`\n${lint_violations.length} problem(s) found.`);
283
+ process.exit(1);
284
+ }
285
+ console.log('OK: no Domain-First rule violations.');
@@ -0,0 +1,14 @@
1
+ export type Violation = {
2
+ /**
3
+ * The broken rule, as printed above its violations.
4
+ */
5
+ rule: string;
6
+ file: string;
7
+ line: number;
8
+ text: string;
9
+ };
10
+ export declare const lintProject: (projectRoot: string, rootFolder: string) => Violation[];
11
+ /**
12
+ * Violations grouped under their rules, with paths from the project root.
13
+ */
14
+ export declare const formatViolations: (violations: Violation[], projectRoot: string) => string;
@@ -0,0 +1 @@
1
+ export {};
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.0.0",
4
+ "version": "4.1.0",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -17,7 +17,8 @@
17
17
  },
18
18
  "bin": {
19
19
  "df-ps": "./dist/index.js",
20
- "df-skills": "./bin/df-skills.mjs"
20
+ "df-skills": "./bin/df-skills.mjs",
21
+ "df-lint": "./dist/lint.js"
21
22
  },
22
23
  "main": "./dist/index.cjs",
23
24
  "homepage": "https://domain-first-landing.vercel.app/scaffolder/",
@@ -31,10 +31,19 @@ A file in context A imports **nothing** from context B: no types (`import type`
31
31
  Check before reporting done; fix every finding:
32
32
 
33
33
  ```bash
34
- node <this-skill-dir>/scripts/check-context-isolation.mjs [rootFolder]
34
+ npx df-lint [rootFolder]
35
35
  ```
36
36
 
37
- Run it from the project root; `rootFolder` defaults to the config's. It resolves relative paths and tsconfig `paths` aliases, and checks `import`/`export … from`, side-effect imports, `import()`, and `require()`. It also reports a widget importing another widget (a widget = the nearest folder under `presentation/react/widgets/` with a `*-widget.tsx`, nested widgets included).
37
+ Run it from the project root; `rootFolder` defaults to the config's. It resolves relative paths and tsconfig `paths` aliases, checks `import`/`export … from`, side-effect imports, `import()` and `require()`, and reports:
38
+
39
+ - imports across contexts, and from `shared/` or React outside the exceptions above;
40
+ - imports against the layers ("Ground rules"; specs excluded);
41
+ - 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
+ - `new Date()` / `Date.now()` in domain or application (use the `clock` port).
45
+
46
+ It exits with 1 when anything is found.
38
47
 
39
48
  ## Domain
40
49
 
@@ -58,7 +67,7 @@ export class Order extends domainType(
58
67
  ## Application
59
68
 
60
69
  - Use cases, commands, queries ({handlers}): the member is `handle = defineHandler({ inputSchema, outputSchema, handler })`. Replace the static `{}` schemas with real ones and write the logic in the `handler` callback; dependencies come through the constructor. Execution: the abstract contract holds the static schemas and `abstract handle`; each infrastructure implementation defines `handle` with the contract's schemas and writes only its `handler` callback. Orchestrator: a concrete class composing injected contracts. Call with `x.handle(input)` (returns a result) or `x.handle.unsafe(input)` (throws).
61
- - What a query or command may change: "Commonly confused" in `df-ps-scaffold/references/choosing-components.md`. Data a command returns goes in its output schema.
70
+ - A query only reads: it never changes data (not even idempotently) and never uses a command; an orchestrator query may use a repository, but calls only its reading methods (never `save`/`delete`); see "Commonly confused" in `df-ps-scaffold/references/choosing-components.md`. Data a command returns goes in its output schema.
62
71
  - Ports: abstract members in the port, one implementation per adapter (`api` real, `mock`/`fake` deterministic). Use the shared `clock` port instead of `new Date()`.
63
72
  - Services: what each kind may contain and call is in `choosing-components.md` (steps 13–16, "Port or service?"). Domain services take and return domain types. Application services have no `handle`.
64
73
 
@@ -16,7 +16,7 @@ Follow this order for every request:
16
16
  5. If the task creates files, show the work plan and **stop until it's approved** (rule 1).
17
17
  6. Run the generators in plan order with the driver; check each output.
18
18
  7. Implement with `df-ps-implement`, in its order: domain → application → schema tool runs (migrations) → infrastructure → endpoints → other tool runs (OpenAPI, API client) → React.
19
- 8. Run `df-ps-implement/scripts/check-context-isolation.mjs` and the project's tsc/lint/tests.
19
+ 8. Run `npx df-lint` and the project's tsc/lint/tests.
20
20
  9. Report against the plan.
21
21
 
22
22
  ## Mandatory rules
@@ -19,7 +19,7 @@ Split the request into pieces of logic (one responsibility each). For each piece
19
19
  | 9 | Data or behavior of **another context**? | **Execution query** (read) / **execution command** (write) in this context (see below) |
20
20
  | 10 | Leaves this context's code and storage: external system or time? | **Port** (+ adapters) |
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
- | 12 | A reusable read/write composed of other commands/queries/ports? | **Orchestrator command / query** |
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
24
  | 14 | Application logic reused by 2+ use cases, with any external interaction delegated to injected ports? | **Application service** |
25
25
  | 15 | A technical helper used only by infrastructure code? | **Infrastructure service** |
@@ -47,7 +47,7 @@ Example: `order-confirmation` prepares a message and calls the injected `mailer`
47
47
  | --- | --- |
48
48
  | Port / repository | Own aggregate's persistence → repository. External system → port. |
49
49
  | Port / execution command, query | Own storage or another context → command/query. External system → port. |
50
- | Query / command | A query reads; it may have side effects, but only idempotent ones: repeating it changes nothing further (filling a cache, creating default settings if missing). Any other state change → command. A command may return data (the created order, the new balance). |
50
+ | Query / command | A query only reads: it never changes any state, not even idempotently (no cache filling, no default settings created if missing), and never calls a command. Any state change → command. A command may return data (the created order, the new balance); an orchestrator command may also use execution queries. An orchestrator query may load aggregates through a repository, but never calls its writing methods (`save`, `delete`): the wiring can't forbid it, so it's on the developer. |
51
51
  | Domain service / entity, value object method | One entity / value object → its method. The junction of several → always a domain service, unless they all belong to one aggregate → a method on that aggregate. |
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. |
@@ -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, and orchestration commands/queries see only execution commands and queries from application. 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 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.
10
10
 
11
11
  ## Bounded context
12
12
 
@@ -1,204 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Reports imports that cross bounded-context boundaries outside the allowed places.
4
- *
5
- * Usage (from the project root):
6
- * node check-context-isolation.mjs [rootFolder]
7
- * rootFolder defaults to `rootFolder` in domain-first.project-structure.config.json.
8
- *
9
- * Bounded contexts never import each other (no exceptions).
10
- * Allowed: shared/** may import any context's domain/errors; the shared in-memory DB
11
- * (shared/infrastructure/services/in-memory-db-infrastructure-service.ts) may also import any
12
- * context's domain models: domain/aggregates/** (barrels included, `*-repository` files not),
13
- * domain/entities/**, domain/value-objects/**; presentation/react/** may only
14
- * `import type` from a context's presentation/rest/; presentation/react/ui-kit/** imports
15
- * nothing from bounded contexts, widgets or pages.
16
- * Widgets never import each other: a file of one widget (the nearest folder under widgets/
17
- * that has a `*-widget.tsx`) must not import anything of another widget.
18
- * Everything else that imports another bounded context is reported.
19
- *
20
- * Checked: `import … from`, `export … from`, side-effect `import '…'`, `import('…')`,
21
- * `require('…')`; specifiers are resolved as relative paths or tsconfig `paths` aliases.
22
- * Exit code 1 when violations are found.
23
- */
24
- import fs from 'node:fs';
25
- import path from 'node:path';
26
- import { createRequire } from 'node:module';
27
-
28
- const cwd = process.cwd();
29
-
30
- const readRootFolder = () => {
31
- const configPath = path.join(cwd, 'domain-first.project-structure.config.json');
32
- if (!fs.existsSync(configPath)) return 'src';
33
- return JSON.parse(fs.readFileSync(configPath, 'utf8')).rootFolder ?? 'src';
34
- };
35
-
36
- const root = path.resolve(cwd, process.argv[2] ?? readRootFolder());
37
- const contextsDir = path.join(root, 'bounded-contexts');
38
- const sharedDir = path.join(root, 'shared');
39
- const reactDir = path.join(root, 'presentation', 'react');
40
- const uiKitDir = path.join(reactDir, 'ui-kit');
41
- const widgetsDir = path.join(reactDir, 'widgets');
42
- const inMemoryDbFile = path.join(sharedDir, 'infrastructure', 'services', 'in-memory-db-infrastructure-service.ts');
43
-
44
- // Domain models of a context: aggregate roots, entities and value objects, not repository contracts.
45
- const isDomainModel = (target, layer, part) =>
46
- layer === 'domain' &&
47
- ['aggregates', 'entities', 'value-objects'].includes(part) &&
48
- !/-repository(\.tsx?)?$/.test(path.basename(target));
49
-
50
- // tsconfig `paths` → [{ prefix, wildcard, targets }]
51
- const readTsconfig = (file) => {
52
- try {
53
- const ts = createRequire(path.join(cwd, 'package.json'))('typescript');
54
- const { config, error } = ts.readConfigFile(file, ts.sys.readFile);
55
- if (!error) return config;
56
- } catch {}
57
- const text = fs
58
- .readFileSync(file, 'utf8')
59
- .replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, str) => str ?? '')
60
- .replace(/,(\s*[}\]])/g, '$1');
61
- return JSON.parse(text);
62
- };
63
-
64
- const readAliases = () => {
65
- const file = path.join(cwd, 'tsconfig.json');
66
- if (!fs.existsSync(file)) return [];
67
- let options;
68
- try {
69
- options = readTsconfig(file).compilerOptions ?? {};
70
- } catch (e) {
71
- console.warn(`WARNING: cannot parse tsconfig.json (${e.message}); aliases are not checked\n`);
72
- return [];
73
- }
74
- const base = path.resolve(cwd, options.baseUrl ?? '.');
75
- return Object.entries(options.paths ?? {})
76
- .map(([key, targets]) => {
77
- const wildcard = key.endsWith('*');
78
- return {
79
- prefix: wildcard ? key.slice(0, -1) : key,
80
- wildcard,
81
- targets: targets.map((t) => path.resolve(base, wildcard ? t.replace(/\*$/, '') : t)),
82
- };
83
- })
84
- .sort((a, b) => b.prefix.length - a.prefix.length);
85
- };
86
-
87
- const aliases = readAliases();
88
-
89
- // Absolute path a specifier points to, or null for a package.
90
- const resolveSpecifier = (spec, fromFile) => {
91
- if (spec.startsWith('.')) return path.resolve(path.dirname(fromFile), spec);
92
- for (const { prefix, wildcard, targets } of aliases) {
93
- if (wildcard ? spec.startsWith(prefix) : spec === prefix) {
94
- return path.join(targets[0], wildcard ? spec.slice(prefix.length) : '');
95
- }
96
- }
97
- return null;
98
- };
99
-
100
- const inside = (dir, file) => {
101
- const rel = path.relative(dir, file);
102
- return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel.split(path.sep) : null;
103
- };
104
-
105
- const sourceFiles = (dir) => {
106
- if (!fs.existsSync(dir)) return [];
107
- return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
108
- const full = path.join(dir, entry.name);
109
- if (entry.isDirectory()) return entry.name === 'node_modules' ? [] : sourceFiles(full);
110
- return /\.(c|m)?tsx?$/.test(entry.name) && !entry.name.endsWith('.d.ts') ? [full] : [];
111
- });
112
- };
113
-
114
- // One alternation, scanned left to right, so a match never spans two statements.
115
- const importPattern =
116
- /\b(?:(import|export)\s+(type\s+)?(?:(?!\b(?:import|export)\b)[\w*{}\s,$])*?\s*from\s*|import\s*\(\s*|require\s*\(\s*|import\s*)(['"])([^'"\n]+)\3/g;
117
-
118
- const importsOf = (file) => {
119
- const text = fs.readFileSync(file, 'utf8');
120
- return [...text.matchAll(importPattern)].map((m) => ({
121
- typeOnly: m[1] === 'import' && Boolean(m[2]),
122
- target: resolveSpecifier(m[4], file),
123
- line: text.slice(0, m.index).split('\n').length,
124
- statement: m[0].replace(/\s+/g, ' '),
125
- }));
126
- };
127
-
128
- const contexts = fs.existsSync(contextsDir)
129
- ? fs
130
- .readdirSync(contextsDir, { withFileTypes: true })
131
- .filter((e) => e.isDirectory())
132
- .map((e) => e.name)
133
- .sort()
134
- : [];
135
-
136
- // Folder of the widget a path belongs to: the nearest folder under widgets/ with a `*-widget.tsx`.
137
- const widgetCache = new Map();
138
- const isWidgetFolder = (dir) => {
139
- if (!widgetCache.has(dir)) {
140
- widgetCache.set(
141
- dir,
142
- fs.existsSync(dir) &&
143
- fs.statSync(dir).isDirectory() &&
144
- fs.readdirSync(dir).some((name) => name.endsWith('-widget.tsx')),
145
- );
146
- }
147
- return widgetCache.get(dir);
148
- };
149
- const widgetOf = (target) => {
150
- if (!inside(widgetsDir, target)) return null;
151
- for (let dir = target; inside(widgetsDir, dir); dir = path.dirname(dir)) {
152
- if (isWidgetFolder(dir)) return dir;
153
- }
154
- return null;
155
- };
156
-
157
- const violations = new Map();
158
- const report = (title, file, imp) => {
159
- if (!violations.has(title)) violations.set(title, []);
160
- violations.get(title).push(`${path.relative(cwd, file)}:${imp.line}: ${imp.statement}`);
161
- };
162
-
163
- const scanned = [contextsDir, sharedDir, reactDir].flatMap(sourceFiles);
164
-
165
- for (const file of scanned) {
166
- const ownContext = inside(contextsDir, file)?.[0];
167
- for (const imp of importsOf(file)) {
168
- if (!imp.target) continue;
169
- const [targetContext, layer, part] = inside(contextsDir, imp.target) ?? [];
170
- const allowedInMemoryDbImport = file === inMemoryDbFile && isDomainModel(imp.target, layer, part);
171
-
172
- if (ownContext) {
173
- if (targetContext && targetContext !== ownContext) report(`[${ownContext}] imports another context:`, file, imp);
174
- } else if (inside(sharedDir, file)) {
175
- if (targetContext && !(layer === 'domain' && part === 'errors') && !allowedInMemoryDbImport) {
176
- report('[shared] imports a bounded context outside its domain/errors (and domain models for the in-memory DB):', file, imp);
177
- }
178
- } else if (inside(uiKitDir, file)) {
179
- const [area] = inside(reactDir, imp.target) ?? [];
180
- if (targetContext || area === 'widgets' || area === 'pages') {
181
- report('[presentation/react/ui-kit] imports a bounded context, widget or page:', file, imp);
182
- }
183
- } else if (targetContext && !(imp.typeOnly && layer === 'presentation' && part === 'rest')) {
184
- report('[presentation/react] imports a context other than `import type` from presentation/rest:', file, imp);
185
- }
186
-
187
- const ownWidget = widgetOf(file);
188
- const targetWidget = widgetOf(imp.target);
189
- if (ownWidget && targetWidget && targetWidget !== ownWidget) {
190
- report('[presentation/react/widgets] a widget imports another widget:', file, imp);
191
- }
192
- }
193
- }
194
-
195
- for (const [title, lines] of violations) {
196
- console.log(title);
197
- for (const line of lines) console.log(` ${line}`);
198
- console.log();
199
- }
200
-
201
- if (violations.size === 0) {
202
- console.log(`OK: no cross-context or cross-widget import violations (${contexts.length} contexts)`);
203
- }
204
- process.exit(violations.size === 0 ? 0 : 1);