@domain-first/project-structure 6.0.0 → 7.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.
Files changed (53) hide show
  1. package/README.md +20 -19
  2. package/dist/201.js +46 -35
  3. package/dist/287.js +1762 -1250
  4. package/dist/backend-module-move.d.ts +53 -0
  5. package/dist/backend-module-move.spec.d.ts +1 -0
  6. package/dist/config-file.d.ts +2 -2
  7. package/dist/dependency-rules.d.ts +1 -1
  8. package/dist/file-system.d.ts +5 -0
  9. package/dist/in-memory-db.d.ts +9 -0
  10. package/dist/index.cjs +534 -804
  11. package/dist/index.js +9 -47
  12. package/dist/init.cjs +913 -0
  13. package/dist/init.d.ts +2 -0
  14. package/dist/init.js +36 -0
  15. package/dist/integration.cjs +457 -33
  16. package/dist/integration.js +4 -4
  17. package/dist/integrations/in-memory-db.d.ts +6 -0
  18. package/dist/integrations/index.d.ts +2 -0
  19. package/dist/integrations/missing-domain-first-packages.d.ts +8 -0
  20. package/dist/integrations/rest-endpoint-generator.d.ts +18 -0
  21. package/dist/integrations/rest-endpoint-generator.spec.d.ts +1 -0
  22. package/dist/lint.cjs +8 -8
  23. package/dist/lint.js +7 -7
  24. package/dist/module-move.d.ts +58 -0
  25. package/dist/print-next-steps.d.ts +2 -2
  26. package/dist/react-module-move.d.ts +2 -6
  27. package/dist/react.cjs +986 -0
  28. package/dist/react.d.ts +2 -0
  29. package/dist/react.js +73 -0
  30. package/dist/use-cases/index.d.ts +1 -0
  31. package/dist/use-cases/move-backend-unit.d.ts +7 -0
  32. package/dist/use-cases/rest-endpoint-generator.d.ts +1 -1
  33. package/package.json +3 -1
  34. package/skills/df-ps-implement/SKILL.md +11 -56
  35. package/skills/df-ps-plan-feature/SKILL.md +6 -6
  36. package/skills/df-ps-project-scripts/SKILL.md +1 -1
  37. package/skills/df-ps-react/SKILL.md +82 -0
  38. package/skills/df-ps-react/references/generators.md +80 -0
  39. package/skills/df-ps-scaffold/SKILL.md +39 -20
  40. package/skills/df-ps-scaffold/references/choosing-components.md +7 -28
  41. package/skills/df-ps-scaffold/references/generators.md +6 -179
  42. package/skills/df-ps-scaffold/references/units/aggregate.md +47 -0
  43. package/skills/df-ps-scaffold/references/units/bounded-context.md +13 -0
  44. package/skills/df-ps-scaffold/references/units/command-query.md +32 -0
  45. package/skills/df-ps-scaffold/references/units/endpoint.md +28 -0
  46. package/skills/df-ps-scaffold/references/units/entity-value-object.md +27 -0
  47. package/skills/df-ps-scaffold/references/units/errors.md +26 -0
  48. package/skills/df-ps-scaffold/references/units/move-or-rename.md +21 -0
  49. package/skills/df-ps-scaffold/references/units/port.md +23 -0
  50. package/skills/df-ps-scaffold/references/units/services.md +28 -0
  51. package/skills/df-ps-scaffold/references/units/use-case.md +25 -0
  52. package/skills/df-ps-scaffold/references/units/wire-dependency.md +15 -0
  53. package/skills/df-ps-scaffold/scripts/drive.mjs +12 -4
package/dist/287.js CHANGED
@@ -1,57 +1,8 @@
1
- import { styleText } from "node:util";
2
1
  import node_path from "node:path";
3
2
  import { Separator, checkbox as prompts_checkbox, confirm as prompts_confirm, input, select as prompts_select } from "@inquirer/prompts";
3
+ import { styleText } from "node:util";
4
4
  import node_fs from "node:fs";
5
- import { addImport, availableDependencies, discardPendingChanges, findWiredModules, UnknownFormatNaming, Folder, writePendingChanges, stripJsonComments, readWiredModule, addClassMember, addWireDependencies, addConstructorParameters, filesToOverwrite, ConfigFile, relativeImport, wireDependencies, File, ProjectRoot, implementationType as wiring_implementationType, compilerOption, isSuggestedFor } from "./201.js";
6
- const installCommand = /^\s*npm (?:i|install)((?:\s+(?:--save-dev|-D))?)\s+(.+)$/;
7
- const mergeInstallCommands = (commands)=>{
8
- const runtime = new Set();
9
- const development = new Set();
10
- const rest = [];
11
- for (const command of commands){
12
- const match = installCommand.exec(command);
13
- if (!match) {
14
- rest.push(command);
15
- continue;
16
- }
17
- for (const name of match[2].trim().split(/\s+/))(match[1] ? development : runtime).add(name);
18
- }
19
- const devOnly = [
20
- ...development
21
- ].filter((name)=>!runtime.has(name));
22
- return [
23
- ...runtime.size ? [
24
- `npm install ${[
25
- ...runtime
26
- ].join(' ')}`
27
- ] : [],
28
- ...devOnly.length ? [
29
- `npm install --save-dev ${devOnly.join(' ')}`
30
- ] : [],
31
- ...rest
32
- ];
33
- };
34
- const printNextSteps = (nextSteps)=>{
35
- const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
36
- const commands = mergeInstallCommands(nextSteps.filter(isCommand));
37
- const notes = nextSteps.filter((line)=>!isCommand(line));
38
- const sections = [];
39
- if (commands.length) sections.push([
40
- 'Run these commands to install the required dependencies:',
41
- ...commands.map((line)=>styleText([
42
- 'bold',
43
- 'cyan'
44
- ], line))
45
- ].join('\n'));
46
- if (notes.length) sections.push([
47
- 'Additional information:',
48
- ...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + styleText([
49
- 'bold',
50
- 'cyan'
51
- ], path)))
52
- ].join('\n'));
53
- if (sections.length) console.log(sections.join('\n\n'));
54
- };
5
+ import { addImport, availableDependencies, discardPendingChanges, findWiredModules, UnknownFormatNaming, Folder, writePendingChanges, readWiredModule, stripJsonComments, addClassMember, withoutOverwrites, addWireDependencies, addConstructorParameters, filesToOverwrite, ConfigFile, relativeImport, wireDependencies, File, ProjectRoot, implementationType as wiring_implementationType, isSuggestedFor, compilerOption } from "./201.js";
55
6
  const savePendingChanges = async ()=>{
56
7
  const overwrittenFiles = filesToOverwrite();
57
8
  if (overwrittenFiles.length) {
@@ -71,493 +22,542 @@ const savePendingChanges = async ()=>{
71
22
  writePendingChanges();
72
23
  return true;
73
24
  };
74
- const missingDomainFirstPackages = ()=>{
75
- const packages = ConfigFile.Instance.data.domainFirstPackages;
76
- const manifest = JSON.parse(new File(node_path.join(new ProjectRoot().path, 'package.json')).data);
77
- const dependencies = {
78
- ...manifest.dependencies,
79
- ...manifest.devDependencies,
80
- ...manifest.optionalDependencies
81
- };
82
- const missing = [
83
- ...new Set(packages)
84
- ].filter((name)=>!Object.hasOwn(dependencies, name));
85
- return missing.length ? [
86
- `npm i ${missing.join(' ')}`
87
- ] : [];
25
+ const inMemoryImplementationType = 'in-memory';
26
+ const in_memory_db_className = 'InMemoryDbInfrastructureService';
27
+ const wireName = 'wireInMemoryDbInfrastructureService';
28
+ const parameterName = 'inMemoryDbInfrastructureService';
29
+ const inMemoryDbService = `type Entry = {
30
+ id: unknown;
31
+ item: any;
88
32
  };
89
- const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
90
- class NestedName {
91
- folders;
92
- folderName;
93
- fileName;
94
- ClassName;
95
- classNameSegments;
96
- constructor(rawSource){
97
- const segments = splitSegments(rawSource);
98
- this.folders = segments.slice(0, -1);
99
- this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
100
- this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
101
- this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
102
- this.ClassName = this.classNameSegments.join('');
103
- }
104
- static validate = (rawSource)=>{
105
- const segments = splitSegments(rawSource);
106
- if (!segments.length) return 'Name is required';
107
- if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
108
- return true;
109
- };
110
- }
111
- const reactPageContent = (ClassName, { imports = [], body = '<></>' } = {})=>`
112
- ${[
113
- ...imports,
114
- "import { type FC } from 'react'"
115
- ].join('\n')}
116
33
 
117
- export type ${ClassName}PageProps = {}
118
-
119
- export const ${ClassName}Page: FC<${ClassName}PageProps> = (props) => {
120
- return ${body}
34
+ declare global {
35
+ var ___SHARED_IN_MEMORY_DB___: Record<string, Array<Entry>> | undefined;
121
36
  }
122
- `.trim();
123
- const scaffoldReactPage = async (presentationReactFolder)=>{
124
- const name = await input({
125
- message: 'Provide name (folders split by "/"):',
126
- validate: NestedName.validate
127
- });
128
- const { folders, ClassName, fileName } = new NestedName(name);
129
- presentationReactFolder.subitem([
130
- 'pages',
131
- ...folders
132
- ]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
133
- };
134
- const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
135
- const rootFolderSegments = (rootFolder)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n `).join('');
136
- const openapiExtractor = (rootFolder)=>`import path from 'node:path';
137
- import {
138
- type DocNode,
139
- DocPlainText,
140
- TSDocConfiguration,
141
- TSDocParser,
142
- TSDocTagDefinition,
143
- TSDocTagSyntaxKind
144
- } from '@microsoft/tsdoc';
145
- import { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';
146
-
147
- type BlockTag = \`@\${string}\`;
148
37
 
149
- type OpenApiDataTags = {
150
- /** Omit to take the summary from the comment text before the first tag. */
151
- summary?: BlockTag;
152
- description?: BlockTag;
38
+ type Section<T, TId> = {
39
+ all: (predicate?: (x: T) => boolean) => T[];
40
+ first: (predicate: (x: T) => boolean) => T | null;
41
+ withId: (id: TId) => T | null;
42
+ lastAddedItem: () => T | null;
43
+ save: (payload: T extends { id: TId } ? T : [TId, T]) => void;
44
+ deleteById: (id: TId) => void;
45
+ delete: (predicate: (x: T) => boolean) => void;
153
46
  };
154
47
 
155
- type OpenApiData = Partial<{
156
- summary: string;
157
- description: string;
158
- operationId: string;
159
- }>;
160
-
161
- const project = new Project({
162
- tsConfigFilePath: 'tsconfig.json'
163
- });
164
-
165
- const getText = (node: DocNode): string =>
166
- node
167
- .getChildNodes()
168
- .map((child) => {
169
- if (child instanceof DocPlainText) {
170
- return child.text;
171
- }
172
-
173
- return getText(child);
174
- })
175
- .join('');
48
+ type IdsAreEqual<TId> = (a: TId, b: TId) => boolean;
176
49
 
177
- const getRawCommentText = (comment: string): string =>
178
- comment
179
- .replace(/^\\/\\*\\*/, '')
180
- .replace(/\\*\\/$/, '')
181
- .split(/\\r?\\n/)
182
- .map((line) => line.replace(/^\\s*\\*\\s?/, ''))
183
- .join('\\n');
50
+ const comparisonMethodNames = ['equals', 'same', 'isSame', 'isEqual'] as const;
184
51
 
185
- // TSDoc treats an unknown tag as summary content, so every block tag of the
186
- // comment has to be registered for the summary section to end before it.
187
- const parseSummary = (comment: string): string | undefined => {
188
- const configuration = new TSDocConfiguration();
189
- const tagNames = getRawCommentText(comment).matchAll(/(?:^|\\n)\\s*(@\\w+)/g);
52
+ const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
53
+ if (typeof a !== 'object' || a === null) {
54
+ return Object.is(a, b);
55
+ }
190
56
 
191
- for (const [, tagName] of tagNames) {
192
- if (!configuration.tryGetTagDefinition(tagName)) {
193
- configuration.addTagDefinition(
194
- new TSDocTagDefinition({
195
- tagName,
196
- syntaxKind: TSDocTagSyntaxKind.BlockTag
197
- })
198
- );
57
+ for (const methodName of comparisonMethodNames) {
58
+ const method: unknown = (a as Record<string, unknown>)[methodName];
59
+ if (typeof method === 'function') {
60
+ return Boolean(method.call(a, b));
199
61
  }
200
62
  }
201
63
 
202
- const { docComment } = new TSDocParser(configuration).parseString(comment);
203
-
204
- return getText(docComment.summarySection).trim() || undefined;
205
- };
206
-
207
- // Parsed by hand rather than through TSDoc, which drops the line breaks.
208
- const getTagText = (comment: string, tag: BlockTag): string | undefined => {
209
- const tagMatch = getRawCommentText(comment).match(
210
- new RegExp(
211
- \`(?:^|\\\\n)\\\\s*\${tag}(?:[ \\\\t]*\\\\n|[ \\\\t]+)([\\\\s\\\\S]*?)(?=\\\\n\\\\s*@\\\\w+|\\\\s*$)\`
212
- )
213
- );
214
-
215
- return tagMatch?.[1].trim() || undefined;
64
+ return Object.is(a, b);
216
65
  };
217
66
 
218
- // Endpoints pass their logic as the generator's first argument
219
- // (\`this.endpointGenerator(this.handler.handle, ...)\`), while other injected
220
- // queries only serve as helpers, e.g. guest checks.
221
- const findHandlerClass = (endpointFile: SourceFile) =>
222
- endpointFile
223
- .getDescendantsOfKind(SyntaxKind.CallExpression)
224
- .map((call) => call.getArguments()[0])
225
- .filter(Node.isPropertyAccessExpression)
226
- .find((argument) => argument.getName() === 'handle')
227
- ?.getExpression()
228
- .getType()
229
- .getSymbol()
230
- ?.getDeclarations()
231
- .find(Node.isClassDeclaration);
67
+ const hasId = (x: unknown): x is { id: unknown } =>
68
+ typeof x === 'object' && x !== null && 'id' in x;
232
69
 
233
- // Path parameters (\`:id\`) can't be part of file and folder names
234
- // everywhere (Windows), so endpoints name them \`_id_\` there.
235
- const pathParameterAsName = (segment: string) =>
236
- segment.startsWith(':') ? \`_\${segment.slice(1)}_\` : segment;
70
+ export class InMemoryDbInfrastructureService {
71
+ protected section<T extends { id: unknown }>(
72
+ key: string,
73
+ idsAreEqual?: IdsAreEqual<T['id']>
74
+ ): Section<T, T['id']>;
75
+ protected section<T, TId>(
76
+ key: string,
77
+ idsAreEqual?: IdsAreEqual<TId>
78
+ ): Section<T, TId>;
79
+ protected section<T, TId>(
80
+ key: string,
81
+ idsAreEqual: IdsAreEqual<TId> = defaultIdsAreEqual
82
+ ): Section<T, TId> {
83
+ if (!globalThis.___SHARED_IN_MEMORY_DB___) {
84
+ globalThis.___SHARED_IN_MEMORY_DB___ = {};
85
+ }
237
86
 
238
- export const createOpenApiDataFromEndpointLogicExtractor = ({
239
- summary: summaryTag,
240
- description: descriptionTag = '@description'
241
- }: OpenApiDataTags = {}) => {
242
- return (routeMetadata: {
243
- method: string;
244
- path: readonly string[];
245
- }): OpenApiData | undefined => {
246
- try {
247
- const [currentBoundedContext, controller, ...relativePath] =
248
- routeMetadata.path;
87
+ if (!globalThis.___SHARED_IN_MEMORY_DB___[key]) {
88
+ globalThis.___SHARED_IN_MEMORY_DB___[key] = [];
89
+ }
249
90
 
250
- if (!currentBoundedContext || !controller) {
251
- return undefined;
252
- }
91
+ const items = (): T[] =>
92
+ globalThis.___SHARED_IN_MEMORY_DB___![key].map(
93
+ (entry) => entry.item
94
+ );
253
95
 
254
- const endpointFile = project.getSourceFile(
255
- path.join(
256
- ${rootFolderSegments(rootFolder)}'bounded-contexts',
257
- currentBoundedContext,
258
- 'presentation',
259
- 'rest',
260
- controller,
261
- ...relativePath.map(pathParameterAsName),
262
- \`\${routeMetadata.method.toUpperCase()}.ts\`
263
- )
264
- );
265
-
266
- if (!endpointFile) {
267
- return undefined;
96
+ return {
97
+ all: (predicate: (x: T) => boolean = () => true): T[] =>
98
+ items().filter(predicate),
99
+ first: (predicate: (x: T) => boolean): T | null =>
100
+ items().find(predicate) ?? null,
101
+ withId: (id: TId): T | null =>
102
+ items().find(
103
+ (x: T) => hasId(x) && idsAreEqual(x.id as TId, id)
104
+ ) ?? null,
105
+ lastAddedItem: (): T | null =>
106
+ globalThis.___SHARED_IN_MEMORY_DB___![key].at(-1)?.item ?? null,
107
+ save: (payload: T extends { id: TId } ? T : [TId, T]) => {
108
+ const id = Array.isArray(payload) ? payload[0] : payload.id;
109
+ const item = Array.isArray(payload) ? payload[1] : payload;
110
+ const entries = globalThis.___SHARED_IN_MEMORY_DB___![key];
111
+ const existing = entries.find((entry) =>
112
+ idsAreEqual(entry.id as TId, id)
113
+ );
114
+ if (existing) {
115
+ existing.item = item;
116
+ return;
117
+ }
118
+ entries.push({ id, item });
119
+ },
120
+ deleteById: (id: TId) => {
121
+ globalThis.___SHARED_IN_MEMORY_DB___![key] =
122
+ globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
123
+ (entry) => !idsAreEqual(entry.id as TId, id)
124
+ );
125
+ },
126
+ delete: (predicate: (x: T) => boolean) => {
127
+ globalThis.___SHARED_IN_MEMORY_DB___![key] =
128
+ globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
129
+ (entry) => !predicate(entry.item)
130
+ );
268
131
  }
132
+ };
133
+ }
134
+ }
135
+ `;
136
+ const inMemoryDbWiring = `import { wireClass } from '@domain-first/wire';
137
+ import { InMemoryDbInfrastructureService } from '../../infrastructure/services/in-memory-db-infrastructure-service';
269
138
 
270
- const declaration = findHandlerClass(endpointFile);
271
- const operationId = declaration?.getName();
272
- const comment = declaration?.getJsDocs().at(-1)?.getText();
139
+ export const wireInMemoryDbInfrastructureService = wireClass(
140
+ InMemoryDbInfrastructureService,
141
+ []
142
+ );
143
+ `;
144
+ const inMemoryDbSpec = (testingLibrary, withWiring)=>`
145
+ import { describe, test, expect, beforeEach } from '${testingLibrary}'
146
+ ${withWiring ? `import { type InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'
147
+ import { wireInMemoryDbInfrastructureService } from '../../wiring/infrastructure-services/wire-in-memory-db-infrastructure-service'` : "import { InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'"}
273
148
 
274
- if (!comment) {
275
- return { operationId };
276
- }
149
+ let inMemoryDbInfrastructureService: InMemoryDbInfrastructureService
277
150
 
278
- return {
279
- summary: summaryTag
280
- ? getTagText(comment, summaryTag)
281
- : parseSummary(comment),
282
- description: getTagText(comment, descriptionTag),
283
- operationId
284
- };
285
- } catch (e: unknown) {
286
- console.error(e);
287
- return undefined;
288
- }
289
- };
151
+ beforeEach(() => {
152
+ inMemoryDbInfrastructureService = ${withWiring ? 'wireInMemoryDbInfrastructureService()' : 'new InMemoryDbInfrastructureService()'}
153
+ })
154
+
155
+ describe('in memory db', () => {
156
+ test('can be ${withWiring ? 'wired' : 'created'}', () => {
157
+ expect(inMemoryDbInfrastructureService).toBeDefined()
158
+ })
159
+ })
160
+ `.trim();
161
+ const in_memory_db_withWiring = ()=>ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
162
+ const in_memory_db_sharedFolder = ()=>new Folder(new ProjectRoot().path).subitem([
163
+ ConfigFile.Instance.data.rootFolder,
164
+ 'shared-kernel'
165
+ ]);
166
+ const serviceFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
167
+ 'infrastructure',
168
+ 'services',
169
+ 'in-memory-db-infrastructure-service.ts'
170
+ ]);
171
+ const in_memory_db_wireFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
172
+ 'wiring',
173
+ 'infrastructure-services',
174
+ 'wire-in-memory-db-infrastructure-service.ts'
175
+ ]);
176
+ const scaffoldInMemoryDb = (shared)=>{
177
+ const { testingLibrary } = ConfigFile.Instance.data;
178
+ const servicesFolder = shared.subitem([
179
+ 'infrastructure',
180
+ 'services'
181
+ ]);
182
+ servicesFolder.createFile('in-memory-db-infrastructure-service.ts', inMemoryDbService);
183
+ if (testingLibrary) servicesFolder.createFile('in-memory-db-infrastructure-service.spec.ts', inMemoryDbSpec(testingLibrary, in_memory_db_withWiring()));
184
+ if (in_memory_db_withWiring()) shared.subitem([
185
+ 'wiring',
186
+ 'infrastructure-services'
187
+ ]).createFile('wire-in-memory-db-infrastructure-service.ts', inMemoryDbWiring);
290
188
  };
