@domain-first/project-structure 5.1.2 → 7.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -21
- package/dist/201.js +46 -35
- package/dist/287.js +3290 -0
- package/dist/config-file.d.ts +2 -2
- package/dist/dependency-rules.d.ts +1 -1
- package/dist/file-system.d.ts +5 -0
- package/dist/in-memory-db.d.ts +5 -0
- package/dist/index.cjs +195 -2156
- package/dist/index.js +9 -3169
- package/dist/init.cjs +868 -0
- package/dist/init.d.ts +2 -0
- package/dist/init.js +36 -0
- package/dist/integration.cjs +2063 -0
- package/dist/integration.d.ts +2 -0
- package/dist/integration.js +31 -0
- package/dist/integrations/in-memory-db.d.ts +6 -0
- package/dist/integrations/index.d.ts +2 -0
- package/dist/integrations/missing-domain-first-packages.d.ts +8 -0
- package/dist/integrations/orval.d.ts +7 -4
- package/dist/integrations/rest-endpoint-generator.d.ts +18 -0
- package/dist/integrations/rest-endpoint-generator.spec.d.ts +1 -0
- package/dist/lint.cjs +8 -8
- package/dist/lint.js +7 -7
- package/dist/print-next-steps.d.ts +9 -2
- package/dist/react.cjs +915 -0
- package/dist/react.d.ts +2 -0
- package/dist/react.js +73 -0
- package/dist/use-cases/add-integration-order.spec.d.ts +1 -0
- package/dist/use-cases/rest-endpoint-generator.d.ts +1 -1
- package/package.json +5 -2
- package/skills/df-ps-implement/SKILL.md +12 -57
- package/skills/df-ps-plan-feature/SKILL.md +7 -7
- package/skills/df-ps-project-scripts/SKILL.md +1 -1
- package/skills/df-ps-react/SKILL.md +82 -0
- package/skills/df-ps-react/references/generators.md +80 -0
- package/skills/df-ps-scaffold/SKILL.md +46 -28
- package/skills/df-ps-scaffold/references/choosing-components.md +7 -28
- package/skills/df-ps-scaffold/references/generators.md +6 -179
- package/skills/df-ps-scaffold/references/units/aggregate.md +47 -0
- package/skills/df-ps-scaffold/references/units/bounded-context.md +13 -0
- package/skills/df-ps-scaffold/references/units/command-query.md +32 -0
- package/skills/df-ps-scaffold/references/units/endpoint.md +28 -0
- package/skills/df-ps-scaffold/references/units/entity-value-object.md +27 -0
- package/skills/df-ps-scaffold/references/units/errors.md +26 -0
- package/skills/df-ps-scaffold/references/units/port.md +23 -0
- package/skills/df-ps-scaffold/references/units/services.md +28 -0
- package/skills/df-ps-scaffold/references/units/use-case.md +25 -0
- package/skills/df-ps-scaffold/references/units/wire-dependency.md +15 -0
- package/skills/df-ps-scaffold/scripts/drive.mjs +12 -4
package/dist/287.js
ADDED
|
@@ -0,0 +1,3290 @@
|
|
|
1
|
+
import node_path from "node:path";
|
|
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
|
+
import node_fs from "node:fs";
|
|
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";
|
|
6
|
+
const savePendingChanges = async ()=>{
|
|
7
|
+
const overwrittenFiles = filesToOverwrite();
|
|
8
|
+
if (overwrittenFiles.length) {
|
|
9
|
+
const root = new ProjectRoot().path;
|
|
10
|
+
console.log('These files already exist and will be overwritten:');
|
|
11
|
+
for (const filePath of overwrittenFiles)console.log(` ${node_path.relative(root, filePath)}`);
|
|
12
|
+
const overwrite = await prompts_confirm({
|
|
13
|
+
message: 'Overwrite them?',
|
|
14
|
+
default: false
|
|
15
|
+
});
|
|
16
|
+
if (!overwrite) {
|
|
17
|
+
discardPendingChanges();
|
|
18
|
+
console.log('Cancelled: nothing was written.');
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
writePendingChanges();
|
|
23
|
+
return true;
|
|
24
|
+
};
|
|
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;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
declare global {
|
|
35
|
+
var ___SHARED_IN_MEMORY_DB___: Record<string, Array<Entry>> | undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
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;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
type IdsAreEqual<TId> = (a: TId, b: TId) => boolean;
|
|
49
|
+
|
|
50
|
+
const comparisonMethodNames = ['equals', 'same', 'isSame', 'isEqual'] as const;
|
|
51
|
+
|
|
52
|
+
const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
|
|
53
|
+
if (typeof a !== 'object' || a === null) {
|
|
54
|
+
return Object.is(a, b);
|
|
55
|
+
}
|
|
56
|
+
|
|
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));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return Object.is(a, b);
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const hasId = (x: unknown): x is { id: unknown } =>
|
|
68
|
+
typeof x === 'object' && x !== null && 'id' in x;
|
|
69
|
+
|
|
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
|
+
}
|
|
86
|
+
|
|
87
|
+
if (!globalThis.___SHARED_IN_MEMORY_DB___[key]) {
|
|
88
|
+
globalThis.___SHARED_IN_MEMORY_DB___[key] = [];
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const items = (): T[] =>
|
|
92
|
+
globalThis.___SHARED_IN_MEMORY_DB___![key].map(
|
|
93
|
+
(entry) => entry.item
|
|
94
|
+
);
|
|
95
|
+
|
|
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
|
+
);
|
|
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';
|
|
138
|
+
|
|
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'"}
|
|
148
|
+
|
|
149
|
+
let inMemoryDbInfrastructureService: InMemoryDbInfrastructureService
|
|
150
|
+
|
|
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);
|
|
188
|
+
};
|
|
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}
|
|
211
|
+
}
|
|
212
|
+
`.trim();
|
|
213
|
+
const keepInMemoryDbSection = (classFile, field)=>{
|
|
214
|
+
classFile.update(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)).replace('constructor() {}', inMemoryDbSectionMembers(field, false)));
|
|
215
|
+
};
|
|
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
|
+
]));
|
|
221
|
+
};
|
|
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
|
+
]));
|
|
226
|
+
};
|
|
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);
|
|
247
|
+
return [
|
|
248
|
+
manifest.dependencies,
|
|
249
|
+
manifest.devDependencies,
|
|
250
|
+
manifest.optionalDependencies
|
|
251
|
+
].some((dependencies)=>dependencies && Object.hasOwn(dependencies, name));
|
|
252
|
+
};
|
|
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
|
+
] : [];
|
|
260
|
+
};
|
|
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;
|
|
282
|
+
};
|
|
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
|
|
300
|
+
});
|
|
301
|
+
const { folders, ClassName, fileName } = new NestedName(name);
|
|
302
|
+
presentationReactFolder.subitem([
|
|
303
|
+
'pages',
|
|
304
|
+
...folders
|
|
305
|
+
]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
|
|
306
|
+
};
|
|
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;
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
type OpenApiData = Partial<{
|
|
329
|
+
summary: string;
|
|
330
|
+
description: string;
|
|
331
|
+
operationId: string;
|
|
332
|
+
}>;
|
|
333
|
+
|
|
334
|
+
const project = new Project({
|
|
335
|
+
tsConfigFilePath: 'tsconfig.json'
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
const getText = (node: DocNode): string =>
|
|
339
|
+
node
|
|
340
|
+
.getChildNodes()
|
|
341
|
+
.map((child) => {
|
|
342
|
+
if (child instanceof DocPlainText) {
|
|
343
|
+
return child.text;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
return getText(child);
|
|
347
|
+
})
|
|
348
|
+
.join('');
|
|
349
|
+
|
|
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');
|
|
357
|
+
|
|
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);
|
|
363
|
+
|
|
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
|
+
}
|
|
374
|
+
|
|
375
|
+
const { docComment } = new TSDocParser(configuration).parseString(comment);
|
|
376
|
+
|
|
377
|
+
return getText(docComment.summarySection).trim() || undefined;
|
|
378
|
+
};
|
|
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;
|
|
389
|
+
};
|
|
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
|
+
const root = new ProjectRoot().path;
|
|
562
|
+
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
563
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
564
|
+
const dependencies = {
|
|
565
|
+
...manifest.dependencies,
|
|
566
|
+
...manifest.devDependencies
|
|
567
|
+
};
|
|
568
|
+
const routePrefix = await input({
|
|
569
|
+
message: 'Route prefix the REST handlers are served under:',
|
|
570
|
+
default: '/api'
|
|
571
|
+
});
|
|
572
|
+
const outputPath = await input({
|
|
573
|
+
message: 'OpenAPI document path:',
|
|
574
|
+
default: defaultOpenapiPath(Boolean(dependencies.next)),
|
|
575
|
+
validate: (value)=>splitPath(value).length ? true : 'Path is required'
|
|
576
|
+
});
|
|
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'
|
|
605
|
+
],
|
|
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
|
+
[
|
|
778
|
+
'api-client/mutator.ts',
|
|
779
|
+
orvalMutator
|
|
780
|
+
]
|
|
781
|
+
],
|
|
782
|
+
...'hooks' === target ? [
|
|
783
|
+
[
|
|
784
|
+
'query-provider.tsx',
|
|
785
|
+
queryProvider
|
|
786
|
+
]
|
|
787
|
+
] : []
|
|
788
|
+
]){
|
|
789
|
+
const file = new File(node_path.join(root, dataLayer, name));
|
|
790
|
+
if (!file.exists) file.data = fileContent;
|
|
791
|
+
}
|
|
792
|
+
addGitignoreEntry(root, `/${dataLayer}/orval/`);
|
|
793
|
+
}
|
|
794
|
+
const generated = targets.map((target)=>'hooks' === target ? `React Query hooks in ${dataLayerFolder(rootFolder, 'hooks')}/orval` : `a typed API client in ${dataLayerFolder(rootFolder, 'client')}/orval`);
|
|
795
|
+
const missing = (names)=>names.filter((name)=>!dependencies[name]);
|
|
796
|
+
const runtime = missing(targets.includes('hooks') ? [
|
|
797
|
+
'@tanstack/react-query'
|
|
798
|
+
] : []);
|
|
799
|
+
const development = missing([
|
|
800
|
+
'orval'
|
|
801
|
+
]);
|
|
802
|
+
return [
|
|
803
|
+
...runtime.length ? [
|
|
804
|
+
`npm install ${runtime.join(' ')}`
|
|
805
|
+
] : [],
|
|
806
|
+
...development.length ? [
|
|
807
|
+
`npm install --save-dev ${development.join(' ')}`
|
|
808
|
+
] : [],
|
|
809
|
+
...describeScripts(selected, {
|
|
810
|
+
'client:orval': `generate ${generated.join(' and ')} from ${openapiPath.trim()}`
|
|
811
|
+
}),
|
|
812
|
+
...targets.includes('hooks') ? [
|
|
813
|
+
`Wrap your app in QueryProvider from ${dataLayerFolder(rootFolder, 'hooks')}/query-provider.tsx`
|
|
814
|
+
] : [],
|
|
815
|
+
...generatedOpenapiPath ? [] : [
|
|
816
|
+
'npx df-integration → OpenAPI generates the OpenAPI document the client is built from'
|
|
817
|
+
]
|
|
818
|
+
];
|
|
819
|
+
};
|
|
820
|
+
const playwrightScripts = {
|
|
821
|
+
'test:e2e': 'playwright test'
|
|
822
|
+
};
|
|
823
|
+
const playwrightConfig = `import { defineConfig, devices } from '@playwright/test';
|
|
824
|
+
|
|
825
|
+
export default defineConfig({
|
|
826
|
+
testDir: './specs/e2e',
|
|
827
|
+
fullyParallel: true,
|
|
828
|
+
forbidOnly: !!process.env.CI,
|
|
829
|
+
retries: process.env.CI ? 2 : 0,
|
|
830
|
+
workers: process.env.CI ? 1 : undefined,
|
|
831
|
+
reporter: 'html',
|
|
832
|
+
use: {
|
|
833
|
+
baseURL: 'http://localhost:3000',
|
|
834
|
+
trace: 'on-first-retry',
|
|
835
|
+
screenshot: 'only-on-failure',
|
|
836
|
+
video: 'retain-on-failure'
|
|
837
|
+
},
|
|
838
|
+
|
|
839
|
+
projects: [
|
|
840
|
+
{
|
|
841
|
+
name: 'chromium',
|
|
842
|
+
use: { ...devices['Desktop Chrome'] }
|
|
843
|
+
},
|
|
844
|
+
{
|
|
845
|
+
name: 'firefox',
|
|
846
|
+
use: { ...devices['Desktop Firefox'] }
|
|
847
|
+
},
|
|
848
|
+
{
|
|
849
|
+
name: 'webkit',
|
|
850
|
+
use: { ...devices['Desktop Safari'] }
|
|
851
|
+
},
|
|
852
|
+
{
|
|
853
|
+
name: 'Mobile Chrome',
|
|
854
|
+
use: { ...devices['Pixel 5'] }
|
|
855
|
+
},
|
|
856
|
+
{
|
|
857
|
+
name: 'Mobile Safari',
|
|
858
|
+
use: { ...devices['iPhone 12'] }
|
|
859
|
+
}
|
|
860
|
+
],
|
|
861
|
+
|
|
862
|
+
webServer: {
|
|
863
|
+
// Playwright only stops the dev server on a clean shutdown. If its process dies any other
|
|
864
|
+
// way (SIGHUP, SIGKILL), the dev server lives on in its own process group, so it is killed
|
|
865
|
+
// as soon as Playwright is gone.
|
|
866
|
+
command:
|
|
867
|
+
process.platform === 'win32'
|
|
868
|
+
? 'npm run dev'
|
|
869
|
+
: \`npm run dev & while kill -0 \${process.pid} 2>/dev/null && kill -0 $! 2>/dev/null; do sleep 1; done; kill 0\`,
|
|
870
|
+
url: 'http://localhost:3000',
|
|
871
|
+
timeout: 120000,
|
|
872
|
+
reuseExistingServer: !process.env.CI
|
|
873
|
+
}
|
|
874
|
+
});
|
|
875
|
+
`;
|
|
876
|
+
const exampleSpec = `import { expect, test } from '@playwright/test';
|
|
877
|
+
|
|
878
|
+
test.describe('home page', () => {
|
|
879
|
+
test('opens the home page', async ({ page, baseURL }) => {
|
|
880
|
+
await page.goto('/');
|
|
881
|
+
await expect(page).toHaveURL(\`\${baseURL}/\`);
|
|
882
|
+
});
|
|
883
|
+
});
|
|
884
|
+
`;
|
|
885
|
+
const exampleReadme = `# Home page e2e cases
|
|
886
|
+
|
|
887
|
+
## User Stories
|
|
888
|
+
|
|
889
|
+
1. Guest opens \`/\` and stays on the home page.
|
|
890
|
+
`;
|
|
891
|
+
const gitignoreEntries = [
|
|
892
|
+
'/test-results/',
|
|
893
|
+
'/playwright-report/',
|
|
894
|
+
'/blob-report/',
|
|
895
|
+
'/playwright/.cache/',
|
|
896
|
+
'/playwright/.auth/'
|
|
897
|
+
];
|
|
898
|
+
const addPlaywright = async ()=>{
|
|
899
|
+
const root = new ProjectRoot().path;
|
|
900
|
+
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
901
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
902
|
+
const dependencies = {
|
|
903
|
+
...manifest.dependencies,
|
|
904
|
+
...manifest.devDependencies
|
|
905
|
+
};
|
|
906
|
+
const selected = await addPackageScripts(manifestFile, playwrightScripts);
|
|
907
|
+
const configFile = new File(node_path.join(root, 'playwright.config.ts'));
|
|
908
|
+
if (!configFile.exists || configFile.data !== playwrightConfig) configFile.data = playwrightConfig;
|
|
909
|
+
const exampleFolder = node_path.join(root, 'specs/e2e/home');
|
|
910
|
+
for (const [name, content] of [
|
|
911
|
+
[
|
|
912
|
+
'home.e2e.spec.ts',
|
|
913
|
+
exampleSpec
|
|
914
|
+
],
|
|
915
|
+
[
|
|
916
|
+
'README.MD',
|
|
917
|
+
exampleReadme
|
|
918
|
+
]
|
|
919
|
+
]){
|
|
920
|
+
const file = new File(node_path.join(exampleFolder, name));
|
|
921
|
+
if (!file.exists) file.data = content;
|
|
922
|
+
}
|
|
923
|
+
for (const entry of gitignoreEntries)addGitignoreEntry(root, entry);
|
|
924
|
+
return [
|
|
925
|
+
...dependencies['@playwright/test'] ? [] : [
|
|
926
|
+
'npm install --save-dev @playwright/test'
|
|
927
|
+
],
|
|
928
|
+
'npx playwright install --with-deps',
|
|
929
|
+
...describeScripts(selected, {
|
|
930
|
+
'test:e2e': 'start the dev server and run end-to-end specs from specs/e2e'
|
|
931
|
+
})
|
|
932
|
+
];
|
|
933
|
+
};
|
|
934
|
+
const runtimePackages = [
|
|
935
|
+
'@prisma/orm-postgres',
|
|
936
|
+
'temporal-polyfill',
|
|
937
|
+
'dotenv'
|
|
938
|
+
];
|
|
939
|
+
const developmentPackages = [
|
|
940
|
+
'prisma',
|
|
941
|
+
'@prisma/cli-engine'
|
|
942
|
+
];
|
|
943
|
+
const prismaScripts = (rootFolder)=>{
|
|
944
|
+
const config = JSON.stringify(node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'shared-kernel/infrastructure/prisma/prisma.config.ts'));
|
|
945
|
+
const emit = `prisma contract emit --config ${config}`;
|
|
946
|
+
return {
|
|
947
|
+
'prisma:emit': emit,
|
|
948
|
+
'prisma:migration:plan': `${emit} && prisma migration plan --config ${config}`,
|
|
949
|
+
'prisma:migration:apply': `prisma db migrate --advance-ref db --config ${config}`
|
|
950
|
+
};
|
|
951
|
+
};
|
|
952
|
+
const prismaConfig = `import 'dotenv/config';
|
|
953
|
+
import { definePrismaConfig } from '@prisma/cli-engine';
|
|
954
|
+
import { defineConfig as ormConfig } from '@prisma/orm-postgres/config';
|
|
955
|
+
|
|
956
|
+
export default definePrismaConfig({
|
|
957
|
+
orm: ormConfig({
|
|
958
|
+
contract: './contract.prisma',
|
|
959
|
+
migrations: { dir: './migrations' },
|
|
960
|
+
db: {
|
|
961
|
+
connection: process.env.DATABASE_URL
|
|
962
|
+
}
|
|
963
|
+
})
|
|
964
|
+
});
|
|
965
|
+
`;
|
|
966
|
+
const prismaService = `import 'temporal-polyfill/global';
|
|
967
|
+
import postgres from '@prisma/orm-postgres/runtime';
|
|
968
|
+
import type {} from 'temporal-polyfill/types/global';
|
|
969
|
+
import type { Contract } from '../prisma/contract.d';
|
|
970
|
+
import contractJson from '../prisma/contract.json' with { type: 'json' };
|
|
971
|
+
|
|
972
|
+
type PrismaClient = ReturnType<typeof postgres<Contract>>;
|
|
973
|
+
|
|
974
|
+
const globalForPrisma = globalThis as typeof globalThis & {
|
|
975
|
+
prismaClient?: PrismaClient;
|
|
976
|
+
};
|
|
977
|
+
|
|
978
|
+
// Reuse the client across development hot reloads.
|
|
979
|
+
const prismaClient = globalForPrisma.prismaClient ??
|
|
980
|
+
postgres<Contract>({ contractJson, url: process.env.DATABASE_URL });
|
|
981
|
+
|
|
982
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
983
|
+
globalForPrisma.prismaClient = prismaClient;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
export class PrismaInfrastructureService {
|
|
987
|
+
readonly orm = prismaClient.orm.public;
|
|
988
|
+
}
|
|
989
|
+
`;
|
|
990
|
+
const prismaWiring = `import { wireClass } from '@domain-first/wire';
|
|
991
|
+
import { PrismaInfrastructureService } from '../../infrastructure/services/prisma-infrastructure-service';
|
|
992
|
+
|
|
993
|
+
export const wirePrismaInfrastructureService = wireClass(
|
|
994
|
+
PrismaInfrastructureService,
|
|
995
|
+
[]
|
|
996
|
+
);
|
|
997
|
+
`;
|
|
998
|
+
const stageFile = (filePath, content)=>{
|
|
999
|
+
const file = new File(filePath);
|
|
1000
|
+
if (!file.exists || file.data !== content) file.data = content;
|
|
1001
|
+
};
|
|
1002
|
+
const addPrisma = async ()=>{
|
|
1003
|
+
const config = ConfigFile.Instance.data;
|
|
1004
|
+
const root = new ProjectRoot().path;
|
|
1005
|
+
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
1006
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
1007
|
+
const dependencies = {
|
|
1008
|
+
...manifest.dependencies,
|
|
1009
|
+
...manifest.devDependencies
|
|
1010
|
+
};
|
|
1011
|
+
const shared = node_path.resolve(root, config.rootFolder, 'shared-kernel');
|
|
1012
|
+
const prismaFolder = node_path.join(shared, 'infrastructure/prisma');
|
|
1013
|
+
if (dependencies['@prisma/client'] || dependencies.prisma && !/^[~^]?8\./.test(dependencies.prisma) || dependencies['@prisma/orm-mongo'] || dependencies['@prisma/orm-sqlite'] || [
|
|
1014
|
+
node_path.join(root, 'prisma/schema.prisma'),
|
|
1015
|
+
node_path.join(prismaFolder, 'schema.prisma')
|
|
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.');
|
|
1017
|
+
const withService = await prompts_confirm({
|
|
1018
|
+
message: 'Create the Prisma infrastructure service in the Shared Kernel?',
|
|
1019
|
+
default: true
|
|
1020
|
+
});
|
|
1021
|
+
const useByDefault = 'prisma' !== config.defaultPersistenceLayerImplementation && await prompts_confirm({
|
|
1022
|
+
message: 'Use prisma as the default persistence implementation?',
|
|
1023
|
+
default: false
|
|
1024
|
+
});
|
|
1025
|
+
const selected = await addPackageScripts(manifestFile, prismaScripts(config.rootFolder));
|
|
1026
|
+
stageFile(node_path.join(prismaFolder, 'prisma.config.ts'), prismaConfig);
|
|
1027
|
+
const contract = new File(node_path.join(prismaFolder, 'contract.prisma'));
|
|
1028
|
+
if (!contract.exists) contract.data = '// use prisma-8\n\n// Add your application models here before running prisma:emit.\n';
|
|
1029
|
+
if (withService) {
|
|
1030
|
+
stageFile(node_path.join(shared, 'infrastructure/services/prisma-infrastructure-service.ts'), prismaService);
|
|
1031
|
+
if (config.domainFirstPackages.includes('@domain-first/wire')) stageFile(node_path.join(shared, 'wiring/infrastructure-services/wire-prisma-infrastructure-service.ts'), prismaWiring);
|
|
1032
|
+
}
|
|
1033
|
+
if (useByDefault) ConfigFile.write({
|
|
1034
|
+
...config,
|
|
1035
|
+
defaultPersistenceLayerImplementation: 'prisma'
|
|
1036
|
+
});
|
|
1037
|
+
const install = (packages, dev)=>{
|
|
1038
|
+
const missing = packages.filter((name)=>!dependencies[name]);
|
|
1039
|
+
return missing.length ? [
|
|
1040
|
+
`npm install${dev ? ' --save-dev' : ''} ${missing.join(' ')}`
|
|
1041
|
+
] : [];
|
|
1042
|
+
};
|
|
1043
|
+
const relativeFolder = node_path.relative(root, prismaFolder).split(node_path.sep).join('/');
|
|
1044
|
+
return [
|
|
1045
|
+
...install(runtimePackages, false),
|
|
1046
|
+
...install(developmentPackages, true),
|
|
1047
|
+
`Add !${relativeFolder} in your linter, to ignore prisma files.`,
|
|
1048
|
+
...describeScripts(selected, {
|
|
1049
|
+
'prisma:emit': 'emit contract.json and contract.d.ts from contract.prisma',
|
|
1050
|
+
'prisma:migration:plan': 'emit the contract and plan a migration',
|
|
1051
|
+
'prisma:migration:apply': 'apply planned migrations to the database in DATABASE_URL'
|
|
1052
|
+
})
|
|
1053
|
+
];
|
|
1054
|
+
};
|
|
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'
|
|
1065
|
+
};
|
|
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
|
+
];
|
|
1094
|
+
};
|
|
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
|
+
});
|
|
1381
|
+
const storybookScripts = (rootFolder)=>{
|
|
1382
|
+
const folder = node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react');
|
|
1383
|
+
const quote = (value)=>JSON.stringify(value);
|
|
1384
|
+
return {
|
|
1385
|
+
storybook: `storybook dev -p 6006 -c ${quote(`${folder}/.storybook`)}`,
|
|
1386
|
+
'build-storybook': `storybook build -c ${quote(`${folder}/.storybook`)} -o ${quote(`${folder}/storybook-static`)}`
|
|
1387
|
+
};
|
|
1388
|
+
};
|
|
1389
|
+
const addStorybook = async ()=>{
|
|
1390
|
+
const config = ConfigFile.Instance.data;
|
|
1391
|
+
if ((!config.useReact || config.storybookFramework && '@storybook/react-vite' !== config.storybookFramework) && !await prompts_confirm({
|
|
1392
|
+
message: 'Configure React scaffolding with @storybook/react-vite?',
|
|
1393
|
+
default: false
|
|
1394
|
+
})) return [];
|
|
1395
|
+
const root = new ProjectRoot().path;
|
|
1396
|
+
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
1397
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
1398
|
+
const selected = await addPackageScripts(manifestFile, storybookScripts(config.rootFolder));
|
|
1399
|
+
const folder = new Folder(root).subitem([
|
|
1400
|
+
config.rootFolder,
|
|
1401
|
+
'presentation',
|
|
1402
|
+
'react',
|
|
1403
|
+
'.storybook'
|
|
1404
|
+
]);
|
|
1405
|
+
for (const [name, content] of Object.entries(storybookFiles(node_path.relative(folder.path, root).split(node_path.sep).join('/')))){
|
|
1406
|
+
const file = new File(node_path.join(folder.path, name));
|
|
1407
|
+
if (!file.exists || file.data !== content) file.data = content;
|
|
1408
|
+
}
|
|
1409
|
+
if (!config.useReact || '@storybook/react-vite' !== config.storybookFramework) ConfigFile.write({
|
|
1410
|
+
...config,
|
|
1411
|
+
useReact: true,
|
|
1412
|
+
storybookFramework: '@storybook/react-vite'
|
|
1413
|
+
});
|
|
1414
|
+
const buildFolder = node_path.posix.join(config.rootFolder.replaceAll('\\', '/'), 'presentation/react/storybook-static');
|
|
1415
|
+
addGitignoreEntry(root, `/${buildFolder}/`);
|
|
1416
|
+
const dependencies = {
|
|
1417
|
+
...manifest.dependencies,
|
|
1418
|
+
...manifest.devDependencies
|
|
1419
|
+
};
|
|
1420
|
+
const missing = [
|
|
1421
|
+
'storybook',
|
|
1422
|
+
'@storybook/react-vite',
|
|
1423
|
+
'vite',
|
|
1424
|
+
'@vitejs/plugin-react'
|
|
1425
|
+
].filter((name)=>!dependencies[name]);
|
|
1426
|
+
const missingReact = [
|
|
1427
|
+
'react',
|
|
1428
|
+
'react-dom'
|
|
1429
|
+
].filter((name)=>!dependencies[name]);
|
|
1430
|
+
return [
|
|
1431
|
+
...missing.length ? [
|
|
1432
|
+
`npm install --save-dev ${missing.join(' ')}`
|
|
1433
|
+
] : [],
|
|
1434
|
+
...missingReact.length ? [
|
|
1435
|
+
`npm install ${missingReact.join(' ')}`
|
|
1436
|
+
] : [],
|
|
1437
|
+
...describeScripts(selected, {
|
|
1438
|
+
storybook: 'start Storybook on http://localhost:6006',
|
|
1439
|
+
'build-storybook': `build static Storybook into ${buildFolder}`
|
|
1440
|
+
})
|
|
1441
|
+
];
|
|
1442
|
+
};
|
|
1443
|
+
const integrationFolder = 'specs/integration';
|
|
1444
|
+
const testcontainersScripts = {
|
|
1445
|
+
'test:integration': `vitest run --config ${integrationFolder}/vitest.config.ts --reporter=dot --silent=passed-only`
|
|
1446
|
+
};
|
|
1447
|
+
const testcontainersVitestConfig = (inlineHandlersNext)=>{
|
|
1448
|
+
const server = inlineHandlersNext ? `,
|
|
1449
|
+
server: {
|
|
1450
|
+
deps: {
|
|
1451
|
+
// Imports \`next/headers\` without an extension, which only a bundler can resolve
|
|
1452
|
+
inline: ['@domain-first/handlers-next']
|
|
1453
|
+
}
|
|
1454
|
+
}` : '';
|
|
1455
|
+
return `import { fileURLToPath } from 'node:url';
|
|
1456
|
+
import { defineConfig } from 'vitest/config';
|
|
1457
|
+
|
|
1458
|
+
// Runs specs from this folder against PostgreSQL in a container, see global-setup.ts.
|
|
1459
|
+
export default defineConfig({
|
|
1460
|
+
// Paths below are relative to the project root, not this folder
|
|
1461
|
+
root: fileURLToPath(new URL('../..', import.meta.url)),
|
|
1462
|
+
resolve: {
|
|
1463
|
+
tsconfigPaths: true
|
|
1464
|
+
},
|
|
1465
|
+
test: {
|
|
1466
|
+
include: ['${integrationFolder}/**/*.spec.ts'],
|
|
1467
|
+
// Development implementations work with the real database
|
|
1468
|
+
env: { NODE_ENV: 'development' },
|
|
1469
|
+
globalSetup: ['${integrationFolder}/global-setup.ts'],
|
|
1470
|
+
setupFiles: ['${integrationFolder}/setup-env.ts'],
|
|
1471
|
+
// Pulling the image on the first run takes a while
|
|
1472
|
+
hookTimeout: 120_000${server}
|
|
1473
|
+
}
|
|
1474
|
+
});
|
|
1475
|
+
`;
|
|
1476
|
+
};
|
|
1477
|
+
const testcontainersGlobalSetup = (migrationCommand)=>{
|
|
1478
|
+
const migrations = migrationCommand ? `
|
|
1479
|
+
// dotenv in the Prisma config does not override an already set variable
|
|
1480
|
+
execSync(${JSON.stringify(migrationCommand)}, {
|
|
1481
|
+
cwd: project.config.root,
|
|
1482
|
+
env: { ...process.env, DATABASE_URL: databaseUrl },
|
|
1483
|
+
// On failure the error carries the command's output
|
|
1484
|
+
stdio: 'pipe'
|
|
1485
|
+
});
|
|
1486
|
+
` : `
|
|
1487
|
+
// Apply your migrations to databaseUrl here.
|
|
1488
|
+
`;
|
|
1489
|
+
return `${migrationCommand ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
|
|
1490
|
+
import type { TestProject } from 'vitest/node';
|
|
1491
|
+
|
|
1492
|
+
declare module 'vitest' {
|
|
1493
|
+
export interface ProvidedContext {
|
|
1494
|
+
databaseUrl: string;
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1498
|
+
const POSTGRES_IMAGE = 'postgres:15';
|
|
1499
|
+
const POSTGRES_PORT = 5432;
|
|
1500
|
+
const POSTGRES_USER = 'test';
|
|
1501
|
+
const POSTGRES_PASSWORD = 'test';
|
|
1502
|
+
const POSTGRES_DB = 'test';
|
|
1503
|
+
|
|
1504
|
+
export default async function setup(project: TestProject) {
|
|
1505
|
+
const container = await new GenericContainer(POSTGRES_IMAGE)
|
|
1506
|
+
.withEnvironment({ POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB })
|
|
1507
|
+
.withExposedPorts(POSTGRES_PORT)
|
|
1508
|
+
// During init PostgreSQL listens on a unix socket only and restarts,
|
|
1509
|
+
// so checking over TCP passes once the final server is up
|
|
1510
|
+
.withHealthCheck({
|
|
1511
|
+
test: [
|
|
1512
|
+
'CMD-SHELL',
|
|
1513
|
+
\`pg_isready --host localhost --username \${POSTGRES_USER} --dbname \${POSTGRES_DB}\`
|
|
1514
|
+
],
|
|
1515
|
+
interval: 250,
|
|
1516
|
+
timeout: 1000,
|
|
1517
|
+
retries: 1000
|
|
1518
|
+
})
|
|
1519
|
+
.withWaitStrategy(Wait.forHealthCheck())
|
|
1520
|
+
.withStartupTimeout(120_000)
|
|
1521
|
+
.start();
|
|
1522
|
+
|
|
1523
|
+
const databaseUrl = \`postgresql://\${POSTGRES_USER}:\${POSTGRES_PASSWORD}@\${container.getHost()}:\${container.getMappedPort(POSTGRES_PORT)}/\${POSTGRES_DB}\`;
|
|
1524
|
+
${migrations}
|
|
1525
|
+
project.provide('databaseUrl', databaseUrl);
|
|
1526
|
+
|
|
1527
|
+
return async () => {
|
|
1528
|
+
await container.stop();
|
|
1529
|
+
};
|
|
1530
|
+
}
|
|
1531
|
+
`;
|
|
1532
|
+
};
|
|
1533
|
+
const testcontainersSetupEnv = `import 'dotenv/config';
|
|
1534
|
+
import { inject } from 'vitest';
|
|
1535
|
+
|
|
1536
|
+
// Runs before each spec's imports: development implementations get the .env
|
|
1537
|
+
// config, and DATABASE_URL points to the container instead of the one from .env.
|
|
1538
|
+
if (process.env.NODE_ENV !== 'development') {
|
|
1539
|
+
throw new Error(
|
|
1540
|
+
\`Integration specs need NODE_ENV=development to wire development implementations, got "\${process.env.NODE_ENV}"\`
|
|
1541
|
+
);
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
process.env.DATABASE_URL = inject('databaseUrl');
|
|
1545
|
+
`;
|
|
1546
|
+
const testcontainers_exampleSpec = `import { expect, inject, test } from 'vitest';
|
|
1547
|
+
|
|
1548
|
+
test('connects to the database in the container', () => {
|
|
1549
|
+
expect(process.env.DATABASE_URL).toBe(inject('databaseUrl'));
|
|
1550
|
+
});
|
|
1551
|
+
`;
|
|
1552
|
+
const excludeFromUnitTests = (content)=>{
|
|
1553
|
+
const exclude = /(exclude:\s*\[\s*\.\.\.configDefaults\.exclude\b[^\]]*?)(,?)(\s*)\]/;
|
|
1554
|
+
if (!exclude.test(content)) return;
|
|
1555
|
+
const entry = `'${integrationFolder}/**'`;
|
|
1556
|
+
return content.replace(exclude, (_, items, comma, whitespace)=>{
|
|
1557
|
+
const indent = whitespace.includes('\n') ? /\n([ \t]*)[^\n]*$/.exec(items)?.[1] : void 0;
|
|
1558
|
+
const separator = void 0 === indent ? ', ' : `,\n${indent}`;
|
|
1559
|
+
return `${items}${separator}${entry}${comma}${whitespace}]`;
|
|
1560
|
+
}).replace('// Playwright runs end-to-end specs\n', '// Playwright runs end-to-end specs, test:integration runs integration ones\n');
|
|
1561
|
+
};
|
|
1562
|
+
const testcontainers_stageFile = (filePath, content)=>{
|
|
1563
|
+
const file = new File(filePath);
|
|
1564
|
+
if (!file.exists || file.data !== content) file.data = content;
|
|
1565
|
+
};
|
|
1566
|
+
const addTestcontainers = async ()=>{
|
|
1567
|
+
const config = ConfigFile.Instance.data;
|
|
1568
|
+
const root = new ProjectRoot().path;
|
|
1569
|
+
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
1570
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
1571
|
+
const dependencies = {
|
|
1572
|
+
...manifest.dependencies,
|
|
1573
|
+
...manifest.devDependencies
|
|
1574
|
+
};
|
|
1575
|
+
const selected = await addPackageScripts(manifestFile, testcontainersScripts);
|
|
1576
|
+
const withPrisma = new File(node_path.resolve(root, config.rootFolder, 'shared-kernel/infrastructure/prisma/prisma.config.ts')).exists;
|
|
1577
|
+
const migrationCommand = withPrisma ? `npx ${prismaScripts(config.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}` : void 0;
|
|
1578
|
+
const folder = node_path.join(root, integrationFolder);
|
|
1579
|
+
testcontainers_stageFile(node_path.join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
|
|
1580
|
+
testcontainers_stageFile(node_path.join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommand));
|
|
1581
|
+
testcontainers_stageFile(node_path.join(folder, 'setup-env.ts'), testcontainersSetupEnv);
|
|
1582
|
+
const example = new File(node_path.join(folder, 'database/database.spec.ts'));
|
|
1583
|
+
if (!example.exists) example.data = testcontainers_exampleSpec;
|
|
1584
|
+
const unitConfig = new File(node_path.join(root, 'vitest.config.ts'));
|
|
1585
|
+
let excludedFromUnitTests = !unitConfig.exists || unitConfig.data.includes(integrationFolder);
|
|
1586
|
+
if (!excludedFromUnitTests) {
|
|
1587
|
+
const excluded = excludeFromUnitTests(unitConfig.data);
|
|
1588
|
+
if (excluded) {
|
|
1589
|
+
unitConfig.update(excluded);
|
|
1590
|
+
excludedFromUnitTests = true;
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
const missing = [
|
|
1594
|
+
'vitest',
|
|
1595
|
+
'testcontainers',
|
|
1596
|
+
'dotenv'
|
|
1597
|
+
].filter((name)=>!dependencies[name]);
|
|
1598
|
+
return [
|
|
1599
|
+
...missing.length ? [
|
|
1600
|
+
`npm install --save-dev ${missing.join(' ')}`
|
|
1601
|
+
] : [],
|
|
1602
|
+
`Integration specs run against postgres:15 and get its address in DATABASE_URL. Change the image, credentials and connection string in ${integrationFolder}/global-setup.ts, and the variable name in ${integrationFolder}/setup-env.ts.`,
|
|
1603
|
+
...migrationCommand ? [] : [
|
|
1604
|
+
`Apply your migrations in ${integrationFolder}/global-setup.ts.`
|
|
1605
|
+
],
|
|
1606
|
+
...excludedFromUnitTests ? [] : [
|
|
1607
|
+
`Add '${integrationFolder}/**' to test.exclude in vitest.config.ts, so unit tests skip integration specs.`
|
|
1608
|
+
],
|
|
1609
|
+
'Docker must be running for integration specs.',
|
|
1610
|
+
...describeScripts(selected, {
|
|
1611
|
+
'test:integration': `run integration specs from ${integrationFolder} against PostgreSQL in a container`
|
|
1612
|
+
})
|
|
1613
|
+
];
|
|
1614
|
+
};
|
|
1615
|
+
const vitestScripts = {
|
|
1616
|
+
test: 'vitest run --reporter=dot --silent=passed-only',
|
|
1617
|
+
'test:coverage': 'vitest run --coverage --reporter=dot --silent=passed-only'
|
|
1618
|
+
};
|
|
1619
|
+
const vitestConfig = (rootFolder, inlineHandlersNext)=>{
|
|
1620
|
+
const folder = (subpath)=>JSON.stringify(node_path.posix.join(rootFolder.replaceAll('\\', '/'), subpath));
|
|
1621
|
+
const server = inlineHandlersNext ? `,
|
|
1622
|
+
server: {
|
|
1623
|
+
deps: {
|
|
1624
|
+
// Imports \`next/headers\` without an extension, which only a bundler can resolve
|
|
1625
|
+
inline: ['@domain-first/handlers-next']
|
|
1626
|
+
}
|
|
1627
|
+
}` : '';
|
|
1628
|
+
return `import { configDefaults, defineConfig } from 'vitest/config';
|
|
1629
|
+
|
|
1630
|
+
export default defineConfig({
|
|
1631
|
+
resolve: {
|
|
1632
|
+
tsconfigPaths: true
|
|
1633
|
+
},
|
|
1634
|
+
test: {
|
|
1635
|
+
// Playwright runs end-to-end specs, test:integration runs integration ones
|
|
1636
|
+
exclude: [...configDefaults.exclude, 'specs/e2e/**', 'specs/integration/**'],
|
|
1637
|
+
coverage: {
|
|
1638
|
+
provider: 'v8',
|
|
1639
|
+
include: [${folder('bounded-contexts/**/*.ts')}, ${folder('shared-kernel/**/*.ts')}],
|
|
1640
|
+
exclude: [
|
|
1641
|
+
'**/*.spec.ts',
|
|
1642
|
+
${folder('shared-kernel/infrastructure/**')},
|
|
1643
|
+
${folder('bounded-contexts/*/infrastructure/**')},
|
|
1644
|
+
${folder('bounded-contexts/*/presentation/rest/**')},
|
|
1645
|
+
${folder('shared-kernel/wiring/**')},
|
|
1646
|
+
${folder('bounded-contexts/*/wiring/**')}
|
|
1647
|
+
],
|
|
1648
|
+
reporter: [['text', { skipFull: true }], 'html']
|
|
1649
|
+
}${server}
|
|
1650
|
+
}
|
|
1651
|
+
});
|
|
1652
|
+
`;
|
|
1653
|
+
};
|
|
1654
|
+
const addVitest = async ()=>{
|
|
1655
|
+
const config = ConfigFile.Instance.data;
|
|
1656
|
+
if (config.testingLibrary && 'vitest' !== config.testingLibrary && !await prompts_confirm({
|
|
1657
|
+
message: `Replace testing library "${config.testingLibrary}" with vitest for generated tests?`,
|
|
1658
|
+
default: false
|
|
1659
|
+
})) return [];
|
|
1660
|
+
const root = new ProjectRoot().path;
|
|
1661
|
+
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
1662
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
1663
|
+
const dependencies = {
|
|
1664
|
+
...manifest.dependencies,
|
|
1665
|
+
...manifest.devDependencies
|
|
1666
|
+
};
|
|
1667
|
+
const selected = await addPackageScripts(manifestFile, vitestScripts);
|
|
1668
|
+
const configFile = new File(node_path.join(root, 'vitest.config.ts'));
|
|
1669
|
+
const content = vitestConfig(config.rootFolder, Boolean(dependencies['@domain-first/handlers-next']));
|
|
1670
|
+
if (!configFile.exists || configFile.data !== content) configFile.data = content;
|
|
1671
|
+
if ('vitest' !== config.testingLibrary) ConfigFile.write({
|
|
1672
|
+
...config,
|
|
1673
|
+
testingLibrary: 'vitest'
|
|
1674
|
+
});
|
|
1675
|
+
addGitignoreEntry(root, '/coverage/');
|
|
1676
|
+
const missing = [
|
|
1677
|
+
'vitest',
|
|
1678
|
+
'@vitest/coverage-v8'
|
|
1679
|
+
].filter((name)=>!dependencies[name]);
|
|
1680
|
+
return [
|
|
1681
|
+
...missing.length ? [
|
|
1682
|
+
`npm install --save-dev ${missing.join(' ')}`
|
|
1683
|
+
] : [],
|
|
1684
|
+
...describeScripts(selected, {
|
|
1685
|
+
test: 'run unit tests',
|
|
1686
|
+
'test:coverage': 'run unit tests with a V8 coverage report in coverage/'
|
|
1687
|
+
})
|
|
1688
|
+
];
|
|
1689
|
+
};
|
|
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
|
+
];
|
|
1717
|
+
};
|
|
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'));
|
|
1738
|
+
};
|
|
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')
|
|
1799
|
+
}
|
|
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
|
+
] : [];
|
|
1818
|
+
};
|
|
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);
|
|
1831
|
+
};
|
|
1832
|
+
const initializeUseCase = async ()=>{
|
|
1833
|
+
const rootFolderName = await input({
|
|
1834
|
+
message: 'Root folder (use "/" for inner folders):',
|
|
1835
|
+
default: 'src'
|
|
1836
|
+
});
|
|
1837
|
+
const domainFirstPackages = await prompts_checkbox({
|
|
1838
|
+
message: '@domain-first packages',
|
|
1839
|
+
choices: [
|
|
1840
|
+
'@domain-first/types',
|
|
1841
|
+
'@domain-first/errors',
|
|
1842
|
+
'@domain-first/handlers',
|
|
1843
|
+
'@domain-first/wire',
|
|
1844
|
+
'@domain-first/handlers-rest'
|
|
1845
|
+
]
|
|
1846
|
+
});
|
|
1847
|
+
const withNextAdapter = domainFirstPackages.includes('@domain-first/handlers-rest') && await askNextAdapter();
|
|
1848
|
+
const defaultPersistenceLayerImplementation = await input({
|
|
1849
|
+
message: 'Default persistence layer implementation:'
|
|
1850
|
+
});
|
|
1851
|
+
const withInMemoryDb = await prompts_confirm({
|
|
1852
|
+
message: 'Scaffold in-memory DB for test implementations'
|
|
1853
|
+
});
|
|
1854
|
+
const useReact = await prompts_confirm({
|
|
1855
|
+
message: 'Use React'
|
|
1856
|
+
});
|
|
1857
|
+
let storybookFramework;
|
|
1858
|
+
const withStorybook = useReact ? await prompts_confirm({
|
|
1859
|
+
message: 'Use Storybook'
|
|
1860
|
+
}) : false;
|
|
1861
|
+
if (withStorybook) storybookFramework = await input({
|
|
1862
|
+
message: 'Storybook framework package:',
|
|
1863
|
+
default: '@storybook/react-vite'
|
|
1864
|
+
});
|
|
1865
|
+
let testingLibrary;
|
|
1866
|
+
const withTests = await prompts_confirm({
|
|
1867
|
+
message: 'Scaffold unit tests'
|
|
1868
|
+
});
|
|
1869
|
+
if (withTests) testingLibrary = await input({
|
|
1870
|
+
message: 'Unit testing library:',
|
|
1871
|
+
default: 'vitest'
|
|
1872
|
+
});
|
|
1873
|
+
ConfigFile.write({
|
|
1874
|
+
rootFolder: rootFolderName,
|
|
1875
|
+
domainFirstPackages,
|
|
1876
|
+
defaultPersistenceLayerImplementation,
|
|
1877
|
+
withInMemoryDb,
|
|
1878
|
+
useReact,
|
|
1879
|
+
storybookFramework,
|
|
1880
|
+
testingLibrary
|
|
1881
|
+
});
|
|
1882
|
+
const { path } = new ProjectRoot();
|
|
1883
|
+
const rootFolder = new Folder(path);
|
|
1884
|
+
if (domainFirstPackages.includes('@domain-first/wire')) rootFolder.subitem([
|
|
1885
|
+
rootFolderName,
|
|
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;
|
|
1904
|
+
};
|
|
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
|
+
});
|
|
1928
|
+
};
|
|
1929
|
+
const toPosix = (value)=>value.split(node_path.sep).join('/');
|
|
1930
|
+
const nestedName = (folders, fileBase)=>{
|
|
1931
|
+
const prefix = `${folders.join('-')}-`;
|
|
1932
|
+
const last = folders.length && fileBase.startsWith(prefix) ? fileBase.slice(prefix.length) : fileBase;
|
|
1933
|
+
return [
|
|
1934
|
+
...folders,
|
|
1935
|
+
last
|
|
1936
|
+
].join('/');
|
|
1937
|
+
};
|
|
1938
|
+
const declaredClassName = (filePath, suffix, name)=>{
|
|
1939
|
+
const content = node_fs.readFileSync(filePath, 'utf8');
|
|
1940
|
+
const declared = content.match(new RegExp(`export\\s+(?:const|function)\\s+(\\w+)${suffix}\\b`))?.[1];
|
|
1941
|
+
return declared ?? new NestedName(name).ClassName;
|
|
1942
|
+
};
|
|
1943
|
+
const findReactModules = (reactFolder, kind)=>{
|
|
1944
|
+
const modules = 'page' === kind ? walk(node_path.join(reactFolder, 'pages')).filter((file)=>file.endsWith('-page.tsx')).map((file)=>{
|
|
1945
|
+
const folders = node_path.relative(node_path.join(reactFolder, 'pages'), node_path.dirname(file)).split(node_path.sep).filter((segment)=>!!segment);
|
|
1946
|
+
const fileBase = node_path.basename(file, '-page.tsx');
|
|
1947
|
+
const name = nestedName(folders, fileBase);
|
|
1948
|
+
return {
|
|
1949
|
+
kind,
|
|
1950
|
+
name,
|
|
1951
|
+
path: file,
|
|
1952
|
+
fileBase,
|
|
1953
|
+
ClassName: declaredClassName(file, 'Page', name)
|
|
1954
|
+
};
|
|
1955
|
+
}) : walk(node_path.join(reactFolder, 'widgets')).filter((file)=>file.endsWith('-widget.tsx')).map((file)=>{
|
|
1956
|
+
const folder = node_path.dirname(file);
|
|
1957
|
+
const name = toPosix(node_path.relative(node_path.join(reactFolder, 'widgets'), folder));
|
|
1958
|
+
return {
|
|
1959
|
+
kind,
|
|
1960
|
+
name,
|
|
1961
|
+
path: folder,
|
|
1962
|
+
fileBase: node_path.basename(file, '-widget.tsx'),
|
|
1963
|
+
ClassName: declaredClassName(file, 'Widget', name)
|
|
1964
|
+
};
|
|
1965
|
+
});
|
|
1966
|
+
return modules.sort((a, b)=>a.name.localeCompare(b.name));
|
|
1967
|
+
};
|
|
1968
|
+
const targetPath = (reactFolder, module, rawName)=>{
|
|
1969
|
+
const { folders, folderName, fileName } = new NestedName(rawName);
|
|
1970
|
+
return 'page' === module.kind ? node_path.join(reactFolder, 'pages', ...folders, `${fileName}-page.tsx`) : node_path.join(reactFolder, 'widgets', ...folders, folderName);
|
|
1971
|
+
};
|
|
1972
|
+
const validateMove = (reactFolder, module, rawName)=>{
|
|
1973
|
+
const nameError = NestedName.validate(rawName);
|
|
1974
|
+
if (true !== nameError) return nameError;
|
|
1975
|
+
const target = targetPath(reactFolder, module, rawName);
|
|
1976
|
+
if (target !== module.path && node_fs.existsSync(target)) return `${node_path.relative(reactFolder, target)} already exists`;
|
|
1977
|
+
if (target.startsWith(`${module.path}${node_path.sep}`)) return 'A widget cannot be moved into itself';
|
|
1978
|
+
return true;
|
|
1979
|
+
};
|
|
1980
|
+
const readAliases = (projectRoot)=>{
|
|
1981
|
+
const tsconfig = node_path.join(projectRoot, 'tsconfig.json');
|
|
1982
|
+
if (!node_fs.existsSync(tsconfig)) return [];
|
|
1983
|
+
try {
|
|
1984
|
+
const { compilerOptions = {} } = JSON.parse(stripJsonComments(node_fs.readFileSync(tsconfig, 'utf8')));
|
|
1985
|
+
const base = node_path.resolve(projectRoot, compilerOptions.baseUrl ?? '.');
|
|
1986
|
+
return Object.entries(compilerOptions.paths ?? {}).filter(([pattern, targets])=>pattern.endsWith('*') && targets[0]?.endsWith('*')).map(([pattern, [target]])=>({
|
|
1987
|
+
prefix: pattern.slice(0, -1),
|
|
1988
|
+
target: node_path.resolve(base, target.slice(0, -1))
|
|
1989
|
+
}));
|
|
1990
|
+
} catch {
|
|
1991
|
+
return [];
|
|
1992
|
+
}
|
|
1993
|
+
};
|
|
1994
|
+
const specifierPattern = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])([^'"\n]+)\2/g;
|
|
1995
|
+
const reExportPattern = /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*(['"])([^'"\n]+)\1/g;
|
|
1996
|
+
const importPaths = (file)=>{
|
|
1997
|
+
const withoutExtension = file.replace(codeExtension, '');
|
|
1998
|
+
return 'index' === node_path.basename(withoutExtension) ? [
|
|
1999
|
+
withoutExtension,
|
|
2000
|
+
node_path.dirname(withoutExtension)
|
|
2001
|
+
] : [
|
|
2002
|
+
withoutExtension
|
|
2003
|
+
];
|
|
2004
|
+
};
|
|
2005
|
+
const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
|
|
2006
|
+
const newName = new NestedName(rawName);
|
|
2007
|
+
const target = targetPath(reactFolder, module, rawName);
|
|
2008
|
+
const newClassName = newName.ClassName;
|
|
2009
|
+
const renameFile = (name)=>name.replace(new RegExp(`^(use-)?${escapeRegExp(module.fileBase)}(?=[-.])`), (_, use = '')=>`${use}${newName.fileName}`);
|
|
2010
|
+
const oldFolder = 'page' === module.kind ? node_path.dirname(module.path) : module.path;
|
|
2011
|
+
const newFolder = 'page' === module.kind ? node_path.dirname(target) : target;
|
|
2012
|
+
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}`);
|
|
2013
|
+
const movedPath = (candidate)=>{
|
|
2014
|
+
if (!ownsPath(candidate)) return;
|
|
2015
|
+
const segments = node_path.relative(oldFolder, candidate).split(node_path.sep);
|
|
2016
|
+
const last = segments.length - 1;
|
|
2017
|
+
segments[last] = renameFile(segments[last]);
|
|
2018
|
+
return node_path.join(newFolder, ...segments);
|
|
2019
|
+
};
|
|
2020
|
+
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);
|
|
2021
|
+
const moves = new Map(moduleFiles.map((file)=>[
|
|
2022
|
+
file,
|
|
2023
|
+
movedPath(file) ?? file
|
|
2024
|
+
]));
|
|
2025
|
+
const aliases = readAliases(projectRoot);
|
|
2026
|
+
const resolve = (specifier, fromFile)=>{
|
|
2027
|
+
if (specifier.startsWith('.')) return {
|
|
2028
|
+
resolved: node_path.resolve(node_path.dirname(fromFile), specifier),
|
|
2029
|
+
alias: void 0
|
|
2030
|
+
};
|
|
2031
|
+
const alias = aliases.find(({ prefix })=>specifier.startsWith(prefix));
|
|
2032
|
+
return alias ? {
|
|
2033
|
+
resolved: node_path.resolve(alias.target, specifier.slice(alias.prefix.length)),
|
|
2034
|
+
alias
|
|
2035
|
+
} : void 0;
|
|
2036
|
+
};
|
|
2037
|
+
const specifierFor = (fromFile, toPath, alias)=>{
|
|
2038
|
+
const aliased = alias && toPosix(node_path.relative(alias.target, toPath));
|
|
2039
|
+
if (aliased && !aliased.startsWith('..')) return `${alias.prefix}${aliased}`;
|
|
2040
|
+
const relative = toPosix(node_path.relative(node_path.dirname(fromFile), toPath));
|
|
2041
|
+
return relative.startsWith('.') ? relative : `./${relative}`;
|
|
2042
|
+
};
|
|
2043
|
+
const suffixes = 'page' === module.kind ? 'Page' : 'Widget|UIModel';
|
|
2044
|
+
const classPattern = new RegExp(`(?<![\\w$])(use)?${escapeRegExp(module.ClassName)}(?=${suffixes})`, 'g');
|
|
2045
|
+
const oldTitle = `Widgets/${module.name.split('/').map((segment)=>new NestedName(segment).ClassName).join('/')}`;
|
|
2046
|
+
const titlePattern = new RegExp(`(['"\`])${escapeRegExp(oldTitle)}\\1`, 'g');
|
|
2047
|
+
const newTitle = [
|
|
2048
|
+
'Widgets',
|
|
2049
|
+
...newName.classNameSegments
|
|
2050
|
+
].join('/');
|
|
2051
|
+
const codeFiles = new Map(walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
|
|
2052
|
+
file,
|
|
2053
|
+
node_fs.readFileSync(file, 'utf8')
|
|
2054
|
+
]));
|
|
2055
|
+
const barrels = new Set();
|
|
2056
|
+
const isBarrel = (resolved)=>barrels.has(resolved.replace(codeExtension, ''));
|
|
2057
|
+
for(let found = true; found;){
|
|
2058
|
+
found = false;
|
|
2059
|
+
for (const [file, content] of codeFiles){
|
|
2060
|
+
if (moves.has(file) || isBarrel(file)) continue;
|
|
2061
|
+
const reExportsModule = [
|
|
2062
|
+
...content.matchAll(reExportPattern)
|
|
2063
|
+
].some(([, , specifier])=>{
|
|
2064
|
+
const resolution = resolve(specifier, file);
|
|
2065
|
+
return !!resolution && (!!movedPath(resolution.resolved) || isBarrel(resolution.resolved));
|
|
2066
|
+
});
|
|
2067
|
+
if (reExportsModule) {
|
|
2068
|
+
for (const importPath of importPaths(file))barrels.add(importPath);
|
|
2069
|
+
found = true;
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
}
|
|
2073
|
+
const rewrite = (content, oldFile, newFile)=>{
|
|
2074
|
+
let referencesModule = false;
|
|
2075
|
+
const rewritten = content.replace(specifierPattern, (match, keyword, quote, specifier)=>{
|
|
2076
|
+
const resolution = resolve(specifier, oldFile);
|
|
2077
|
+
if (!resolution) return match;
|
|
2078
|
+
const moved = movedPath(resolution.resolved);
|
|
2079
|
+
if (moved || isBarrel(resolution.resolved)) referencesModule = true;
|
|
2080
|
+
if (!moved && oldFile === newFile) return match;
|
|
2081
|
+
const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
|
|
2082
|
+
return `${keyword}${quote}${next}${quote}`;
|
|
2083
|
+
});
|
|
2084
|
+
if (!referencesModule && !moves.has(oldFile)) return content;
|
|
2085
|
+
const renamed = rewritten.replace(classPattern, (_, use = '')=>`${use}${newClassName}`);
|
|
2086
|
+
return moves.has(oldFile) && 'widget' === module.kind ? renamed.replace(titlePattern, (_, quote)=>`${quote}${newTitle}${quote}`) : renamed;
|
|
2087
|
+
};
|
|
2088
|
+
for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new File(file).moveTo(newFile, reactFolder);
|
|
2089
|
+
const updated = [];
|
|
2090
|
+
for (const [file, content] of codeFiles){
|
|
2091
|
+
const newFile = moves.get(file);
|
|
2092
|
+
const next = rewrite(content, file, newFile ?? file);
|
|
2093
|
+
if (newFile && newFile !== file) {
|
|
2094
|
+
new File(newFile).data = next;
|
|
2095
|
+
new File(file).delete(reactFolder);
|
|
2096
|
+
} else if (next !== content) {
|
|
2097
|
+
new File(file).update(next);
|
|
2098
|
+
if (!newFile) updated.push(file);
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
return {
|
|
2102
|
+
moves: [
|
|
2103
|
+
...moves
|
|
2104
|
+
].filter(([from, to])=>from !== to),
|
|
2105
|
+
updated
|
|
2106
|
+
};
|
|
2107
|
+
};
|
|
2108
|
+
const moveReactModuleUseCase = async (presentationReactFolder, kind)=>{
|
|
2109
|
+
const reactFolder = presentationReactFolder.path;
|
|
2110
|
+
const modules = findReactModules(reactFolder, kind);
|
|
2111
|
+
if (!modules.length) return void console.log(`No ${kind}s generated by df-react were found.`);
|
|
2112
|
+
const module = await prompts_select({
|
|
2113
|
+
message: 'page' === kind ? 'Page:' : 'Widget:',
|
|
2114
|
+
choices: modules.map((value)=>({
|
|
2115
|
+
name: value.name,
|
|
2116
|
+
value,
|
|
2117
|
+
description: node_path.relative(reactFolder, value.path)
|
|
2118
|
+
}))
|
|
2119
|
+
});
|
|
2120
|
+
const name = await input({
|
|
2121
|
+
message: 'New name (folders split by "/"):',
|
|
2122
|
+
default: module.name,
|
|
2123
|
+
validate: (value)=>validateMove(reactFolder, module, value)
|
|
2124
|
+
});
|
|
2125
|
+
const root = new ProjectRoot().path;
|
|
2126
|
+
const { moves, updated } = moveReactModule(root, reactFolder, module, name);
|
|
2127
|
+
if (!moves.length && !updated.length) return void console.log('Nothing to change.');
|
|
2128
|
+
const relative = (file)=>node_path.relative(root, file);
|
|
2129
|
+
console.log([
|
|
2130
|
+
'Files to move:',
|
|
2131
|
+
...moves.map(([from, to])=>` ${relative(from)} → ${relative(to)}`),
|
|
2132
|
+
...updated.length ? [
|
|
2133
|
+
'Files with updated imports:',
|
|
2134
|
+
...updated.map((file)=>` ${relative(file)}`)
|
|
2135
|
+
] : []
|
|
2136
|
+
].join('\n'));
|
|
2137
|
+
if (!await prompts_confirm({
|
|
2138
|
+
message: 'Apply?',
|
|
2139
|
+
default: true
|
|
2140
|
+
})) {
|
|
2141
|
+
discardPendingChanges();
|
|
2142
|
+
console.log('Cancelled: nothing was written.');
|
|
2143
|
+
}
|
|
2144
|
+
};
|
|
2145
|
+
const scaffoldNewAggregateUseCase = async (boundedContextFolder)=>{
|
|
2146
|
+
const aggregateName = await input({
|
|
2147
|
+
message: 'Aggregate name:'
|
|
2148
|
+
});
|
|
2149
|
+
const aggregateNaming = new UnknownFormatNaming(aggregateName);
|
|
2150
|
+
const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
|
|
2151
|
+
const withRepository = await prompts_confirm({
|
|
2152
|
+
message: 'With Repository'
|
|
2153
|
+
});
|
|
2154
|
+
const aggregatesFolder = boundedContextFolder.subitem([
|
|
2155
|
+
'domain',
|
|
2156
|
+
'aggregates',
|
|
2157
|
+
aggregateName
|
|
2158
|
+
]);
|
|
2159
|
+
const withTypes = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/types');
|
|
2160
|
+
aggregatesFolder.createFile(`${aggregateNaming.fileName}.aggregate-root.ts`, withTypes ? `
|
|
2161
|
+
import { domainType } from '@domain-first/types'
|
|
2162
|
+
|
|
2163
|
+
export class ${aggregateNaming.ClassName} extends domainType() {
|
|
2164
|
+
|
|
2165
|
+
}`.trim() : `export class ${aggregateNaming.ClassName} {}`);
|
|
2166
|
+
const barrelFile = aggregatesFolder.createFile("index.ts", `export * from './${aggregateNaming.fileName}.aggregate-root'`);
|
|
2167
|
+
if (scaffoldUnitTests) aggregatesFolder.createFile(`${aggregateNaming.fileName}.aggregate-root.spec.ts`, `
|
|
2168
|
+
import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
|
|
2169
|
+
import { ${aggregateNaming.ClassName} } from './${aggregateNaming.fileName}.aggregate-root'
|
|
2170
|
+
|
|
2171
|
+
let ${aggregateNaming.variableName}: ${aggregateNaming.ClassName}
|
|
2172
|
+
|
|
2173
|
+
beforeEach(() => {
|
|
2174
|
+
${aggregateNaming.variableName} = ${withTypes ? `${aggregateNaming.ClassName}.of({})` : `new ${aggregateNaming.ClassName}()`}
|
|
2175
|
+
})
|
|
2176
|
+
|
|
2177
|
+
describe('${aggregateNaming.withSpaces}', () => {
|
|
2178
|
+
test('can be instantiated via ${withTypes ? 'of' : 'constructor'}', () => {
|
|
2179
|
+
expect(${aggregateNaming.variableName}).toBeDefined()
|
|
2180
|
+
})
|
|
2181
|
+
})
|
|
2182
|
+
`.trim());
|
|
2183
|
+
if (withRepository) {
|
|
2184
|
+
aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.ts`, `export abstract class ${aggregateNaming.ClassName}Repository { }`);
|
|
2185
|
+
barrelFile.addLine(`export * from './${aggregateNaming.fileName}-repository'`);
|
|
2186
|
+
const infrastructureImplementationType = await input({
|
|
2187
|
+
message: 'Repository infrastructure implementation type:',
|
|
2188
|
+
default: ConfigFile.Instance.data.defaultPersistenceLayerImplementation
|
|
2189
|
+
});
|
|
2190
|
+
let addTestImplementation = false;
|
|
2191
|
+
let testImplementationType = '';
|
|
2192
|
+
addTestImplementation = await prompts_confirm({
|
|
2193
|
+
message: 'Add a test implementation for Repository'
|
|
2194
|
+
});
|
|
2195
|
+
if (addTestImplementation) testImplementationType = await input({
|
|
2196
|
+
message: 'Test Repository infrastructure implementation type:',
|
|
2197
|
+
default: 'in-memory'
|
|
2198
|
+
});
|
|
2199
|
+
const infrastructureRepositoriesFolder = boundedContextFolder.subitem([
|
|
2200
|
+
'infrastructure',
|
|
2201
|
+
'repositories'
|
|
2202
|
+
]);
|
|
2203
|
+
const implementationTypes = [
|
|
2204
|
+
infrastructureImplementationType,
|
|
2205
|
+
testImplementationType
|
|
2206
|
+
].filter((x)=>!!x);
|
|
2207
|
+
for (const implementation of implementationTypes){
|
|
2208
|
+
const naming = new UnknownFormatNaming(implementation);
|
|
2209
|
+
const repositoryFolder = infrastructureRepositoriesFolder.subitem([
|
|
2210
|
+
naming.fileName
|
|
2211
|
+
]);
|
|
2212
|
+
const repositoryFileName = `${naming.fileName}-${aggregateName}-repository.ts`;
|
|
2213
|
+
if (usesInMemoryDb(implementation) && !ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
|
|
2214
|
+
const section = addInMemoryDbSection(aggregateNaming, aggregatesFolder.path);
|
|
2215
|
+
repositoryFolder.createFile(repositoryFileName, `
|
|
2216
|
+
${inMemoryDbTypeImport(repositoryFolder.subitem([
|
|
2217
|
+
repositoryFileName
|
|
2218
|
+
]).path)}
|
|
2219
|
+
import { ${aggregateNaming.ClassName}Repository } from '../../../domain/aggregates/${aggregateName}'
|
|
2220
|
+
|
|
2221
|
+
export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implements ${aggregateNaming.ClassName}Repository {
|
|
2222
|
+
${inMemoryDbSectionMembers(section, false)}
|
|
2223
|
+
}
|
|
2224
|
+
`.trim());
|
|
2225
|
+
continue;
|
|
2226
|
+
}
|
|
2227
|
+
repositoryFolder.createFile(repositoryFileName, `
|
|
2228
|
+
import { ${aggregateNaming.ClassName}Repository } from '../../../domain/aggregates/${aggregateName}'
|
|
2229
|
+
|
|
2230
|
+
export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implements ${aggregateNaming.ClassName}Repository {
|
|
2231
|
+
constructor() {}
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
`.trim());
|
|
2235
|
+
}
|
|
2236
|
+
if (scaffoldUnitTests) {
|
|
2237
|
+
const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
|
|
2238
|
+
const specFile = aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.spec.ts`, `
|
|
2239
|
+
import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
|
|
2240
|
+
${ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? `import { wire${aggregateNaming.ClassName}Repository } from '../../../wiring/repositories/wire-${aggregateNaming.fileName}-repository'
|
|
2241
|
+
import type { ${aggregateNaming.ClassName}Repository } from './${aggregateNaming.fileName}-repository'` : `import { ${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository } from '../../../infrastructure/repositories/${implementationNaming.fileName}/${implementationNaming.fileName}-${aggregateNaming.fileName}-repository'
|
|
2242
|
+
|
|
2243
|
+
type ${aggregateNaming.ClassName}Repository = ${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository`}
|
|
2244
|
+
|
|
2245
|
+
let ${aggregateNaming.variableName}Repository: ${aggregateNaming.ClassName}Repository
|
|
2246
|
+
|
|
2247
|
+
beforeEach(() => {
|
|
2248
|
+
${aggregateNaming.variableName}Repository = ${ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? `wire${aggregateNaming.ClassName}Repository()` : `new ${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository()`}
|
|
2249
|
+
})
|
|
2250
|
+
|
|
2251
|
+
describe('${aggregateNaming.withSpaces} repository', () => {
|
|
2252
|
+
test('can be ${ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? 'wired' : 'created via constructor'}', () => {
|
|
2253
|
+
expect(${aggregateNaming.variableName}Repository).toBeDefined()
|
|
2254
|
+
})
|
|
2255
|
+
})
|
|
2256
|
+
`.trim());
|
|
2257
|
+
if (!ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') && usesInMemoryDb(infrastructureImplementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository`);
|
|
2258
|
+
}
|
|
2259
|
+
if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
|
|
2260
|
+
const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
|
|
2261
|
+
const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
|
|
2262
|
+
const wireFile = boundedContextFolder.subitem([
|
|
2263
|
+
'wiring',
|
|
2264
|
+
'repositories'
|
|
2265
|
+
]).createFile(`wire-${aggregateNaming.fileName}-repository.ts`, `
|
|
2266
|
+
import { wireClass } from '@domain-first/wire'
|
|
2267
|
+
import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
|
|
2268
|
+
${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${aggregateNaming.ClassName}Repository } from '../../infrastructure/repositories/${fileName}/${fileName}-${aggregateNaming.fileName}-repository'`).join('\n')}
|
|
2269
|
+
|
|
2270
|
+
${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${aggregateNaming.ClassName}Repository, [])`).join('\n\n')}
|
|
2271
|
+
|
|
2272
|
+
export const wire${aggregateNaming.ClassName}Repository = envBranchedWire({
|
|
2273
|
+
test: wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation,
|
|
2274
|
+
development: wire${implementationNaming.ClassName}Implementation,
|
|
2275
|
+
production: wire${implementationNaming.ClassName}Implementation
|
|
2276
|
+
})
|
|
2277
|
+
`.trim());
|
|
2278
|
+
await wireNewModuleDependencies(boundedContextFolder, wireFile, (implementation, dependency)=>{
|
|
2279
|
+
if (!isInMemoryDb(dependency)) return false;
|
|
2280
|
+
keepInMemoryDbSection(new File(implementation.file), addInMemoryDbSection(aggregateNaming, aggregatesFolder.path));
|
|
2281
|
+
wireInMemoryDb(wireFile, implementation.className);
|
|
2282
|
+
return true;
|
|
2283
|
+
});
|
|
2284
|
+
}
|
|
2285
|
+
}
|
|
2286
|
+
};
|
|
2287
|
+
const scaffoldNewApplicationPort = async (boundedContextFolder)=>{
|
|
2288
|
+
const name = await input({
|
|
2289
|
+
message: 'Name: '
|
|
2290
|
+
});
|
|
2291
|
+
const naming = new UnknownFormatNaming(name);
|
|
2292
|
+
const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
|
|
2293
|
+
const wiringFolder = boundedContextFolder.subitem([
|
|
2294
|
+
'wiring',
|
|
2295
|
+
'application-ports'
|
|
2296
|
+
]);
|
|
2297
|
+
const applicationPortsFolder = boundedContextFolder.subitem([
|
|
2298
|
+
'application',
|
|
2299
|
+
'ports'
|
|
2300
|
+
]);
|
|
2301
|
+
applicationPortsFolder.createFile(`${naming.fileName}.ts`, `
|
|
2302
|
+
export abstract class ${naming.ClassName} {
|
|
2303
|
+
|
|
2304
|
+
}
|
|
2305
|
+
`.trim());
|
|
2306
|
+
const implementationType = await input({
|
|
2307
|
+
message: 'Adapter implementation type:',
|
|
2308
|
+
default: 'api'
|
|
2309
|
+
});
|
|
2310
|
+
const addTestImplementation = await prompts_confirm({
|
|
2311
|
+
message: 'With test implementation'
|
|
2312
|
+
});
|
|
2313
|
+
let testImplementationType = '';
|
|
2314
|
+
if (addTestImplementation) testImplementationType = await input({
|
|
2315
|
+
message: 'Test adapter implementation type:',
|
|
2316
|
+
default: 'mock'
|
|
2317
|
+
});
|
|
2318
|
+
const infrastructureFolder = boundedContextFolder.subitem([
|
|
2319
|
+
'infrastructure',
|
|
2320
|
+
'application-adapters'
|
|
2321
|
+
]);
|
|
2322
|
+
const implementationTypes = [
|
|
2323
|
+
implementationType,
|
|
2324
|
+
testImplementationType
|
|
2325
|
+
].filter((x)=>!!x);
|
|
2326
|
+
for (const implementation of implementationTypes){
|
|
2327
|
+
const currentNaming = new UnknownFormatNaming(`${implementation}-${naming.fileName}`);
|
|
2328
|
+
infrastructureFolder.subitem([
|
|
2329
|
+
implementation
|
|
2330
|
+
]).createFile(`${currentNaming.fileName}.ts`, `
|
|
2331
|
+
import { ${naming.ClassName} } from '../../../application/ports/${naming.fileName}'
|
|
2332
|
+
|
|
2333
|
+
export class ${currentNaming.ClassName} extends ${naming.ClassName} {
|
|
2334
|
+
|
|
2335
|
+
}
|
|
2336
|
+
`.trim());
|
|
2337
|
+
}
|
|
2338
|
+
if (scaffoldUnitTests) {
|
|
2339
|
+
const implementationNaming = new UnknownFormatNaming(implementationType);
|
|
2340
|
+
applicationPortsFolder.createFile(`${naming.fileName}.spec.ts`, `
|
|
2341
|
+
import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
|
|
2342
|
+
${ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? `import { type ${naming.ClassName} } from './${naming.fileName}'
|
|
2343
|
+
import { wire${naming.ClassName} } from '../../wiring/application-ports/wire-${naming.fileName}'` : `import { ${implementationNaming.ClassName}${naming.ClassName} } from '../../infrastructure/application-adapters/${implementationNaming.fileName}/${implementationNaming.fileName}-${naming.fileName}'
|
|
2344
|
+
|
|
2345
|
+
type ${naming.ClassName} = ${implementationNaming.ClassName}${naming.ClassName}`}
|
|
2346
|
+
|
|
2347
|
+
let ${naming.variableName}: ${naming.ClassName}
|
|
2348
|
+
|
|
2349
|
+
beforeEach(() => {
|
|
2350
|
+
${naming.variableName} = ${ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? `wire${naming.ClassName}()` : `new ${implementationNaming.ClassName}${naming.ClassName}()`}
|
|
2351
|
+
})
|
|
2352
|
+
|
|
2353
|
+
describe('${naming.withSpaces}', () => {
|
|
2354
|
+
test('can be ${ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? 'wired' : 'created via constructor'}', () => {
|
|
2355
|
+
expect(${naming.variableName}).toBeDefined()
|
|
2356
|
+
})
|
|
2357
|
+
})
|
|
2358
|
+
`.trim());
|
|
2359
|
+
}
|
|
2360
|
+
if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
|
|
2361
|
+
const wireFile = wiringFolder.createFile(`wire-${naming.fileName}.ts`, `
|
|
2362
|
+
import { wireClass } from '@domain-first/wire'
|
|
2363
|
+
import { envBranchedWire } from '../../../${'shared-kernel' === boundedContextFolder.name ? '' : '../'}shared-kernel/wiring/env-branched-wire'
|
|
2364
|
+
${implementationTypes.map((x)=>({
|
|
2365
|
+
naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
|
|
2366
|
+
implementation: x
|
|
2367
|
+
})).map(({ naming: { ClassName, fileName }, implementation })=>`import { ${ClassName} } from '../../infrastructure/application-adapters/${implementation}/${fileName}'`).join('\n')}
|
|
2368
|
+
|
|
2369
|
+
${implementationTypes.map((x)=>({
|
|
2370
|
+
naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
|
|
2371
|
+
implementation: x
|
|
2372
|
+
})).map(({ naming: { ClassName }, implementation })=>`const wire${new UnknownFormatNaming(implementation).ClassName}Implementation = wireClass(${ClassName}, [])`).join('\n\n')}
|
|
2373
|
+
|
|
2374
|
+
export const wire${naming.ClassName} = envBranchedWire({
|
|
2375
|
+
test: wire${new UnknownFormatNaming(`${implementationTypes.at(-1)}-implementation`).ClassName},
|
|
2376
|
+
development: wire${new UnknownFormatNaming(`${implementationTypes.at(0)}-implementation`).ClassName},
|
|
2377
|
+
production: wire${new UnknownFormatNaming(`${implementationTypes.at(0)}-implementation`).ClassName}
|
|
2378
|
+
})
|
|
2379
|
+
|
|
2380
|
+
`.trim());
|
|
2381
|
+
await wireNewModuleDependencies(boundedContextFolder, wireFile);
|
|
2382
|
+
}
|
|
2383
|
+
};
|
|
2384
|
+
const scaffoldNewApplicationService = async (boundedContextFolder)=>{
|
|
2385
|
+
const name = await input({
|
|
2386
|
+
message: 'Name: '
|
|
2387
|
+
});
|
|
2388
|
+
const naming = new UnknownFormatNaming(name);
|
|
2389
|
+
const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
|
|
2390
|
+
const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
|
|
2391
|
+
const wiringFolder = boundedContextFolder.subitem([
|
|
2392
|
+
'wiring',
|
|
2393
|
+
'application-services'
|
|
2394
|
+
]);
|
|
2395
|
+
const applicationServicesFolder = boundedContextFolder.subitem([
|
|
2396
|
+
'application',
|
|
2397
|
+
'services'
|
|
2398
|
+
]);
|
|
2399
|
+
applicationServicesFolder.createFile(`${naming.fileName}-application-service.ts`, `
|
|
2400
|
+
export class ${naming.ClassName}ApplicationService {
|
|
2401
|
+
|
|
2402
|
+
}
|
|
2403
|
+
`.trim());
|
|
2404
|
+
if (scaffoldUnitTests) applicationServicesFolder.createFile(`${naming.fileName}-application-service.spec.ts`, `
|
|
2405
|
+
import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
|
|
2406
|
+
${withWiring ? `import { type ${naming.ClassName}ApplicationService } from './${naming.fileName}-application-service'
|
|
2407
|
+
import { wire${naming.ClassName}ApplicationService } from '../../wiring/application-services/wire-${naming.fileName}-application-service'` : `import { ${naming.ClassName}ApplicationService } from './${naming.fileName}-application-service'`}
|
|
2408
|
+
|
|
2409
|
+
let ${naming.variableName}ApplicationService: ${naming.ClassName}ApplicationService
|
|
2410
|
+
|
|
2411
|
+
beforeEach(() => {
|
|
2412
|
+
${naming.variableName}ApplicationService = ${withWiring ? `wire${naming.ClassName}ApplicationService()` : `new ${naming.ClassName}ApplicationService()`}
|
|
2413
|
+
})
|
|
2414
|
+
|
|
2415
|
+
describe('${naming.withSpaces}', () => {
|
|
2416
|
+
test('can be ${withWiring ? 'wired' : 'created'}', () => {
|
|
2417
|
+
expect(${naming.variableName}ApplicationService).toBeDefined()
|
|
2418
|
+
})
|
|
2419
|
+
})
|
|
2420
|
+
`.trim());
|
|
2421
|
+
if (withWiring) {
|
|
2422
|
+
const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-application-service.ts`, `
|
|
2423
|
+
import { wireClass } from '@domain-first/wire'
|
|
2424
|
+
import { ${naming.ClassName}ApplicationService } from '../../application/services/${naming.fileName}-application-service'
|
|
2425
|
+
|
|
2426
|
+
export const wire${naming.ClassName}ApplicationService = wireClass(
|
|
2427
|
+
${naming.ClassName}ApplicationService,
|
|
2428
|
+
[]
|
|
2429
|
+
)
|
|
2430
|
+
`.trim());
|
|
2431
|
+
await wireNewModuleDependencies(boundedContextFolder, wireFile);
|
|
2432
|
+
}
|
|
2433
|
+
};
|
|
2434
|
+
const scaffoldNewBoundedContextUseCase = async ()=>{
|
|
2435
|
+
const name = await input({
|
|
2436
|
+
message: 'Name:',
|
|
2437
|
+
validate: (x)=>!!x.length
|
|
2438
|
+
});
|
|
2439
|
+
const { path } = new ProjectRoot();
|
|
2440
|
+
const rootFolder = new Folder(path);
|
|
2441
|
+
const folder = rootFolder.subitem([
|
|
2442
|
+
ConfigFile.Instance.data.rootFolder,
|
|
2443
|
+
'bounded-contexts',
|
|
2444
|
+
name
|
|
2445
|
+
]);
|
|
2446
|
+
folder.createIfNotExisted();
|
|
2447
|
+
};
|
|
2448
|
+
const scaffoldNewCommand = async (boundedContextFolder)=>{
|
|
2449
|
+
const commandsFolder = boundedContextFolder.subitem([
|
|
2450
|
+
'application',
|
|
2451
|
+
'commands'
|
|
2452
|
+
]);
|
|
2453
|
+
const infrastructureFolder = boundedContextFolder.subitem([
|
|
2454
|
+
'infrastructure',
|
|
2455
|
+
'commands'
|
|
2456
|
+
]);
|
|
2457
|
+
const commandName = await input({
|
|
2458
|
+
message: 'Name: '
|
|
2459
|
+
});
|
|
2460
|
+
const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
|
|
2461
|
+
const naming = new UnknownFormatNaming(commandName);
|
|
2462
|
+
const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
|
|
2463
|
+
const implementationType = await input({
|
|
2464
|
+
message: 'Command infrastructure implementation type:',
|
|
2465
|
+
default: ConfigFile.Instance.data.defaultPersistenceLayerImplementation
|
|
2466
|
+
});
|
|
2467
|
+
let addTestImplementation = false;
|
|
2468
|
+
let testImplementationType = '';
|
|
2469
|
+
addTestImplementation = await prompts_confirm({
|
|
2470
|
+
message: 'Add a test implementation for Command'
|
|
2471
|
+
});
|
|
2472
|
+
if (addTestImplementation) testImplementationType = await input({
|
|
2473
|
+
message: 'Test Command infrastructure implementation type:',
|
|
2474
|
+
default: 'in-memory'
|
|
2475
|
+
});
|
|
2476
|
+
const implementationTypes = [
|
|
2477
|
+
implementationType,
|
|
2478
|
+
testImplementationType
|
|
2479
|
+
].filter((x)=>!!x);
|
|
2480
|
+
for (const implementation of implementationTypes){
|
|
2481
|
+
const formatNaming = new UnknownFormatNaming(implementation);
|
|
2482
|
+
const implementationFile = infrastructureFolder.subitem([
|
|
2483
|
+
formatNaming.fileName
|
|
2484
|
+
]).createFile(`${formatNaming.fileName}-${naming.fileName}-command.ts`, ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
|
|
2485
|
+
import { defineHandler } from '@domain-first/handlers'
|
|
2486
|
+
import { ${naming.ClassName}Command } from '../../../application/commands/${naming.fileName}-command'
|
|
2487
|
+
|
|
2488
|
+
export class ${formatNaming.ClassName}${naming.ClassName}Command extends ${naming.ClassName}Command {
|
|
2489
|
+
constructor() {
|
|
2490
|
+
super()
|
|
2491
|
+
}
|
|
2492
|
+
|
|
2493
|
+
handle = defineHandler({
|
|
2494
|
+
inputSchema: ${naming.ClassName}Command.inputSchema,
|
|
2495
|
+
outputSchema: ${naming.ClassName}Command.outputSchema,
|
|
2496
|
+
handler: async (input) => {
|
|
2497
|
+
return {}
|
|
2498
|
+
}
|
|
2499
|
+
})
|
|
2500
|
+
}
|
|
2501
|
+
`.trim() : `
|
|
2502
|
+
import { ${naming.ClassName}Command } from '../../../application/commands/${naming.fileName}-command'
|
|
2503
|
+
|
|
2504
|
+
export class ${formatNaming.ClassName}${naming.ClassName}Command extends ${naming.ClassName}Command {
|
|
2505
|
+
constructor() {
|
|
2506
|
+
super()
|
|
2507
|
+
}
|
|
2508
|
+
}
|
|
2509
|
+
`.trim());
|
|
2510
|
+
if (!withWiring && usesInMemoryDb(implementation)) injectInMemoryDb(implementationFile, `${formatNaming.ClassName}${naming.ClassName}Command`);
|
|
2511
|
+
}
|
|
2512
|
+
if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers')) commandsFolder.createFile(`${naming.fileName}-command.ts`, `
|
|
2513
|
+
import type { Handler } from '@domain-first/handlers'
|
|
2514
|
+
|
|
2515
|
+
export abstract class ${naming.ClassName}Command {
|
|
2516
|
+
static inputSchema = {}
|
|
2517
|
+
static outputSchema = {}
|
|
2518
|
+
|
|
2519
|
+
abstract handle: Handler<typeof ${naming.ClassName}Command.inputSchema, typeof ${naming.ClassName}Command.outputSchema>
|
|
2520
|
+
}
|
|
2521
|
+
`.trim());
|
|
2522
|
+
else commandsFolder.createFile(`${naming.fileName}-command.ts`, `
|
|
2523
|
+
export abstract class ${naming.ClassName}Command {
|
|
2524
|
+
|
|
2525
|
+
}`.trim());
|
|
2526
|
+
if (scaffoldUnitTests) {
|
|
2527
|
+
const implementationNaming = new UnknownFormatNaming(implementationType);
|
|
2528
|
+
const specFile = commandsFolder.createFile(`${naming.fileName}-command.spec.ts`, `
|
|
2529
|
+
import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
|
|
2530
|
+
${withWiring ? `import { type ${naming.ClassName}Command } from './${naming.fileName}-command'
|
|
2531
|
+
import { wire${naming.ClassName}Command } from '../../wiring/commands/wire-${naming.fileName}-command'` : `import { ${implementationNaming.ClassName}${naming.ClassName}Command } from '../../infrastructure/commands/${implementationNaming.fileName}/${implementationNaming.fileName}-${naming.fileName}-command'
|
|
2532
|
+
|
|
2533
|
+
type ${naming.ClassName}Command = ${implementationNaming.ClassName}${naming.ClassName}Command`}
|
|
2534
|
+
|
|
2535
|
+
let ${naming.variableName}Command: ${naming.ClassName}Command
|
|
2536
|
+
|
|
2537
|
+
beforeEach(() => {
|
|
2538
|
+
${naming.variableName}Command = ${withWiring ? `wire${naming.ClassName}Command()` : `new ${implementationNaming.ClassName}${naming.ClassName}Command()`}
|
|
2539
|
+
})
|
|
2540
|
+
|
|
2541
|
+
describe('${naming.withSpaces} command', () => {
|
|
2542
|
+
test('can be ${withWiring ? 'wired' : 'created via constructor'}', () => {
|
|
2543
|
+
expect(${naming.variableName}Command).toBeDefined()
|
|
2544
|
+
})
|
|
2545
|
+
})
|
|
2546
|
+
`.trim());
|
|
2547
|
+
if (!withWiring && usesInMemoryDb(implementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${naming.ClassName}Command`);
|
|
2548
|
+
}
|
|
2549
|
+
if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
|
|
2550
|
+
const implementationNaming = new UnknownFormatNaming(implementationType);
|
|
2551
|
+
const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
|
|
2552
|
+
const wireFile = boundedContextFolder.subitem([
|
|
2553
|
+
'wiring',
|
|
2554
|
+
'commands'
|
|
2555
|
+
]).createFile(`wire-${naming.fileName}-command.ts`, `
|
|
2556
|
+
import { wireClass } from '@domain-first/wire'
|
|
2557
|
+
import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
|
|
2558
|
+
${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${naming.ClassName}Command } from '../../infrastructure/commands/${fileName}/${fileName}-${naming.fileName}-command'`).join('\n')}
|
|
2559
|
+
|
|
2560
|
+
${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${naming.ClassName}Command, [])`).join('\n\n')}
|
|
2561
|
+
|
|
2562
|
+
export const wire${naming.ClassName}Command = envBranchedWire({
|
|
2563
|
+
test: wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation,
|
|
2564
|
+
development: wire${implementationNaming.ClassName}Implementation,
|
|
2565
|
+
production: wire${implementationNaming.ClassName}Implementation
|
|
2566
|
+
})
|
|
2567
|
+
`.trim());
|
|
2568
|
+
await wireNewModuleDependencies(boundedContextFolder, wireFile);
|
|
2569
|
+
}
|
|
2570
|
+
};
|
|
2571
|
+
const noAggregate = 'No aggregate';
|
|
2572
|
+
const scaffoldNewDomainObject = async (boundedContextFolder, kind)=>{
|
|
2573
|
+
const name = await input({
|
|
2574
|
+
message: 'Name: '
|
|
2575
|
+
});
|
|
2576
|
+
const naming = new UnknownFormatNaming(name);
|
|
2577
|
+
const aggregatesFolder = boundedContextFolder.subitem([
|
|
2578
|
+
'domain',
|
|
2579
|
+
'aggregates'
|
|
2580
|
+
]);
|
|
2581
|
+
const aggregateNames = aggregatesFolder.content.subfolderNames;
|
|
2582
|
+
const aggregate = aggregateNames.length ? await prompts_select({
|
|
2583
|
+
message: 'Aggregate:',
|
|
2584
|
+
choices: [
|
|
2585
|
+
...aggregateNames,
|
|
2586
|
+
noAggregate
|
|
2587
|
+
]
|
|
2588
|
+
}) : noAggregate;
|
|
2589
|
+
const kindFolderName = 'entity' === kind ? 'entities' : 'value-objects';
|
|
2590
|
+
const folder = aggregate === noAggregate ? boundedContextFolder.subitem([
|
|
2591
|
+
'domain',
|
|
2592
|
+
kindFolderName
|
|
2593
|
+
]) : aggregatesFolder.subitem([
|
|
2594
|
+
aggregate,
|
|
2595
|
+
kindFolderName
|
|
2596
|
+
]);
|
|
2597
|
+
const fileName = `${naming.fileName}.${kind}`;
|
|
2598
|
+
const withTypes = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/types');
|
|
2599
|
+
folder.createFile(`${fileName}.ts`, withTypes ? `
|
|
2600
|
+
import { domainType } from '@domain-first/types'
|
|
2601
|
+
|
|
2602
|
+
export class ${naming.ClassName} extends domainType() {
|
|
2603
|
+
|
|
2604
|
+
}`.trim() : `export class ${naming.ClassName} {}`);
|
|
2605
|
+
if (aggregate !== noAggregate) aggregatesFolder.subitem([
|
|
2606
|
+
aggregate
|
|
2607
|
+
]).file('index.ts').addLineIfMissing(`export * from './${kindFolderName}/${fileName}'`);
|
|
2608
|
+
const { testingLibrary } = ConfigFile.Instance.data;
|
|
2609
|
+
if (testingLibrary) folder.createFile(`${fileName}.spec.ts`, `
|
|
2610
|
+
import { describe, test, expect, beforeEach } from '${testingLibrary}'
|
|
2611
|
+
import { ${naming.ClassName} } from './${fileName}'
|
|
2612
|
+
|
|
2613
|
+
let ${naming.variableName}: ${naming.ClassName}
|
|
2614
|
+
|
|
2615
|
+
beforeEach(() => {
|
|
2616
|
+
${naming.variableName} = ${withTypes ? `${naming.ClassName}.of({})` : `new ${naming.ClassName}()`}
|
|
2617
|
+
})
|
|
2618
|
+
|
|
2619
|
+
describe('${naming.withSpaces}', () => {
|
|
2620
|
+
test('can be instantiated via ${withTypes ? 'of' : 'constructor'}', () => {
|
|
2621
|
+
expect(${naming.variableName}).toBeDefined()
|
|
2622
|
+
})
|
|
2623
|
+
})
|
|
2624
|
+
`.trim());
|
|
2625
|
+
};
|
|
2626
|
+
const scaffoldNewDomainService = async (boundedContextFolder)=>{
|
|
2627
|
+
const portName = await input({
|
|
2628
|
+
message: 'Name:'
|
|
2629
|
+
});
|
|
2630
|
+
const naming = new UnknownFormatNaming(portName);
|
|
2631
|
+
const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
|
|
2632
|
+
const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
|
|
2633
|
+
const domainServicesFolder = boundedContextFolder.subitem([
|
|
2634
|
+
'domain',
|
|
2635
|
+
'services'
|
|
2636
|
+
]);
|
|
2637
|
+
domainServicesFolder.createFile(`${naming.fileName}-domain-service.ts`, `
|
|
2638
|
+
export class ${naming.ClassName}DomainService {
|
|
2639
|
+
|
|
2640
|
+
}
|
|
2641
|
+
`.trim());
|
|
2642
|
+
if (scaffoldUnitTests) domainServicesFolder.createFile(`${naming.fileName}-domain-service.spec.ts`, `
|
|
2643
|
+
import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
|
|
2644
|
+
${withWiring ? `import { type ${naming.ClassName}DomainService } from './${naming.fileName}-domain-service'
|
|
2645
|
+
import { wire${naming.ClassName}DomainService } from '../../wiring/domain-services/wire-${naming.fileName}-domain-service'` : `import { ${naming.ClassName}DomainService } from './${naming.fileName}-domain-service'`}
|
|
2646
|
+
|
|
2647
|
+
let ${naming.variableName}DomainService: ${naming.ClassName}DomainService
|
|
2648
|
+
|
|
2649
|
+
beforeEach(() => {
|
|
2650
|
+
${naming.variableName}DomainService = ${withWiring ? `wire${naming.ClassName}DomainService()` : `new ${naming.ClassName}DomainService()`}
|
|
2651
|
+
})
|
|
2652
|
+
|
|
2653
|
+
describe('${naming.withSpaces}', () => {
|
|
2654
|
+
test('can be ${withWiring ? 'wired' : 'created'}', () => {
|
|
2655
|
+
expect(${naming.variableName}DomainService).toBeDefined()
|
|
2656
|
+
})
|
|
2657
|
+
})
|
|
2658
|
+
`.trim());
|
|
2659
|
+
if (withWiring) {
|
|
2660
|
+
const wireFile = boundedContextFolder.subitem([
|
|
2661
|
+
'wiring',
|
|
2662
|
+
'domain-services'
|
|
2663
|
+
]).createFile(`wire-${naming.fileName}-domain-service.ts`, `
|
|
2664
|
+
import { wireClass } from '@domain-first/wire'
|
|
2665
|
+
import { ${naming.ClassName}DomainService } from '../../domain/services/${naming.fileName}-domain-service'
|
|
2666
|
+
|
|
2667
|
+
export const wire${naming.ClassName}DomainService = wireClass(
|
|
2668
|
+
${naming.ClassName}DomainService,
|
|
2669
|
+
[]
|
|
2670
|
+
)
|
|
2671
|
+
`.trim());
|
|
2672
|
+
await wireNewModuleDependencies(boundedContextFolder, wireFile);
|
|
2673
|
+
}
|
|
2674
|
+
};
|
|
2675
|
+
const errorNames = (boundedContextFolder)=>{
|
|
2676
|
+
const isShared = boundedContextFolder.path === new Folder(new ProjectRoot().path).subitem([
|
|
2677
|
+
ConfigFile.Instance.data.rootFolder,
|
|
2678
|
+
'shared-kernel'
|
|
2679
|
+
]).path;
|
|
2680
|
+
return {
|
|
2681
|
+
namespace: (namespaceName)=>`${namespaceName}${isShared ? 'SharedKernel' : ''}Errors`,
|
|
2682
|
+
error: (errorName)=>`${errorName}${isShared ? 'SharedKernelError' : ''}`
|
|
2683
|
+
};
|
|
2684
|
+
};
|
|
2685
|
+
const namespacePattern = /export\s+const\s+(\w+)\s*=\s*errorNamespace\b/;
|
|
2686
|
+
const exportedNamespace = (file, fallback)=>namespacePattern.exec(file.data)?.[1] ?? fallback;
|
|
2687
|
+
const rootNamespace = (indexFile, namespace, code)=>{
|
|
2688
|
+
const content = indexFile.exists ? indexFile.data.trim() : '';
|
|
2689
|
+
const existing = namespacePattern.exec(content)?.[1];
|
|
2690
|
+
if (existing) return existing;
|
|
2691
|
+
indexFile.update([
|
|
2692
|
+
"import { errorNamespace } from '@domain-first/errors'",
|
|
2693
|
+
`export const ${namespace} = errorNamespace('${code}')`,
|
|
2694
|
+
content
|
|
2695
|
+
].filter((x)=>!!x).join('\n\n'));
|
|
2696
|
+
return namespace;
|
|
2697
|
+
};
|
|
2698
|
+
const errorClass = (className, namespace, code)=>`export class ${className} extends ${namespace}.define('${code}') {}`;
|
|
2699
|
+
const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
|
|
2700
|
+
const currentErrorFolder = boundedContextFolder.subitem([
|
|
2701
|
+
'domain',
|
|
2702
|
+
'errors'
|
|
2703
|
+
]);
|
|
2704
|
+
const names = errorNames(boundedContextFolder);
|
|
2705
|
+
const contextNaming = new UnknownFormatNaming(boundedContextFolder.name);
|
|
2706
|
+
const currentErrorNamespaces = currentErrorFolder.content.fileNames.filter((x)=>'index' !== x);
|
|
2707
|
+
const variants = [
|
|
2708
|
+
'New error without namespace',
|
|
2709
|
+
...currentErrorNamespaces.map((x)=>`New error in namespace ${x}`),
|
|
2710
|
+
'New namespace'
|
|
2711
|
+
];
|
|
2712
|
+
const selectedVariant = await prompts_select({
|
|
2713
|
+
choices: variants,
|
|
2714
|
+
message: 'Action:'
|
|
2715
|
+
});
|
|
2716
|
+
if ('New error without namespace' === selectedVariant) {
|
|
2717
|
+
const errorName = await input({
|
|
2718
|
+
message: 'Error name:'
|
|
2719
|
+
});
|
|
2720
|
+
const naming = new UnknownFormatNaming(errorName);
|
|
2721
|
+
const indexFile = currentErrorFolder.file('index.ts');
|
|
2722
|
+
indexFile.addLineIfMissing(errorClass(names.error(naming.ClassName), rootNamespace(indexFile, `${contextNaming.ClassName}Errors`, boundedContextFolder.name), naming.fileName), '\n\n');
|
|
2723
|
+
return;
|
|
2724
|
+
}
|
|
2725
|
+
if ('New namespace' === selectedVariant) {
|
|
2726
|
+
const namespaceName = await input({
|
|
2727
|
+
message: 'Namespace name:'
|
|
2728
|
+
});
|
|
2729
|
+
const { ClassName, fileName } = new UnknownFormatNaming(namespaceName);
|
|
2730
|
+
if (!currentErrorFolder.file(`${fileName}.ts`).exists) currentErrorFolder.createFile(`${fileName}.ts`, `
|
|
2731
|
+
import { errorNamespace } from '@domain-first/errors'
|
|
2732
|
+
|
|
2733
|
+
export const ${names.namespace(ClassName)} = errorNamespace('${boundedContextFolder.name}').subnamespace('${fileName}')
|
|
2734
|
+
`.trim());
|
|
2735
|
+
currentErrorFolder.file('index.ts').addLineIfMissing(`export * from './${fileName}'`, '\n\n');
|
|
2736
|
+
return;
|
|
2737
|
+
}
|
|
2738
|
+
const namespace = selectedVariant.substring(23);
|
|
2739
|
+
const namespaceNaming = new UnknownFormatNaming(namespace);
|
|
2740
|
+
const errorName = await input({
|
|
2741
|
+
message: 'Error name:'
|
|
2742
|
+
});
|
|
2743
|
+
const { ClassName, fileName } = new UnknownFormatNaming(errorName);
|
|
2744
|
+
const namespaceFile = currentErrorFolder.file(`${namespace}.ts`);
|
|
2745
|
+
namespaceFile.addLineIfMissing(errorClass(names.error(`${namespaceNaming.ClassName}${ClassName}`), exportedNamespace(namespaceFile, names.namespace(namespaceNaming.ClassName)), fileName), '\n\n');
|
|
2746
|
+
};
|
|
2747
|
+
const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
|
|
2748
|
+
const restPresentationFolder = boundedContextFolder.subitem([
|
|
2749
|
+
'presentation',
|
|
2750
|
+
'rest'
|
|
2751
|
+
]);
|
|
2752
|
+
const controllers = restPresentationFolder.content.subfolderNames;
|
|
2753
|
+
let controller = await prompts_select({
|
|
2754
|
+
message: 'Controller: ',
|
|
2755
|
+
choices: [
|
|
2756
|
+
...controllers,
|
|
2757
|
+
'New controller'
|
|
2758
|
+
]
|
|
2759
|
+
});
|
|
2760
|
+
if ('New controller' === controller) {
|
|
2761
|
+
controller = await input({
|
|
2762
|
+
message: 'Name: '
|
|
2763
|
+
});
|
|
2764
|
+
if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
|
|
2765
|
+
boundedContextFolder.subitem([
|
|
2766
|
+
'wiring',
|
|
2767
|
+
'presentation',
|
|
2768
|
+
'rest'
|
|
2769
|
+
]).file('index.ts').addLine(`export * from './${controller}'`);
|
|
2770
|
+
const sharedRestFolder = boundedContextFolder.subitem([
|
|
2771
|
+
'..',
|
|
2772
|
+
'..',
|
|
2773
|
+
'presentation',
|
|
2774
|
+
'rest'
|
|
2775
|
+
]);
|
|
2776
|
+
sharedRestFolder.file('wires.ts').addLine(`export * from '../../bounded-contexts/${boundedContextFolder.name}/wiring/presentation/rest/${controller}'`);
|
|
2777
|
+
if (!sharedRestFolder.file('index.ts').exists) sharedRestFolder.createFile('index.ts', `
|
|
2778
|
+
import * as wires from './wires'
|
|
2779
|
+
|
|
2780
|
+
const restWires = Object.values(wires)
|
|
2781
|
+
|
|
2782
|
+
export const restHandlers = restWires.map(x => x().handle)
|
|
2783
|
+
`.trim());
|
|
2784
|
+
}
|
|
2785
|
+
}
|
|
2786
|
+
const method = await prompts_select({
|
|
2787
|
+
message: 'Method:',
|
|
2788
|
+
choices: [
|
|
2789
|
+
'get',
|
|
2790
|
+
'post',
|
|
2791
|
+
'patch',
|
|
2792
|
+
'delete',
|
|
2793
|
+
'put'
|
|
2794
|
+
]
|
|
2795
|
+
});
|
|
2796
|
+
const routeSegments = (await input({
|
|
2797
|
+
message: 'Relative path (split by "/"):'
|
|
2798
|
+
})).split('/').filter((x)=>!!x);
|
|
2799
|
+
const pathParameterAsName = (segment)=>segment.startsWith(':') ? `_${segment.slice(1)}_` : segment;
|
|
2800
|
+
const controllerFolder = restPresentationFolder.subitem([
|
|
2801
|
+
controller
|
|
2802
|
+
]);
|
|
2803
|
+
const endpointFolder = controllerFolder.subitem(routeSegments.map(pathParameterAsName));
|
|
2804
|
+
const nameBase = `${controller}-${routeSegments.length ? `${routeSegments.map(pathParameterAsName).join('-')}-` : ''}${method}-endpoint`;
|
|
2805
|
+
const endpointClassName = [
|
|
2806
|
+
controller,
|
|
2807
|
+
...routeSegments,
|
|
2808
|
+
method,
|
|
2809
|
+
'endpoint'
|
|
2810
|
+
].map((segment)=>segment.startsWith(':') ? pathParameterAsName(segment) : new UnknownFormatNaming(segment).ClassName).join('');
|
|
2811
|
+
const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
|
|
2812
|
+
const endpointGenerator = findRestEndpointGenerator(boundedContextFolder.subitem([
|
|
2813
|
+
'..',
|
|
2814
|
+
'..',
|
|
2815
|
+
'shared-kernel'
|
|
2816
|
+
]));
|
|
2817
|
+
const handler = withWiring ? await promptEndpointHandler(boundedContextFolder) : void 0;
|
|
2818
|
+
const endpointFile = node_path.join(endpointFolder.path, `${method.toUpperCase()}.ts`);
|
|
2819
|
+
endpointFolder.createFile(`${method.toUpperCase()}.ts`, `
|
|
2820
|
+
${endpointGenerator ? `import type { ${endpointGenerator.typeName} } from '${relativeImport(endpointFile, endpointGenerator.typeFile)}'` : "import { EndpointGenerator } from '@domain-first/handlers-rest'"}${handler ? `
|
|
2821
|
+
import type { ${handler.typeName} } from '${relativeImport(endpointFile, handler.typeFile)}'` : ''}
|
|
2822
|
+
|
|
2823
|
+
export class ${endpointClassName} {
|
|
2824
|
+
constructor(
|
|
2825
|
+
private readonly endpointGenerator: ${endpointGenerator?.typeName ?? 'EndpointGenerator'},
|
|
2826
|
+
private readonly handler: ${handler?.typeName ?? 'never'}
|
|
2827
|
+
) {}
|
|
2828
|
+
|
|
2829
|
+
get handle() {
|
|
2830
|
+
return this.endpointGenerator(this.handler.handle, {
|
|
2831
|
+
route: { method: '${method}', path: ['${boundedContextFolder.name}', '${controller}'${routeSegments.length ? `, ${routeSegments.map((x)=>`'${x}'`).join(', ')}` : ''}] },
|
|
2832
|
+
tags: ['${boundedContextFolder.name}: ${controller}'],
|
|
2833
|
+
})
|
|
2834
|
+
}
|
|
2835
|
+
}
|
|
2836
|
+
`.trim());
|
|
2837
|
+
if (withWiring) {
|
|
2838
|
+
const wiringFolder = boundedContextFolder.subitem([
|
|
2839
|
+
'wiring',
|
|
2840
|
+
'presentation',
|
|
2841
|
+
'rest',
|
|
2842
|
+
controller
|
|
2843
|
+
]);
|
|
2844
|
+
const wireNameBase = `wire-${nameBase}`;
|
|
2845
|
+
const wireNaming = new UnknownFormatNaming(wireNameBase);
|
|
2846
|
+
const wireFile = node_path.join(wiringFolder.path, `${wireNaming.fileName}.ts`);
|
|
2847
|
+
const dependencies = endpointGenerator ? [
|
|
2848
|
+
endpointGenerator,
|
|
2849
|
+
handler
|
|
2850
|
+
].filter((x)=>!!x) : [];
|
|
2851
|
+
wiringFolder.createFile(`${wireNaming.fileName}.ts`, `
|
|
2852
|
+
import { wireClass } from '@domain-first/wire'
|
|
2853
|
+
import { ${endpointClassName} } from '${relativeImport(wireFile, endpointFile)}'
|
|
2854
|
+
${dependencies.map((x)=>`import { ${x.wireName} } from '${relativeImport(wireFile, x.wireFile)}'`).join('\n')}
|
|
2855
|
+
|
|
2856
|
+
export const wire${endpointClassName} = wireClass(
|
|
2857
|
+
${endpointClassName},
|
|
2858
|
+
[${dependencies.map((x)=>x.wireName).join(', ')}]
|
|
2859
|
+
)
|
|
2860
|
+
`.trim());
|
|
2861
|
+
wiringFolder.file('index.ts').addLine(`export * from './${wireNaming.fileName}'`);
|
|
2862
|
+
}
|
|
2863
|
+
};
|
|
2864
|
+
const scaffoldNewInfrastructureService = async (boundedContextFolder)=>{
|
|
2865
|
+
const name = await input({
|
|
2866
|
+
message: 'Name: '
|
|
2867
|
+
});
|
|
2868
|
+
const naming = new UnknownFormatNaming(name);
|
|
2869
|
+
const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
|
|
2870
|
+
const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
|
|
2871
|
+
const wiringFolder = boundedContextFolder.subitem([
|
|
2872
|
+
'wiring',
|
|
2873
|
+
'infrastructure-services'
|
|
2874
|
+
]);
|
|
2875
|
+
const infrastructureServicesFolder = boundedContextFolder.subitem([
|
|
2876
|
+
'infrastructure',
|
|
2877
|
+
'services'
|
|
2878
|
+
]);
|
|
2879
|
+
infrastructureServicesFolder.createFile(`${naming.fileName}-infrastructure-service.ts`, `
|
|
2880
|
+
export class ${naming.ClassName}InfrastructureService {
|
|
2881
|
+
|
|
2882
|
+
}
|
|
2883
|
+
`.trim());
|
|
2884
|
+
if (scaffoldUnitTests) infrastructureServicesFolder.createFile(`${naming.fileName}-infrastructure-service.spec.ts`, `
|
|
2885
|
+
import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
|
|
2886
|
+
${withWiring ? `import { type ${naming.ClassName}InfrastructureService } from './${naming.fileName}-infrastructure-service'
|
|
2887
|
+
import { wire${naming.ClassName}InfrastructureService } from '../../wiring/infrastructure-services/wire-${naming.fileName}-infrastructure-service'` : `import { ${naming.ClassName}InfrastructureService } from './${naming.fileName}-infrastructure-service'`}
|
|
2888
|
+
|
|
2889
|
+
let ${naming.variableName}InfrastructureService: ${naming.ClassName}InfrastructureService
|
|
2890
|
+
|
|
2891
|
+
beforeEach(() => {
|
|
2892
|
+
${naming.variableName}InfrastructureService = ${withWiring ? `wire${naming.ClassName}InfrastructureService()` : `new ${naming.ClassName}InfrastructureService()`}
|
|
2893
|
+
})
|
|
2894
|
+
|
|
2895
|
+
describe('${naming.withSpaces}', () => {
|
|
2896
|
+
test('can be ${withWiring ? 'wired' : 'created'}', () => {
|
|
2897
|
+
expect(${naming.variableName}InfrastructureService).toBeDefined()
|
|
2898
|
+
})
|
|
2899
|
+
})
|
|
2900
|
+
`.trim());
|
|
2901
|
+
if (withWiring) {
|
|
2902
|
+
const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-infrastructure-service.ts`, `
|
|
2903
|
+
import { wireClass } from '@domain-first/wire'
|
|
2904
|
+
import { ${naming.ClassName}InfrastructureService } from '../../infrastructure/services/${naming.fileName}-infrastructure-service'
|
|
2905
|
+
|
|
2906
|
+
export const wire${naming.ClassName}InfrastructureService = wireClass(
|
|
2907
|
+
${naming.ClassName}InfrastructureService,
|
|
2908
|
+
[]
|
|
2909
|
+
)
|
|
2910
|
+
`.trim());
|
|
2911
|
+
await wireNewModuleDependencies(boundedContextFolder, wireFile);
|
|
2912
|
+
}
|
|
2913
|
+
};
|
|
2914
|
+
const scaffoldNewQuery = async (boundedContextFolder)=>{
|
|
2915
|
+
const queriesFolder = boundedContextFolder.subitem([
|
|
2916
|
+
'application',
|
|
2917
|
+
'queries'
|
|
2918
|
+
]);
|
|
2919
|
+
const infrastructureFolder = boundedContextFolder.subitem([
|
|
2920
|
+
'infrastructure',
|
|
2921
|
+
'queries'
|
|
2922
|
+
]);
|
|
2923
|
+
const queryName = await input({
|
|
2924
|
+
message: 'Name: '
|
|
2925
|
+
});
|
|
2926
|
+
const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
|
|
2927
|
+
const naming = new UnknownFormatNaming(queryName);
|
|
2928
|
+
const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
|
|
2929
|
+
const implementationType = await input({
|
|
2930
|
+
message: 'Query infrastructure implementation type:',
|
|
2931
|
+
default: ConfigFile.Instance.data.defaultPersistenceLayerImplementation
|
|
2932
|
+
});
|
|
2933
|
+
let addTestImplementation = false;
|
|
2934
|
+
let testImplementationType = '';
|
|
2935
|
+
addTestImplementation = await prompts_confirm({
|
|
2936
|
+
message: 'Add a test implementation for Query'
|
|
2937
|
+
});
|
|
2938
|
+
if (addTestImplementation) testImplementationType = await input({
|
|
2939
|
+
message: 'Test Query infrastructure implementation type:',
|
|
2940
|
+
default: 'in-memory'
|
|
2941
|
+
});
|
|
2942
|
+
const implementationTypes = [
|
|
2943
|
+
implementationType,
|
|
2944
|
+
testImplementationType
|
|
2945
|
+
].filter((x)=>!!x);
|
|
2946
|
+
for (const implementation of implementationTypes){
|
|
2947
|
+
const formatNaming = new UnknownFormatNaming(implementation);
|
|
2948
|
+
const implementationFile = infrastructureFolder.subitem([
|
|
2949
|
+
formatNaming.fileName
|
|
2950
|
+
]).createFile(`${formatNaming.fileName}-${naming.fileName}-query.ts`, ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
|
|
2951
|
+
import { defineHandler } from '@domain-first/handlers'
|
|
2952
|
+
import { ${naming.ClassName}Query } from '../../../application/queries/${naming.fileName}-query'
|
|
2953
|
+
|
|
2954
|
+
export class ${formatNaming.ClassName}${naming.ClassName}Query extends ${naming.ClassName}Query {
|
|
2955
|
+
constructor() {
|
|
2956
|
+
super()
|
|
2957
|
+
}
|
|
2958
|
+
|
|
2959
|
+
handle = defineHandler({
|
|
2960
|
+
inputSchema: ${naming.ClassName}Query.inputSchema,
|
|
2961
|
+
outputSchema: ${naming.ClassName}Query.outputSchema,
|
|
2962
|
+
handler: async (input) => {
|
|
2963
|
+
return {}
|
|
2964
|
+
}
|
|
2965
|
+
})
|
|
2966
|
+
}
|
|
2967
|
+
`.trim() : `
|
|
2968
|
+
import { ${naming.ClassName}Query } from '../../../application/queries/${naming.fileName}-query'
|
|
2969
|
+
|
|
2970
|
+
export class ${formatNaming.ClassName}${naming.ClassName}Query extends ${naming.ClassName}Query {
|
|
2971
|
+
constructor() {
|
|
2972
|
+
super()
|
|
2973
|
+
}
|
|
2974
|
+
}
|
|
2975
|
+
`.trim());
|
|
2976
|
+
if (!withWiring && usesInMemoryDb(implementation)) injectInMemoryDb(implementationFile, `${formatNaming.ClassName}${naming.ClassName}Query`);
|
|
2977
|
+
}
|
|
2978
|
+
if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers')) queriesFolder.createFile(`${naming.fileName}-query.ts`, `
|
|
2979
|
+
import type { Handler } from '@domain-first/handlers'
|
|
2980
|
+
|
|
2981
|
+
export abstract class ${naming.ClassName}Query {
|
|
2982
|
+
static inputSchema = {}
|
|
2983
|
+
static outputSchema = {}
|
|
2984
|
+
|
|
2985
|
+
abstract handle: Handler<typeof ${naming.ClassName}Query.inputSchema, typeof ${naming.ClassName}Query.outputSchema>
|
|
2986
|
+
}
|
|
2987
|
+
`.trim());
|
|
2988
|
+
else queriesFolder.createFile(`${naming.fileName}-query.ts`, `
|
|
2989
|
+
export abstract class ${naming.ClassName}Query {
|
|
2990
|
+
|
|
2991
|
+
}`.trim());
|
|
2992
|
+
if (scaffoldUnitTests) {
|
|
2993
|
+
const implementationNaming = new UnknownFormatNaming(implementationType);
|
|
2994
|
+
const specFile = queriesFolder.createFile(`${naming.fileName}-query.spec.ts`, `
|
|
2995
|
+
import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
|
|
2996
|
+
${withWiring ? `import { type ${naming.ClassName}Query } from './${naming.fileName}-query'
|
|
2997
|
+
import { wire${naming.ClassName}Query } from '../../wiring/queries/wire-${naming.fileName}-query'` : `import { ${implementationNaming.ClassName}${naming.ClassName}Query } from '../../infrastructure/queries/${implementationNaming.fileName}/${implementationNaming.fileName}-${naming.fileName}-query'
|
|
2998
|
+
|
|
2999
|
+
type ${naming.ClassName}Query = ${implementationNaming.ClassName}${naming.ClassName}Query`}
|
|
3000
|
+
|
|
3001
|
+
let ${naming.variableName}Query: ${naming.ClassName}Query
|
|
3002
|
+
|
|
3003
|
+
beforeEach(() => {
|
|
3004
|
+
${naming.variableName}Query = ${withWiring ? `wire${naming.ClassName}Query()` : `new ${implementationNaming.ClassName}${naming.ClassName}Query()`}
|
|
3005
|
+
})
|
|
3006
|
+
|
|
3007
|
+
describe('${naming.withSpaces} query', () => {
|
|
3008
|
+
test('can be ${withWiring ? 'wired' : 'created via constructor'}', () => {
|
|
3009
|
+
expect(${naming.variableName}Query).toBeDefined()
|
|
3010
|
+
})
|
|
3011
|
+
})
|
|
3012
|
+
`.trim());
|
|
3013
|
+
if (!withWiring && usesInMemoryDb(implementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${naming.ClassName}Query`);
|
|
3014
|
+
}
|
|
3015
|
+
if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
|
|
3016
|
+
const implementationNaming = new UnknownFormatNaming(implementationType);
|
|
3017
|
+
const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
|
|
3018
|
+
const wireFile = boundedContextFolder.subitem([
|
|
3019
|
+
'wiring',
|
|
3020
|
+
'queries'
|
|
3021
|
+
]).createFile(`wire-${naming.fileName}-query.ts`, `
|
|
3022
|
+
import { wireClass } from '@domain-first/wire'
|
|
3023
|
+
import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
|
|
3024
|
+
${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${naming.ClassName}Query } from '../../infrastructure/queries/${fileName}/${fileName}-${naming.fileName}-query'`).join('\n')}
|
|
3025
|
+
|
|
3026
|
+
${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${naming.ClassName}Query, [])`).join('\n\n')}
|
|
3027
|
+
|
|
3028
|
+
export const wire${naming.ClassName}Query = envBranchedWire({
|
|
3029
|
+
test: wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation,
|
|
3030
|
+
development: wire${implementationNaming.ClassName}Implementation,
|
|
3031
|
+
production: wire${implementationNaming.ClassName}Implementation
|
|
3032
|
+
})
|
|
3033
|
+
`.trim());
|
|
3034
|
+
await wireNewModuleDependencies(boundedContextFolder, wireFile);
|
|
3035
|
+
}
|
|
3036
|
+
};
|
|
3037
|
+
const scaffoldNewUseCase = async (boundedContextFolder)=>{
|
|
3038
|
+
const useCasesFolder = boundedContextFolder.subitem([
|
|
3039
|
+
'application',
|
|
3040
|
+
'use-cases'
|
|
3041
|
+
]);
|
|
3042
|
+
const useCaseName = await input({
|
|
3043
|
+
message: 'Name: '
|
|
3044
|
+
});
|
|
3045
|
+
const naming = new UnknownFormatNaming(useCaseName);
|
|
3046
|
+
const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
|
|
3047
|
+
const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
|
|
3048
|
+
useCasesFolder.createFile(`${naming.fileName}-use-case.ts`, ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
|
|
3049
|
+
import { defineHandler } from '@domain-first/handlers'
|
|
3050
|
+
|
|
3051
|
+
export class ${naming.ClassName}UseCase {
|
|
3052
|
+
constructor() {}
|
|
3053
|
+
|
|
3054
|
+
static inputSchema = {}
|
|
3055
|
+
static outputSchema = {}
|
|
3056
|
+
|
|
3057
|
+
handle = defineHandler({
|
|
3058
|
+
inputSchema: ${naming.ClassName}UseCase.inputSchema,
|
|
3059
|
+
outputSchema: ${naming.ClassName}UseCase.outputSchema,
|
|
3060
|
+
handler: async (input) => {
|
|
3061
|
+
return {}
|
|
3062
|
+
}
|
|
3063
|
+
})
|
|
3064
|
+
}
|
|
3065
|
+
`.trim() : `
|
|
3066
|
+
export class ${naming.ClassName}UseCase {
|
|
3067
|
+
|
|
3068
|
+
}
|
|
3069
|
+
`.trim());
|
|
3070
|
+
if (scaffoldUnitTests) useCasesFolder.createFile(`${naming.fileName}-use-case.spec.ts`, `
|
|
3071
|
+
import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
|
|
3072
|
+
${withWiring ? `import { type ${naming.ClassName}UseCase } from './${naming.fileName}-use-case'
|
|
3073
|
+
import { wire${naming.ClassName}UseCase } from '../../wiring/use-cases/wire-${naming.fileName}-use-case'` : `import { ${naming.ClassName}UseCase } from './${naming.fileName}-use-case'`}
|
|
3074
|
+
|
|
3075
|
+
let ${naming.variableName}UseCase: ${naming.ClassName}UseCase
|
|
3076
|
+
|
|
3077
|
+
beforeEach(() => {
|
|
3078
|
+
${naming.variableName}UseCase = ${withWiring ? `wire${naming.ClassName}UseCase()` : `new ${naming.ClassName}UseCase()`}
|
|
3079
|
+
})
|
|
3080
|
+
|
|
3081
|
+
describe('${naming.withSpaces} use case', () => {
|
|
3082
|
+
test('can be ${withWiring ? 'wired' : 'created'}', () => {
|
|
3083
|
+
expect(${naming.variableName}UseCase).toBeDefined()
|
|
3084
|
+
})
|
|
3085
|
+
})
|
|
3086
|
+
`.trim());
|
|
3087
|
+
if (withWiring) {
|
|
3088
|
+
const wireFile = boundedContextFolder.subitem([
|
|
3089
|
+
'wiring',
|
|
3090
|
+
'use-cases'
|
|
3091
|
+
]).createFile(`wire-${naming.fileName}-use-case.ts`, `
|
|
3092
|
+
import { wireClass } from '@domain-first/wire'
|
|
3093
|
+
import { ${naming.ClassName}UseCase } from '../../application/use-cases/${naming.fileName}-use-case'
|
|
3094
|
+
|
|
3095
|
+
export const wire${naming.ClassName}UseCase = wireClass(
|
|
3096
|
+
${naming.ClassName}UseCase,
|
|
3097
|
+
[]
|
|
3098
|
+
)
|
|
3099
|
+
|
|
3100
|
+
`.trim());
|
|
3101
|
+
await wireNewModuleDependencies(boundedContextFolder, wireFile);
|
|
3102
|
+
}
|
|
3103
|
+
};
|
|
3104
|
+
const scaffoldReactSharedHook = async (presentationReactFolder)=>{
|
|
3105
|
+
const name = await input({
|
|
3106
|
+
message: 'Name without "use" (e.g. debounce): '
|
|
3107
|
+
});
|
|
3108
|
+
const { ClassName, fileName } = new UnknownFormatNaming(name.trim().replace(/^use-/, ''));
|
|
3109
|
+
presentationReactFolder.subitem([
|
|
3110
|
+
'hooks'
|
|
3111
|
+
]).createFile(`use-${fileName}.ts`, `
|
|
3112
|
+
export const use${ClassName} = () => {
|
|
3113
|
+
return {}
|
|
3114
|
+
}
|
|
3115
|
+
`.trim());
|
|
3116
|
+
};
|
|
3117
|
+
const scaffoldReactUIKitComponent = async (presentationReactFolder)=>{
|
|
3118
|
+
const name = await input({
|
|
3119
|
+
message: 'Name: '
|
|
3120
|
+
});
|
|
3121
|
+
const { ClassName, fileName } = new UnknownFormatNaming(name);
|
|
3122
|
+
const componentFolder = presentationReactFolder.subitem([
|
|
3123
|
+
'ui-kit',
|
|
3124
|
+
fileName
|
|
3125
|
+
]);
|
|
3126
|
+
componentFolder.createFile('index.ts', `export * from './${fileName}'`);
|
|
3127
|
+
componentFolder.createFile(`${fileName}.tsx`, `
|
|
3128
|
+
import { type FC } from 'react'
|
|
3129
|
+
|
|
3130
|
+
export type ${ClassName}Props = {}
|
|
3131
|
+
|
|
3132
|
+
export const ${ClassName}: FC<${ClassName}Props> = (props) => {
|
|
3133
|
+
return <></>
|
|
3134
|
+
}
|
|
3135
|
+
`.trim());
|
|
3136
|
+
const { storybookFramework } = ConfigFile.Instance.data;
|
|
3137
|
+
if (storybookFramework) componentFolder.createFile(`${fileName}.stories.tsx`, `
|
|
3138
|
+
import type { Meta, StoryObj } from '${storybookFramework}'
|
|
3139
|
+
import { ${ClassName} } from './${fileName}'
|
|
3140
|
+
|
|
3141
|
+
const meta = {
|
|
3142
|
+
title: 'UI-kit/${ClassName}',
|
|
3143
|
+
component: ${ClassName}
|
|
3144
|
+
} satisfies Meta<typeof ${ClassName}>
|
|
3145
|
+
|
|
3146
|
+
export default meta
|
|
3147
|
+
|
|
3148
|
+
type Story = StoryObj<typeof meta>
|
|
3149
|
+
|
|
3150
|
+
export const Default: Story = {
|
|
3151
|
+
args: {}
|
|
3152
|
+
}
|
|
3153
|
+
`.trim());
|
|
3154
|
+
};
|
|
3155
|
+
const scaffoldReactWidget = async (presentationReactFolder)=>{
|
|
3156
|
+
const widgetName = await input({
|
|
3157
|
+
message: 'Name (folders split by "/"): ',
|
|
3158
|
+
validate: NestedName.validate
|
|
3159
|
+
});
|
|
3160
|
+
const widgetType = await prompts_select({
|
|
3161
|
+
choices: [
|
|
3162
|
+
'monolithic',
|
|
3163
|
+
'with separated ui',
|
|
3164
|
+
'headless'
|
|
3165
|
+
],
|
|
3166
|
+
message: 'Type: '
|
|
3167
|
+
});
|
|
3168
|
+
const { folders, folderName, ClassName, fileName, classNameSegments } = new NestedName(widgetName);
|
|
3169
|
+
const folder = presentationReactFolder.subitem([
|
|
3170
|
+
'widgets',
|
|
3171
|
+
...folders,
|
|
3172
|
+
folderName
|
|
3173
|
+
]);
|
|
3174
|
+
const storyTitle = [
|
|
3175
|
+
'Widgets',
|
|
3176
|
+
...classNameSegments
|
|
3177
|
+
].join('/');
|
|
3178
|
+
const widgetFileName = `${fileName}-widget`;
|
|
3179
|
+
const uiFileName = `${fileName}-widget-ui`;
|
|
3180
|
+
const uiModelFileName = `use-${fileName}-ui-model`;
|
|
3181
|
+
folder.createFile('index.ts', `export * from './${widgetFileName}'`);
|
|
3182
|
+
switch(widgetType){
|
|
3183
|
+
case 'monolithic':
|
|
3184
|
+
folder.createFile(`${widgetFileName}.tsx`, `
|
|
3185
|
+
import { type FC } from 'react'
|
|
3186
|
+
|
|
3187
|
+
export type ${ClassName}WidgetProps = {}
|
|
3188
|
+
|
|
3189
|
+
export const ${ClassName}Widget: FC<${ClassName}WidgetProps> = (props) => {
|
|
3190
|
+
return <></>
|
|
3191
|
+
}
|
|
3192
|
+
`.trim());
|
|
3193
|
+
break;
|
|
3194
|
+
case 'with separated ui':
|
|
3195
|
+
{
|
|
3196
|
+
folder.createFile('types.ts', `
|
|
3197
|
+
export type ${ClassName}WidgetProps = { }
|
|
3198
|
+
|
|
3199
|
+
export type ${ClassName}WidgetUIProps = { }
|
|
3200
|
+
`.trim());
|
|
3201
|
+
folder.createFile(`${widgetFileName}.tsx`, `
|
|
3202
|
+
import { type FC } from 'react'
|
|
3203
|
+
import type { ${ClassName}WidgetProps } from './types'
|
|
3204
|
+
import { ${ClassName}WidgetUI } from './ui/${uiFileName}'
|
|
3205
|
+
import { use${ClassName}UIModel } from './hooks/${uiModelFileName}'
|
|
3206
|
+
|
|
3207
|
+
export const ${ClassName}Widget: FC<${ClassName}WidgetProps> = (props) => {
|
|
3208
|
+
const uiModel = use${ClassName}UIModel(props)
|
|
3209
|
+
return <${ClassName}WidgetUI {...uiModel} />
|
|
3210
|
+
}
|
|
3211
|
+
|
|
3212
|
+
export type { ${ClassName}WidgetProps }
|
|
3213
|
+
`.trim());
|
|
3214
|
+
folder.subitem([
|
|
3215
|
+
'ui'
|
|
3216
|
+
]).createFile(`${uiFileName}.tsx`, `
|
|
3217
|
+
import { FC } from 'react'
|
|
3218
|
+
import type { ${ClassName}WidgetUIProps } from '../types'
|
|
3219
|
+
|
|
3220
|
+
export const ${ClassName}WidgetUI: FC<${ClassName}WidgetUIProps> = (props) => {
|
|
3221
|
+
return <></>
|
|
3222
|
+
}
|
|
3223
|
+
`.trim());
|
|
3224
|
+
const { storybookFramework } = ConfigFile.Instance.data;
|
|
3225
|
+
if (storybookFramework) folder.subitem([
|
|
3226
|
+
'ui'
|
|
3227
|
+
]).createFile(`${uiFileName}.stories.tsx`, `
|
|
3228
|
+
import type { Meta, StoryObj } from '${storybookFramework}'
|
|
3229
|
+
import { ${ClassName}WidgetUI } from './${uiFileName}'
|
|
3230
|
+
|
|
3231
|
+
const meta = {
|
|
3232
|
+
title: '${storyTitle}',
|
|
3233
|
+
component: ${ClassName}WidgetUI
|
|
3234
|
+
} satisfies Meta<typeof ${ClassName}WidgetUI>
|
|
3235
|
+
|
|
3236
|
+
export default meta
|
|
3237
|
+
|
|
3238
|
+
type Story = StoryObj<typeof meta>
|
|
3239
|
+
|
|
3240
|
+
export const Default: Story = {
|
|
3241
|
+
args: {}
|
|
3242
|
+
}
|
|
3243
|
+
`.trim());
|
|
3244
|
+
folder.subitem([
|
|
3245
|
+
'hooks'
|
|
3246
|
+
]).createFile(`${uiModelFileName}.ts`, `
|
|
3247
|
+
import type { ${ClassName}WidgetProps, ${ClassName}WidgetUIProps } from '../types'
|
|
3248
|
+
|
|
3249
|
+
export const use${ClassName}UIModel = (widgetProps: ${ClassName}WidgetProps): ${ClassName}WidgetUIProps => {
|
|
3250
|
+
return {}
|
|
3251
|
+
}
|
|
3252
|
+
`.trim());
|
|
3253
|
+
break;
|
|
3254
|
+
}
|
|
3255
|
+
case 'headless':
|
|
3256
|
+
folder.createFile('types.ts', `
|
|
3257
|
+
import { type FC } from 'react'
|
|
3258
|
+
|
|
3259
|
+
export type ${ClassName}WidgetUIProps = { }
|
|
3260
|
+
|
|
3261
|
+
export type ${ClassName}WidgetProps = {
|
|
3262
|
+
UI: FC<${ClassName}WidgetUIProps>
|
|
3263
|
+
}
|
|
3264
|
+
|
|
3265
|
+
`.trim());
|
|
3266
|
+
folder.createFile(`${widgetFileName}.tsx`, `
|
|
3267
|
+
import { type FC } from 'react'
|
|
3268
|
+
import type { ${ClassName}WidgetProps } from './types'
|
|
3269
|
+
import { use${ClassName}UIModel } from './hooks/${uiModelFileName}'
|
|
3270
|
+
|
|
3271
|
+
export const ${ClassName}Widget: FC<${ClassName}WidgetProps> = (props) => {
|
|
3272
|
+
const uiModel = use${ClassName}UIModel(props)
|
|
3273
|
+
return <props.UI {...uiModel} />
|
|
3274
|
+
}
|
|
3275
|
+
|
|
3276
|
+
export type { ${ClassName}WidgetProps }
|
|
3277
|
+
`.trim());
|
|
3278
|
+
folder.subitem([
|
|
3279
|
+
'hooks'
|
|
3280
|
+
]).createFile(`${uiModelFileName}.ts`, `
|
|
3281
|
+
import type { ${ClassName}WidgetProps, ${ClassName}WidgetUIProps } from '../types'
|
|
3282
|
+
|
|
3283
|
+
export const use${ClassName}UIModel = (widgetProps: Omit<${ClassName}WidgetProps, 'UI'>): ${ClassName}WidgetUIProps => {
|
|
3284
|
+
return {}
|
|
3285
|
+
}
|
|
3286
|
+
`.trim());
|
|
3287
|
+
break;
|
|
3288
|
+
}
|
|
3289
|
+
};
|
|
3290
|
+
export { addIntegration, initializeUseCase, moveReactModuleUseCase, printNextSteps, savePendingChanges, scaffoldNewAggregateUseCase, scaffoldNewApplicationPort, scaffoldNewApplicationService, scaffoldNewBoundedContextUseCase, scaffoldNewCommand, scaffoldNewDomainObject, scaffoldNewDomainService, scaffoldNewErrorUseCase, scaffoldNewHandlersRestEndpoint, scaffoldNewInfrastructureService, scaffoldNewPresentationService, scaffoldNewQuery, scaffoldNewUseCase, scaffoldReactPage, scaffoldReactSharedHook, scaffoldReactUIKitComponent, scaffoldReactWidget, wireDependency };
|