291
- `;
292
- const addPackageScripts = async (file, additions)=>{
293
- const original = file.data;
294
- const manifest = JSON.parse(original);
295
- const scripts = {
296
- ...manifest.scripts
297
- };
298
- const selected = {};
299
- for (const [name, command] of Object.entries(additions)){
300
- let target = name;
301
- if (Object.hasOwn(scripts, name) && scripts[name] !== command) {
302
- const action = await prompts_select({
303
- message: `Script "${name}" already exists: ${scripts[name]}`,
304
- choices: [
305
- 'Keep existing',
306
- 'Replace',
307
- 'Use another name'
308
- ]
309
- });
310
- if ('Keep existing' === action) continue;
311
- if ('Use another name' === action) target = await input({
312
- message: "New script name:",
313
- validate: (value)=>!/^[a-zA-Z0-9:_-]+$/.test(value) || Object.hasOwn(scripts, value) || Object.hasOwn(additions, value) ? "Enter an unused script name (letters, numbers, :, _, -)." : true
314
- });
315
- }
316
- scripts[target] = command;
317
- selected[name] = target;
318
- }
319
- if (JSON.stringify(manifest.scripts) !== JSON.stringify(scripts)) {
320
- manifest.scripts = scripts;
321
- const indent = original.match(/\n([\t ]+)"/)?.[1] ?? ' ';
322
- file.update(`${JSON.stringify(manifest, null, indent)}\n`);
189
+ const inMemoryDbScaffolded = ()=>serviceFile().exists && (!in_memory_db_withWiring() || in_memory_db_wireFile().exists);
190
+ const usesInMemoryDb = (implementationType)=>Boolean(ConfigFile.Instance.data.withInMemoryDb) && new UnknownFormatNaming(implementationType).fileName === inMemoryImplementationType && inMemoryDbScaffolded();
191
+ const plural = (word)=>{
192
+ if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
193
+ if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
194
+ return `${word}s`;
195
+ };
196
+ const addInMemoryDbSection = (typeNaming, typeImportTarget)=>{
197
+ const file = serviceFile();
198
+ const sectionNaming = new UnknownFormatNaming(plural(typeNaming.fileName));
199
+ const field = sectionNaming.variableName;
200
+ if (new RegExp(`\\b${field}\\s*=\\s*this\\.section\\b`).test(file.data)) return field;
201
+ const withImport = addImport(file.data, `import type { ${typeNaming.ClassName} } from '${relativeImport(file.path, typeImportTarget)}';`);
202
+ file.update(addClassMember(withImport, in_memory_db_className, `${field} = this.section<${typeNaming.ClassName}>('${sectionNaming.fileName.toUpperCase()}');`));
203
+ return field;
204
+ };
205
+ const inMemoryDbTypeImport = (fromFile)=>`import type { ${in_memory_db_className} } from '${relativeImport(fromFile, serviceFile().path)}'`;
206
+ const inMemoryDbSectionMembers = (field, derived)=>`
207
+ private readonly data: ${in_memory_db_className}['${field}']
208
+
209
+ constructor(${parameterName}: ${in_memory_db_className}) {
210
+ ${derived ? 'super()\n ' : ''}this.data = ${parameterName}.${field}
323
211
  }
324
- return selected;
212
+ `.trim();
213
+ const keepInMemoryDbSection = (classFile, field)=>{
214
+ classFile.update(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)).replace('constructor() {}', inMemoryDbSectionMembers(field, false)));
325
215
  };
326
- const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
327
- const openapiScriptPath = "scripts/generate-openapi.ts";
328
- const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
329
- const extractorPackages = [
330
- 'ts-morph',
331
- '@microsoft/tsdoc'
332
- ];
333
- const swaggerPagePath = (rootFolder)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/pages/swagger-page.tsx');
334
- const swaggerPage = (rootFolder, outputPath)=>{
335
- const specImport = node_path.posix.relative(node_path.posix.dirname(swaggerPagePath(rootFolder)), outputPath);
336
- return reactPageContent('Swagger', {
337
- imports: [
338
- "import 'swagger-ui-react/swagger-ui.css'",
339
- "import SwaggerUI from 'swagger-ui-react'",
340
- `import spec from '${specImport.startsWith('.') ? specImport : `./${specImport}`}' with { type: 'json' }`
341
- ],
342
- body: '<SwaggerUI displayOperationId spec={spec} />'
343
- });
216
+ const isInMemoryDb = (module)=>module.wireName === wireName;
217
+ const injectInMemoryDb = (classFile, implementationName)=>{
218
+ classFile.update(addConstructorParameters(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)), implementationName, [
219
+ `private readonly ${parameterName}: ${in_memory_db_className}`
220
+ ]));
344
221
  };
345
- const openapiScripts = {
346
- openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
222
+ const wireInMemoryDb = (consumerWireFile, implementationName)=>{
223
+ consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${wireName} } from '${relativeImport(consumerWireFile.path, in_memory_db_wireFile().path)}'`), implementationName, [
224
+ wireName
225
+ ]));
347
226
  };
348
- const splitPath = (value)=>value.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
349
- const apiTitle = (packageName)=>{
350
- const words = String(packageName ?? '').replace(/^@[^/]*\//, '').split(/[^a-zA-Z0-9]+/).filter((word)=>!!word).map((word)=>word[0].toUpperCase() + word.slice(1));
227
+ const passInMemoryDb = (specFile, implementationName)=>{
228
+ specFile.update(addImport(specFile.data, `import { ${in_memory_db_className} } from '${relativeImport(specFile.path, serviceFile().path)}'`).replace(`new ${implementationName}()`, `new ${implementationName}(new ${in_memory_db_className}())`));
229
+ };
230
+ const addInMemoryDb = ()=>{
231
+ const config = ConfigFile.Instance.data;
232
+ if (!config.withInMemoryDb) ConfigFile.write({
233
+ ...config,
234
+ withInMemoryDb: true
235
+ });
236
+ withoutOverwrites(()=>scaffoldInMemoryDb(new Folder(new ProjectRoot().path).subitem([
237
+ config.rootFolder,
238
+ 'shared-kernel'
239
+ ])));
240
+ return [];
241
+ };
242
+ const inMemoryDbApplied = ()=>Boolean(ConfigFile.Instance.data.withInMemoryDb) && inMemoryDbScaffolded();
243
+ const hasDependency = (name)=>{
244
+ const manifestFile = new File(node_path.join(new ProjectRoot().path, 'package.json'));
245
+ if (!manifestFile.exists) return false;
246
+ const manifest = JSON.parse(manifestFile.data);
351
247
  return [
352
- ...words,
353
- 'API'
354
- ].join(' ');
248
+ manifest.dependencies,
249
+ manifest.devDependencies,
250
+ manifest.optionalDependencies
251
+ ].some((dependencies)=>dependencies && Object.hasOwn(dependencies, name));
355
252
  };
356
- const openapiGenerator = (rootFolder, title, routePrefix, outputPath, withExtractor = false)=>{
357
- const restFolder = node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/rest');
358
- const restImport = node_path.posix.relative(node_path.posix.dirname(openapiScriptPath), restFolder);
359
- const prefixSegments = splitPath(routePrefix);
360
- const apiRoutePrefix = prefixSegments.length ? `\n apiRoutePrefix: [${prefixSegments.map((segment)=>`'${segment}'`).join(', ')}],` : '';
361
- const extractorImport = `./${node_path.posix.relative(node_path.posix.dirname(openapiScriptPath), openapiExtractorPath.replace(/\.ts$/, ''))}`;
362
- const handlers = withExtractor ? `
363
- const extractOpenApiDataFromEndpointLogic =
364
- createOpenApiDataFromEndpointLogicExtractor();
365
-
366
- const handlers = restHandlers.map((x) => ({
367
- ...x,
368
- metadata: {
369
- ...x.metadata,
370
- openApiMetadata: {
371
- ...extractOpenApiDataFromEndpointLogic(x.metadata.route),
372
- ...(x.metadata.openApiMetadata ?? {})
373
- }
374
- }
375
- }));
376
- ` : '';
377
- return `import { generateOpenAPI } from '@domain-first/handlers-rest';
378
- import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}';${withExtractor ? `\nimport { createOpenApiDataFromEndpointLogicExtractor } from '${extractorImport}';` : ''}
379
- ${handlers}
380
- generateOpenAPI(${withExtractor ? 'handlers' : 'restHandlers'}, {
381
- document: { info: { title: '${title}', version: '1.0.0' } },${apiRoutePrefix}
382
- outputFile: { path: '${outputPath}' }
383
- });
384
- `;
253
+ const missingPackages = (packages)=>{
254
+ const missing = [
255
+ ...new Set(packages)
256
+ ].filter((name)=>!hasDependency(name));
257
+ return missing.length ? [
258
+ `npm i ${missing.join(' ')}`
259
+ ] : [];
385
260
  };
386
- const addOpenapi = async ()=>{
387
- const { rootFolder } = ConfigFile.Instance.data;
388
- const root = new ProjectRoot().path;
389
- const manifestFile = new File(node_path.join(root, 'package.json'));
390
- const manifest = JSON.parse(manifestFile.data);
391
- const dependencies = {
392
- ...manifest.dependencies,
393
- ...manifest.devDependencies
261
+ const missingDomainFirstPackages = ()=>missingPackages(ConfigFile.Instance.data.domainFirstPackages);
262
+ const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
263
+ class NestedName {
264
+ folders;
265
+ folderName;
266
+ fileName;
267
+ ClassName;
268
+ classNameSegments;
269
+ constructor(rawSource){
270
+ const segments = splitSegments(rawSource);
271
+ this.folders = segments.slice(0, -1);
272
+ this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
273
+ this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
274
+ this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
275
+ this.ClassName = this.classNameSegments.join('');
276
+ }
277
+ static validate = (rawSource)=>{
278
+ const segments = splitSegments(rawSource);
279
+ if (!segments.length) return 'Name is required';
280
+ if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
281
+ return true;
394
282
  };
395
- const routePrefix = await input({
396
- message: 'Route prefix the REST handlers are served under:',
397
- default: '/api'
398
- });
399
- const outputPath = await input({
400
- message: 'OpenAPI document path:',
401
- default: defaultOpenapiPath(Boolean(dependencies.next)),
402
- validate: (value)=>splitPath(value).length ? true : 'Path is required'
403
- });
404
- const withExtractor = await prompts_confirm({
405
- message: "Fill operationId, summary and description from the endpoint logic TSDoc?",
406
- default: true
407
- });
408
- const withSwaggerPage = ConfigFile.Instance.data.useReact && await prompts_confirm({
409
- message: 'Add a Swagger UI page?',
410
- default: true
283
+ }
284
+ const reactPageContent = (ClassName, { imports = [], body = '<></>' } = {})=>`
285
+ ${[
286
+ ...imports,
287
+ "import { type FC } from 'react'"
288
+ ].join('\n')}
289
+
290
+ export type ${ClassName}PageProps = {}
291
+
292
+ export const ${ClassName}Page: FC<${ClassName}PageProps> = (props) => {
293
+ return ${body}
294
+ }
295
+ `.trim();
296
+ const scaffoldReactPage = async (presentationReactFolder)=>{
297
+ const name = await input({
298
+ message: 'Provide name (folders split by "/"):',
299
+ validate: NestedName.validate
411
300
  });
412
- const selected = await addPackageScripts(manifestFile, openapiScripts);
413
- if (withExtractor) {
414
- const extractorFile = new File(node_path.join(root, openapiExtractorPath));
415
- const extractor = openapiExtractor(rootFolder);
416
- if (!extractorFile.exists || extractorFile.data !== extractor) extractorFile.data = extractor;
417
- }
418
- const generatorFile = new File(node_path.join(root, openapiScriptPath));
419
- const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
420
- if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
421
- if (withSwaggerPage) {
422
- const pageFile = new File(node_path.join(root, swaggerPagePath(rootFolder)));
423
- const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'));
424
- if (!pageFile.exists || pageFile.data !== page) pageFile.data = page;
425
- }
426
- const resolveJsonModule = withSwaggerPage ? compilerOption(node_path.join(root, 'tsconfig.json'), 'resolveJsonModule') : true;
427
- const hasRestHandlers = new File(node_path.join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
428
- const missingExtractorPackages = withExtractor ? extractorPackages.filter((name)=>!dependencies[name]) : [];
429
- return [
430
- ...dependencies['@domain-first/handlers-rest'] ? [] : [
431
- 'npm install @domain-first/handlers-rest'
432
- ],
433
- ...dependencies.tsx ? [] : [
434
- 'npm install --save-dev tsx'
435
- ],
436
- ...missingExtractorPackages.length ? [
437
- `npm install --save-dev ${missingExtractorPackages.join(' ')}`
438
- ] : [],
439
- ...withSwaggerPage && !dependencies['swagger-ui-react'] ? [
440
- 'npm install swagger-ui-react'
441
- ] : [],
442
- ...withSwaggerPage && !dependencies['@types/swagger-ui-react'] ? [
443
- 'npm install --save-dev @types/swagger-ui-react'
444
- ] : [],
445
- ...true === resolveJsonModule || null === resolveJsonModule ? [] : [
446
- 'set "resolveJsonModule": true in compilerOptions of tsconfig.json — the Swagger UI page imports the OpenAPI document as JSON'
447
- ],
448
- ...describeScripts(selected, {
449
- openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
450
- }),
451
- ...withSwaggerPage ? [
452
- `SwaggerPage from ${swaggerPagePath(rootFolder)} shows ${splitPath(outputPath).join('/')} once it is generated — render it on a route of your app`
453
- ] : [],
454
- ...hasRestHandlers ? [] : [
455
- `restHandlers appear in ${node_path.posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
456
- ]
457
- ];
301
+ const { folders, ClassName, fileName } = new NestedName(name);
302
+ presentationReactFolder.subitem([
303
+ 'pages',
304
+ ...folders
305
+ ]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
458
306
  };
459
- const addGitignoreEntry = (root, entry)=>{
460
- const gitignore = new File(node_path.join(root, '.gitignore'));
461
- const ignored = gitignore.exists ? gitignore.data : '';
462
- if (ignored.split(/\r?\n/).includes(entry)) return;
463
- const newline = ignored.includes('\r\n') ? '\r\n' : '\n';
464
- gitignore.update(`${ignored}${ignored && !ignored.endsWith('\n') ? newline : ''}${entry}${newline}`);
307
+ const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
308
+ const rootFolderSegments = (rootFolder)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n `).join('');
309
+ const openapiExtractor = (rootFolder)=>`import path from 'node:path';
310
+ import {
311
+ type DocNode,
312
+ DocPlainText,
313
+ TSDocConfiguration,
314
+ TSDocParser,
315
+ TSDocTagDefinition,
316
+ TSDocTagSyntaxKind
317
+ } from '@microsoft/tsdoc';
318
+ import { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';
319
+
320
+ type BlockTag = \`@\${string}\`;
321
+
322
+ type OpenApiDataTags = {
323
+ /** Omit to take the summary from the comment text before the first tag. */
324
+ summary?: BlockTag;
325
+ description?: BlockTag;
465
326
  };
466
- const dataLayerFolder = (rootFolder, target)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'hooks' === target ? 'presentation/react/data-layer' : 'presentation/data-layer');
467
- const orvalScripts = (rootFolder, targets)=>({
468
- 'client:orval': targets.map((target)=>`orval --config ${JSON.stringify(`${dataLayerFolder(rootFolder, target)}/orval.config.ts`)}`).join(' && ')
469
- });
470
- const orvalConfig = (rootFolder, openapiPath, withNext, target = 'hooks', mutatorPath = './api-client/mutator.ts')=>{
471
- const inputPath = node_path.posix.relative(dataLayerFolder(rootFolder, target), openapiPath);
472
- const baseUrl = withNext ? `
473
- baseUrl: {
474
- runtime: 'process.env.NEXT_PUBLIC_API_BASE_URL ?? ""'
475
- },` : '';
476
- const client = 'hooks' === target ? `
477
- client: 'react-query',
478
- httpClient: 'fetch',` : `
479
- client: 'fetch',`;
480
- const query = 'hooks' === target ? `,
481
- query: {
482
- version: 5
483
- }` : '';
484
- return `import { defineConfig } from 'orval';
485
327
 
486
- export default defineConfig({
487
- api: {
488
- input: '${inputPath.startsWith('.') ? inputPath : `./${inputPath}`}',
489
- output: {
490
- mode: 'tags-split',
491
- target: './orval',
492
- schemas: './orval/model',${client}${baseUrl}
493
- clean: true,
494
- override: {
495
- mutator: {
496
- path: '${mutatorPath}',
497
- name: 'customInstance'
498
- },
499
- fetch: {
500
- includeHttpResponseReturnType: false
501
- }${query}
502
- }
503
- }
504
- }
328
+ type OpenApiData = Partial<{
329
+ summary: string;
330
+ description: string;
331
+ operationId: string;
332
+ }>;
333
+
334
+ const project = new Project({
335
+ tsConfigFilePath: 'tsconfig.json'
505
336
  });
506
- `;
507
- };
508
- const orvalMutator = `/** Error of the generated requests, with the parsed response body. */
509
- export class ApiError<Body = unknown> extends Error {
510
- constructor(
511
- public readonly status: number,
512
- public readonly body: Body
513
- ) {
514
- super(\`API error \${status}\`);
515
- this.name = 'ApiError';
516
- }
517
- }
518
337
 
519
- /** Error type of the generated requests, typed per endpoint by Orval. */
520
- export type ErrorType<Body> = ApiError<Body>;
338
+ const getText = (node: DocNode): string =>
339
+ node
340
+ .getChildNodes()
341
+ .map((child) => {
342
+ if (child instanceof DocPlainText) {
343
+ return child.text;
344
+ }
521
345
 
522
- /** Every generated request goes through here: add auth headers, token refresh, logging. */
523
- export const customInstance = async <T>(
524
- url: string,
525
- init?: RequestInit
526
- ): Promise<T> => {
527
- const response = await fetch(url, init);
528
- const text = await response.text();
529
- const body = text ? JSON.parse(text) : undefined;
346
+ return getText(child);
347
+ })
348
+ .join('');
530
349
 
531
- if (!response.ok) {
532
- throw new ApiError(response.status, body);
533
- }
350
+ const getRawCommentText = (comment: string): string =>
351
+ comment
352
+ .replace(/^\\/\\*\\*/, '')
353
+ .replace(/\\*\\/$/, '')
354
+ .split(/\\r?\\n/)
355
+ .map((line) => line.replace(/^\\s*\\*\\s?/, ''))
356
+ .join('\\n');
534
357
 
535
- return body as T;
536
- };
537
- `;
538
- const queryProvider = `'use client';
358
+ // TSDoc treats an unknown tag as summary content, so every block tag of the
359
+ // comment has to be registered for the summary section to end before it.
360
+ const parseSummary = (comment: string): string | undefined => {
361
+ const configuration = new TSDocConfiguration();
362
+ const tagNames = getRawCommentText(comment).matchAll(/(?:^|\\n)\\s*(@\\w+)/g);
539
363
 
540
- import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
541
- import { type FC, type ReactNode, useState } from 'react';
364
+ for (const [, tagName] of tagNames) {
365
+ if (!configuration.tryGetTagDefinition(tagName)) {
366
+ configuration.addTagDefinition(
367
+ new TSDocTagDefinition({
368
+ tagName,
369
+ syntaxKind: TSDocTagSyntaxKind.BlockTag
370
+ })
371
+ );
372
+ }
373
+ }
542
374
 
543
- export const QueryProvider: FC<{ children: ReactNode }> = ({ children }) => {
544
- // One client per browser session; a module-level client would be shared between requests on the server
545
- const [queryClient] = useState(() => new QueryClient());
375
+ const { docComment } = new TSDocParser(configuration).parseString(comment);
546
376
 
547
- return (
548
- <QueryClientProvider client={queryClient}>
549
- {children}
550
- </QueryClientProvider>
551
- );
377
+ return getText(docComment.summarySection).trim() || undefined;
552
378
  };
553
- `;
554
- const openapiOutputPath = (root)=>{
555
- const generator = new File(node_path.join(root, openapiScriptPath));
556
- if (!generator.exists) return;
557
- return generator.data.match(/outputFile:\s*{\s*path:\s*'([^']+)'/)?.[1];
379
+
380
+ // Parsed by hand rather than through TSDoc, which drops the line breaks.
381
+ const getTagText = (comment: string, tag: BlockTag): string | undefined => {
382
+ const tagMatch = getRawCommentText(comment).match(
383
+ new RegExp(
384
+ \`(?:^|\\\\n)\\\\s*\${tag}(?:[ \\\\t]*\\\\n|[ \\\\t]+)([\\\\s\\\\S]*?)(?=\\\\n\\\\s*@\\\\w+|\\\\s*$)\`
385
+ )
386
+ );
387
+
388
+ return tagMatch?.[1].trim() || undefined;
558
389
  };
559
- const addOrval = async ()=>{
560
- const { rootFolder, useReact } = ConfigFile.Instance.data;
390
+
391
+ // Endpoints pass their logic as the generator's first argument
392
+ // (\`this.endpointGenerator(this.handler.handle, ...)\`), while other injected
393
+ // queries only serve as helpers, e.g. guest checks.
394
+ const findHandlerClass = (endpointFile: SourceFile) =>
395
+ endpointFile
396
+ .getDescendantsOfKind(SyntaxKind.CallExpression)
397
+ .map((call) => call.getArguments()[0])
398
+ .filter(Node.isPropertyAccessExpression)
399
+ .find((argument) => argument.getName() === 'handle')
400
+ ?.getExpression()
401
+ .getType()
402
+ .getSymbol()
403
+ ?.getDeclarations()
404
+ .find(Node.isClassDeclaration);
405
+
406
+ // Path parameters (\`:id\`) can't be part of file and folder names
407
+ // everywhere (Windows), so endpoints name them \`_id_\` there.
408
+ const pathParameterAsName = (segment: string) =>
409
+ segment.startsWith(':') ? \`_\${segment.slice(1)}_\` : segment;
410
+
411
+ export const createOpenApiDataFromEndpointLogicExtractor = ({
412
+ summary: summaryTag,
413
+ description: descriptionTag = '@description'
414
+ }: OpenApiDataTags = {}) => {
415
+ return (routeMetadata: {
416
+ method: string;
417
+ path: readonly string[];
418
+ }): OpenApiData | undefined => {
419
+ try {
420
+ const [currentBoundedContext, controller, ...relativePath] =
421
+ routeMetadata.path;
422
+
423
+ if (!currentBoundedContext || !controller) {
424
+ return undefined;
425
+ }
426
+
427
+ const endpointFile = project.getSourceFile(
428
+ path.join(
429
+ ${rootFolderSegments(rootFolder)}'bounded-contexts',
430
+ currentBoundedContext,
431
+ 'presentation',
432
+ 'rest',
433
+ controller,
434
+ ...relativePath.map(pathParameterAsName),
435
+ \`\${routeMetadata.method.toUpperCase()}.ts\`
436
+ )
437
+ );
438
+
439
+ if (!endpointFile) {
440
+ return undefined;
441
+ }
442
+
443
+ const declaration = findHandlerClass(endpointFile);
444
+ const operationId = declaration?.getName();
445
+ const comment = declaration?.getJsDocs().at(-1)?.getText();
446
+
447
+ if (!comment) {
448
+ return { operationId };
449
+ }
450
+
451
+ return {
452
+ summary: summaryTag
453
+ ? getTagText(comment, summaryTag)
454
+ : parseSummary(comment),
455
+ description: getTagText(comment, descriptionTag),
456
+ operationId
457
+ };
458
+ } catch (e: unknown) {
459
+ console.error(e);
460
+ return undefined;
461
+ }
462
+ };
463
+ };
464
+ `;
465
+ const addPackageScripts = async (file, additions)=>{
466
+ const original = file.data;
467
+ const manifest = JSON.parse(original);
468
+ const scripts = {
469
+ ...manifest.scripts
470
+ };
471
+ const selected = {};
472
+ for (const [name, command] of Object.entries(additions)){
473
+ let target = name;
474
+ if (Object.hasOwn(scripts, name) && scripts[name] !== command) {
475
+ const action = await prompts_select({
476
+ message: `Script "${name}" already exists: ${scripts[name]}`,
477
+ choices: [
478
+ 'Keep existing',
479
+ 'Replace',
480
+ 'Use another name'
481
+ ]
482
+ });
483
+ if ('Keep existing' === action) continue;
484
+ if ('Use another name' === action) target = await input({
485
+ message: "New script name:",
486
+ validate: (value)=>!/^[a-zA-Z0-9:_-]+$/.test(value) || Object.hasOwn(scripts, value) || Object.hasOwn(additions, value) ? "Enter an unused script name (letters, numbers, :, _, -)." : true
487
+ });
488
+ }
489
+ scripts[target] = command;
490
+ selected[name] = target;
491
+ }
492
+ if (JSON.stringify(manifest.scripts) !== JSON.stringify(scripts)) {
493
+ manifest.scripts = scripts;
494
+ const indent = original.match(/\n([\t ]+)"/)?.[1] ?? ' ';
495
+ file.update(`${JSON.stringify(manifest, null, indent)}\n`);
496
+ }
497
+ return selected;
498
+ };
499
+ const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
500
+ const openapiScriptPath = "scripts/generate-openapi.ts";
501
+ const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
502
+ const extractorPackages = [
503
+ 'ts-morph',
504
+ '@microsoft/tsdoc'
505
+ ];
506
+ const swaggerPagePath = (rootFolder)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/pages/swagger-page.tsx');
507
+ const swaggerPage = (rootFolder, outputPath)=>{
508
+ const specImport = node_path.posix.relative(node_path.posix.dirname(swaggerPagePath(rootFolder)), outputPath);
509
+ return reactPageContent('Swagger', {
510
+ imports: [
511
+ "import 'swagger-ui-react/swagger-ui.css'",
512
+ "import SwaggerUI from 'swagger-ui-react'",
513
+ `import spec from '${specImport.startsWith('.') ? specImport : `./${specImport}`}' with { type: 'json' }`
514
+ ],
515
+ body: '<SwaggerUI displayOperationId spec={spec} />'
516
+ });
517
+ };
518
+ const openapiScripts = {
519
+ openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
520
+ };
521
+ const splitPath = (value)=>value.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
522
+ const apiTitle = (packageName)=>{
523
+ const words = String(packageName ?? '').replace(/^@[^/]*\//, '').split(/[^a-zA-Z0-9]+/).filter((word)=>!!word).map((word)=>word[0].toUpperCase() + word.slice(1));
524
+ return [
525
+ ...words,
526
+ 'API'
527
+ ].join(' ');
528
+ };
529
+ const openapiGenerator = (rootFolder, title, routePrefix, outputPath, withExtractor = false)=>{
530
+ const restFolder = node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/rest');
531
+ const restImport = node_path.posix.relative(node_path.posix.dirname(openapiScriptPath), restFolder);
532
+ const prefixSegments = splitPath(routePrefix);
533
+ const apiRoutePrefix = prefixSegments.length ? `\n apiRoutePrefix: [${prefixSegments.map((segment)=>`'${segment}'`).join(', ')}],` : '';
534
+ const extractorImport = `./${node_path.posix.relative(node_path.posix.dirname(openapiScriptPath), openapiExtractorPath.replace(/\.ts$/, ''))}`;
535
+ const handlers = withExtractor ? `
536
+ const extractOpenApiDataFromEndpointLogic =
537
+ createOpenApiDataFromEndpointLogicExtractor();
538
+
539
+ const handlers = restHandlers.map((x) => ({
540
+ ...x,
541
+ metadata: {
542
+ ...x.metadata,
543
+ openApiMetadata: {
544
+ ...extractOpenApiDataFromEndpointLogic(x.metadata.route),
545
+ ...(x.metadata.openApiMetadata ?? {})
546
+ }
547
+ }
548
+ }));
549
+ ` : '';
550
+ return `import { generateOpenAPI } from '@domain-first/handlers-rest';
551
+ import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}';${withExtractor ? `\nimport { createOpenApiDataFromEndpointLogicExtractor } from '${extractorImport}';` : ''}
552
+ ${handlers}
553
+ generateOpenAPI(${withExtractor ? 'handlers' : 'restHandlers'}, {
554
+ document: { info: { title: '${title}', version: '1.0.0' } },${apiRoutePrefix}
555
+ outputFile: { path: '${outputPath}' }
556
+ });
557
+ `;
558
+ };
559
+ const addOpenapi = async ()=>{
560
+ const { rootFolder } = ConfigFile.Instance.data;
561
561
  const root = new ProjectRoot().path;
562
562
  const manifestFile = new File(node_path.join(root, 'package.json'));
563
563
  const manifest = JSON.parse(manifestFile.data);
@@ -565,43 +565,216 @@ const addOrval = async ()=>{
565
565
  ...manifest.dependencies,
566
566
  ...manifest.devDependencies
567
567
  };
568
- const withNext = Boolean(dependencies.next);
569
- const generatedOpenapiPath = openapiOutputPath(root);
570
- const openapiPath = await input({
568
+ const routePrefix = await input({
569
+ message: 'Route prefix the REST handlers are served under:',
570
+ default: '/api'
571
+ });
572
+ const outputPath = await input({
571
573
  message: 'OpenAPI document path:',
572
- default: generatedOpenapiPath ?? defaultOpenapiPath(withNext),
573
- validate: (value)=>value.trim() ? true : 'Path is required'
574
+ default: defaultOpenapiPath(Boolean(dependencies.next)),
575
+ validate: (value)=>splitPath(value).length ? true : 'Path is required'
574
576
  });
575
- const targets = useReact ? await prompts_checkbox({
576
- message: 'Generate:',
577
- choices: [
578
- {
579
- name: 'React Query hooks',
580
- value: 'hooks',
581
- checked: true
582
- },
583
- {
584
- name: 'Typed API client',
585
- value: 'client'
586
- }
577
+ const withExtractor = await prompts_confirm({
578
+ message: "Fill operationId, summary and description from the endpoint logic TSDoc?",
579
+ default: true
580
+ });
581
+ const withSwaggerPage = ConfigFile.Instance.data.useReact && await prompts_confirm({
582
+ message: 'Add a Swagger UI page?',
583
+ default: true
584
+ });
585
+ const selected = await addPackageScripts(manifestFile, openapiScripts);
586
+ if (withExtractor) {
587
+ const extractorFile = new File(node_path.join(root, openapiExtractorPath));
588
+ const extractor = openapiExtractor(rootFolder);
589
+ if (!extractorFile.exists || extractorFile.data !== extractor) extractorFile.data = extractor;
590
+ }
591
+ const generatorFile = new File(node_path.join(root, openapiScriptPath));
592
+ const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
593
+ if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
594
+ if (withSwaggerPage) {
595
+ const pageFile = new File(node_path.join(root, swaggerPagePath(rootFolder)));
596
+ const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'));
597
+ if (!pageFile.exists || pageFile.data !== page) pageFile.data = page;
598
+ }
599
+ const resolveJsonModule = withSwaggerPage ? compilerOption(node_path.join(root, 'tsconfig.json'), 'resolveJsonModule') : true;
600
+ const hasRestHandlers = new File(node_path.join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
601
+ const missingExtractorPackages = withExtractor ? extractorPackages.filter((name)=>!dependencies[name]) : [];
602
+ return [
603
+ ...dependencies['@domain-first/handlers-rest'] ? [] : [
604
+ 'npm install @domain-first/handlers-rest'
587
605
  ],
588
- required: true
589
- }) : [
590
- 'client'
591
- ];
592
- const selected = await addPackageScripts(manifestFile, orvalScripts(rootFolder, targets));
593
- const document = node_path.posix.normalize(openapiPath.trim().replaceAll('\\', '/'));
594
- const withClient = targets.includes('client');
595
- for (const target of targets){
596
- const dataLayer = dataLayerFolder(rootFolder, target);
597
- const sharedMutator = 'hooks' === target && withClient;
598
- const mutatorPath = sharedMutator ? `${node_path.posix.relative(dataLayer, dataLayerFolder(rootFolder, 'client'))}/api-client/mutator.ts` : void 0;
599
- const configFile = new File(node_path.join(root, dataLayer, 'orval.config.ts'));
600
- const content = orvalConfig(rootFolder, document, withNext, target, mutatorPath);
601
- if (!configFile.exists || configFile.data !== content) configFile.data = content;
602
- for (const [name, fileContent] of [
603
- ...sharedMutator ? [] : [
604
- [
606
+ ...dependencies.tsx ? [] : [
607
+ 'npm install --save-dev tsx'
608
+ ],
609
+ ...missingExtractorPackages.length ? [
610
+ `npm install --save-dev ${missingExtractorPackages.join(' ')}`
611
+ ] : [],
612
+ ...withSwaggerPage && !dependencies['swagger-ui-react'] ? [
613
+ 'npm install swagger-ui-react'
614
+ ] : [],
615
+ ...withSwaggerPage && !dependencies['@types/swagger-ui-react'] ? [
616
+ 'npm install --save-dev @types/swagger-ui-react'
617
+ ] : [],
618
+ ...true === resolveJsonModule || null === resolveJsonModule ? [] : [
619
+ 'set "resolveJsonModule": true in compilerOptions of tsconfig.json — the Swagger UI page imports the OpenAPI document as JSON'
620
+ ],
621
+ ...describeScripts(selected, {
622
+ openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
623
+ }),
624
+ ...withSwaggerPage ? [
625
+ `SwaggerPage from ${swaggerPagePath(rootFolder)} shows ${splitPath(outputPath).join('/')} once it is generated — render it on a route of your app`
626
+ ] : [],
627
+ ...hasRestHandlers ? [] : [
628
+ `restHandlers appear in ${node_path.posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
629
+ ]
630
+ ];
631
+ };
632
+ const addGitignoreEntry = (root, entry)=>{
633
+ const gitignore = new File(node_path.join(root, '.gitignore'));
634
+ const ignored = gitignore.exists ? gitignore.data : '';
635
+ if (ignored.split(/\r?\n/).includes(entry)) return;
636
+ const newline = ignored.includes('\r\n') ? '\r\n' : '\n';
637
+ gitignore.update(`${ignored}${ignored && !ignored.endsWith('\n') ? newline : ''}${entry}${newline}`);
638
+ };
639
+ const dataLayerFolder = (rootFolder, target)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'hooks' === target ? 'presentation/react/data-layer' : 'presentation/data-layer');
640
+ const orvalScripts = (rootFolder, targets)=>({
641
+ 'client:orval': targets.map((target)=>`orval --config ${JSON.stringify(`${dataLayerFolder(rootFolder, target)}/orval.config.ts`)}`).join(' && ')
642
+ });
643
+ const orvalConfig = (rootFolder, openapiPath, withNext, target = 'hooks', mutatorPath = './api-client/mutator.ts')=>{
644
+ const inputPath = node_path.posix.relative(dataLayerFolder(rootFolder, target), openapiPath);
645
+ const baseUrl = withNext ? `
646
+ baseUrl: {
647
+ runtime: 'process.env.NEXT_PUBLIC_API_BASE_URL ?? ""'
648
+ },` : '';
649
+ const client = 'hooks' === target ? `
650
+ client: 'react-query',
651
+ httpClient: 'fetch',` : `
652
+ client: 'fetch',`;
653
+ const query = 'hooks' === target ? `,
654
+ query: {
655
+ version: 5
656
+ }` : '';
657
+ return `import { defineConfig } from 'orval';
658
+
659
+ export default defineConfig({
660
+ api: {
661
+ input: '${inputPath.startsWith('.') ? inputPath : `./${inputPath}`}',
662
+ output: {
663
+ mode: 'tags-split',
664
+ target: './orval',
665
+ schemas: './orval/model',${client}${baseUrl}
666
+ clean: true,
667
+ override: {
668
+ mutator: {
669
+ path: '${mutatorPath}',
670
+ name: 'customInstance'
671
+ },
672
+ fetch: {
673
+ includeHttpResponseReturnType: false
674
+ }${query}
675
+ }
676
+ }
677
+ }
678
+ });
679
+ `;
680
+ };
681
+ const orvalMutator = `/** Error of the generated requests, with the parsed response body. */
682
+ export class ApiError<Body = unknown> extends Error {
683
+ constructor(
684
+ public readonly status: number,
685
+ public readonly body: Body
686
+ ) {
687
+ super(\`API error \${status}\`);
688
+ this.name = 'ApiError';
689
+ }
690
+ }
691
+
692
+ /** Error type of the generated requests, typed per endpoint by Orval. */
693
+ export type ErrorType<Body> = ApiError<Body>;
694
+
695
+ /** Every generated request goes through here: add auth headers, token refresh, logging. */
696
+ export const customInstance = async <T>(
697
+ url: string,
698
+ init?: RequestInit
699
+ ): Promise<T> => {
700
+ const response = await fetch(url, init);
701
+ const text = await response.text();
702
+ const body = text ? JSON.parse(text) : undefined;
703
+
704
+ if (!response.ok) {
705
+ throw new ApiError(response.status, body);
706
+ }
707
+
708
+ return body as T;
709
+ };
710
+ `;
711
+ const queryProvider = `'use client';
712
+
713
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
714
+ import { type FC, type ReactNode, useState } from 'react';
715
+
716
+ export const QueryProvider: FC<{ children: ReactNode }> = ({ children }) => {
717
+ // One client per browser session; a module-level client would be shared between requests on the server
718
+ const [queryClient] = useState(() => new QueryClient());
719
+
720
+ return (
721
+ <QueryClientProvider client={queryClient}>
722
+ {children}
723
+ </QueryClientProvider>
724
+ );
725
+ };
726
+ `;
727
+ const openapiOutputPath = (root)=>{
728
+ const generator = new File(node_path.join(root, openapiScriptPath));
729
+ if (!generator.exists) return;
730
+ return generator.data.match(/outputFile:\s*{\s*path:\s*'([^']+)'/)?.[1];
731
+ };
732
+ const addOrval = async ()=>{
733
+ const { rootFolder, useReact } = ConfigFile.Instance.data;
734
+ const root = new ProjectRoot().path;
735
+ const manifestFile = new File(node_path.join(root, 'package.json'));
736
+ const manifest = JSON.parse(manifestFile.data);
737
+ const dependencies = {
738
+ ...manifest.dependencies,
739
+ ...manifest.devDependencies
740
+ };
741
+ const withNext = Boolean(dependencies.next);
742
+ const generatedOpenapiPath = openapiOutputPath(root);
743
+ const openapiPath = await input({
744
+ message: 'OpenAPI document path:',
745
+ default: generatedOpenapiPath ?? defaultOpenapiPath(withNext),
746
+ validate: (value)=>value.trim() ? true : 'Path is required'
747
+ });
748
+ const targets = useReact ? await prompts_checkbox({
749
+ message: 'Generate:',
750
+ choices: [
751
+ {
752
+ name: 'React Query hooks',
753
+ value: 'hooks',
754
+ checked: true
755
+ },
756
+ {
757
+ name: 'Typed API client',
758
+ value: 'client'
759
+ }
760
+ ],
761
+ required: true
762
+ }) : [
763
+ 'client'
764
+ ];
765
+ const selected = await addPackageScripts(manifestFile, orvalScripts(rootFolder, targets));
766
+ const document = node_path.posix.normalize(openapiPath.trim().replaceAll('\\', '/'));
767
+ const withClient = targets.includes('client');
768
+ for (const target of targets){
769
+ const dataLayer = dataLayerFolder(rootFolder, target);
770
+ const sharedMutator = 'hooks' === target && withClient;
771
+ const mutatorPath = sharedMutator ? `${node_path.posix.relative(dataLayer, dataLayerFolder(rootFolder, 'client'))}/api-client/mutator.ts` : void 0;
772
+ const configFile = new File(node_path.join(root, dataLayer, 'orval.config.ts'));
773
+ const content = orvalConfig(rootFolder, document, withNext, target, mutatorPath);
774
+ if (!configFile.exists || configFile.data !== content) configFile.data = content;
775
+ for (const [name, fileContent] of [
776
+ ...sharedMutator ? [] : [
777
+ [
605
778
  'api-client/mutator.ts',
606
779
  orvalMutator
607
780
  ]
@@ -768,7 +941,7 @@ const developmentPackages = [
768
941
  '@prisma/cli-engine'
769
942
  ];
770
943
  const prismaScripts = (rootFolder)=>{
771
- const config = JSON.stringify(node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'shared/infrastructure/prisma/prisma.config.ts'));
944
+ const config = JSON.stringify(node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'shared-kernel/infrastructure/prisma/prisma.config.ts'));
772
945
  const emit = `prisma contract emit --config ${config}`;
773
946
  return {
774
947
  'prisma:emit': emit,
@@ -835,14 +1008,14 @@ const addPrisma = async ()=>{
835
1008
  ...manifest.dependencies,
836
1009
  ...manifest.devDependencies
837
1010
  };
838
- const shared = node_path.resolve(root, config.rootFolder, 'shared');
1011
+ const shared = node_path.resolve(root, config.rootFolder, 'shared-kernel');
839
1012
  const prismaFolder = node_path.join(shared, 'infrastructure/prisma');
840
1013
  if (dependencies['@prisma/client'] || dependencies.prisma && !/^[~^]?8\./.test(dependencies.prisma) || dependencies['@prisma/orm-mongo'] || dependencies['@prisma/orm-sqlite'] || [
841
1014
  node_path.join(root, 'prisma/schema.prisma'),
842
1015
  node_path.join(prismaFolder, 'schema.prisma')
843
1016
  ].some((filePath)=>new File(filePath).exists)) throw new Error('This preset adds Prisma 8 for PostgreSQL. Migrate the existing Prisma setup separately before using it.');
844
1017
  const withService = await prompts_confirm({
845
- message: 'Create shared Prisma infrastructure service?',
1018
+ message: 'Create the Prisma infrastructure service in the Shared Kernel?',
846
1019
  default: true
847
1020
  });
848
1021
  const useByDefault = 'prisma' !== config.defaultPersistenceLayerImplementation && await prompts_confirm({
@@ -879,54 +1052,332 @@ const addPrisma = async ()=>{
879
1052
  })
880
1053
  ];
881
1054
  };
882
- const storybookFiles = (relativeProjectRoot)=>({
883
- 'main.ts': `import { resolve } from 'node:path';
884
- import react from '@vitejs/plugin-react';
885
- import type { StorybookConfig } from '@storybook/react-vite';
886
-
887
- const projectRoot = resolve(import.meta.dirname, ${JSON.stringify(relativeProjectRoot)});
888
-
889
- const config: StorybookConfig = {
890
- stories: ['../**/*.mdx', '../**/*.stories.@(ts|tsx)'],
891
- framework: {
892
- name: '@storybook/react-vite',
893
- options: {}
894
- },
895
- core: {
896
- disableTelemetry: true
897
- },
898
- async viteFinal(viteConfig) {
899
- const { mergeConfig } = await import('vite');
900
-
901
- return mergeConfig(viteConfig, {
902
- plugins: [react()],
903
- resolve: {
904
- alias: {
905
- '@': projectRoot
906
- }
907
- }
908
- });
909
- }
1055
+ const kindTitles = {
1056
+ repositories: 'Repositories',
1057
+ 'domain-services': 'Domain services',
1058
+ 'application-ports': 'Ports',
1059
+ 'application-services': 'Application services',
1060
+ queries: 'Queries',
1061
+ commands: 'Commands',
1062
+ 'use-cases': 'Use cases',
1063
+ 'infrastructure-services': 'Infrastructure services',
1064
+ 'presentation-services': 'Presentation services'
910
1065
  };
911
-
912
- export default config;
913
- `,
914
- 'preview.ts': `import type { Preview } from '@storybook/react-vite';
915
-
916
- const preview: Preview = {
917
- parameters: {
918
- controls: {
919
- matchers: {
920
- color: /(background|color)$/i,
921
- date: /Date$/i
922
- }
923
- }
924
- }
1066
+ const groupedChoices = (items, suggested = [])=>{
1067
+ const suggestedChoices = suggested.length ? [
1068
+ new Separator('── Suggested'),
1069
+ ...suggested.map((x)=>({
1070
+ name: x.label,
1071
+ value: x,
1072
+ checked: true
1073
+ }))
1074
+ ] : [];
1075
+ const kinds = [
1076
+ ...new Set([
1077
+ ...Object.keys(kindTitles),
1078
+ ...items.map((x)=>x.module.kind)
1079
+ ])
1080
+ ];
1081
+ return [
1082
+ ...suggestedChoices,
1083
+ ...kinds.flatMap((kind)=>{
1084
+ const group = items.filter((x)=>x.module.kind === kind && !suggested.includes(x));
1085
+ return group.length ? [
1086
+ new Separator(`── ${kindTitles[kind] ?? kind}`),
1087
+ ...group.map((x)=>({
1088
+ name: x.label,
1089
+ value: x
1090
+ }))
1091
+ ] : [];
1092
+ })
1093
+ ];
925
1094
  };
926
-
927
- export default preview;
928
- `
929
- });
1095
+ const groupedPageSize = 20;
1096
+ const contextAndSharedModules = (boundedContextFolder)=>{
1097
+ const sharedFolder = new Folder(new ProjectRoot().path).subitem([
1098
+ ConfigFile.Instance.data.rootFolder,
1099
+ 'shared-kernel'
1100
+ ]);
1101
+ const isShared = sharedFolder.path === boundedContextFolder.path;
1102
+ return [
1103
+ ...findWiredModules(boundedContextFolder.path).map((x)=>({
1104
+ module: x,
1105
+ label: x.typeName
1106
+ })),
1107
+ ...isShared ? [] : findWiredModules(sharedFolder.path).map((x)=>({
1108
+ module: x,
1109
+ label: `${x.typeName} (shared-kernel)`
1110
+ }))
1111
+ ];
1112
+ };
1113
+ const promptDependencies = async (boundedContextFolder, consumer, implementations = consumer.implementations, customWiring)=>{
1114
+ const options = contextAndSharedModules(boundedContextFolder);
1115
+ let asked = false;
1116
+ for (const implementation of implementations){
1117
+ const available = availableDependencies(consumer, implementation, options.map((x)=>x.module));
1118
+ const candidates = options.filter((x)=>available.includes(x.module));
1119
+ if (!candidates.length) continue;
1120
+ asked = true;
1121
+ const type = wiring_implementationType(consumer, implementation);
1122
+ const suggested = type ? candidates.filter((x)=>isSuggestedFor(x.module, type)) : [];
1123
+ const dependencies = await prompts_checkbox({
1124
+ message: consumer.branched ? `Dependencies for ${implementation.className}:` : 'Dependencies:',
1125
+ choices: groupedChoices(candidates, suggested),
1126
+ pageSize: groupedPageSize,
1127
+ loop: false
1128
+ });
1129
+ const defaultWired = dependencies.map((x)=>x.module).filter((x)=>!customWiring?.(implementation, x));
1130
+ if (defaultWired.length) wireDependencies(consumer, implementation, defaultWired);
1131
+ }
1132
+ return asked;
1133
+ };
1134
+ const wireNewModuleDependencies = async (boundedContextFolder, wireFile, customWiring)=>{
1135
+ const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
1136
+ if (consumer) await promptDependencies(boundedContextFolder, consumer, consumer.implementations, customWiring);
1137
+ };
1138
+ const wireDependency = async (boundedContextFolder)=>{
1139
+ const modules = findWiredModules(boundedContextFolder.path);
1140
+ if (!modules.length) return void console.log('No wired modules here yet.');
1141
+ const { module: consumer, implementation } = await prompts_select({
1142
+ message: 'Module:',
1143
+ choices: groupedChoices(modules.flatMap((x)=>x.implementations.map((implementation)=>{
1144
+ const type = wiring_implementationType(x, implementation);
1145
+ return {
1146
+ module: x,
1147
+ label: type ? `${x.typeName} (${type})` : x.typeName,
1148
+ implementation
1149
+ };
1150
+ }))),
1151
+ pageSize: groupedPageSize,
1152
+ loop: false
1153
+ });
1154
+ if (!await promptDependencies(boundedContextFolder, consumer, [
1155
+ implementation
1156
+ ])) console.log('No dependencies available for this module.');
1157
+ };
1158
+ const promptEndpointHandler = async (boundedContextFolder)=>{
1159
+ const handlers = findWiredModules(boundedContextFolder.path).filter((x)=>[
1160
+ 'queries',
1161
+ 'commands',
1162
+ 'use-cases'
1163
+ ].includes(x.kind)).map((x)=>({
1164
+ module: x,
1165
+ label: x.typeName
1166
+ }));
1167
+ return handlers.length ? (await prompts_select({
1168
+ message: 'Handler:',
1169
+ choices: groupedChoices(handlers),
1170
+ pageSize: groupedPageSize,
1171
+ loop: false
1172
+ })).module : void 0;
1173
+ };
1174
+ const createPresentationService = (boundedContextFolder, name, classFile)=>{
1175
+ const naming = new UnknownFormatNaming(name);
1176
+ const className = `${naming.ClassName}PresentationService`;
1177
+ const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
1178
+ const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
1179
+ const wiringFolder = boundedContextFolder.subitem([
1180
+ 'wiring',
1181
+ 'presentation-services'
1182
+ ]);
1183
+ const presentationServicesFolder = boundedContextFolder.subitem([
1184
+ 'presentation',
1185
+ 'services'
1186
+ ]);
1187
+ presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.ts`, classFile?.(className) ?? `
1188
+ export class ${className} {
1189
+
1190
+ }
1191
+ `.trim());
1192
+ if (scaffoldUnitTests) presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.spec.ts`, `
1193
+ import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
1194
+ ${withWiring ? `import { type ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'
1195
+ import { wire${naming.ClassName}PresentationService } from '../../wiring/presentation-services/wire-${naming.fileName}-presentation-service'` : `import { ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'`}
1196
+
1197
+ let ${naming.variableName}PresentationService: ${naming.ClassName}PresentationService
1198
+
1199
+ beforeEach(() => {
1200
+ ${naming.variableName}PresentationService = ${withWiring ? `wire${naming.ClassName}PresentationService()` : `new ${naming.ClassName}PresentationService()`}
1201
+ })
1202
+
1203
+ describe('${naming.withSpaces}', () => {
1204
+ test('can be ${withWiring ? 'wired' : 'created'}', () => {
1205
+ expect(${naming.variableName}PresentationService).toBeDefined()
1206
+ })
1207
+ })
1208
+ `.trim());
1209
+ if (withWiring) return wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
1210
+ import { wireClass } from '@domain-first/wire'
1211
+ import { ${naming.ClassName}PresentationService } from '../../presentation/services/${naming.fileName}-presentation-service'
1212
+
1213
+ export const wire${naming.ClassName}PresentationService = wireClass(
1214
+ ${naming.ClassName}PresentationService,
1215
+ []
1216
+ )
1217
+ `.trim());
1218
+ };
1219
+ const scaffoldNewPresentationService = async (boundedContextFolder)=>{
1220
+ const name = await input({
1221
+ message: 'Name: '
1222
+ });
1223
+ const wireFile = createPresentationService(boundedContextFolder, name);
1224
+ if (wireFile) await wireNewModuleDependencies(boundedContextFolder, wireFile);
1225
+ };
1226
+ const rest_endpoint_generator_name = 'rest-endpoint-generator';
1227
+ const scaffoldRestEndpointGenerator = (sharedFolder, { withNextAdapter = false } = {})=>createPresentationService(sharedFolder, rest_endpoint_generator_name, (className)=>{
1228
+ const adapter = withNextAdapter ? 'nextAdapter' : 'adapter';
1229
+ return `
1230
+ import {
1231
+ ${withNextAdapter ? '' : ' type Adapter,\n'} type EndpointGenerator,
1232
+ createEndpoint,
1233
+ invalidRequest
1234
+ } from '@domain-first/handlers-rest'
1235
+ ${withNextAdapter ? "import { nextAdapter } from '@domain-first/handlers-next'" : `
1236
+ /**
1237
+ * The adapter of your HTTP framework.
1238
+ */
1239
+ const adapter = undefined as unknown as Adapter<any[], any>`}
1240
+
1241
+ export class ${className} {
1242
+ get withoutGuards(): EndpointGenerator {
1243
+ return createEndpoint({
1244
+ errors: [invalidRequest()]
1245
+ })(${adapter}) as EndpointGenerator
1246
+ }
1247
+ }
1248
+ `.trim();
1249
+ });
1250
+ const findRestEndpointGenerator = (sharedFolder)=>{
1251
+ const typeFile = node_path.join(sharedFolder.path, 'presentation', 'services', `${rest_endpoint_generator_name}-presentation-service.ts`);
1252
+ if (!new File(typeFile).exists) return;
1253
+ return {
1254
+ typeName: 'RestEndpointGeneratorPresentationService',
1255
+ typeFile,
1256
+ wireName: 'wireRestEndpointGeneratorPresentationService',
1257
+ wireFile: node_path.join(sharedFolder.path, 'wiring', 'presentation-services', `wire-${rest_endpoint_generator_name}-presentation-service.ts`)
1258
+ };
1259
+ };
1260
+ const nextAppFolder = (root)=>[
1261
+ 'app',
1262
+ 'src/app'
1263
+ ].find((folder)=>new Folder(node_path.join(root, folder)).exists) ?? 'app';
1264
+ const nextRoutePath = (root)=>node_path.posix.join(nextAppFolder(root), 'api/[...path]/route.ts');
1265
+ const nextRoute = (restHandlersImport)=>`
1266
+ import { nextEndpoints } from '@domain-first/handlers-next'
1267
+ ${restHandlersImport ? `import { restHandlers } from '${restHandlersImport}'
1268
+
1269
+ const handler = nextEndpoints(restHandlers)` : `
1270
+ /**
1271
+ * Pass the endpoints' handle here; their paths are relative to this route's folder.
1272
+ */
1273
+ const handler = nextEndpoints([])`}
1274
+
1275
+ export const GET = handler
1276
+ export const POST = handler
1277
+ export const PUT = handler
1278
+ export const PATCH = handler
1279
+ export const DELETE = handler
1280
+ `.trim();
1281
+ const scaffoldNextRoute = (root)=>{
1282
+ const { rootFolder, domainFirstPackages } = ConfigFile.Instance.data;
1283
+ const routePath = nextRoutePath(root);
1284
+ const routeFile = node_path.join(root, routePath);
1285
+ if (new File(routeFile).exists) return [];
1286
+ if (!domainFirstPackages.includes('@domain-first/wire')) {
1287
+ new File(routeFile).data = nextRoute(void 0);
1288
+ return [];
1289
+ }
1290
+ const restFolder = new Folder(root).subitem([
1291
+ rootFolder,
1292
+ 'presentation',
1293
+ 'rest'
1294
+ ]);
1295
+ new File(routeFile).data = nextRoute(relativeImport(routeFile, restFolder.path));
1296
+ return new File(node_path.join(restFolder.path, 'index.ts')).exists ? [] : [
1297
+ `${routePath} serves restHandlers from ${node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/rest/index.ts')}, which appears with the first REST endpoint — generate one with df-scaffold (Presentation → New Handlers-REST Endpoint) and the route compiles`
1298
+ ];
1299
+ };
1300
+ const askNextAdapter = async ()=>hasDependency('next') && await prompts_confirm({
1301
+ message: 'Use Next adapter for REST endpoints'
1302
+ });
1303
+ const scaffoldRestEndpointGeneratorFiles = ({ withNextAdapter })=>{
1304
+ const root = new ProjectRoot().path;
1305
+ const generatorExisted = restEndpointGeneratorApplied();
1306
+ const routeNotes = withoutOverwrites(()=>{
1307
+ scaffoldRestEndpointGenerator(new Folder(root).subitem([
1308
+ ConfigFile.Instance.data.rootFolder,
1309
+ 'shared-kernel'
1310
+ ]), {
1311
+ withNextAdapter
1312
+ });
1313
+ return withNextAdapter ? scaffoldNextRoute(root) : [];
1314
+ });
1315
+ if (!withNextAdapter) return [];
1316
+ return [
1317
+ ...missingPackages([
1318
+ '@domain-first/handlers-next'
1319
+ ]),
1320
+ ...routeNotes,
1321
+ ...generatorExisted ? [
1322
+ 'the existing endpoint generator was kept — pass nextAdapter from @domain-first/handlers-next to its createEndpoint calls'
1323
+ ] : []
1324
+ ];
1325
+ };
1326
+ const addRestEndpointGenerator = async ()=>scaffoldRestEndpointGeneratorFiles({
1327
+ withNextAdapter: await askNextAdapter()
1328
+ });
1329
+ const restEndpointGeneratorApplied = ()=>Boolean(findRestEndpointGenerator(new Folder(new ProjectRoot().path).subitem([
1330
+ ConfigFile.Instance.data.rootFolder,
1331
+ 'shared-kernel'
1332
+ ])));
1333
+ const storybookFiles = (relativeProjectRoot)=>({
1334
+ 'main.ts': `import { resolve } from 'node:path';
1335
+ import react from '@vitejs/plugin-react';
1336
+ import type { StorybookConfig } from '@storybook/react-vite';
1337
+
1338
+ const projectRoot = resolve(import.meta.dirname, ${JSON.stringify(relativeProjectRoot)});
1339
+
1340
+ const config: StorybookConfig = {
1341
+ stories: ['../**/*.mdx', '../**/*.stories.@(ts|tsx)'],
1342
+ framework: {
1343
+ name: '@storybook/react-vite',
1344
+ options: {}
1345
+ },
1346
+ core: {
1347
+ disableTelemetry: true
1348
+ },
1349
+ async viteFinal(viteConfig) {
1350
+ const { mergeConfig } = await import('vite');
1351
+
1352
+ return mergeConfig(viteConfig, {
1353
+ plugins: [react()],
1354
+ resolve: {
1355
+ alias: {
1356
+ '@': projectRoot
1357
+ }
1358
+ }
1359
+ });
1360
+ }
1361
+ };
1362
+
1363
+ export default config;
1364
+ `,
1365
+ 'preview.ts': `import type { Preview } from '@storybook/react-vite';
1366
+
1367
+ const preview: Preview = {
1368
+ parameters: {
1369
+ controls: {
1370
+ matchers: {
1371
+ color: /(background|color)$/i,
1372
+ date: /Date$/i
1373
+ }
1374
+ }
1375
+ }
1376
+ };
1377
+
1378
+ export default preview;
1379
+ `
1380
+ });
930
1381
  const storybookScripts = (rootFolder)=>{
931
1382
  const folder = node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react');
932
1383
  const quote = (value)=>JSON.stringify(value);
@@ -1122,7 +1573,7 @@ const addTestcontainers = async ()=>{
1122
1573
  ...manifest.devDependencies
1123
1574
  };
1124
1575
  const selected = await addPackageScripts(manifestFile, testcontainersScripts);
1125
- const withPrisma = new File(node_path.resolve(root, config.rootFolder, 'shared/infrastructure/prisma/prisma.config.ts')).exists;
1576
+ const withPrisma = new File(node_path.resolve(root, config.rootFolder, 'shared-kernel/infrastructure/prisma/prisma.config.ts')).exists;
1126
1577
  const migrationCommand = withPrisma ? `npx ${prismaScripts(config.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}` : void 0;
1127
1578
  const folder = node_path.join(root, integrationFolder);
1128
1579
  testcontainers_stageFile(node_path.join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
@@ -1185,13 +1636,13 @@ export default defineConfig({
1185
1636
  exclude: [...configDefaults.exclude, 'specs/e2e/**', 'specs/integration/**'],
1186
1637
  coverage: {
1187
1638
  provider: 'v8',
1188
- include: [${folder('bounded-contexts/**/*.ts')}, ${folder('shared/**/*.ts')}],
1639
+ include: [${folder('bounded-contexts/**/*.ts')}, ${folder('shared-kernel/**/*.ts')}],
1189
1640
  exclude: [
1190
1641
  '**/*.spec.ts',
1191
- ${folder('shared/infrastructure/**')},
1642
+ ${folder('shared-kernel/infrastructure/**')},
1192
1643
  ${folder('bounded-contexts/*/infrastructure/**')},
1193
1644
  ${folder('bounded-contexts/*/presentation/rest/**')},
1194
- ${folder('shared/wiring/**')},
1645
+ ${folder('shared-kernel/wiring/**')},
1195
1646
  ${folder('bounded-contexts/*/wiring/**')}
1196
1647
  ],
1197
1648
  reporter: [['text', { skipFull: true }], 'html']
@@ -1236,513 +1687,149 @@ const addVitest = async ()=>{
1236
1687
  })
1237
1688
  ];
1238
1689
  };
1239
- const withHandlersRest = ()=>ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers-rest');
1240
- const created = (...segments)=>new File(node_path.join(new ProjectRoot().path, ...segments)).exists;
1241
- const createdInRoot = (...segments)=>created(ConfigFile.Instance.data.rootFolder, ...segments);
1242
- const integrations = [
1243
- {
1244
- name: 'Storybook (React + Vite)',
1245
- group: 'frontend',
1246
- run: addStorybook,
1247
- applied: ()=>createdInRoot('presentation/react/.storybook/main.ts')
1248
- },
1249
- {
1250
- name: 'Prisma 8 (PostgreSQL, RC)',
1251
- group: 'backend',
1252
- run: addPrisma,
1253
- applied: ()=>createdInRoot('shared/infrastructure/prisma/prisma.config.ts')
1254
- },
1255
- {
1256
- name: 'Vitest',
1257
- group: 'backend',
1258
- run: addVitest,
1259
- applied: ()=>created('vitest.config.ts')
1260
- },
1261
- {
1262
- name: 'Playwright',
1263
- group: 'frontend',
1264
- run: addPlaywright,
1265
- applied: ()=>created('playwright.config.ts')
1266
- },
1267
- {
1268
- name: 'Integration tests (Testcontainers, PostgreSQL)',
1269
- group: 'backend',
1270
- run: addTestcontainers,
1271
- applied: ()=>created('specs/integration/vitest.config.ts')
1272
- },
1273
- {
1274
- name: 'OpenAPI',
1275
- group: 'backend',
1276
- run: addOpenapi,
1277
- available: ()=>withHandlersRest(),
1278
- applied: ()=>created(openapiScriptPath)
1279
- },
1280
- {
1281
- name: 'Orval (API client)',
1282
- group: 'frontend',
1283
- run: addOrval,
1284
- available: ()=>withHandlersRest(),
1285
- applied: ()=>createdInRoot('presentation/react/data-layer/orval.config.ts') || createdInRoot('presentation/data-layer/orval.config.ts')
1286
- },
1287
- {
1288
- name: 'Missing domain-first packages',
1289
- group: 'backend',
1290
- run: missingDomainFirstPackages,
1291
- applied: ()=>!missingDomainFirstPackages().length
1292
- }
1293
- ];
1294
- const addIntegration = async ()=>{
1295
- const available = integrations.filter(({ available })=>available?.() ?? true).map((value)=>({
1296
- value,
1297
- applied: value.applied()
1298
- }));
1299
- const section = (title, applied)=>{
1300
- const items = [
1301
- 'backend',
1302
- 'frontend'
1303
- ].flatMap((group)=>available.filter((item)=>item.applied === applied && item.value.group === group));
1304
- return items.length ? [
1305
- new Separator(title),
1306
- ...items.map(({ value })=>({
1307
- name: `${value.name} · ${value.group}`,
1308
- value
1309
- }))
1310
- ] : [];
1311
- };
1312
- const choices = [
1313
- ...section('New integrations', false),
1314
- ...section('Already applied (select to reapply)', true)
1315
- ];
1316
- const selected = await prompts_checkbox({
1317
- message: 'Integrations:',
1318
- choices,
1319
- pageSize: choices.length
1320
- });
1321
- const nextSteps = [];
1322
- for (const integration of integrations.filter((value)=>selected.includes(value)))nextSteps.push(...await integration.run());
1323
- if (await savePendingChanges()) printNextSteps(nextSteps);
1324
- };
1325
- const inMemoryImplementationType = 'in-memory';
1326
- const in_memory_db_className = 'InMemoryDbInfrastructureService';
1327
- const wireName = 'wireInMemoryDbInfrastructureService';
1328
- const parameterName = 'inMemoryDbInfrastructureService';
1329
- const inMemoryDbService = `type Entry = {
1330
- id: unknown;
1331
- item: any;
1332
- };
1333
-
1334
- declare global {
1335
- var ___SHARED_IN_MEMORY_DB___: Record<string, Array<Entry>> | undefined;
1336
- }
1337
-
1338
- type Section<T, TId> = {
1339
- all: (predicate?: (x: T) => boolean) => T[];
1340
- first: (predicate: (x: T) => boolean) => T | null;
1341
- withId: (id: TId) => T | null;
1342
- lastAddedItem: () => T | null;
1343
- save: (payload: T extends { id: TId } ? T : [TId, T]) => void;
1344
- deleteById: (id: TId) => void;
1345
- delete: (predicate: (x: T) => boolean) => void;
1346
- };
1347
-
1348
- type IdsAreEqual<TId> = (a: TId, b: TId) => boolean;
1349
-
1350
- const comparisonMethodNames = ['equals', 'same', 'isSame', 'isEqual'] as const;
1351
-
1352
- const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
1353
- if (typeof a !== 'object' || a === null) {
1354
- return Object.is(a, b);
1355
- }
1356
-
1357
- for (const methodName of comparisonMethodNames) {
1358
- const method: unknown = (a as Record<string, unknown>)[methodName];
1359
- if (typeof method === 'function') {
1360
- return Boolean(method.call(a, b));
1361
- }
1362
- }
1363
-
1364
- return Object.is(a, b);
1365
- };
1366
-
1367
- const hasId = (x: unknown): x is { id: unknown } =>
1368
- typeof x === 'object' && x !== null && 'id' in x;
1369
-
1370
- export class InMemoryDbInfrastructureService {
1371
- protected section<T extends { id: unknown }>(
1372
- key: string,
1373
- idsAreEqual?: IdsAreEqual<T['id']>
1374
- ): Section<T, T['id']>;
1375
- protected section<T, TId>(
1376
- key: string,
1377
- idsAreEqual?: IdsAreEqual<TId>
1378
- ): Section<T, TId>;
1379
- protected section<T, TId>(
1380
- key: string,
1381
- idsAreEqual: IdsAreEqual<TId> = defaultIdsAreEqual
1382
- ): Section<T, TId> {
1383
- if (!globalThis.___SHARED_IN_MEMORY_DB___) {
1384
- globalThis.___SHARED_IN_MEMORY_DB___ = {};
1385
- }
1386
-
1387
- if (!globalThis.___SHARED_IN_MEMORY_DB___[key]) {
1388
- globalThis.___SHARED_IN_MEMORY_DB___[key] = [];
1389
- }
1390
-
1391
- const items = (): T[] =>
1392
- globalThis.___SHARED_IN_MEMORY_DB___![key].map(
1393
- (entry) => entry.item
1394
- );
1395
-
1396
- return {
1397
- all: (predicate: (x: T) => boolean = () => true): T[] =>
1398
- items().filter(predicate),
1399
- first: (predicate: (x: T) => boolean): T | null =>
1400
- items().find(predicate) ?? null,
1401
- withId: (id: TId): T | null =>
1402
- items().find(
1403
- (x: T) => hasId(x) && idsAreEqual(x.id as TId, id)
1404
- ) ?? null,
1405
- lastAddedItem: (): T | null =>
1406
- globalThis.___SHARED_IN_MEMORY_DB___![key].at(-1)?.item ?? null,
1407
- save: (payload: T extends { id: TId } ? T : [TId, T]) => {
1408
- const id = Array.isArray(payload) ? payload[0] : payload.id;
1409
- const item = Array.isArray(payload) ? payload[1] : payload;
1410
- const entries = globalThis.___SHARED_IN_MEMORY_DB___![key];
1411
- const existing = entries.find((entry) =>
1412
- idsAreEqual(entry.id as TId, id)
1413
- );
1414
- if (existing) {
1415
- existing.item = item;
1416
- return;
1417
- }
1418
- entries.push({ id, item });
1419
- },
1420
- deleteById: (id: TId) => {
1421
- globalThis.___SHARED_IN_MEMORY_DB___![key] =
1422
- globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
1423
- (entry) => !idsAreEqual(entry.id as TId, id)
1424
- );
1425
- },
1426
- delete: (predicate: (x: T) => boolean) => {
1427
- globalThis.___SHARED_IN_MEMORY_DB___![key] =
1428
- globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
1429
- (entry) => !predicate(entry.item)
1430
- );
1431
- }
1432
- };
1433
- }
1434
- }
1435
- `;
1436
- const inMemoryDbWiring = `import { wireClass } from '@domain-first/wire';
1437
- import { InMemoryDbInfrastructureService } from '../../infrastructure/services/in-memory-db-infrastructure-service';
1438
-
1439
- export const wireInMemoryDbInfrastructureService = wireClass(
1440
- InMemoryDbInfrastructureService,
1441
- []
1442
- );
1443
- `;
1444
- const inMemoryDbSpec = (testingLibrary, withWiring)=>`
1445
- import { describe, test, expect, beforeEach } from '${testingLibrary}'
1446
- ${withWiring ? `import { type InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'
1447
- import { wireInMemoryDbInfrastructureService } from '../../wiring/infrastructure-services/wire-in-memory-db-infrastructure-service'` : "import { InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'"}
1448
-
1449
- let inMemoryDbInfrastructureService: InMemoryDbInfrastructureService
1450
-
1451
- beforeEach(() => {
1452
- inMemoryDbInfrastructureService = ${withWiring ? 'wireInMemoryDbInfrastructureService()' : 'new InMemoryDbInfrastructureService()'}
1453
- })
1454
-
1455
- describe('in memory db', () => {
1456
- test('can be ${withWiring ? 'wired' : 'created'}', () => {
1457
- expect(inMemoryDbInfrastructureService).toBeDefined()
1458
- })
1459
- })
1460
- `.trim();
1461
- const in_memory_db_withWiring = ()=>ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
1462
- const in_memory_db_sharedFolder = ()=>new Folder(new ProjectRoot().path).subitem([
1463
- ConfigFile.Instance.data.rootFolder,
1464
- 'shared'
1465
- ]);
1466
- const serviceFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
1467
- 'infrastructure',
1468
- 'services',
1469
- 'in-memory-db-infrastructure-service.ts'
1470
- ]);
1471
- const in_memory_db_wireFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
1472
- 'wiring',
1473
- 'infrastructure-services',
1474
- 'wire-in-memory-db-infrastructure-service.ts'
1475
- ]);
1476
- const scaffoldInMemoryDb = (shared)=>{
1477
- const { testingLibrary } = ConfigFile.Instance.data;
1478
- const servicesFolder = shared.subitem([
1479
- 'infrastructure',
1480
- 'services'
1481
- ]);
1482
- servicesFolder.createFile('in-memory-db-infrastructure-service.ts', inMemoryDbService);
1483
- if (testingLibrary) servicesFolder.createFile('in-memory-db-infrastructure-service.spec.ts', inMemoryDbSpec(testingLibrary, in_memory_db_withWiring()));
1484
- if (in_memory_db_withWiring()) shared.subitem([
1485
- 'wiring',
1486
- 'infrastructure-services'
1487
- ]).createFile('wire-in-memory-db-infrastructure-service.ts', inMemoryDbWiring);
1488
- };
1489
- const usesInMemoryDb = (implementationType)=>Boolean(ConfigFile.Instance.data.withInMemoryDb) && new UnknownFormatNaming(implementationType).fileName === inMemoryImplementationType && serviceFile().exists && (!in_memory_db_withWiring() || in_memory_db_wireFile().exists);
1490
- const plural = (word)=>{
1491
- if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
1492
- if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
1493
- return `${word}s`;
1494
- };
1495
- const addInMemoryDbSection = (typeNaming, typeImportTarget)=>{
1496
- const file = serviceFile();
1497
- const sectionNaming = new UnknownFormatNaming(plural(typeNaming.fileName));
1498
- const field = sectionNaming.variableName;
1499
- if (new RegExp(`\\b${field}\\s*=\\s*this\\.section\\b`).test(file.data)) return field;
1500
- const withImport = addImport(file.data, `import type { ${typeNaming.ClassName} } from '${relativeImport(file.path, typeImportTarget)}';`);
1501
- file.update(addClassMember(withImport, in_memory_db_className, `${field} = this.section<${typeNaming.ClassName}>('${sectionNaming.fileName.toUpperCase()}');`));
1502
- return field;
1503
- };
1504
- const inMemoryDbTypeImport = (fromFile)=>`import type { ${in_memory_db_className} } from '${relativeImport(fromFile, serviceFile().path)}'`;
1505
- const inMemoryDbSectionMembers = (field, derived)=>`
1506
- private readonly data: ${in_memory_db_className}['${field}']
1507
-
1508
- constructor(${parameterName}: ${in_memory_db_className}) {
1509
- ${derived ? 'super()\n ' : ''}this.data = ${parameterName}.${field}
1510
- }
1511
- `.trim();
1512
- const keepInMemoryDbSection = (classFile, field)=>{
1513
- classFile.update(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)).replace('constructor() {}', inMemoryDbSectionMembers(field, false)));
1514
- };
1515
- const isInMemoryDb = (module)=>module.wireName === wireName;
1516
- const injectInMemoryDb = (classFile, implementationName)=>{
1517
- classFile.update(addConstructorParameters(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)), implementationName, [
1518
- `private readonly ${parameterName}: ${in_memory_db_className}`
1519
- ]));
1520
- };
1521
- const wireInMemoryDb = (consumerWireFile, implementationName)=>{
1522
- consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${wireName} } from '${relativeImport(consumerWireFile.path, in_memory_db_wireFile().path)}'`), implementationName, [
1523
- wireName
1524
- ]));
1525
- };
1526
- const passInMemoryDb = (specFile, implementationName)=>{
1527
- specFile.update(addImport(specFile.data, `import { ${in_memory_db_className} } from '${relativeImport(specFile.path, serviceFile().path)}'`).replace(`new ${implementationName}()`, `new ${implementationName}(new ${in_memory_db_className}())`));
1528
- };
1529
- const kindTitles = {
1530
- repositories: 'Repositories',
1531
- 'domain-services': 'Domain services',
1532
- 'application-ports': 'Ports',
1533
- 'application-services': 'Application services',
1534
- queries: 'Queries',
1535
- commands: 'Commands',
1536
- 'use-cases': 'Use cases',
1537
- 'infrastructure-services': 'Infrastructure services',
1538
- 'presentation-services': 'Presentation services'
1539
- };
1540
- const groupedChoices = (items, suggested = [])=>{
1541
- const suggestedChoices = suggested.length ? [
1542
- new Separator('── Suggested'),
1543
- ...suggested.map((x)=>({
1544
- name: x.label,
1545
- value: x,
1546
- checked: true
1547
- }))
1548
- ] : [];
1549
- const kinds = [
1550
- ...new Set([
1551
- ...Object.keys(kindTitles),
1552
- ...items.map((x)=>x.module.kind)
1553
- ])
1554
- ];
1555
- return [
1556
- ...suggestedChoices,
1557
- ...kinds.flatMap((kind)=>{
1558
- const group = items.filter((x)=>x.module.kind === kind && !suggested.includes(x));
1559
- return group.length ? [
1560
- new Separator(`── ${kindTitles[kind] ?? kind}`),
1561
- ...group.map((x)=>({
1562
- name: x.label,
1563
- value: x
1564
- }))
1565
- ] : [];
1566
- })
1567
- ];
1568
- };
1569
- const groupedPageSize = 20;
1570
- const contextAndSharedModules = (boundedContextFolder)=>{
1571
- const sharedFolder = new Folder(new ProjectRoot().path).subitem([
1572
- ConfigFile.Instance.data.rootFolder,
1573
- 'shared'
1574
- ]);
1575
- const isShared = sharedFolder.path === boundedContextFolder.path;
1576
- return [
1577
- ...findWiredModules(boundedContextFolder.path).map((x)=>({
1578
- module: x,
1579
- label: x.typeName
1580
- })),
1581
- ...isShared ? [] : findWiredModules(sharedFolder.path).map((x)=>({
1582
- module: x,
1583
- label: `${x.typeName} (shared)`
1584
- }))
1585
- ];
1586
- };
1587
- const promptDependencies = async (boundedContextFolder, consumer, implementations = consumer.implementations, customWiring)=>{
1588
- const options = contextAndSharedModules(boundedContextFolder);
1589
- let asked = false;
1590
- for (const implementation of implementations){
1591
- const available = availableDependencies(consumer, implementation, options.map((x)=>x.module));
1592
- const candidates = options.filter((x)=>available.includes(x.module));
1593
- if (!candidates.length) continue;
1594
- asked = true;
1595
- const type = wiring_implementationType(consumer, implementation);
1596
- const suggested = type ? candidates.filter((x)=>isSuggestedFor(x.module, type)) : [];
1597
- const dependencies = await prompts_checkbox({
1598
- message: consumer.branched ? `Dependencies for ${implementation.className}:` : 'Dependencies:',
1599
- choices: groupedChoices(candidates, suggested),
1600
- pageSize: groupedPageSize,
1601
- loop: false
1602
- });
1603
- const defaultWired = dependencies.map((x)=>x.module).filter((x)=>!customWiring?.(implementation, x));
1604
- if (defaultWired.length) wireDependencies(consumer, implementation, defaultWired);
1605
- }
1606
- return asked;
1607
- };
1608
- const wireNewModuleDependencies = async (boundedContextFolder, wireFile, customWiring)=>{
1609
- const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
1610
- if (consumer) await promptDependencies(boundedContextFolder, consumer, consumer.implementations, customWiring);
1611
- };
1612
- const wireDependency = async (boundedContextFolder)=>{
1613
- const modules = findWiredModules(boundedContextFolder.path);
1614
- if (!modules.length) return void console.log('No wired modules here yet.');
1615
- const { module: consumer, implementation } = await prompts_select({
1616
- message: 'Module:',
1617
- choices: groupedChoices(modules.flatMap((x)=>x.implementations.map((implementation)=>{
1618
- const type = wiring_implementationType(x, implementation);
1619
- return {
1620
- module: x,
1621
- label: type ? `${x.typeName} (${type})` : x.typeName,
1622
- implementation
1623
- };
1624
- }))),
1625
- pageSize: groupedPageSize,
1626
- loop: false
1627
- });
1628
- if (!await promptDependencies(boundedContextFolder, consumer, [
1629
- implementation
1630
- ])) console.log('No dependencies available for this module.');
1631
- };
1632
- const promptEndpointHandler = async (boundedContextFolder)=>{
1633
- const handlers = findWiredModules(boundedContextFolder.path).filter((x)=>[
1634
- 'queries',
1635
- 'commands',
1636
- 'use-cases'
1637
- ].includes(x.kind)).map((x)=>({
1638
- module: x,
1639
- label: x.typeName
1640
- }));
1641
- return handlers.length ? (await prompts_select({
1642
- message: 'Handler:',
1643
- choices: groupedChoices(handlers),
1644
- pageSize: groupedPageSize,
1645
- loop: false
1646
- })).module : void 0;
1647
- };
1648
- const createPresentationService = (boundedContextFolder, name, classFile)=>{
1649
- const naming = new UnknownFormatNaming(name);
1650
- const className = `${naming.ClassName}PresentationService`;
1651
- const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
1652
- const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
1653
- const wiringFolder = boundedContextFolder.subitem([
1654
- 'wiring',
1655
- 'presentation-services'
1656
- ]);
1657
- const presentationServicesFolder = boundedContextFolder.subitem([
1658
- 'presentation',
1659
- 'services'
1660
- ]);
1661
- presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.ts`, classFile?.(className) ?? `
1662
- export class ${className} {
1663
-
1664
- }
1665
- `.trim());
1666
- if (scaffoldUnitTests) presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.spec.ts`, `
1667
- import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
1668
- ${withWiring ? `import { type ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'
1669
- import { wire${naming.ClassName}PresentationService } from '../../wiring/presentation-services/wire-${naming.fileName}-presentation-service'` : `import { ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'`}
1670
-
1671
- let ${naming.variableName}PresentationService: ${naming.ClassName}PresentationService
1672
-
1673
- beforeEach(() => {
1674
- ${naming.variableName}PresentationService = ${withWiring ? `wire${naming.ClassName}PresentationService()` : `new ${naming.ClassName}PresentationService()`}
1675
- })
1676
-
1677
- describe('${naming.withSpaces}', () => {
1678
- test('can be ${withWiring ? 'wired' : 'created'}', () => {
1679
- expect(${naming.variableName}PresentationService).toBeDefined()
1680
- })
1681
- })
1682
- `.trim());
1683
- if (withWiring) return wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
1684
- import { wireClass } from '@domain-first/wire'
1685
- import { ${naming.ClassName}PresentationService } from '../../presentation/services/${naming.fileName}-presentation-service'
1686
-
1687
- export const wire${naming.ClassName}PresentationService = wireClass(
1688
- ${naming.ClassName}PresentationService,
1689
- []
1690
- )
1691
- `.trim());
1690
+ const installCommand = /^\s*npm (?:i|install)((?:\s+(?:--save-dev|-D))?)\s+(.+)$/;
1691
+ const mergeInstallCommands = (commands)=>{
1692
+ const runtime = new Set();
1693
+ const development = new Set();
1694
+ const rest = [];
1695
+ for (const command of commands){
1696
+ const match = installCommand.exec(command);
1697
+ if (!match) {
1698
+ rest.push(command);
1699
+ continue;
1700
+ }
1701
+ for (const name of match[2].trim().split(/\s+/))(match[1] ? development : runtime).add(name);
1702
+ }
1703
+ const devOnly = [
1704
+ ...development
1705
+ ].filter((name)=>!runtime.has(name));
1706
+ return [
1707
+ ...runtime.size ? [
1708
+ `npm install ${[
1709
+ ...runtime
1710
+ ].join(' ')}`
1711
+ ] : [],
1712
+ ...devOnly.length ? [
1713
+ `npm install --save-dev ${devOnly.join(' ')}`
1714
+ ] : [],
1715
+ ...rest
1716
+ ];
1692
1717
  };
1693
- const scaffoldNewPresentationService = async (boundedContextFolder)=>{
1694
- const name = await input({
1695
- message: 'Name: '
1696
- });
1697
- const wireFile = createPresentationService(boundedContextFolder, name);
1698
- if (wireFile) await wireNewModuleDependencies(boundedContextFolder, wireFile);
1718
+ const printNextSteps = (nextSteps)=>{
1719
+ const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
1720
+ const commands = mergeInstallCommands(nextSteps.filter(isCommand));
1721
+ const notes = nextSteps.filter((line)=>!isCommand(line));
1722
+ const sections = [];
1723
+ if (commands.length) sections.push([
1724
+ 'Run this command to install the required dependencies:',
1725
+ styleText([
1726
+ 'bold',
1727
+ 'cyan'
1728
+ ], commands.join(' && '))
1729
+ ].join('\n'));
1730
+ if (notes.length) sections.push([
1731
+ 'Additional information:',
1732
+ ...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + styleText([
1733
+ 'bold',
1734
+ 'cyan'
1735
+ ], path)))
1736
+ ].join('\n'));
1737
+ if (sections.length) console.log(sections.join('\n\n'));
1699
1738
  };
1700
- const rest_endpoint_generator_name = 'rest-endpoint-generator';
1701
- const scaffoldRestEndpointGenerator = (sharedFolder, { withNextAdapter = false } = {})=>createPresentationService(sharedFolder, rest_endpoint_generator_name, (className)=>{
1702
- const adapter = withNextAdapter ? 'nextAdapter' : 'adapter';
1703
- return `
1704
- import {
1705
- ${withNextAdapter ? '' : ' type Adapter,\n'} type EndpointGenerator,
1706
- createEndpoint,
1707
- invalidRequest
1708
- } from '@domain-first/handlers-rest'
1709
- ${withNextAdapter ? "import { nextAdapter } from '@domain-first/handlers-next'" : `
1710
- /**
1711
- * The adapter of your HTTP framework.
1712
- */
1713
- const adapter = undefined as unknown as Adapter<any[], any>`}
1714
-
1715
- export class ${className} {
1716
- get withoutGuards(): EndpointGenerator {
1717
- return createEndpoint({
1718
- errors: [invalidRequest()]
1719
- })(${adapter}) as EndpointGenerator
1739
+ const withHandlersRest = ()=>ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers-rest');
1740
+ const created = (...segments)=>new File(node_path.join(new ProjectRoot().path, ...segments)).exists;
1741
+ const createdInRoot = (...segments)=>created(ConfigFile.Instance.data.rootFolder, ...segments);
1742
+ const integrations = [
1743
+ {
1744
+ name: 'Storybook (React + Vite)',
1745
+ group: 'frontend',
1746
+ run: addStorybook,
1747
+ applied: ()=>createdInRoot('presentation/react/.storybook/main.ts')
1748
+ },
1749
+ {
1750
+ name: 'REST endpoint generator',
1751
+ group: 'backend',
1752
+ run: addRestEndpointGenerator,
1753
+ available: ()=>withHandlersRest(),
1754
+ applied: restEndpointGeneratorApplied
1755
+ },
1756
+ {
1757
+ name: 'In-memory DB',
1758
+ group: 'backend',
1759
+ run: addInMemoryDb,
1760
+ applied: inMemoryDbApplied
1761
+ },
1762
+ {
1763
+ name: 'Prisma 8 (PostgreSQL, RC)',
1764
+ group: 'backend',
1765
+ run: addPrisma,
1766
+ applied: ()=>createdInRoot('shared-kernel/infrastructure/prisma/prisma.config.ts')
1767
+ },
1768
+ {
1769
+ name: 'Vitest',
1770
+ group: 'backend',
1771
+ run: addVitest,
1772
+ applied: ()=>created('vitest.config.ts')
1773
+ },
1774
+ {
1775
+ name: 'Playwright',
1776
+ group: 'frontend',
1777
+ run: addPlaywright,
1778
+ applied: ()=>created('playwright.config.ts')
1779
+ },
1780
+ {
1781
+ name: 'Integration tests (Testcontainers, PostgreSQL)',
1782
+ group: 'backend',
1783
+ run: addTestcontainers,
1784
+ applied: ()=>created('specs/integration/vitest.config.ts')
1785
+ },
1786
+ {
1787
+ name: 'OpenAPI',
1788
+ group: 'backend',
1789
+ run: addOpenapi,
1790
+ available: ()=>withHandlersRest(),
1791
+ applied: ()=>created(openapiScriptPath)
1792
+ },
1793
+ {
1794
+ name: 'Orval (API client)',
1795
+ group: 'frontend',
1796
+ run: addOrval,
1797
+ available: ()=>withHandlersRest(),
1798
+ applied: ()=>createdInRoot('presentation/react/data-layer/orval.config.ts') || createdInRoot('presentation/data-layer/orval.config.ts')
1720
1799
  }
1721
- }
1722
- `.trim();
1723
- });
1724
- const findRestEndpointGenerator = (sharedFolder)=>{
1725
- const typeFile = node_path.join(sharedFolder.path, 'presentation', 'services', `${rest_endpoint_generator_name}-presentation-service.ts`);
1726
- if (!new File(typeFile).exists) return;
1727
- return {
1728
- typeName: 'RestEndpointGeneratorPresentationService',
1729
- typeFile,
1730
- wireName: 'wireRestEndpointGeneratorPresentationService',
1731
- wireFile: node_path.join(sharedFolder.path, 'wiring', 'presentation-services', `wire-${rest_endpoint_generator_name}-presentation-service.ts`)
1800
+ ];
1801
+ const addIntegration = async ()=>{
1802
+ const available = integrations.filter(({ available })=>available?.() ?? true).map((value)=>({
1803
+ value,
1804
+ applied: value.applied()
1805
+ }));
1806
+ const section = (title, applied)=>{
1807
+ const items = [
1808
+ 'backend',
1809
+ 'frontend'
1810
+ ].flatMap((group)=>available.filter((item)=>item.applied === applied && item.value.group === group));
1811
+ return items.length ? [
1812
+ new Separator(title),
1813
+ ...items.map(({ value })=>({
1814
+ name: `${value.name} · ${value.group}`,
1815
+ value
1816
+ }))
1817
+ ] : [];
1732
1818
  };
1733
- };
1734
- const hasDependency = (root, name)=>{
1735
- const manifestFile = new File(node_path.join(root, 'package.json'));
1736
- if (!manifestFile.exists) return false;
1737
- const manifest = JSON.parse(manifestFile.data);
1738
- return [
1739
- manifest.dependencies,
1740
- manifest.devDependencies,
1741
- manifest.optionalDependencies
1742
- ].some((dependencies)=>dependencies && Object.hasOwn(dependencies, name));
1819
+ const choices = [
1820
+ ...section('New integrations', false),
1821
+ ...section('Already applied (select to reapply)', true)
1822
+ ];
1823
+ const selected = await prompts_checkbox({
1824
+ message: 'Integrations:',
1825
+ choices,
1826
+ pageSize: choices.length
1827
+ });
1828
+ const nextSteps = [];
1829
+ for (const integration of integrations.filter((value)=>selected.includes(value)))nextSteps.push(...await integration.run());
1830
+ if (await savePendingChanges()) printNextSteps(nextSteps);
1743
1831
  };
1744
1832
  const initializeUseCase = async ()=>{
1745
- const nextSteps = [];
1746
1833
  const rootFolderName = await input({
1747
1834
  message: 'Root folder (use "/" for inner folders):',
1748
1835
  default: 'src'
@@ -1757,9 +1844,7 @@ const initializeUseCase = async ()=>{
1757
1844
  '@domain-first/handlers-rest'
1758
1845
  ]
1759
1846
  });
1760
- const withNextAdapter = domainFirstPackages.includes('@domain-first/handlers-rest') && hasDependency(new ProjectRoot().path, 'next') && await prompts_confirm({
1761
- message: 'Use Next adapter for REST endpoints'
1762
- });
1847
+ const withNextAdapter = domainFirstPackages.includes('@domain-first/handlers-rest') && await askNextAdapter();
1763
1848
  const defaultPersistenceLayerImplementation = await input({
1764
1849
  message: 'Default persistence layer implementation:'
1765
1850
  });
@@ -1798,116 +1883,50 @@ const initializeUseCase = async ()=>{
1798
1883
  const rootFolder = new Folder(path);
1799
1884
  if (domainFirstPackages.includes('@domain-first/wire')) rootFolder.subitem([
1800
1885
  rootFolderName,
1801
- 'shared',
1802
- 'wiring'
1803
- ]).createFile('env-branched-wire.ts', `
1804
- import { branchedWire } from '@domain-first/wire'
1805
-
1806
- export const envBranchedWire = branchedWire(() => {
1807
- return process.env.NODE_ENV ?? 'development' as 'test' | 'development' | 'production'
1808
- });
1809
- `.trim());
1810
- if (withInMemoryDb) scaffoldInMemoryDb(rootFolder.subitem([
1811
- rootFolderName,
1812
- 'shared'
1813
- ]));
1814
- if (domainFirstPackages.includes('@domain-first/errors')) rootFolder.subitem([
1815
- rootFolderName,
1816
- 'shared'
1817
- ]).subitem([
1818
- 'domain',
1819
- 'errors'
1820
- ]).createFile('index.ts', `
1821
- import { errorNamespace } from '@domain-first/errors'
1822
-
1823
- export const SharedErrors = errorNamespace('shared')
1824
- `.trim());
1825
- if (domainFirstPackages.includes('@domain-first/handlers-rest')) {
1826
- scaffoldRestEndpointGenerator(rootFolder.subitem([
1827
- rootFolderName,
1828
- 'shared'
1829
- ]), {
1830
- withNextAdapter
1831
- });
1832
- if (withNextAdapter && !hasDependency(path, '@domain-first/handlers-next')) nextSteps.push('npm i @domain-first/handlers-next');
1833
- }
1834
- return nextSteps;
1835
- };
1836
- const ignoredFolders = new Set([
1837
- 'node_modules',
1838
- '.git',
1839
- '.next',
1840
- 'dist',
1841
- 'build',
1842
- 'out',
1843
- 'coverage',
1844
- 'storybook-static'
1845
- ]);
1846
- const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
1847
- const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1848
- const walk = (folder)=>{
1849
- if (!node_fs.existsSync(folder)) return [];
1850
- return node_fs.readdirSync(folder, {
1851
- withFileTypes: true
1852
- }).flatMap((entry)=>{
1853
- const entryPath = node_path.join(folder, entry.name);
1854
- if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : walk(entryPath);
1855
- return entry.isFile() ? [
1856
- entryPath
1857
- ] : [];
1858
- });
1859
- };
1860
- const toPosix = (value)=>value.split(node_path.sep).join('/');
1861
- const nestedName = (folders, fileBase)=>{
1862
- const prefix = `${folders.join('-')}-`;
1863
- const last = folders.length && fileBase.startsWith(prefix) ? fileBase.slice(prefix.length) : fileBase;
1864
- return [
1865
- ...folders,
1866
- last
1867
- ].join('/');
1868
- };
1869
- const declaredClassName = (filePath, suffix, name)=>{
1870
- const content = node_fs.readFileSync(filePath, 'utf8');
1871
- const declared = content.match(new RegExp(`export\\s+(?:const|function)\\s+(\\w+)${suffix}\\b`))?.[1];
1872
- return declared ?? new NestedName(name).ClassName;
1873
- };
1874
- const findReactModules = (reactFolder, kind)=>{
1875
- const modules = 'page' === kind ? walk(node_path.join(reactFolder, 'pages')).filter((file)=>file.endsWith('-page.tsx')).map((file)=>{
1876
- const folders = node_path.relative(node_path.join(reactFolder, 'pages'), node_path.dirname(file)).split(node_path.sep).filter((segment)=>!!segment);
1877
- const fileBase = node_path.basename(file, '-page.tsx');
1878
- const name = nestedName(folders, fileBase);
1879
- return {
1880
- kind,
1881
- name,
1882
- path: file,
1883
- fileBase,
1884
- ClassName: declaredClassName(file, 'Page', name)
1885
- };
1886
- }) : walk(node_path.join(reactFolder, 'widgets')).filter((file)=>file.endsWith('-widget.tsx')).map((file)=>{
1887
- const folder = node_path.dirname(file);
1888
- const name = toPosix(node_path.relative(node_path.join(reactFolder, 'widgets'), folder));
1889
- return {
1890
- kind,
1891
- name,
1892
- path: folder,
1893
- fileBase: node_path.basename(file, '-widget.tsx'),
1894
- ClassName: declaredClassName(file, 'Widget', name)
1895
- };
1896
- });
1897
- return modules.sort((a, b)=>a.name.localeCompare(b.name));
1898
- };
1899
- const targetPath = (reactFolder, module, rawName)=>{
1900
- const { folders, folderName, fileName } = new NestedName(rawName);
1901
- return 'page' === module.kind ? node_path.join(reactFolder, 'pages', ...folders, `${fileName}-page.tsx`) : node_path.join(reactFolder, 'widgets', ...folders, folderName);
1886
+ 'shared-kernel',
1887
+ 'wiring'
1888
+ ]).createFile('env-branched-wire.ts', `
1889
+ import { branchedWire } from '@domain-first/wire'
1890
+
1891
+ export const envBranchedWire = branchedWire(() => {
1892
+ return process.env.NODE_ENV ?? 'development' as 'test' | 'development' | 'production'
1893
+ });
1894
+ `.trim());
1895
+ if (withInMemoryDb) scaffoldInMemoryDb(rootFolder.subitem([
1896
+ rootFolderName,
1897
+ 'shared-kernel'
1898
+ ]));
1899
+ const nextSteps = missingDomainFirstPackages();
1900
+ if (domainFirstPackages.includes('@domain-first/handlers-rest')) nextSteps.push(...scaffoldRestEndpointGeneratorFiles({
1901
+ withNextAdapter
1902
+ }));
1903
+ return nextSteps;
1902
1904
  };
1903
- const validateMove = (reactFolder, module, rawName)=>{
1904
- const nameError = NestedName.validate(rawName);
1905
- if (true !== nameError) return nameError;
1906
- const target = targetPath(reactFolder, module, rawName);
1907
- if (target !== module.path && node_fs.existsSync(target)) return `${node_path.relative(reactFolder, target)} already exists`;
1908
- if (target.startsWith(`${module.path}${node_path.sep}`)) return 'A widget cannot be moved into itself';
1909
- return true;
1905
+ const ignoredFolders = new Set([
1906
+ 'node_modules',
1907
+ '.git',
1908
+ '.next',
1909
+ 'dist',
1910
+ 'build',
1911
+ 'out',
1912
+ 'coverage',
1913
+ 'storybook-static'
1914
+ ]);
1915
+ const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
1916
+ const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1917
+ const walk = (folder)=>{
1918
+ if (!node_fs.existsSync(folder)) return [];
1919
+ return node_fs.readdirSync(folder, {
1920
+ withFileTypes: true
1921
+ }).flatMap((entry)=>{
1922
+ const entryPath = node_path.join(folder, entry.name);
1923
+ if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : walk(entryPath);
1924
+ return entry.isFile() ? [
1925
+ entryPath
1926
+ ] : [];
1927
+ });
1910
1928
  };
1929
+ const toPosix = (value)=>value.split(node_path.sep).join('/');
1911
1930
  const readAliases = (projectRoot)=>{
1912
1931
  const tsconfig = node_path.join(projectRoot, 'tsconfig.json');
1913
1932
  if (!node_fs.existsSync(tsconfig)) return [];
@@ -1933,26 +1952,7 @@ const importPaths = (file)=>{
1933
1952
  withoutExtension
1934
1953
  ];
1935
1954
  };
1936
- const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
1937
- const newName = new NestedName(rawName);
1938
- const target = targetPath(reactFolder, module, rawName);
1939
- const newClassName = newName.ClassName;
1940
- const renameFile = (name)=>name.replace(new RegExp(`^(use-)?${escapeRegExp(module.fileBase)}(?=[-.])`), (_, use = '')=>`${use}${newName.fileName}`);
1941
- const oldFolder = 'page' === module.kind ? node_path.dirname(module.path) : module.path;
1942
- const newFolder = 'page' === module.kind ? node_path.dirname(target) : target;
1943
- const ownsPath = (candidate)=>'page' === module.kind ? node_path.dirname(candidate) === oldFolder && new RegExp(`^${escapeRegExp(module.fileBase)}-page(?:\\.|$)`).test(node_path.basename(candidate)) : candidate === oldFolder || candidate.startsWith(`${oldFolder}${node_path.sep}`);
1944
- const movedPath = (candidate)=>{
1945
- if (!ownsPath(candidate)) return;
1946
- const segments = node_path.relative(oldFolder, candidate).split(node_path.sep);
1947
- const last = segments.length - 1;
1948
- segments[last] = renameFile(segments[last]);
1949
- return node_path.join(newFolder, ...segments);
1950
- };
1951
- const moduleFiles = 'page' === module.kind ? node_fs.readdirSync(oldFolder).map((name)=>node_path.join(oldFolder, name)).filter((file)=>node_fs.statSync(file).isFile() && ownsPath(file)) : walk(oldFolder);
1952
- const moves = new Map(moduleFiles.map((file)=>[
1953
- file,
1954
- movedPath(file) ?? file
1955
- ]));
1955
+ const projectImports = (projectRoot)=>{
1956
1956
  const aliases = readAliases(projectRoot);
1957
1957
  const resolve = (specifier, fromFile)=>{
1958
1958
  if (specifier.startsWith('.')) return {
@@ -1971,18 +1971,22 @@ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
1971
1971
  const relative = toPosix(node_path.relative(node_path.dirname(fromFile), toPath));
1972
1972
  return relative.startsWith('.') ? relative : `./${relative}`;
1973
1973
  };
1974
- const suffixes = 'page' === module.kind ? 'Page' : 'Widget|UIModel';
1975
- const classPattern = new RegExp(`(?<![\\w$])(use)?${escapeRegExp(module.ClassName)}(?=${suffixes})`, 'g');
1976
- const oldTitle = `Widgets/${module.name.split('/').map((segment)=>new NestedName(segment).ClassName).join('/')}`;
1977
- const titlePattern = new RegExp(`(['"\`])${escapeRegExp(oldTitle)}\\1`, 'g');
1978
- const newTitle = [
1979
- 'Widgets',
1980
- ...newName.classNameSegments
1981
- ].join('/');
1982
1974
  const codeFiles = new Map(walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
1983
1975
  file,
1984
1976
  node_fs.readFileSync(file, 'utf8')
1985
1977
  ]));
1978
+ const importsOf = (file)=>[
1979
+ ...(codeFiles.get(file) ?? '').matchAll(specifierPattern)
1980
+ ].map(([, , , specifier])=>resolve(specifier, file)?.resolved).filter((resolved)=>!!resolved);
1981
+ return {
1982
+ resolve,
1983
+ specifierFor,
1984
+ codeFiles,
1985
+ importsOf
1986
+ };
1987
+ };
1988
+ const stageModuleMove = ({ projectRoot, stopAt, moves, movedPath, rename, everyFile = (content)=>content })=>{
1989
+ const { resolve, specifierFor, codeFiles } = projectImports(projectRoot);
1986
1990
  const barrels = new Set();
1987
1991
  const isBarrel = (resolved)=>barrels.has(resolved.replace(codeExtension, ''));
1988
1992
  for(let found = true; found;){
@@ -2012,18 +2016,20 @@ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
2012
2016
  const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
2013
2017
  return `${keyword}${quote}${next}${quote}`;
2014
2018
  });
2015
- if (!referencesModule && !moves.has(oldFile)) return content;
2016
- const renamed = rewritten.replace(classPattern, (_, use = '')=>`${use}${newClassName}`);
2017
- return moves.has(oldFile) && 'widget' === module.kind ? renamed.replace(titlePattern, (_, quote)=>`${quote}${newTitle}${quote}`) : renamed;
2019
+ const changed = everyFile(rewritten);
2020
+ if (!referencesModule && !moves.has(oldFile)) return changed;
2021
+ return rename(changed, {
2022
+ moved: moves.has(oldFile)
2023
+ });
2018
2024
  };
2019
- for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new File(file).moveTo(newFile, reactFolder);
2025
+ for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new File(file).moveTo(newFile, stopAt);
2020
2026
  const updated = [];
2021
2027
  for (const [file, content] of codeFiles){
2022
2028
  const newFile = moves.get(file);
2023
2029
  const next = rewrite(content, file, newFile ?? file);
2024
2030
  if (newFile && newFile !== file) {
2025
2031
  new File(newFile).data = next;
2026
- new File(file).delete(reactFolder);
2032
+ new File(file).delete(stopAt);
2027
2033
  } else if (next !== content) {
2028
2034
  new File(file).update(next);
2029
2035
  if (!newFile) updated.push(file);
@@ -2036,10 +2042,512 @@ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
2036
2042
  updated
2037
2043
  };
2038
2044
  };
2045
+ const serviceLayout = (layer)=>({
2046
+ title: `${layer[0].toUpperCase()}${layer.slice(1)} services`,
2047
+ core: (ClassName)=>`${ClassName}${layer[0].toUpperCase()}${layer.slice(1)}Service`,
2048
+ files: ({ name })=>[
2049
+ `${layer}/services/${name}-${layer}-service.ts`,
2050
+ `${layer}/services/${name}-${layer}-service.spec.ts`,
2051
+ `wiring/${layer}-services/wire-${name}-${layer}-service.ts`
2052
+ ],
2053
+ wired: true,
2054
+ sharedKernel: true
2055
+ });
2056
+ const handlerLayout = (kind)=>{
2057
+ const folder = 'command' === kind ? 'commands' : 'queries';
2058
+ const Suffix = 'command' === kind ? 'Command' : 'Query';
2059
+ return {
2060
+ title: 'command' === kind ? 'Commands' : 'Queries',
2061
+ core: (ClassName)=>`${ClassName}${Suffix}`,
2062
+ files: ({ name }, labels)=>[
2063
+ `application/${folder}/${name}-${kind}.ts`,
2064
+ `application/${folder}/${name}-${kind}.spec.ts`,
2065
+ ...labels.map((label)=>`infrastructure/${folder}/${label}/${label}-${name}-${kind}.ts`),
2066
+ `wiring/${folder}/wire-${name}-${kind}.ts`
2067
+ ],
2068
+ implementations: `infrastructure/${folder}`,
2069
+ wired: true,
2070
+ sharedKernel: false
2071
+ };
2072
+ };
2073
+ const domainModelLayout = (kind)=>{
2074
+ const folder = 'entity' === kind ? 'entities' : 'value-objects';
2075
+ return {
2076
+ title: 'entity' === kind ? 'Entities' : 'Value objects',
2077
+ core: (ClassName)=>ClassName,
2078
+ files: ({ name, aggregate })=>{
2079
+ const base = aggregate ? `domain/aggregates/${aggregate}/${folder}` : `domain/${folder}`;
2080
+ return [
2081
+ `${base}/${name}.${kind}.ts`,
2082
+ `${base}/${name}.${kind}.spec.ts`
2083
+ ];
2084
+ },
2085
+ wired: false,
2086
+ sharedKernel: true
2087
+ };
2088
+ };
2089
+ const aggregateOwnFiles = (name)=>[
2090
+ `${name}.aggregate-root.ts`,
2091
+ `${name}.aggregate-root.spec.ts`,
2092
+ `${name}-repository.ts`,
2093
+ `${name}-repository.spec.ts`,
2094
+ 'index.ts'
2095
+ ];
2096
+ const kindLayouts = {
2097
+ aggregate: {
2098
+ title: 'Aggregates',
2099
+ core: (ClassName)=>`${ClassName}Repository`,
2100
+ files: ({ name }, labels)=>[
2101
+ ...aggregateOwnFiles(name).map((file)=>`domain/aggregates/${name}/${file}`),
2102
+ ...labels.map((label)=>`infrastructure/repositories/${label}/${label}-${name}-repository.ts`),
2103
+ `wiring/repositories/wire-${name}-repository.ts`
2104
+ ],
2105
+ implementations: 'infrastructure/repositories',
2106
+ wired: true,
2107
+ sharedKernel: false
2108
+ },
2109
+ entity: domainModelLayout('entity'),
2110
+ 'value-object': domainModelLayout('value-object'),
2111
+ 'domain-service': serviceLayout('domain'),
2112
+ 'application-service': serviceLayout('application'),
2113
+ 'infrastructure-service': serviceLayout('infrastructure'),
2114
+ 'presentation-service': serviceLayout('presentation'),
2115
+ 'use-case': {
2116
+ title: 'Use cases',
2117
+ core: (ClassName)=>`${ClassName}UseCase`,
2118
+ files: ({ name })=>[
2119
+ `application/use-cases/${name}-use-case.ts`,
2120
+ `application/use-cases/${name}-use-case.spec.ts`,
2121
+ `wiring/use-cases/wire-${name}-use-case.ts`
2122
+ ],
2123
+ wired: true,
2124
+ sharedKernel: false
2125
+ },
2126
+ command: handlerLayout('command'),
2127
+ query: handlerLayout('query'),
2128
+ port: {
2129
+ title: 'Ports',
2130
+ core: (ClassName)=>ClassName,
2131
+ files: ({ name }, labels)=>[
2132
+ `application/ports/${name}.ts`,
2133
+ `application/ports/${name}.spec.ts`,
2134
+ ...labels.map((label)=>`infrastructure/application-adapters/${label}/${label}-${name}.ts`),
2135
+ `wiring/application-ports/wire-${name}.ts`
2136
+ ],
2137
+ implementations: 'infrastructure/application-adapters',
2138
+ wired: true,
2139
+ sharedKernel: true
2140
+ }
2141
+ };
2142
+ const subfolders = (folder)=>node_fs.existsSync(folder) ? node_fs.readdirSync(folder, {
2143
+ withFileTypes: true
2144
+ }).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name).sort() : [];
2145
+ const namesBySuffix = (folder, suffix)=>node_fs.existsSync(folder) ? node_fs.readdirSync(folder).filter((file)=>file.endsWith(suffix) && !file.endsWith('.spec.ts')).map((file)=>file.slice(0, -suffix.length)).sort() : [];
2146
+ const labelsOf = (ownerPath, kind, name)=>{
2147
+ const { implementations } = kindLayouts[kind];
2148
+ if (!implementations) return [];
2149
+ return subfolders(node_path.join(ownerPath, implementations)).filter((label)=>kindLayouts[kind].files({
2150
+ ownerPath,
2151
+ name
2152
+ }, [
2153
+ label
2154
+ ]).some((file)=>file.startsWith(`${implementations}/`) && node_fs.existsSync(node_path.join(ownerPath, file))));
2155
+ };
2156
+ const aggregatesOf = (ownerPath)=>subfolders(node_path.join(ownerPath, 'domain/aggregates')).filter((name)=>node_fs.existsSync(node_path.join(ownerPath, 'domain/aggregates', name, `${name}.aggregate-root.ts`)));
2157
+ const findBackendUnits = (ownerPath)=>{
2158
+ const unit = (kind, name, aggregate)=>({
2159
+ kind,
2160
+ name,
2161
+ ownerPath,
2162
+ aggregate,
2163
+ labels: labelsOf(ownerPath, kind, name)
2164
+ });
2165
+ const aggregates = aggregatesOf(ownerPath);
2166
+ const inAggregates = (kind)=>aggregates.flatMap((aggregate)=>namesBySuffix(node_path.join(ownerPath, 'domain/aggregates', aggregate, 'entity' === kind ? 'entities' : 'value-objects'), `.${kind}.ts`).map((name)=>unit(kind, name, aggregate)));
2167
+ const at = (folder, suffix, kind)=>namesBySuffix(node_path.join(ownerPath, folder), suffix).map((name)=>unit(kind, name));
2168
+ return [
2169
+ ...aggregates.map((name)=>unit('aggregate', name)),
2170
+ ...inAggregates('entity'),
2171
+ ...at('domain/entities', '.entity.ts', 'entity'),
2172
+ ...inAggregates('value-object'),
2173
+ ...at('domain/value-objects', '.value-object.ts', 'value-object'),
2174
+ ...at('domain/services', '-domain-service.ts', 'domain-service'),
2175
+ ...at('application/ports', '.ts', 'port'),
2176
+ ...at('application/queries', '-query.ts', 'query'),
2177
+ ...at('application/commands', '-command.ts', 'command'),
2178
+ ...at('application/use-cases', '-use-case.ts', 'use-case'),
2179
+ ...at('application/services', '-application-service.ts', 'application-service'),
2180
+ ...at('infrastructure/services', '-infrastructure-service.ts', 'infrastructure-service'),
2181
+ ...at('presentation/services', '-presentation-service.ts', 'presentation-service')
2182
+ ];
2183
+ };
2184
+ const kebabName = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
2185
+ const lowerFirst = (value)=>value[0].toLowerCase() + value.slice(1);
2186
+ const unitMoves = (unit, target)=>{
2187
+ const layout = kindLayouts[unit.kind];
2188
+ const from = layout.files(unit, unit.labels);
2189
+ const to = layout.files(target, unit.labels);
2190
+ const moves = new Map();
2191
+ from.forEach((file, index)=>{
2192
+ const oldPath = node_path.join(unit.ownerPath, file);
2193
+ if (node_fs.existsSync(oldPath)) moves.set(oldPath, node_path.join(target.ownerPath, to[index]));
2194
+ });
2195
+ if ('aggregate' === unit.kind) {
2196
+ const oldFolder = node_path.join(unit.ownerPath, 'domain/aggregates', unit.name);
2197
+ const newFolder = node_path.join(target.ownerPath, 'domain/aggregates', target.name);
2198
+ const own = new Set(aggregateOwnFiles(unit.name).map((file)=>node_path.join(oldFolder, file)));
2199
+ for (const file of walk(oldFolder))if (!own.has(file)) moves.set(file, node_path.join(newFolder, node_path.relative(oldFolder, file)));
2200
+ }
2201
+ return moves;
2202
+ };
2203
+ const validateBackendMove = (unit, target, sharedKernelPath)=>{
2204
+ if (!kebabName.test(target.name)) return 'Use kebab-case: lowercase words split by "-", e.g. place-order';
2205
+ if (target.ownerPath === sharedKernelPath && !kindLayouts[unit.kind].sharedKernel) return `${kindLayouts[unit.kind].title} are not part of the Shared Kernel`;
2206
+ if (target.ownerPath === unit.ownerPath && target.name === unit.name && target.aggregate === unit.aggregate) return 'Nothing to change: enter a new name or pick another place';
2207
+ for (const [from, to] of unitMoves(unit, target))if (to !== from && node_fs.existsSync(to)) return `${node_path.relative(target.ownerPath, to)} already exists`;
2208
+ return true;
2209
+ };
2210
+ const ownerOf = (rootFolderPath, file)=>{
2211
+ const [area, context] = node_path.relative(rootFolderPath, file).split(node_path.sep);
2212
+ if ('bounded-contexts' === area && context) return {
2213
+ context,
2214
+ path: node_path.join(rootFolderPath, area, context)
2215
+ };
2216
+ if ('shared-kernel' === area) return {
2217
+ context: void 0,
2218
+ path: node_path.join(rootFolderPath, area)
2219
+ };
2220
+ };
2221
+ const inMemoryDbFile = (rootFolderPath)=>node_path.join(rootFolderPath, 'shared-kernel/infrastructure/services/in-memory-db-infrastructure-service.ts');
2222
+ const isolationAllows = (rootFolderPath, from, to)=>{
2223
+ const fromOwner = ownerOf(rootFolderPath, from);
2224
+ const toOwner = ownerOf(rootFolderPath, to);
2225
+ if (!fromOwner || !toOwner?.context) return true;
2226
+ if (fromOwner.context) return fromOwner.context === toOwner.context;
2227
+ const inside = (folder)=>to === node_path.join(toOwner.path, folder) || to.startsWith(node_path.join(toOwner.path, folder) + node_path.sep);
2228
+ return inside('domain/errors') || from.replace(codeExtension, '') === inMemoryDbFile(rootFolderPath).replace(codeExtension, '') && inside('domain');
2229
+ };
2230
+ const moveBackendUnit = (projectRoot, rootFolderPath, unit, target)=>{
2231
+ const layout = kindLayouts[unit.kind];
2232
+ const moves = unitMoves(unit, target);
2233
+ const withoutExtension = new Map([
2234
+ ...moves
2235
+ ].map(([from, to])=>[
2236
+ from.replace(codeExtension, ''),
2237
+ to.replace(codeExtension, '')
2238
+ ]));
2239
+ const folders = 'aggregate' === unit.kind ? [
2240
+ [
2241
+ node_path.join(unit.ownerPath, 'domain/aggregates', unit.name),
2242
+ node_path.join(target.ownerPath, 'domain/aggregates', target.name)
2243
+ ]
2244
+ ] : [];
2245
+ const movedPath = (candidate)=>{
2246
+ const extension = candidate.match(codeExtension)?.[0];
2247
+ if (extension) return moves.get(candidate);
2248
+ return withoutExtension.get(candidate) ?? folders.find(([from])=>from === candidate)?.[1];
2249
+ };
2250
+ const { codeFiles, importsOf, resolve } = projectImports(projectRoot);
2251
+ const oldNaming = new UnknownFormatNaming(unit.name);
2252
+ const newNaming = new UnknownFormatNaming(target.name);
2253
+ const leavesAggregate = !!unit.aggregate && (unit.aggregate !== target.aggregate || unit.ownerPath !== target.ownerPath);
2254
+ const oldAggregateFolder = unit.aggregate && node_path.join(unit.ownerPath, 'domain/aggregates', unit.aggregate);
2255
+ const isOldBarrel = (resolved)=>!!oldAggregateFolder && (resolved === oldAggregateFolder || resolved === node_path.join(oldAggregateFolder, 'index'));
2256
+ const mainFile = [
2257
+ ...moves.keys()
2258
+ ][0];
2259
+ const newMainFile = moves.get(mainFile);
2260
+ const namedImports = /import\s+(type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\3;?/g;
2261
+ const barrelImporters = leavesAggregate ? [
2262
+ ...codeFiles
2263
+ ].filter(([file, content])=>!moves.has(file) && [
2264
+ ...content.matchAll(namedImports)
2265
+ ].some(([, , names, , specifier])=>isOldBarrel(resolve(specifier, file)?.resolved) && new RegExp(`(?<![\\w$])${oldNaming.ClassName}(?![\\w$])`).test(names))) : [];
2266
+ const violations = [];
2267
+ const relative = (file)=>toPosix(node_path.relative(projectRoot, file));
2268
+ for (const file of codeFiles.keys()){
2269
+ const from = moves.get(file) ?? file;
2270
+ for (const imported of importsOf(file)){
2271
+ const to = movedPath(imported);
2272
+ if (moves.has(file) || to) {
2273
+ if (!isolationAllows(rootFolderPath, from, to ?? imported)) violations.push([
2274
+ relative(from),
2275
+ relative(to ?? imported)
2276
+ ]);
2277
+ }
2278
+ }
2279
+ }
2280
+ for (const [file] of barrelImporters)if (!isolationAllows(rootFolderPath, file, newMainFile)) violations.push([
2281
+ relative(file),
2282
+ relative(newMainFile)
2283
+ ]);
2284
+ if (violations.length) return {
2285
+ violations
2286
+ };
2287
+ const word = (form)=>`(?<![\\w$])${escapeRegExp(form)}(?![\\w$])`;
2288
+ const oldCore = layout.core(oldNaming.ClassName);
2289
+ const newCore = layout.core(newNaming.ClassName);
2290
+ const prefixes = [
2291
+ ...unit.labels.map((label)=>new UnknownFormatNaming(label).ClassName),
2292
+ ...layout.wired ? [
2293
+ 'wire'
2294
+ ] : []
2295
+ ];
2296
+ const renames = [
2297
+ {
2298
+ pattern: new RegExp(`(?<![\\w$])(${prefixes.map(escapeRegExp).join('|')})?${escapeRegExp(oldCore)}(?![\\w$])`, 'g'),
2299
+ to: `$1${newCore}`
2300
+ },
2301
+ {
2302
+ pattern: new RegExp(word(lowerFirst(oldCore)), 'g'),
2303
+ to: lowerFirst(newCore)
2304
+ },
2305
+ {
2306
+ pattern: new RegExp(`(describe\\(\\s*['"\`])${escapeRegExp(oldNaming.withSpaces)}(?=[ '"\`])`, 'g'),
2307
+ to: `$1${newNaming.withSpaces}`,
2308
+ movedOnly: true
2309
+ }
2310
+ ];
2311
+ if ('aggregate' === unit.kind) renames.push({
2312
+ pattern: new RegExp(word(oldNaming.ClassName), 'g'),
2313
+ to: newNaming.ClassName
2314
+ }, {
2315
+ pattern: new RegExp(word(oldNaming.variableName), 'g'),
2316
+ to: newNaming.variableName,
2317
+ movedOnly: true
2318
+ });
2319
+ if ('entity' === unit.kind || 'value-object' === unit.kind) renames.push({
2320
+ pattern: new RegExp(word(oldNaming.variableName), 'g'),
2321
+ to: newNaming.variableName,
2322
+ movedOnly: true
2323
+ });
2324
+ const oldSection = new UnknownFormatNaming(plural(unit.name));
2325
+ const newSection = new UnknownFormatNaming(plural(target.name));
2326
+ const renamesSection = 'aggregate' === unit.kind && unit.name !== target.name;
2327
+ const everyFile = (content)=>renamesSection ? content.replace(new RegExp(`(InMemoryDbInfrastructureService\\[\\s*['"])${oldSection.variableName}(?=['"]\\s*\\])`, 'g'), `$1${newSection.variableName}`).replace(new RegExp(`(inMemoryDbInfrastructureService\\s*\\.\\s*)${oldSection.variableName}(?![\\w$])`, 'g'), `$1${newSection.variableName}`).replace(new RegExp(`(?<![\\w$.])${oldSection.variableName}(\\s*=\\s*this\\.section<[^>]*>\\(\\s*['"])${oldSection.fileName.toUpperCase()}(?=['"])`, 'g'), `${newSection.variableName}$1${newSection.fileName.toUpperCase()}`) : content;
2328
+ const plan = stageModuleMove({
2329
+ projectRoot,
2330
+ stopAt: rootFolderPath,
2331
+ moves,
2332
+ movedPath,
2333
+ rename: (content, { moved })=>renames.reduce((result, { pattern, to, movedOnly })=>movedOnly && !moved ? result : result.replace(pattern, to), content),
2334
+ everyFile
2335
+ });
2336
+ if (leavesAggregate && oldAggregateFolder) {
2337
+ const indexFile = new File(node_path.join(oldAggregateFolder, 'index.ts'));
2338
+ const exportLine = /^export\s+\*\s+from\s+(['"])([^'"\n]+)\1;?\s*$/;
2339
+ indexFile.update(indexFile.data.split('\n').filter((line)=>{
2340
+ const specifier = line.match(exportLine)?.[2];
2341
+ return !specifier || node_path.resolve(node_path.dirname(indexFile.path), specifier) !== newMainFile.replace(codeExtension, '');
2342
+ }).join('\n'));
2343
+ if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
2344
+ for (const [file] of barrelImporters){
2345
+ const importer = new File(file);
2346
+ let content = importer.data;
2347
+ for (const match of content.matchAll(namedImports)){
2348
+ const [statement, typeOnly = '', names, quote, specifier] = match;
2349
+ if (!isOldBarrel(resolve(specifier, file)?.resolved)) continue;
2350
+ const items = names.split(',').map((item)=>item.trim()).filter((item)=>!!item);
2351
+ const own = new RegExp(`^(?:type\\s+)?${newNaming.ClassName}(?:\\s+as\\s+[\\w$]+)?$`);
2352
+ const moved = items.filter((item)=>own.test(item));
2353
+ if (!moved.length) continue;
2354
+ const rest = items.filter((item)=>!own.test(item));
2355
+ const direct = `import ${typeOnly}{ ${moved.join(', ')} } from ${quote}${projectRelative(file, newMainFile)}${quote}`;
2356
+ content = content.replace(statement, rest.length ? `import ${typeOnly}{ ${rest.join(', ')} } from ${quote}${specifier}${quote}\n${direct}` : direct);
2357
+ }
2358
+ importer.update(content);
2359
+ }
2360
+ }
2361
+ if (target.aggregate && (target.aggregate !== unit.aggregate || target.ownerPath !== unit.ownerPath)) {
2362
+ const kindFolder = 'entity' === unit.kind ? 'entities' : 'value-objects';
2363
+ const indexFile = new File(node_path.join(target.ownerPath, 'domain/aggregates', target.aggregate, 'index.ts'));
2364
+ indexFile.addLineIfMissing(`export * from './${kindFolder}/${target.name}.${unit.kind}'`);
2365
+ if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
2366
+ }
2367
+ return plan;
2368
+ };
2369
+ const projectRelative = (fromFile, toFile)=>{
2370
+ const relative = toPosix(node_path.relative(node_path.dirname(fromFile), toFile.replace(codeExtension, '')));
2371
+ return relative.startsWith('.') ? relative : `./${relative}`;
2372
+ };
2373
+ const noAggregate = 'No aggregate';
2374
+ const moveBackendUnitUseCase = async (ownerFolder)=>{
2375
+ const root = new ProjectRoot().path;
2376
+ const rootFolderPath = node_path.join(root, ConfigFile.Instance.data.rootFolder);
2377
+ const sharedKernelPath = node_path.join(rootFolderPath, 'shared-kernel');
2378
+ const units = findBackendUnits(ownerFolder.path);
2379
+ if (!units.length) return void console.log('No modules generated by df-scaffold were found here.');
2380
+ const unit = await prompts_select({
2381
+ message: 'Module:',
2382
+ choices: Object.keys(kindLayouts).flatMap((kind)=>{
2383
+ const group = units.filter((x)=>x.kind === kind);
2384
+ return group.length ? [
2385
+ new Separator(`── ${kindLayouts[group[0].kind].title}`),
2386
+ ...group.map((value)=>({
2387
+ name: value.aggregate ? `${value.name} (${value.aggregate})` : value.name,
2388
+ value
2389
+ }))
2390
+ ] : [];
2391
+ }),
2392
+ pageSize: 20
2393
+ });
2394
+ const placeName = (ownerPath)=>ownerPath === sharedKernelPath ? 'Shared Kernel' : `Bounded Context: ${node_path.basename(ownerPath)}`;
2395
+ const contexts = new Folder(rootFolderPath).subitem([
2396
+ 'bounded-contexts'
2397
+ ]).content.subfolderNames.map((name)=>node_path.join(rootFolderPath, 'bounded-contexts', name));
2398
+ const places = [
2399
+ unit.ownerPath,
2400
+ ...contexts,
2401
+ ...kindLayouts[unit.kind].sharedKernel ? [
2402
+ sharedKernelPath
2403
+ ] : []
2404
+ ].filter((place, index, all)=>all.indexOf(place) === index);
2405
+ const ownerPath = await prompts_select({
2406
+ message: 'Move to:',
2407
+ choices: places.map((value)=>({
2408
+ name: value === unit.ownerPath ? `${placeName(value)} (stays)` : placeName(value),
2409
+ value
2410
+ }))
2411
+ });
2412
+ let aggregate;
2413
+ const aggregates = ownerPath === sharedKernelPath ? [] : aggregatesOf(ownerPath);
2414
+ if (('entity' === unit.kind || 'value-object' === unit.kind) && aggregates.length) {
2415
+ const picked = await prompts_select({
2416
+ message: 'Aggregate:',
2417
+ choices: [
2418
+ noAggregate,
2419
+ ...aggregates
2420
+ ],
2421
+ default: ownerPath === unit.ownerPath && unit.aggregate ? unit.aggregate : noAggregate
2422
+ });
2423
+ aggregate = picked === noAggregate ? void 0 : picked;
2424
+ }
2425
+ const target = (name)=>({
2426
+ ownerPath,
2427
+ aggregate,
2428
+ name: name.trim()
2429
+ });
2430
+ const name = await input({
2431
+ message: 'New name:',
2432
+ default: unit.name,
2433
+ validate: (value)=>validateBackendMove(unit, target(value), sharedKernelPath)
2434
+ });
2435
+ const result = moveBackendUnit(root, rootFolderPath, unit, target(name));
2436
+ if (result.violations) return void console.log([
2437
+ "Nothing was moved: these imports would cross a bounded context boundary.",
2438
+ ...result.violations.map(([from, to])=>` ${from} → ${to}`),
2439
+ 'Give the other context its own query or command, or move what it depends on first.'
2440
+ ].join('\n'));
2441
+ const relative = (file)=>node_path.relative(root, file);
2442
+ console.log([
2443
+ 'Files to move:',
2444
+ ...result.moves.map(([from, to])=>` ${relative(from)} → ${relative(to)}`),
2445
+ ...result.updated.length ? [
2446
+ 'Files with updated imports and names:',
2447
+ ...result.updated.map((file)=>` ${relative(file)}`)
2448
+ ] : []
2449
+ ].join('\n'));
2450
+ if (!await prompts_confirm({
2451
+ message: 'Apply?',
2452
+ default: true
2453
+ })) {
2454
+ discardPendingChanges();
2455
+ console.log('Cancelled: nothing was written.');
2456
+ }
2457
+ };
2458
+ const nestedName = (folders, fileBase)=>{
2459
+ const prefix = `${folders.join('-')}-`;
2460
+ const last = folders.length && fileBase.startsWith(prefix) ? fileBase.slice(prefix.length) : fileBase;
2461
+ return [
2462
+ ...folders,
2463
+ last
2464
+ ].join('/');
2465
+ };
2466
+ const declaredClassName = (filePath, suffix, name)=>{
2467
+ const content = node_fs.readFileSync(filePath, 'utf8');
2468
+ const declared = content.match(new RegExp(`export\\s+(?:const|function)\\s+(\\w+)${suffix}\\b`))?.[1];
2469
+ return declared ?? new NestedName(name).ClassName;
2470
+ };
2471
+ const findReactModules = (reactFolder, kind)=>{
2472
+ const modules = 'page' === kind ? walk(node_path.join(reactFolder, 'pages')).filter((file)=>file.endsWith('-page.tsx')).map((file)=>{
2473
+ const folders = node_path.relative(node_path.join(reactFolder, 'pages'), node_path.dirname(file)).split(node_path.sep).filter((segment)=>!!segment);
2474
+ const fileBase = node_path.basename(file, '-page.tsx');
2475
+ const name = nestedName(folders, fileBase);
2476
+ return {
2477
+ kind,
2478
+ name,
2479
+ path: file,
2480
+ fileBase,
2481
+ ClassName: declaredClassName(file, 'Page', name)
2482
+ };
2483
+ }) : walk(node_path.join(reactFolder, 'widgets')).filter((file)=>file.endsWith('-widget.tsx')).map((file)=>{
2484
+ const folder = node_path.dirname(file);
2485
+ const name = toPosix(node_path.relative(node_path.join(reactFolder, 'widgets'), folder));
2486
+ return {
2487
+ kind,
2488
+ name,
2489
+ path: folder,
2490
+ fileBase: node_path.basename(file, '-widget.tsx'),
2491
+ ClassName: declaredClassName(file, 'Widget', name)
2492
+ };
2493
+ });
2494
+ return modules.sort((a, b)=>a.name.localeCompare(b.name));
2495
+ };
2496
+ const targetPath = (reactFolder, module, rawName)=>{
2497
+ const { folders, folderName, fileName } = new NestedName(rawName);
2498
+ return 'page' === module.kind ? node_path.join(reactFolder, 'pages', ...folders, `${fileName}-page.tsx`) : node_path.join(reactFolder, 'widgets', ...folders, folderName);
2499
+ };
2500
+ const validateMove = (reactFolder, module, rawName)=>{
2501
+ const nameError = NestedName.validate(rawName);
2502
+ if (true !== nameError) return nameError;
2503
+ const target = targetPath(reactFolder, module, rawName);
2504
+ if (target !== module.path && node_fs.existsSync(target)) return `${node_path.relative(reactFolder, target)} already exists`;
2505
+ if (target.startsWith(`${module.path}${node_path.sep}`)) return 'A widget cannot be moved into itself';
2506
+ return true;
2507
+ };
2508
+ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
2509
+ const newName = new NestedName(rawName);
2510
+ const target = targetPath(reactFolder, module, rawName);
2511
+ const newClassName = newName.ClassName;
2512
+ const renameFile = (name)=>name.replace(new RegExp(`^(use-)?${escapeRegExp(module.fileBase)}(?=[-.])`), (_, use = '')=>`${use}${newName.fileName}`);
2513
+ const oldFolder = 'page' === module.kind ? node_path.dirname(module.path) : module.path;
2514
+ const newFolder = 'page' === module.kind ? node_path.dirname(target) : target;
2515
+ const ownsPath = (candidate)=>'page' === module.kind ? node_path.dirname(candidate) === oldFolder && new RegExp(`^${escapeRegExp(module.fileBase)}-page(?:\\.|$)`).test(node_path.basename(candidate)) : candidate === oldFolder || candidate.startsWith(`${oldFolder}${node_path.sep}`);
2516
+ const movedPath = (candidate)=>{
2517
+ if (!ownsPath(candidate)) return;
2518
+ const segments = node_path.relative(oldFolder, candidate).split(node_path.sep);
2519
+ const last = segments.length - 1;
2520
+ segments[last] = renameFile(segments[last]);
2521
+ return node_path.join(newFolder, ...segments);
2522
+ };
2523
+ const moduleFiles = 'page' === module.kind ? node_fs.readdirSync(oldFolder).map((name)=>node_path.join(oldFolder, name)).filter((file)=>node_fs.statSync(file).isFile() && ownsPath(file)) : walk(oldFolder);
2524
+ const moves = new Map(moduleFiles.map((file)=>[
2525
+ file,
2526
+ movedPath(file) ?? file
2527
+ ]));
2528
+ const suffixes = 'page' === module.kind ? 'Page' : 'Widget|UIModel';
2529
+ const classPattern = new RegExp(`(?<![\\w$])(use)?${escapeRegExp(module.ClassName)}(?=${suffixes})`, 'g');
2530
+ const oldTitle = `Widgets/${module.name.split('/').map((segment)=>new NestedName(segment).ClassName).join('/')}`;
2531
+ const titlePattern = new RegExp(`(['"\`])${escapeRegExp(oldTitle)}\\1`, 'g');
2532
+ const newTitle = [
2533
+ 'Widgets',
2534
+ ...newName.classNameSegments
2535
+ ].join('/');
2536
+ return stageModuleMove({
2537
+ projectRoot,
2538
+ stopAt: reactFolder,
2539
+ moves,
2540
+ movedPath,
2541
+ rename: (content, { moved })=>{
2542
+ const renamed = content.replace(classPattern, (_, use = '')=>`${use}${newClassName}`);
2543
+ return moved && 'widget' === module.kind ? renamed.replace(titlePattern, (_, quote)=>`${quote}${newTitle}${quote}`) : renamed;
2544
+ }
2545
+ });
2546
+ };
2039
2547
  const moveReactModuleUseCase = async (presentationReactFolder, kind)=>{
2040
2548
  const reactFolder = presentationReactFolder.path;
2041
2549
  const modules = findReactModules(reactFolder, kind);
2042
- if (!modules.length) return void console.log(`No ${kind}s generated by df-scaffold were found.`);
2550
+ if (!modules.length) return void console.log(`No ${kind}s generated by df-react were found.`);
2043
2551
  const module = await prompts_select({
2044
2552
  message: 'page' === kind ? 'Page:' : 'Widget:',
2045
2553
  choices: modules.map((value)=>({
@@ -2195,7 +2703,7 @@ describe('${aggregateNaming.withSpaces} repository', () => {
2195
2703
  'repositories'
2196
2704
  ]).createFile(`wire-${aggregateNaming.fileName}-repository.ts`, `
2197
2705
  import { wireClass } from '@domain-first/wire'
2198
- import { envBranchedWire } from '../../../../shared/wiring/env-branched-wire'
2706
+ import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
2199
2707
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${aggregateNaming.ClassName}Repository } from '../../infrastructure/repositories/${fileName}/${fileName}-${aggregateNaming.fileName}-repository'`).join('\n')}
2200
2708
 
2201
2709
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${aggregateNaming.ClassName}Repository, [])`).join('\n\n')}
@@ -2291,7 +2799,7 @@ describe('${naming.withSpaces}', () => {
2291
2799
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2292
2800
  const wireFile = wiringFolder.createFile(`wire-${naming.fileName}.ts`, `
2293
2801
  import { wireClass } from '@domain-first/wire'
2294
- import { envBranchedWire } from '../../../${'shared' === boundedContextFolder.name ? '' : '../'}shared/wiring/env-branched-wire'
2802
+ import { envBranchedWire } from '../../../${'shared-kernel' === boundedContextFolder.name ? '' : '../'}shared-kernel/wiring/env-branched-wire'
2295
2803
  ${implementationTypes.map((x)=>({
2296
2804
  naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
2297
2805
  implementation: x
@@ -2374,14 +2882,6 @@ const scaffoldNewBoundedContextUseCase = async ()=>{
2374
2882
  'bounded-contexts',
2375
2883
  name
2376
2884
  ]);
2377
- if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/errors')) folder.subitem([
2378
- 'domain',
2379
- 'errors'
2380
- ]).createFile('index.ts', `
2381
- import { errorNamespace } from '@domain-first/errors'
2382
-
2383
- export const ${new UnknownFormatNaming(name).ClassName}Errors = errorNamespace('${name}')
2384
- `.trim());
2385
2885
  folder.createIfNotExisted();
2386
2886
  };
2387
2887
  const scaffoldNewCommand = async (boundedContextFolder)=>{
@@ -2493,7 +2993,7 @@ describe('${naming.withSpaces} command', () => {
2493
2993
  'commands'
2494
2994
  ]).createFile(`wire-${naming.fileName}-command.ts`, `
2495
2995
  import { wireClass } from '@domain-first/wire'
2496
- import { envBranchedWire } from '../../../../shared/wiring/env-branched-wire'
2996
+ import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
2497
2997
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${naming.ClassName}Command } from '../../infrastructure/commands/${fileName}/${fileName}-${naming.fileName}-command'`).join('\n')}
2498
2998
 
2499
2999
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${naming.ClassName}Command, [])`).join('\n\n')}
@@ -2507,7 +3007,7 @@ export const wire${naming.ClassName}Command = envBranchedWire({
2507
3007
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
2508
3008
  }
2509
3009
  };
2510
- const noAggregate = 'No aggregate';
3010
+ const scaffold_new_domain_object_noAggregate = 'No aggregate';
2511
3011
  const scaffoldNewDomainObject = async (boundedContextFolder, kind)=>{
2512
3012
  const name = await input({
2513
3013
  message: 'Name: '
@@ -2522,11 +3022,11 @@ const scaffoldNewDomainObject = async (boundedContextFolder, kind)=>{
2522
3022
  message: 'Aggregate:',
2523
3023
  choices: [
2524
3024
  ...aggregateNames,
2525
- noAggregate
3025
+ scaffold_new_domain_object_noAggregate
2526
3026
  ]
2527
- }) : noAggregate;
3027
+ }) : scaffold_new_domain_object_noAggregate;
2528
3028
  const kindFolderName = 'entity' === kind ? 'entities' : 'value-objects';
2529
- const folder = aggregate === noAggregate ? boundedContextFolder.subitem([
3029
+ const folder = aggregate === scaffold_new_domain_object_noAggregate ? boundedContextFolder.subitem([
2530
3030
  'domain',
2531
3031
  kindFolderName
2532
3032
  ]) : aggregatesFolder.subitem([
@@ -2541,7 +3041,7 @@ import { domainType } from '@domain-first/types'
2541
3041
  export class ${naming.ClassName} extends domainType() {
2542
3042
 
2543
3043
  }`.trim() : `export class ${naming.ClassName} {}`);
2544
- if (aggregate !== noAggregate) aggregatesFolder.subitem([
3044
+ if (aggregate !== scaffold_new_domain_object_noAggregate) aggregatesFolder.subitem([
2545
3045
  aggregate
2546
3046
  ]).file('index.ts').addLineIfMissing(`export * from './${kindFolderName}/${fileName}'`);
2547
3047
  const { testingLibrary } = ConfigFile.Instance.data;
@@ -2614,14 +3114,26 @@ export const wire${naming.ClassName}DomainService = wireClass(
2614
3114
  const errorNames = (boundedContextFolder)=>{
2615
3115
  const isShared = boundedContextFolder.path === new Folder(new ProjectRoot().path).subitem([
2616
3116
  ConfigFile.Instance.data.rootFolder,
2617
- 'shared'
3117
+ 'shared-kernel'
2618
3118
  ]).path;
2619
3119
  return {
2620
- namespace: (namespaceName)=>`${namespaceName}${isShared ? 'Shared' : ''}Errors`,
2621
- error: (errorName)=>`${errorName}${isShared ? 'SharedError' : ''}`
3120
+ namespace: (namespaceName)=>`${namespaceName}${isShared ? 'SharedKernel' : ''}Errors`,
3121
+ error: (errorName)=>`${errorName}${isShared ? 'SharedKernelError' : ''}`
2622
3122
  };
2623
3123
  };
2624
- const exportedNamespace = (file, fallback)=>/export\s+const\s+(\w+)\s*=\s*errorNamespace\b/.exec(file.data)?.[1] ?? fallback;
3124
+ const namespacePattern = /export\s+const\s+(\w+)\s*=\s*errorNamespace\b/;
3125
+ const exportedNamespace = (file, fallback)=>namespacePattern.exec(file.data)?.[1] ?? fallback;
3126
+ const rootNamespace = (indexFile, namespace, code)=>{
3127
+ const content = indexFile.exists ? indexFile.data.trim() : '';
3128
+ const existing = namespacePattern.exec(content)?.[1];
3129
+ if (existing) return existing;
3130
+ indexFile.update([
3131
+ "import { errorNamespace } from '@domain-first/errors'",
3132
+ `export const ${namespace} = errorNamespace('${code}')`,
3133
+ content
3134
+ ].filter((x)=>!!x).join('\n\n'));
3135
+ return namespace;
3136
+ };
2625
3137
  const errorClass = (className, namespace, code)=>`export class ${className} extends ${namespace}.define('${code}') {}`;
2626
3138
  const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
2627
3139
  const currentErrorFolder = boundedContextFolder.subitem([
@@ -2646,7 +3158,7 @@ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
2646
3158
  });
2647
3159
  const naming = new UnknownFormatNaming(errorName);
2648
3160
  const indexFile = currentErrorFolder.file('index.ts');
2649
- indexFile.addLineIfMissing(errorClass(names.error(naming.ClassName), exportedNamespace(indexFile, `${contextNaming.ClassName}Errors`), naming.fileName), '\n\n');
3161
+ indexFile.addLineIfMissing(errorClass(names.error(naming.ClassName), rootNamespace(indexFile, `${contextNaming.ClassName}Errors`, boundedContextFolder.name), naming.fileName), '\n\n');
2650
3162
  return;
2651
3163
  }
2652
3164
  if ('New namespace' === selectedVariant) {
@@ -2739,7 +3251,7 @@ export const restHandlers = restWires.map(x => x().handle)
2739
3251
  const endpointGenerator = findRestEndpointGenerator(boundedContextFolder.subitem([
2740
3252
  '..',
2741
3253
  '..',
2742
- 'shared'
3254
+ 'shared-kernel'
2743
3255
  ]));
2744
3256
  const handler = withWiring ? await promptEndpointHandler(boundedContextFolder) : void 0;
2745
3257
  const endpointFile = node_path.join(endpointFolder.path, `${method.toUpperCase()}.ts`);
@@ -2947,7 +3459,7 @@ describe('${naming.withSpaces} query', () => {
2947
3459
  'queries'
2948
3460
  ]).createFile(`wire-${naming.fileName}-query.ts`, `
2949
3461
  import { wireClass } from '@domain-first/wire'
2950
- import { envBranchedWire } from '../../../../shared/wiring/env-branched-wire'
3462
+ import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
2951
3463
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${naming.ClassName}Query } from '../../infrastructure/queries/${fileName}/${fileName}-${naming.fileName}-query'`).join('\n')}
2952
3464
 
2953
3465
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${naming.ClassName}Query, [])`).join('\n\n')}
@@ -3214,4 +3726,4 @@ export const use${ClassName}UIModel = (widgetProps: Omit<${ClassName}WidgetProps
3214
3726
  break;
3215
3727
  }
3216
3728
  };
3217
- export { addIntegration, initializeUseCase, moveReactModuleUseCase, printNextSteps, savePendingChanges, scaffoldNewAggregateUseCase, scaffoldNewApplicationPort, scaffoldNewApplicationService, scaffoldNewBoundedContextUseCase, scaffoldNewCommand, scaffoldNewDomainObject, scaffoldNewDomainService, scaffoldNewErrorUseCase, scaffoldNewHandlersRestEndpoint, scaffoldNewInfrastructureService, scaffoldNewPresentationService, scaffoldNewQuery, scaffoldNewUseCase, scaffoldReactPage, scaffoldReactSharedHook, scaffoldReactUIKitComponent, scaffoldReactWidget, wireDependency };
3729
+ export { addIntegration, initializeUseCase, moveBackendUnitUseCase, moveReactModuleUseCase, printNextSteps, savePendingChanges, scaffoldNewAggregateUseCase, scaffoldNewApplicationPort, scaffoldNewApplicationService, scaffoldNewBoundedContextUseCase, scaffoldNewCommand, scaffoldNewDomainObject, scaffoldNewDomainService, scaffoldNewErrorUseCase, scaffoldNewHandlersRestEndpoint, scaffoldNewInfrastructureService, scaffoldNewPresentationService, scaffoldNewQuery, scaffoldNewUseCase, scaffoldReactPage, scaffoldReactSharedHook, scaffoldReactUIKitComponent, scaffoldReactWidget, wireDependency };