@domain-first/project-structure 8.7.1 → 8.9.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 +4 -2
- package/dist/287.js +2446 -2005
- package/dist/561.js +19 -3
- package/dist/780.js +9 -2
- package/dist/947.js +4 -0
- package/dist/agent-cli.d.ts +37 -5
- package/dist/agent-requests.d.ts +24 -0
- package/dist/backend-module-move.d.ts +16 -0
- package/dist/config-file.d.ts +38 -18
- package/dist/graph.cjs +13 -2
- package/dist/implementation-options-schema.d.ts +19 -9
- package/dist/in-memory-db.d.ts +4 -0
- package/dist/index.cjs +3465 -2997
- package/dist/init.cjs +94 -77
- package/dist/integration-tests.d.ts +39 -0
- package/dist/integration-tests.spec.d.ts +1 -0
- package/dist/integration.cjs +3489 -3021
- package/dist/integrations/drizzle.d.ts +8 -0
- package/dist/integrations/drizzle.spec.d.ts +1 -0
- package/dist/integrations/index.d.ts +1 -0
- package/dist/integrations/testcontainers.d.ts +1 -1
- package/dist/lint.cjs +13 -2
- package/dist/react.cjs +3465 -2997
- package/dist/upgrade-steps.d.ts +19 -4
- package/dist/upgrade.cjs +9 -2
- package/dist/use-cases/add-integration.d.ts +3 -3
- package/dist/use-cases/prompt-implementation-type.d.ts +2 -0
- package/package.json +1 -1
- package/skills/df-ps-implement/SKILL.md +2 -1
- package/skills/df-ps-project-scripts/SKILL.md +22 -5
- package/skills/df-ps-scaffold/SKILL.md +1 -0
- package/skills/df-ps-scaffold/references/agent-mode.md +1 -1
- package/skills/df-ps-scaffold/references/agent-operations.md +3 -2
- package/skills/df-ps-scaffold/references/generators.md +27 -2
- package/skills/df-ps-scaffold/references/units/aggregate.md +2 -1
- package/skills/df-ps-scaffold/references/units/command-query.md +2 -1
- package/skills/df-ps-scaffold/references/units/implementation.md +1 -1
- package/skills/df-ps-scaffold/references/units/port.md +1 -0
- package/skills/df-ps-scaffold/references/units/services.md +3 -2
package/dist/287.js
CHANGED
|
@@ -1,229 +1,41 @@
|
|
|
1
1
|
import node_path from "node:path";
|
|
2
2
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
3
|
import { Separator, checkbox as prompts_checkbox, confirm as prompts_confirm, input, search, select as prompts_select } from "@inquirer/prompts";
|
|
4
|
-
import { styleText } from "node:util";
|
|
5
4
|
import node_fs from "node:fs";
|
|
5
|
+
import { styleText } from "node:util";
|
|
6
6
|
import { addImport, availableDependencies, findWiredModules, UnknownFormatNaming, readWiredModule, addClassMember, hasNeighboringBoundedContext, addBranchedImplementation, addWireDependencies, boundedContextLocation, addConstructorParameters, relativeImport, wireBranches, wireDependencies, implementationType as wiring_implementationType, crossContextImportAllowed, crossContextImplementation, isSuggestedFor } from "./947.js";
|
|
7
|
-
import { implementationLabelSchema, withoutOverwrites, domainFirstPackages as config_file_domainFirstPackages, scaffoldBackendRules, branchNameSchema, discardPendingChanges, ConfigFile, filesToOverwrite, Folder, writePendingChanges, File, ProjectRoot,
|
|
7
|
+
import { implementationLabelSchema, withoutOverwrites, domainFirstPackages as config_file_domainFirstPackages, scaffoldBackendRules, branchNameSchema, discardPendingChanges, ConfigFile, filesToOverwrite, Folder, implementationKinds, writePendingChanges, File, ProjectRoot, compilerOption } from "./780.js";
|
|
8
8
|
import { missingDomainFirstPackages, walk, projectImports, escapeRegExp, pathParameterAsName, hasLegacyRootEndpoints, stageModuleMove, toPosix, rootStaticSegments, openapiExtractorPath, restControllers, hasDependency, openapiExtractor, missingPackages, codeExtension, isPathParameterName } from "./526.js";
|
|
9
9
|
const moduleId = (module)=>`${boundedContextLocation(module.typeFile)?.name ?? 'shared-kernel'}:${module.typeName}`;
|
|
10
10
|
const unitId = (unit)=>`${unit.kind}:${unit.aggregate ? `${unit.aggregate}/` : ''}${unit.name}`;
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
type IdsAreEqual<TId> = (a: TId, b: TId) => boolean;
|
|
35
|
-
|
|
36
|
-
const comparisonMethodNames = ['equals', 'same', 'isSame', 'isEqual'] as const;
|
|
37
|
-
|
|
38
|
-
const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
|
|
39
|
-
if (typeof a !== 'object' || a === null) {
|
|
40
|
-
return Object.is(a, b);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
for (const methodName of comparisonMethodNames) {
|
|
44
|
-
const method: unknown = (a as Record<string, unknown>)[methodName];
|
|
45
|
-
if (typeof method === 'function') {
|
|
46
|
-
return Boolean(method.call(a, b));
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
return Object.is(a, b);
|
|
51
|
-
};
|
|
52
|
-
|
|
53
|
-
const hasId = (x: unknown): x is { id: unknown } =>
|
|
54
|
-
typeof x === 'object' && x !== null && 'id' in x;
|
|
55
|
-
|
|
56
|
-
export class InMemoryDbInfrastructureService {
|
|
57
|
-
protected section<T extends { id: unknown }>(
|
|
58
|
-
key: string,
|
|
59
|
-
idsAreEqual?: IdsAreEqual<T['id']>
|
|
60
|
-
): Section<T, T['id']>;
|
|
61
|
-
protected section<T, TId>(
|
|
62
|
-
key: string,
|
|
63
|
-
idsAreEqual?: IdsAreEqual<TId>
|
|
64
|
-
): Section<T, TId>;
|
|
65
|
-
protected section<T, TId>(
|
|
66
|
-
key: string,
|
|
67
|
-
idsAreEqual: IdsAreEqual<TId> = defaultIdsAreEqual
|
|
68
|
-
): Section<T, TId> {
|
|
69
|
-
if (!globalThis.___SHARED_IN_MEMORY_DB___) {
|
|
70
|
-
globalThis.___SHARED_IN_MEMORY_DB___ = {};
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
if (!globalThis.___SHARED_IN_MEMORY_DB___[key]) {
|
|
74
|
-
globalThis.___SHARED_IN_MEMORY_DB___[key] = [];
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
const items = (): T[] =>
|
|
78
|
-
globalThis.___SHARED_IN_MEMORY_DB___![key].map(
|
|
79
|
-
(entry) => entry.item
|
|
80
|
-
);
|
|
81
|
-
|
|
82
|
-
return {
|
|
83
|
-
all: (predicate: (x: T) => boolean = () => true): T[] =>
|
|
84
|
-
items().filter(predicate),
|
|
85
|
-
first: (predicate: (x: T) => boolean): T | null =>
|
|
86
|
-
items().find(predicate) ?? null,
|
|
87
|
-
withId: (id: TId): T | null =>
|
|
88
|
-
items().find(
|
|
89
|
-
(x: T) => hasId(x) && idsAreEqual(x.id as TId, id)
|
|
90
|
-
) ?? null,
|
|
91
|
-
lastAddedItem: (): T | null =>
|
|
92
|
-
globalThis.___SHARED_IN_MEMORY_DB___![key].at(-1)?.item ?? null,
|
|
93
|
-
save: (payload: T extends { id: TId } ? T : [TId, T]) => {
|
|
94
|
-
const id = Array.isArray(payload) ? payload[0] : payload.id;
|
|
95
|
-
const item = Array.isArray(payload) ? payload[1] : payload;
|
|
96
|
-
const entries = globalThis.___SHARED_IN_MEMORY_DB___![key];
|
|
97
|
-
const existing = entries.find((entry) =>
|
|
98
|
-
idsAreEqual(entry.id as TId, id)
|
|
99
|
-
);
|
|
100
|
-
if (existing) {
|
|
101
|
-
existing.item = item;
|
|
102
|
-
return;
|
|
103
|
-
}
|
|
104
|
-
entries.push({ id, item });
|
|
105
|
-
},
|
|
106
|
-
deleteById: (id: TId) => {
|
|
107
|
-
globalThis.___SHARED_IN_MEMORY_DB___![key] =
|
|
108
|
-
globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
|
|
109
|
-
(entry) => !idsAreEqual(entry.id as TId, id)
|
|
110
|
-
);
|
|
111
|
-
},
|
|
112
|
-
delete: (predicate: (x: T) => boolean) => {
|
|
113
|
-
globalThis.___SHARED_IN_MEMORY_DB___![key] =
|
|
114
|
-
globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
|
|
115
|
-
(entry) => !predicate(entry.item)
|
|
116
|
-
);
|
|
117
|
-
}
|
|
118
|
-
};
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
`;
|
|
122
|
-
const inMemoryDbWiring = `import { wireClass } from '@domain-first/wire';
|
|
123
|
-
import { InMemoryDbInfrastructureService } from '../../infrastructure/services/in-memory-db-infrastructure-service';
|
|
124
|
-
|
|
125
|
-
export const wireInMemoryDbInfrastructureService = wireClass(
|
|
126
|
-
InMemoryDbInfrastructureService,
|
|
127
|
-
[]
|
|
128
|
-
);
|
|
129
|
-
`;
|
|
130
|
-
const in_memory_db_withWiring = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
|
|
131
|
-
const in_memory_db_sharedFolder = ()=>new Folder(new ProjectRoot().path).subitem([
|
|
132
|
-
ConfigFile.Instance.data.project.rootFolder,
|
|
133
|
-
'shared-kernel'
|
|
134
|
-
]);
|
|
135
|
-
const serviceFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
|
|
136
|
-
'infrastructure',
|
|
137
|
-
'services',
|
|
138
|
-
'in-memory-db-infrastructure-service.ts'
|
|
139
|
-
]);
|
|
140
|
-
const in_memory_db_wireFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
|
|
141
|
-
'wiring',
|
|
142
|
-
'infrastructure-services',
|
|
143
|
-
'wire-in-memory-db-infrastructure-service.ts'
|
|
144
|
-
]);
|
|
145
|
-
const scaffoldInMemoryDb = (shared)=>{
|
|
146
|
-
const servicesFolder = shared.subitem([
|
|
147
|
-
'infrastructure',
|
|
148
|
-
'services'
|
|
149
|
-
]);
|
|
150
|
-
servicesFolder.createFile('in-memory-db-infrastructure-service.ts', inMemoryDbService);
|
|
151
|
-
if (in_memory_db_withWiring()) shared.subitem([
|
|
152
|
-
'wiring',
|
|
153
|
-
'infrastructure-services'
|
|
154
|
-
]).createFile('wire-in-memory-db-infrastructure-service.ts', inMemoryDbWiring);
|
|
155
|
-
};
|
|
156
|
-
const inMemoryDbScaffolded = ()=>serviceFile().exists && (!in_memory_db_withWiring() || in_memory_db_wireFile().exists);
|
|
157
|
-
const usesInMemoryDb = (implementationType)=>Boolean(ConfigFile.Instance.data.backend?.withInMemoryDb) && new UnknownFormatNaming(implementationType).fileName === inMemoryImplementationType && inMemoryDbScaffolded();
|
|
158
|
-
const uncountableEndings = [
|
|
159
|
-
'data',
|
|
160
|
-
'info',
|
|
161
|
-
'usage',
|
|
162
|
-
'feedback',
|
|
163
|
-
'media',
|
|
164
|
-
'ware',
|
|
165
|
-
'equipment',
|
|
166
|
-
'information',
|
|
167
|
-
'knowledge',
|
|
168
|
-
'traffic',
|
|
169
|
-
'telemetry',
|
|
170
|
-
'analytics',
|
|
171
|
-
'series'
|
|
172
|
-
];
|
|
173
|
-
const uncountable = new RegExp(`(${uncountableEndings.join('|')})$`, 'i');
|
|
174
|
-
const plural = (word)=>{
|
|
175
|
-
if (uncountable.test(word)) return word;
|
|
176
|
-
if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
|
|
177
|
-
if (/(^|[^aeiou]|qu)[aeiou]z$/i.test(word)) return `${word}zes`;
|
|
178
|
-
if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
|
|
179
|
-
return `${word}s`;
|
|
180
|
-
};
|
|
181
|
-
const addInMemoryDbSection = (typeNaming, typeImportTarget)=>{
|
|
182
|
-
const file = serviceFile();
|
|
183
|
-
const sectionNaming = new UnknownFormatNaming(plural(typeNaming.fileName));
|
|
184
|
-
const field = sectionNaming.variableName;
|
|
185
|
-
if (new RegExp(`\\b${field}\\s*=\\s*this\\.section\\b`).test(file.data)) return field;
|
|
186
|
-
const withImport = addImport(file.data, `import type { ${typeNaming.ClassName} } from '${relativeImport(file.path, typeImportTarget)}';`);
|
|
187
|
-
file.update(addClassMember(withImport, in_memory_db_className, `${field} = this.section<${typeNaming.ClassName}>('${sectionNaming.fileName.toUpperCase()}');`));
|
|
188
|
-
return field;
|
|
189
|
-
};
|
|
190
|
-
const inMemoryDbTypeImport = (fromFile)=>`import type { ${in_memory_db_className} } from '${relativeImport(fromFile, serviceFile().path)}'`;
|
|
191
|
-
const inMemoryDbSectionMembers = (field, derived)=>`
|
|
192
|
-
private readonly data: ${in_memory_db_className}['${field}']
|
|
193
|
-
|
|
194
|
-
constructor(${parameterName}: ${in_memory_db_className}) {
|
|
195
|
-
${derived ? 'super()\n ' : ''}this.data = ${parameterName}.${field}
|
|
196
|
-
}
|
|
197
|
-
`.trim();
|
|
198
|
-
const keepInMemoryDbSection = (classFile, field)=>{
|
|
199
|
-
classFile.update(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)).replace('constructor() {}', inMemoryDbSectionMembers(field, false)));
|
|
200
|
-
};
|
|
201
|
-
const isInMemoryDb = (module)=>module.wireName === in_memory_db_wireName;
|
|
202
|
-
const injectInMemoryDb = (classFile, implementationName)=>{
|
|
203
|
-
classFile.update(addConstructorParameters(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)), implementationName, [
|
|
204
|
-
`private readonly ${parameterName}: ${in_memory_db_className}`
|
|
205
|
-
]));
|
|
206
|
-
};
|
|
207
|
-
const wireInMemoryDb = (consumerWireFile, implementationName)=>{
|
|
208
|
-
consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${in_memory_db_wireName} } from '${relativeImport(consumerWireFile.path, in_memory_db_wireFile().path)}'`), implementationName, [
|
|
209
|
-
in_memory_db_wireName
|
|
210
|
-
]));
|
|
211
|
-
};
|
|
212
|
-
const addInMemoryDb = ()=>{
|
|
213
|
-
const config = ConfigFile.Instance.data;
|
|
214
|
-
if (!ConfigFile.backend.withInMemoryDb) ConfigFile.update({
|
|
11
|
+
const savedImplementations = (kind, purpose)=>[
|
|
12
|
+
...new Set(ConfigFile.Instance.data.backend?.implementations?.[kind]?.[purpose] ?? [])
|
|
13
|
+
];
|
|
14
|
+
const rememberImplementation = (kind, purpose, label)=>{
|
|
15
|
+
implementationLabelSchema.parse(label);
|
|
16
|
+
const backend = ConfigFile.backend;
|
|
17
|
+
const choices = {
|
|
18
|
+
...backend.implementations
|
|
19
|
+
};
|
|
20
|
+
const group = choices[kind] ?? {
|
|
21
|
+
primary: [],
|
|
22
|
+
test: []
|
|
23
|
+
};
|
|
24
|
+
if (group[purpose].includes(label)) return;
|
|
25
|
+
choices[kind] = {
|
|
26
|
+
...group,
|
|
27
|
+
[purpose]: [
|
|
28
|
+
...group[purpose],
|
|
29
|
+
label
|
|
30
|
+
]
|
|
31
|
+
};
|
|
32
|
+
ConfigFile.update({
|
|
215
33
|
backend: {
|
|
216
|
-
...
|
|
217
|
-
|
|
34
|
+
...backend,
|
|
35
|
+
implementations: choices
|
|
218
36
|
}
|
|
219
37
|
});
|
|
220
|
-
withoutOverwrites(()=>scaffoldInMemoryDb(new Folder(new ProjectRoot().path).subitem([
|
|
221
|
-
config.project.rootFolder,
|
|
222
|
-
'shared-kernel'
|
|
223
|
-
])));
|
|
224
|
-
return [];
|
|
225
38
|
};
|
|
226
|
-
const inMemoryDbApplied = ()=>Boolean(ConfigFile.Instance.data.backend?.withInMemoryDb) && inMemoryDbScaffolded();
|
|
227
39
|
const isSeparator = (choice)=>'function' == typeof Separator && choice instanceof Separator || 'object' == typeof choice && null !== choice && 'separator' === choice.type;
|
|
228
40
|
class RequestError extends Error {
|
|
229
41
|
code;
|
|
@@ -390,74 +202,6 @@ const interaction_checkbox = async (config)=>{
|
|
|
390
202
|
if (config.required && !selected.length) throw interaction_missing(field);
|
|
391
203
|
return selected;
|
|
392
204
|
};
|
|
393
|
-
const usesNext = ()=>ConfigFile.exists && ConfigFile.Instance.data.frontend?.react?.framework === 'next';
|
|
394
|
-
const nextAppFolder = (root)=>[
|
|
395
|
-
'app',
|
|
396
|
-
'src/app'
|
|
397
|
-
].find((folder)=>new Folder(node_path.join(root, folder)).exists) ?? 'app';
|
|
398
|
-
const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
|
|
399
|
-
class NestedName {
|
|
400
|
-
folders;
|
|
401
|
-
folderName;
|
|
402
|
-
fileName;
|
|
403
|
-
ClassName;
|
|
404
|
-
classNameSegments;
|
|
405
|
-
constructor(rawSource){
|
|
406
|
-
const segments = splitSegments(rawSource);
|
|
407
|
-
this.folders = segments.slice(0, -1);
|
|
408
|
-
this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
|
|
409
|
-
this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
|
|
410
|
-
this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
|
|
411
|
-
this.ClassName = this.classNameSegments.join('');
|
|
412
|
-
}
|
|
413
|
-
static validate = (rawSource)=>{
|
|
414
|
-
const segments = splitSegments(rawSource);
|
|
415
|
-
if (!segments.length) return 'Name is required';
|
|
416
|
-
if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
|
|
417
|
-
return true;
|
|
418
|
-
};
|
|
419
|
-
}
|
|
420
|
-
const reactPageContent = (ClassName, { imports = [], body = '<></>' } = {})=>`
|
|
421
|
-
${[
|
|
422
|
-
...imports,
|
|
423
|
-
"import { type FC } from 'react'"
|
|
424
|
-
].join('\n')}
|
|
425
|
-
|
|
426
|
-
export type ${ClassName}PageProps = {}
|
|
427
|
-
|
|
428
|
-
export const ${ClassName}Page: FC<${ClassName}PageProps> = (props) => {
|
|
429
|
-
return ${body}
|
|
430
|
-
}
|
|
431
|
-
`.trim();
|
|
432
|
-
const nextRouteContent = (ClassName, pageImport)=>`
|
|
433
|
-
import { ${ClassName}Page } from '${pageImport}'
|
|
434
|
-
|
|
435
|
-
export default function Page() {
|
|
436
|
-
return <${ClassName}Page />
|
|
437
|
-
}
|
|
438
|
-
`.trim();
|
|
439
|
-
const scaffoldNextRoute = (name, pageFile)=>{
|
|
440
|
-
const root = new ProjectRoot().path;
|
|
441
|
-
const route = node_path.join(root, nextAppFolder(root), ...name.folders, name.folderName, 'page.tsx');
|
|
442
|
-
const relativeRoute = node_path.relative(root, route).split(node_path.sep).join('/');
|
|
443
|
-
const routeFile = new File(route);
|
|
444
|
-
if (routeFile.exists) return void report(`${relativeRoute} already exists: render ${name.ClassName}Page there yourself.`);
|
|
445
|
-
routeFile.data = nextRouteContent(name.ClassName, relativeImport(route, pageFile.path.replace(/\.tsx$/, '')));
|
|
446
|
-
};
|
|
447
|
-
const scaffoldReactPage = async (presentationReactFolder)=>{
|
|
448
|
-
const name = await interaction_input({
|
|
449
|
-
key: 'name',
|
|
450
|
-
message: 'Provide name (folders split by "/"):',
|
|
451
|
-
validate: NestedName.validate
|
|
452
|
-
});
|
|
453
|
-
const nestedName = new NestedName(name);
|
|
454
|
-
const { folders, ClassName, fileName } = nestedName;
|
|
455
|
-
const pageFile = presentationReactFolder.subitem([
|
|
456
|
-
'pages',
|
|
457
|
-
...folders
|
|
458
|
-
]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
|
|
459
|
-
if (usesNext()) scaffoldNextRoute(nestedName, pageFile);
|
|
460
|
-
};
|
|
461
205
|
const addPackageScripts = async (file, additions)=>{
|
|
462
206
|
const original = file.data;
|
|
463
207
|
const manifest = JSON.parse(original);
|
|
@@ -495,67 +239,89 @@ const addPackageScripts = async (file, additions)=>{
|
|
|
495
239
|
return selected;
|
|
496
240
|
};
|
|
497
241
|
const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
|
|
498
|
-
const
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
'
|
|
502
|
-
'@microsoft/tsdoc'
|
|
242
|
+
const runtimePackages = [
|
|
243
|
+
'drizzle-orm',
|
|
244
|
+
'pg',
|
|
245
|
+
'dotenv'
|
|
503
246
|
];
|
|
504
|
-
const
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
};
|
|
516
|
-
const openapiScripts = {
|
|
517
|
-
openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
|
|
518
|
-
};
|
|
519
|
-
const splitPath = (value)=>value.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
|
|
520
|
-
const apiTitle = (packageName)=>{
|
|
521
|
-
const words = String(packageName ?? '').replace(/^@[^/]*\//, '').split(/[^a-zA-Z0-9]+/).filter((word)=>!!word).map((word)=>word[0].toUpperCase() + word.slice(1));
|
|
522
|
-
return [
|
|
523
|
-
...words,
|
|
524
|
-
'API'
|
|
525
|
-
].join(' ');
|
|
247
|
+
const developmentPackages = [
|
|
248
|
+
'drizzle-kit',
|
|
249
|
+
'@types/pg'
|
|
250
|
+
];
|
|
251
|
+
const drizzleFolder = (rootFolder)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'shared-kernel/infrastructure/drizzle');
|
|
252
|
+
const drizzleConfigPath = (rootFolder)=>node_path.posix.join(drizzleFolder(rootFolder), 'drizzle.config.ts');
|
|
253
|
+
const drizzleScripts = (rootFolder)=>{
|
|
254
|
+
const config = JSON.stringify(drizzleConfigPath(rootFolder));
|
|
255
|
+
return {
|
|
256
|
+
'drizzle:generate': `drizzle-kit generate --config ${config}`,
|
|
257
|
+
'drizzle:migrate': `drizzle-kit migrate --config ${config}`
|
|
258
|
+
};
|
|
526
259
|
};
|
|
527
|
-
const
|
|
528
|
-
const
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
const apiRoutePrefix = prefixSegments.length ? `\n apiRoutePrefix: [${prefixSegments.map((segment)=>`'${segment}'`).join(', ')}],` : '';
|
|
532
|
-
const extractorImport = `./${node_path.posix.relative(node_path.posix.dirname(openapiScriptPath), openapiExtractorPath.replace(/\.ts$/, ''))}`;
|
|
533
|
-
const handlers = withExtractor ? `
|
|
534
|
-
const extractOpenApiDataFromEndpointLogic =
|
|
535
|
-
createOpenApiDataFromEndpointLogicExtractor();
|
|
260
|
+
const drizzleConfig = (rootFolder)=>{
|
|
261
|
+
const folder = drizzleFolder(rootFolder);
|
|
262
|
+
return `import 'dotenv/config';
|
|
263
|
+
import { defineConfig } from 'drizzle-kit';
|
|
536
264
|
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
}
|
|
265
|
+
// Paths are relative to the project root, where package scripts run.
|
|
266
|
+
export default defineConfig({
|
|
267
|
+
dialect: 'postgresql',
|
|
268
|
+
schema: ${JSON.stringify(node_path.posix.join(folder, 'schema.ts'))},
|
|
269
|
+
out: ${JSON.stringify(node_path.posix.join(folder, 'migrations'))},
|
|
270
|
+
dbCredentials: {
|
|
271
|
+
url: process.env.DATABASE_URL as string
|
|
545
272
|
}
|
|
546
|
-
}));
|
|
547
|
-
` : '';
|
|
548
|
-
return `import { generateOpenAPI } from '@domain-first/handlers-rest';
|
|
549
|
-
import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}';${withExtractor ? `\nimport { createOpenApiDataFromEndpointLogicExtractor } from '${extractorImport}';` : ''}
|
|
550
|
-
${handlers}
|
|
551
|
-
generateOpenAPI(${withExtractor ? 'handlers' : 'restHandlers'}, {
|
|
552
|
-
document: { info: { title: '${title}', version: '1.0.0' } },${apiRoutePrefix}
|
|
553
|
-
outputFile: { path: '${outputPath}' }
|
|
554
273
|
});
|
|
555
274
|
`;
|
|
556
275
|
};
|
|
557
|
-
const
|
|
558
|
-
|
|
276
|
+
const drizzleSchema = `// Add your application tables here before running drizzle:generate, e.g.
|
|
277
|
+
//
|
|
278
|
+
// import { pgTable, text } from 'drizzle-orm/pg-core';
|
|
279
|
+
//
|
|
280
|
+
// export const orders = pgTable('orders', {
|
|
281
|
+
// id: text('id').primaryKey()
|
|
282
|
+
// });
|
|
283
|
+
|
|
284
|
+
export {};
|
|
285
|
+
`;
|
|
286
|
+
const drizzleService = `import { drizzle } from 'drizzle-orm/node-postgres';
|
|
287
|
+
import { Pool } from 'pg';
|
|
288
|
+
|
|
289
|
+
const createDatabase = () =>
|
|
290
|
+
drizzle({
|
|
291
|
+
client: new Pool({ connectionString: process.env.DATABASE_URL })
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
type DrizzleDatabase = ReturnType<typeof createDatabase>;
|
|
295
|
+
|
|
296
|
+
const globalForDrizzle = globalThis as typeof globalThis & {
|
|
297
|
+
drizzleDatabase?: DrizzleDatabase;
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
// Reuse the connection pool across development hot reloads.
|
|
301
|
+
const drizzleDatabase = globalForDrizzle.drizzleDatabase ?? createDatabase();
|
|
302
|
+
|
|
303
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
304
|
+
globalForDrizzle.drizzleDatabase = drizzleDatabase;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export class DrizzleInfrastructureService {
|
|
308
|
+
readonly db = drizzleDatabase;
|
|
309
|
+
}
|
|
310
|
+
`;
|
|
311
|
+
const drizzleWiring = `import { wireClass } from '@domain-first/wire';
|
|
312
|
+
import { DrizzleInfrastructureService } from '../../infrastructure/services/drizzle-infrastructure-service';
|
|
313
|
+
|
|
314
|
+
export const wireDrizzleInfrastructureService = wireClass(
|
|
315
|
+
DrizzleInfrastructureService,
|
|
316
|
+
[]
|
|
317
|
+
);
|
|
318
|
+
`;
|
|
319
|
+
const stageFile = (filePath, content)=>{
|
|
320
|
+
const file = new File(filePath);
|
|
321
|
+
if (!file.exists || file.data !== content) file.data = content;
|
|
322
|
+
};
|
|
323
|
+
const addDrizzle = async ()=>{
|
|
324
|
+
const config = ConfigFile.Instance.data;
|
|
559
325
|
const root = new ProjectRoot().path;
|
|
560
326
|
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
561
327
|
const manifest = JSON.parse(manifestFile.data);
|
|
@@ -563,1119 +329,738 @@ const addOpenapi = async ()=>{
|
|
|
563
329
|
...manifest.dependencies,
|
|
564
330
|
...manifest.devDependencies
|
|
565
331
|
};
|
|
566
|
-
const
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
});
|
|
577
|
-
const withExtractor = await interaction_confirm({
|
|
578
|
-
key: 'withExtractor',
|
|
579
|
-
message: "Fill operationId, summary and description from the endpoint logic TSDoc?",
|
|
580
|
-
default: true
|
|
581
|
-
});
|
|
582
|
-
const withSwaggerPage = Boolean(ConfigFile.Instance.data.frontend?.react) && await interaction_confirm({
|
|
583
|
-
key: 'swaggerPage',
|
|
584
|
-
message: 'Add a Swagger UI page?',
|
|
332
|
+
const shared = node_path.resolve(root, config.project.rootFolder, 'shared-kernel');
|
|
333
|
+
const folder = node_path.join(shared, 'infrastructure/drizzle');
|
|
334
|
+
if ([
|
|
335
|
+
'drizzle.config.ts',
|
|
336
|
+
'drizzle.config.js',
|
|
337
|
+
'drizzle.config.json'
|
|
338
|
+
].some((name)=>new File(node_path.join(root, name)).exists)) throw new Error('This preset adds Drizzle for PostgreSQL in the Shared Kernel. Move the existing Drizzle setup separately before using it.');
|
|
339
|
+
const withService = await interaction_confirm({
|
|
340
|
+
key: 'withService',
|
|
341
|
+
message: 'Create the Drizzle infrastructure service in the Shared Kernel?',
|
|
585
342
|
default: true
|
|
586
343
|
});
|
|
587
|
-
const selected = await addPackageScripts(manifestFile,
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
|
|
595
|
-
if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
|
|
596
|
-
if (withSwaggerPage) {
|
|
597
|
-
const pageFile = new File(node_path.join(root, swaggerPagePath(rootFolder)));
|
|
598
|
-
const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'));
|
|
599
|
-
if (!pageFile.exists || pageFile.data !== page) pageFile.data = page;
|
|
344
|
+
const selected = await addPackageScripts(manifestFile, drizzleScripts(config.project.rootFolder));
|
|
345
|
+
stageFile(node_path.join(folder, 'drizzle.config.ts'), drizzleConfig(config.project.rootFolder));
|
|
346
|
+
const schema = new File(node_path.join(folder, 'schema.ts'));
|
|
347
|
+
if (!schema.exists) schema.data = drizzleSchema;
|
|
348
|
+
if (withService) {
|
|
349
|
+
stageFile(node_path.join(shared, 'infrastructure/services/drizzle-infrastructure-service.ts'), drizzleService);
|
|
350
|
+
if (ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) stageFile(node_path.join(shared, 'wiring/infrastructure-services/wire-drizzle-infrastructure-service.ts'), drizzleWiring);
|
|
600
351
|
}
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
352
|
+
for (const kind of [
|
|
353
|
+
'repositories',
|
|
354
|
+
'commands',
|
|
355
|
+
'queries'
|
|
356
|
+
])rememberImplementation(kind, 'primary', 'drizzle');
|
|
357
|
+
const install = (packages, dev)=>{
|
|
358
|
+
const missing = packages.filter((name)=>!dependencies[name]);
|
|
359
|
+
return missing.length ? [
|
|
360
|
+
`npm install${dev ? ' --save-dev' : ''} ${missing.join(' ')}`
|
|
361
|
+
] : [];
|
|
362
|
+
};
|
|
363
|
+
const relativeFolder = node_path.relative(root, folder).split(node_path.sep).join('/');
|
|
604
364
|
return [
|
|
605
|
-
...
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
...dependencies.tsx ? [] : [
|
|
609
|
-
'npm install --save-dev tsx'
|
|
610
|
-
],
|
|
611
|
-
...missingExtractorPackages.length ? [
|
|
612
|
-
`npm install --save-dev ${missingExtractorPackages.join(' ')}`
|
|
613
|
-
] : [],
|
|
614
|
-
...withSwaggerPage && !dependencies['swagger-ui-react'] ? [
|
|
615
|
-
'npm install swagger-ui-react'
|
|
616
|
-
] : [],
|
|
617
|
-
...withSwaggerPage && !dependencies['@types/swagger-ui-react'] ? [
|
|
618
|
-
'npm install --save-dev @types/swagger-ui-react'
|
|
619
|
-
] : [],
|
|
620
|
-
...true === resolveJsonModule || null === resolveJsonModule ? [] : [
|
|
621
|
-
'set "resolveJsonModule": true in compilerOptions of tsconfig.json — the Swagger UI page imports the OpenAPI document as JSON'
|
|
622
|
-
],
|
|
365
|
+
...install(runtimePackages, false),
|
|
366
|
+
...install(developmentPackages, true),
|
|
367
|
+
`Add !${relativeFolder}/migrations in your linter, to ignore generated migrations.`,
|
|
623
368
|
...describeScripts(selected, {
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
`SwaggerPage from ${swaggerPagePath(rootFolder)} shows ${splitPath(outputPath).join('/')} once it is generated — render it on a route of your app`
|
|
628
|
-
] : [],
|
|
629
|
-
...hasRestHandlers ? [] : [
|
|
630
|
-
`restHandlers appear in ${node_path.posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
|
|
631
|
-
]
|
|
369
|
+
'drizzle:generate': 'generate a SQL migration from changes in schema.ts',
|
|
370
|
+
'drizzle:migrate': 'apply generated migrations to the database in DATABASE_URL'
|
|
371
|
+
})
|
|
632
372
|
];
|
|
633
373
|
};
|
|
634
|
-
const
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
374
|
+
const inMemoryImplementationType = 'in-memory';
|
|
375
|
+
const in_memory_db_className = 'InMemoryDbInfrastructureService';
|
|
376
|
+
const in_memory_db_wireName = 'wireInMemoryDbInfrastructureService';
|
|
377
|
+
const parameterName = 'inMemoryDbInfrastructureService';
|
|
378
|
+
const inMemoryDbService = `type Entry = {
|
|
379
|
+
id: unknown;
|
|
380
|
+
item: any;
|
|
640
381
|
};
|
|
641
|
-
const dataLayerFolder = (rootFolder, target)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'hooks' === target ? 'presentation/react/data-layer' : 'presentation/data-layer');
|
|
642
|
-
const orvalScripts = (rootFolder, targets)=>({
|
|
643
|
-
'client:orval': targets.map((target)=>`orval --config ${JSON.stringify(`${dataLayerFolder(rootFolder, target)}/orval.config.ts`)}`).join(' && ')
|
|
644
|
-
});
|
|
645
|
-
const orvalConfig = (rootFolder, openapiPath, withNext, target = 'hooks', mutatorPath = './api-client/mutator.ts')=>{
|
|
646
|
-
const inputPath = node_path.posix.relative(dataLayerFolder(rootFolder, target), openapiPath);
|
|
647
|
-
const baseUrl = withNext ? `
|
|
648
|
-
baseUrl: {
|
|
649
|
-
runtime: 'process.env.NEXT_PUBLIC_API_BASE_URL ?? ""'
|
|
650
|
-
},` : '';
|
|
651
|
-
const client = 'hooks' === target ? `
|
|
652
|
-
client: 'react-query',
|
|
653
|
-
httpClient: 'fetch',` : `
|
|
654
|
-
client: 'fetch',`;
|
|
655
|
-
const query = 'hooks' === target ? `,
|
|
656
|
-
query: {
|
|
657
|
-
version: 5
|
|
658
|
-
}` : '';
|
|
659
|
-
return `import { defineConfig } from 'orval';
|
|
660
382
|
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
input: '${inputPath.startsWith('.') ? inputPath : `./${inputPath}`}',
|
|
664
|
-
output: {
|
|
665
|
-
mode: 'tags-split',
|
|
666
|
-
target: './orval',
|
|
667
|
-
schemas: './orval/model',${client}${baseUrl}
|
|
668
|
-
clean: true,
|
|
669
|
-
override: {
|
|
670
|
-
mutator: {
|
|
671
|
-
path: '${mutatorPath}',
|
|
672
|
-
name: 'customInstance'
|
|
673
|
-
},
|
|
674
|
-
fetch: {
|
|
675
|
-
includeHttpResponseReturnType: false
|
|
676
|
-
}${query}
|
|
677
|
-
}
|
|
678
|
-
}
|
|
679
|
-
}
|
|
680
|
-
});
|
|
681
|
-
`;
|
|
682
|
-
};
|
|
683
|
-
const orvalMutator = `/** Error of the generated requests, with the parsed response body. */
|
|
684
|
-
export class ApiError<Body = unknown> extends Error {
|
|
685
|
-
constructor(
|
|
686
|
-
public readonly status: number,
|
|
687
|
-
public readonly body: Body
|
|
688
|
-
) {
|
|
689
|
-
super(\`API error \${status}\`);
|
|
690
|
-
this.name = 'ApiError';
|
|
691
|
-
}
|
|
383
|
+
declare global {
|
|
384
|
+
var ___SHARED_IN_MEMORY_DB___: Record<string, Array<Entry>> | undefined;
|
|
692
385
|
}
|
|
693
386
|
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
const response = await fetch(url, init);
|
|
703
|
-
const text = await response.text();
|
|
704
|
-
const body = text ? JSON.parse(text) : undefined;
|
|
705
|
-
|
|
706
|
-
if (!response.ok) {
|
|
707
|
-
throw new ApiError(response.status, body);
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
return body as T;
|
|
387
|
+
type Section<T, TId> = {
|
|
388
|
+
all: (predicate?: (x: T) => boolean) => T[];
|
|
389
|
+
first: (predicate: (x: T) => boolean) => T | null;
|
|
390
|
+
withId: (id: TId) => T | null;
|
|
391
|
+
lastAddedItem: () => T | null;
|
|
392
|
+
save: (payload: T extends { id: TId } ? T : [TId, T]) => void;
|
|
393
|
+
deleteById: (id: TId) => void;
|
|
394
|
+
delete: (predicate: (x: T) => boolean) => void;
|
|
711
395
|
};
|
|
712
|
-
`;
|
|
713
|
-
const queryProvider = `'use client';
|
|
714
396
|
|
|
715
|
-
|
|
716
|
-
import { type FC, type ReactNode, useState } from 'react';
|
|
397
|
+
type IdsAreEqual<TId> = (a: TId, b: TId) => boolean;
|
|
717
398
|
|
|
718
|
-
|
|
719
|
-
// One client per browser session; a module-level client would be shared between requests on the server
|
|
720
|
-
const [queryClient] = useState(() => new QueryClient());
|
|
399
|
+
const comparisonMethodNames = ['equals', 'same', 'isSame', 'isEqual'] as const;
|
|
721
400
|
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
if (!generator.exists) return;
|
|
732
|
-
return generator.data.match(/outputFile:\s*{\s*path:\s*'([^']+)'/)?.[1];
|
|
733
|
-
};
|
|
734
|
-
const addOrval = async ()=>{
|
|
735
|
-
const { project: { rootFolder }, frontend } = ConfigFile.Instance.data;
|
|
736
|
-
const useReact = Boolean(frontend?.react);
|
|
737
|
-
const root = new ProjectRoot().path;
|
|
738
|
-
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
739
|
-
const manifest = JSON.parse(manifestFile.data);
|
|
740
|
-
const dependencies = {
|
|
741
|
-
...manifest.dependencies,
|
|
742
|
-
...manifest.devDependencies
|
|
743
|
-
};
|
|
744
|
-
const withNext = usesNext();
|
|
745
|
-
const generatedOpenapiPath = openapiOutputPath(root);
|
|
746
|
-
const openapiPath = await interaction_input({
|
|
747
|
-
key: 'openapiPath',
|
|
748
|
-
message: 'OpenAPI document path:',
|
|
749
|
-
default: generatedOpenapiPath ?? defaultOpenapiPath(withNext),
|
|
750
|
-
validate: (value)=>value.trim() ? true : 'Path is required'
|
|
751
|
-
});
|
|
752
|
-
const targets = useReact ? await interaction_checkbox({
|
|
753
|
-
key: 'targets',
|
|
754
|
-
message: 'Generate:',
|
|
755
|
-
choices: [
|
|
756
|
-
{
|
|
757
|
-
name: 'React Query hooks',
|
|
758
|
-
value: 'hooks',
|
|
759
|
-
checked: true
|
|
760
|
-
},
|
|
761
|
-
{
|
|
762
|
-
name: 'Typed API client',
|
|
763
|
-
value: 'client'
|
|
764
|
-
}
|
|
765
|
-
],
|
|
766
|
-
required: true
|
|
767
|
-
}) : [
|
|
768
|
-
'client'
|
|
769
|
-
];
|
|
770
|
-
const selected = await addPackageScripts(manifestFile, orvalScripts(rootFolder, targets));
|
|
771
|
-
const document = node_path.posix.normalize(openapiPath.trim().replaceAll('\\', '/'));
|
|
772
|
-
const withClient = targets.includes('client');
|
|
773
|
-
for (const target of targets){
|
|
774
|
-
const dataLayer = dataLayerFolder(rootFolder, target);
|
|
775
|
-
const sharedMutator = 'hooks' === target && withClient;
|
|
776
|
-
const mutatorPath = sharedMutator ? `${node_path.posix.relative(dataLayer, dataLayerFolder(rootFolder, 'client'))}/api-client/mutator.ts` : void 0;
|
|
777
|
-
const configFile = new File(node_path.join(root, dataLayer, 'orval.config.ts'));
|
|
778
|
-
const content = orvalConfig(rootFolder, document, withNext, target, mutatorPath);
|
|
779
|
-
if (!configFile.exists || configFile.data !== content) configFile.data = content;
|
|
780
|
-
for (const [name, fileContent] of [
|
|
781
|
-
...sharedMutator ? [] : [
|
|
782
|
-
[
|
|
783
|
-
'api-client/mutator.ts',
|
|
784
|
-
orvalMutator
|
|
785
|
-
]
|
|
786
|
-
],
|
|
787
|
-
...'hooks' === target ? [
|
|
788
|
-
[
|
|
789
|
-
'query-provider.tsx',
|
|
790
|
-
queryProvider
|
|
791
|
-
]
|
|
792
|
-
] : []
|
|
793
|
-
]){
|
|
794
|
-
const file = new File(node_path.join(root, dataLayer, name));
|
|
795
|
-
if (!file.exists) file.data = fileContent;
|
|
401
|
+
const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
|
|
402
|
+
if (typeof a !== 'object' || a === null) {
|
|
403
|
+
return Object.is(a, b);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
for (const methodName of comparisonMethodNames) {
|
|
407
|
+
const method: unknown = (a as Record<string, unknown>)[methodName];
|
|
408
|
+
if (typeof method === 'function') {
|
|
409
|
+
return Boolean(method.call(a, b));
|
|
796
410
|
}
|
|
797
|
-
addGitignoreEntry(root, `/${dataLayer}/orval/`);
|
|
798
411
|
}
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
const runtime = missing(targets.includes('hooks') ? [
|
|
802
|
-
'@tanstack/react-query'
|
|
803
|
-
] : []);
|
|
804
|
-
const development = missing([
|
|
805
|
-
'orval'
|
|
806
|
-
]);
|
|
807
|
-
return [
|
|
808
|
-
...runtime.length ? [
|
|
809
|
-
`npm install ${runtime.join(' ')}`
|
|
810
|
-
] : [],
|
|
811
|
-
...development.length ? [
|
|
812
|
-
`npm install --save-dev ${development.join(' ')}`
|
|
813
|
-
] : [],
|
|
814
|
-
...describeScripts(selected, {
|
|
815
|
-
'client:orval': `generate ${generated.join(' and ')} from ${openapiPath.trim()}`
|
|
816
|
-
}),
|
|
817
|
-
...targets.includes('hooks') ? [
|
|
818
|
-
`Wrap your app in QueryProvider from ${dataLayerFolder(rootFolder, 'hooks')}/query-provider.tsx`
|
|
819
|
-
] : [],
|
|
820
|
-
...generatedOpenapiPath ? [] : [
|
|
821
|
-
'npx df-integration → OpenAPI generates the OpenAPI document the client is built from'
|
|
822
|
-
]
|
|
823
|
-
];
|
|
824
|
-
};
|
|
825
|
-
const playwrightScripts = {
|
|
826
|
-
'test:e2e': 'playwright test'
|
|
412
|
+
|
|
413
|
+
return Object.is(a, b);
|
|
827
414
|
};
|
|
828
|
-
const playwrightConfig = `import { defineConfig, devices } from '@playwright/test';
|
|
829
415
|
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
fullyParallel: true,
|
|
833
|
-
forbidOnly: !!process.env.CI,
|
|
834
|
-
retries: process.env.CI ? 2 : 0,
|
|
835
|
-
workers: process.env.CI ? 1 : undefined,
|
|
836
|
-
reporter: 'html',
|
|
837
|
-
use: {
|
|
838
|
-
baseURL: 'http://localhost:3000',
|
|
839
|
-
trace: 'on-first-retry',
|
|
840
|
-
screenshot: 'only-on-failure',
|
|
841
|
-
video: 'retain-on-failure'
|
|
842
|
-
},
|
|
416
|
+
const hasId = (x: unknown): x is { id: unknown } =>
|
|
417
|
+
typeof x === 'object' && x !== null && 'id' in x;
|
|
843
418
|
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
{
|
|
858
|
-
|
|
859
|
-
use: { ...devices['Pixel 5'] }
|
|
860
|
-
},
|
|
861
|
-
{
|
|
862
|
-
name: 'Mobile Safari',
|
|
863
|
-
use: { ...devices['iPhone 12'] }
|
|
419
|
+
export class InMemoryDbInfrastructureService {
|
|
420
|
+
protected section<T extends { id: unknown }>(
|
|
421
|
+
key: string,
|
|
422
|
+
idsAreEqual?: IdsAreEqual<T['id']>
|
|
423
|
+
): Section<T, T['id']>;
|
|
424
|
+
protected section<T, TId>(
|
|
425
|
+
key: string,
|
|
426
|
+
idsAreEqual?: IdsAreEqual<TId>
|
|
427
|
+
): Section<T, TId>;
|
|
428
|
+
protected section<T, TId>(
|
|
429
|
+
key: string,
|
|
430
|
+
idsAreEqual: IdsAreEqual<TId> = defaultIdsAreEqual
|
|
431
|
+
): Section<T, TId> {
|
|
432
|
+
if (!globalThis.___SHARED_IN_MEMORY_DB___) {
|
|
433
|
+
globalThis.___SHARED_IN_MEMORY_DB___ = {};
|
|
864
434
|
}
|
|
865
|
-
],
|
|
866
|
-
|
|
867
|
-
webServer: {
|
|
868
|
-
// Playwright only stops the dev server on a clean shutdown. If its process dies any other
|
|
869
|
-
// way (SIGHUP, SIGKILL), the dev server lives on in its own process group, so it is killed
|
|
870
|
-
// as soon as Playwright is gone.
|
|
871
|
-
command:
|
|
872
|
-
process.platform === 'win32'
|
|
873
|
-
? 'npm run dev'
|
|
874
|
-
: \`npm run dev & while kill -0 \${process.pid} 2>/dev/null && kill -0 $! 2>/dev/null; do sleep 1; done; kill 0\`,
|
|
875
|
-
url: 'http://localhost:3000',
|
|
876
|
-
timeout: 120000,
|
|
877
|
-
reuseExistingServer: !process.env.CI
|
|
878
|
-
}
|
|
879
|
-
});
|
|
880
|
-
`;
|
|
881
|
-
const exampleSpec = `import { expect, test } from '@playwright/test';
|
|
882
435
|
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
await expect(page).toHaveURL(\`\${baseURL}/\`);
|
|
887
|
-
});
|
|
888
|
-
});
|
|
889
|
-
`;
|
|
890
|
-
const exampleReadme = `# Home page e2e cases
|
|
436
|
+
if (!globalThis.___SHARED_IN_MEMORY_DB___[key]) {
|
|
437
|
+
globalThis.___SHARED_IN_MEMORY_DB___[key] = [];
|
|
438
|
+
}
|
|
891
439
|
|
|
892
|
-
|
|
440
|
+
const items = (): T[] =>
|
|
441
|
+
globalThis.___SHARED_IN_MEMORY_DB___![key].map(
|
|
442
|
+
(entry) => entry.item
|
|
443
|
+
);
|
|
893
444
|
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
445
|
+
return {
|
|
446
|
+
all: (predicate: (x: T) => boolean = () => true): T[] =>
|
|
447
|
+
items().filter(predicate),
|
|
448
|
+
first: (predicate: (x: T) => boolean): T | null =>
|
|
449
|
+
items().find(predicate) ?? null,
|
|
450
|
+
withId: (id: TId): T | null =>
|
|
451
|
+
items().find(
|
|
452
|
+
(x: T) => hasId(x) && idsAreEqual(x.id as TId, id)
|
|
453
|
+
) ?? null,
|
|
454
|
+
lastAddedItem: (): T | null =>
|
|
455
|
+
globalThis.___SHARED_IN_MEMORY_DB___![key].at(-1)?.item ?? null,
|
|
456
|
+
save: (payload: T extends { id: TId } ? T : [TId, T]) => {
|
|
457
|
+
const id = Array.isArray(payload) ? payload[0] : payload.id;
|
|
458
|
+
const item = Array.isArray(payload) ? payload[1] : payload;
|
|
459
|
+
const entries = globalThis.___SHARED_IN_MEMORY_DB___![key];
|
|
460
|
+
const existing = entries.find((entry) =>
|
|
461
|
+
idsAreEqual(entry.id as TId, id)
|
|
462
|
+
);
|
|
463
|
+
if (existing) {
|
|
464
|
+
existing.item = item;
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
467
|
+
entries.push({ id, item });
|
|
468
|
+
},
|
|
469
|
+
deleteById: (id: TId) => {
|
|
470
|
+
globalThis.___SHARED_IN_MEMORY_DB___![key] =
|
|
471
|
+
globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
|
|
472
|
+
(entry) => !idsAreEqual(entry.id as TId, id)
|
|
473
|
+
);
|
|
474
|
+
},
|
|
475
|
+
delete: (predicate: (x: T) => boolean) => {
|
|
476
|
+
globalThis.___SHARED_IN_MEMORY_DB___![key] =
|
|
477
|
+
globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
|
|
478
|
+
(entry) => !predicate(entry.item)
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
};
|
|
927
482
|
}
|
|
928
|
-
for (const entry of gitignoreEntries)addGitignoreEntry(root, entry);
|
|
929
|
-
return [
|
|
930
|
-
...dependencies['@playwright/test'] ? [] : [
|
|
931
|
-
'npm install --save-dev @playwright/test'
|
|
932
|
-
],
|
|
933
|
-
'npx playwright install --with-deps',
|
|
934
|
-
...describeScripts(selected, {
|
|
935
|
-
'test:e2e': 'start the dev server and run end-to-end specs from specs/e2e'
|
|
936
|
-
})
|
|
937
|
-
];
|
|
938
|
-
};
|
|
939
|
-
const savedImplementations = (kind, purpose)=>[
|
|
940
|
-
...new Set(ConfigFile.Instance.data.backend?.implementations?.[kind]?.[purpose] ?? [])
|
|
941
|
-
];
|
|
942
|
-
const rememberImplementation = (kind, purpose, label)=>{
|
|
943
|
-
implementationLabelSchema.parse(label);
|
|
944
|
-
const backend = ConfigFile.backend;
|
|
945
|
-
const choices = {
|
|
946
|
-
...backend.implementations
|
|
947
|
-
};
|
|
948
|
-
const group = choices[kind] ?? {
|
|
949
|
-
primary: [],
|
|
950
|
-
test: []
|
|
951
|
-
};
|
|
952
|
-
if (group[purpose].includes(label)) return;
|
|
953
|
-
choices[kind] = {
|
|
954
|
-
...group,
|
|
955
|
-
[purpose]: [
|
|
956
|
-
...group[purpose],
|
|
957
|
-
label
|
|
958
|
-
]
|
|
959
|
-
};
|
|
960
|
-
ConfigFile.update({
|
|
961
|
-
backend: {
|
|
962
|
-
...backend,
|
|
963
|
-
implementations: choices
|
|
964
|
-
}
|
|
965
|
-
});
|
|
966
|
-
};
|
|
967
|
-
const runtimePackages = [
|
|
968
|
-
'@prisma/orm-postgres',
|
|
969
|
-
'temporal-polyfill',
|
|
970
|
-
'dotenv'
|
|
971
|
-
];
|
|
972
|
-
const developmentPackages = [
|
|
973
|
-
'prisma',
|
|
974
|
-
'@prisma/cli-engine'
|
|
975
|
-
];
|
|
976
|
-
const prismaScripts = (rootFolder)=>{
|
|
977
|
-
const config = JSON.stringify(node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'shared-kernel/infrastructure/prisma/prisma.config.ts'));
|
|
978
|
-
const emit = `prisma contract emit --config ${config}`;
|
|
979
|
-
return {
|
|
980
|
-
'prisma:emit': emit,
|
|
981
|
-
'prisma:migration:plan': `${emit} && prisma migration plan --config ${config}`,
|
|
982
|
-
'prisma:migration:apply': `prisma db migrate --advance-ref db --config ${config}`
|
|
983
|
-
};
|
|
984
|
-
};
|
|
985
|
-
const prismaConfig = `import 'dotenv/config';
|
|
986
|
-
import { definePrismaConfig } from '@prisma/cli-engine';
|
|
987
|
-
import { defineConfig as ormConfig } from '@prisma/orm-postgres/config';
|
|
988
|
-
|
|
989
|
-
export default definePrismaConfig({
|
|
990
|
-
orm: ormConfig({
|
|
991
|
-
contract: './contract.prisma',
|
|
992
|
-
migrations: { dir: './migrations' },
|
|
993
|
-
db: {
|
|
994
|
-
connection: process.env.DATABASE_URL
|
|
995
|
-
}
|
|
996
|
-
})
|
|
997
|
-
});
|
|
998
|
-
`;
|
|
999
|
-
const prismaService = `import 'temporal-polyfill/global';
|
|
1000
|
-
import postgres from '@prisma/orm-postgres/runtime';
|
|
1001
|
-
import type {} from 'temporal-polyfill/types/global';
|
|
1002
|
-
import type { Contract } from '../prisma/contract.d';
|
|
1003
|
-
import contractJson from '../prisma/contract.json' with { type: 'json' };
|
|
1004
|
-
|
|
1005
|
-
type PrismaClient = ReturnType<typeof postgres<Contract>>;
|
|
1006
|
-
|
|
1007
|
-
const globalForPrisma = globalThis as typeof globalThis & {
|
|
1008
|
-
prismaClient?: PrismaClient;
|
|
1009
|
-
};
|
|
1010
|
-
|
|
1011
|
-
// Reuse the client across development hot reloads.
|
|
1012
|
-
const prismaClient = globalForPrisma.prismaClient ??
|
|
1013
|
-
postgres<Contract>({ contractJson, url: process.env.DATABASE_URL });
|
|
1014
|
-
|
|
1015
|
-
if (process.env.NODE_ENV !== 'production') {
|
|
1016
|
-
globalForPrisma.prismaClient = prismaClient;
|
|
1017
|
-
}
|
|
1018
|
-
|
|
1019
|
-
export class PrismaInfrastructureService {
|
|
1020
|
-
readonly orm = prismaClient.orm.public;
|
|
1021
483
|
}
|
|
1022
484
|
`;
|
|
1023
|
-
const
|
|
1024
|
-
import {
|
|
485
|
+
const inMemoryDbWiring = `import { wireClass } from '@domain-first/wire';
|
|
486
|
+
import { InMemoryDbInfrastructureService } from '../../infrastructure/services/in-memory-db-infrastructure-service';
|
|
1025
487
|
|
|
1026
|
-
export const
|
|
1027
|
-
|
|
488
|
+
export const wireInMemoryDbInfrastructureService = wireClass(
|
|
489
|
+
InMemoryDbInfrastructureService,
|
|
1028
490
|
[]
|
|
1029
491
|
);
|
|
1030
492
|
`;
|
|
1031
|
-
const
|
|
1032
|
-
|
|
1033
|
-
|
|
493
|
+
const in_memory_db_withWiring = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
|
|
494
|
+
const in_memory_db_sharedFolder = ()=>new Folder(new ProjectRoot().path).subitem([
|
|
495
|
+
ConfigFile.Instance.data.project.rootFolder,
|
|
496
|
+
'shared-kernel'
|
|
497
|
+
]);
|
|
498
|
+
const serviceFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
|
|
499
|
+
'infrastructure',
|
|
500
|
+
'services',
|
|
501
|
+
'in-memory-db-infrastructure-service.ts'
|
|
502
|
+
]);
|
|
503
|
+
const in_memory_db_wireFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
|
|
504
|
+
'wiring',
|
|
505
|
+
'infrastructure-services',
|
|
506
|
+
'wire-in-memory-db-infrastructure-service.ts'
|
|
507
|
+
]);
|
|
508
|
+
const scaffoldInMemoryDb = (shared)=>{
|
|
509
|
+
const servicesFolder = shared.subitem([
|
|
510
|
+
'infrastructure',
|
|
511
|
+
'services'
|
|
512
|
+
]);
|
|
513
|
+
servicesFolder.createFile('in-memory-db-infrastructure-service.ts', inMemoryDbService);
|
|
514
|
+
if (in_memory_db_withWiring()) shared.subitem([
|
|
515
|
+
'wiring',
|
|
516
|
+
'infrastructure-services'
|
|
517
|
+
]).createFile('wire-in-memory-db-infrastructure-service.ts', inMemoryDbWiring);
|
|
1034
518
|
};
|
|
1035
|
-
const
|
|
519
|
+
const inMemoryDbScaffolded = ()=>serviceFile().exists && (!in_memory_db_withWiring() || in_memory_db_wireFile().exists);
|
|
520
|
+
const usesInMemoryDb = (implementationType)=>Boolean(ConfigFile.Instance.data.backend?.withInMemoryDb) && new UnknownFormatNaming(implementationType).fileName === inMemoryImplementationType && inMemoryDbScaffolded();
|
|
521
|
+
const uncountableEndings = [
|
|
522
|
+
'data',
|
|
523
|
+
'info',
|
|
524
|
+
'usage',
|
|
525
|
+
'feedback',
|
|
526
|
+
'media',
|
|
527
|
+
'ware',
|
|
528
|
+
'equipment',
|
|
529
|
+
'information',
|
|
530
|
+
'knowledge',
|
|
531
|
+
'traffic',
|
|
532
|
+
'telemetry',
|
|
533
|
+
'analytics',
|
|
534
|
+
'series'
|
|
535
|
+
];
|
|
536
|
+
const uncountable = new RegExp(`(${uncountableEndings.join('|')})$`, 'i');
|
|
537
|
+
const plural = (word)=>{
|
|
538
|
+
if (uncountable.test(word)) return word;
|
|
539
|
+
if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
|
|
540
|
+
if (/(^|[^aeiou]|qu)[aeiou]z$/i.test(word)) return `${word}zes`;
|
|
541
|
+
if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
|
|
542
|
+
return `${word}s`;
|
|
543
|
+
};
|
|
544
|
+
const addInMemoryDbSection = (typeNaming, typeImportTarget)=>{
|
|
545
|
+
const file = serviceFile();
|
|
546
|
+
const sectionNaming = new UnknownFormatNaming(plural(typeNaming.fileName));
|
|
547
|
+
const field = sectionNaming.variableName;
|
|
548
|
+
if (new RegExp(`\\b${field}\\s*=\\s*this\\.section\\b`).test(file.data)) return field;
|
|
549
|
+
const withImport = addImport(file.data, `import type { ${typeNaming.ClassName} } from '${relativeImport(file.path, typeImportTarget)}';`);
|
|
550
|
+
file.update(addClassMember(withImport, in_memory_db_className, `${field} = this.section<${typeNaming.ClassName}>('${sectionNaming.fileName.toUpperCase()}');`));
|
|
551
|
+
return field;
|
|
552
|
+
};
|
|
553
|
+
const inMemoryDbTypeImport = (fromFile)=>`import type { ${in_memory_db_className} } from '${relativeImport(fromFile, serviceFile().path)}'`;
|
|
554
|
+
const inMemoryDbSectionMembers = (field, derived)=>`
|
|
555
|
+
private readonly data: ${in_memory_db_className}['${field}']
|
|
556
|
+
|
|
557
|
+
constructor(${parameterName}: ${in_memory_db_className}) {
|
|
558
|
+
${derived ? 'super()\n ' : ''}this.data = ${parameterName}.${field}
|
|
559
|
+
}
|
|
560
|
+
`.trim();
|
|
561
|
+
const keepInMemoryDbSection = (classFile, field)=>{
|
|
562
|
+
classFile.update(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)).replace('constructor() {}', inMemoryDbSectionMembers(field, false)));
|
|
563
|
+
};
|
|
564
|
+
const isInMemoryDb = (module)=>module.wireName === in_memory_db_wireName;
|
|
565
|
+
const injectInMemoryDb = (classFile, implementationName)=>{
|
|
566
|
+
classFile.update(addConstructorParameters(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)), implementationName, [
|
|
567
|
+
`private readonly ${parameterName}: ${in_memory_db_className}`
|
|
568
|
+
]));
|
|
569
|
+
};
|
|
570
|
+
const wireInMemoryDb = (consumerWireFile, implementationName)=>{
|
|
571
|
+
consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${in_memory_db_wireName} } from '${relativeImport(consumerWireFile.path, in_memory_db_wireFile().path)}'`), implementationName, [
|
|
572
|
+
in_memory_db_wireName
|
|
573
|
+
]));
|
|
574
|
+
};
|
|
575
|
+
const addInMemoryDb = ()=>{
|
|
1036
576
|
const config = ConfigFile.Instance.data;
|
|
1037
|
-
|
|
1038
|
-
|
|
577
|
+
if (!ConfigFile.backend.withInMemoryDb) ConfigFile.update({
|
|
578
|
+
backend: {
|
|
579
|
+
...ConfigFile.backend,
|
|
580
|
+
withInMemoryDb: true
|
|
581
|
+
}
|
|
582
|
+
});
|
|
583
|
+
withoutOverwrites(()=>scaffoldInMemoryDb(new Folder(new ProjectRoot().path).subitem([
|
|
584
|
+
config.project.rootFolder,
|
|
585
|
+
'shared-kernel'
|
|
586
|
+
])));
|
|
587
|
+
return [];
|
|
588
|
+
};
|
|
589
|
+
const inMemoryDbApplied = ()=>Boolean(ConfigFile.Instance.data.backend?.withInMemoryDb) && inMemoryDbScaffolded();
|
|
590
|
+
const usesNext = ()=>ConfigFile.exists && ConfigFile.Instance.data.frontend?.react?.framework === 'next';
|
|
591
|
+
const nextAppFolder = (root)=>[
|
|
592
|
+
'app',
|
|
593
|
+
'src/app'
|
|
594
|
+
].find((folder)=>new Folder(node_path.join(root, folder)).exists) ?? 'app';
|
|
595
|
+
const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
|
|
596
|
+
class NestedName {
|
|
597
|
+
folders;
|
|
598
|
+
folderName;
|
|
599
|
+
fileName;
|
|
600
|
+
ClassName;
|
|
601
|
+
classNameSegments;
|
|
602
|
+
constructor(rawSource){
|
|
603
|
+
const segments = splitSegments(rawSource);
|
|
604
|
+
this.folders = segments.slice(0, -1);
|
|
605
|
+
this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
|
|
606
|
+
this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
|
|
607
|
+
this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
|
|
608
|
+
this.ClassName = this.classNameSegments.join('');
|
|
609
|
+
}
|
|
610
|
+
static validate = (rawSource)=>{
|
|
611
|
+
const segments = splitSegments(rawSource);
|
|
612
|
+
if (!segments.length) return 'Name is required';
|
|
613
|
+
if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
|
|
614
|
+
return true;
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
const reactPageContent = (ClassName, { imports = [], body = '<></>' } = {})=>`
|
|
618
|
+
${[
|
|
619
|
+
...imports,
|
|
620
|
+
"import { type FC } from 'react'"
|
|
621
|
+
].join('\n')}
|
|
622
|
+
|
|
623
|
+
export type ${ClassName}PageProps = {}
|
|
624
|
+
|
|
625
|
+
export const ${ClassName}Page: FC<${ClassName}PageProps> = (props) => {
|
|
626
|
+
return ${body}
|
|
627
|
+
}
|
|
628
|
+
`.trim();
|
|
629
|
+
const nextRouteContent = (ClassName, pageImport)=>`
|
|
630
|
+
import { ${ClassName}Page } from '${pageImport}'
|
|
631
|
+
|
|
632
|
+
export default function Page() {
|
|
633
|
+
return <${ClassName}Page />
|
|
634
|
+
}
|
|
635
|
+
`.trim();
|
|
636
|
+
const scaffoldNextRoute = (name, pageFile)=>{
|
|
637
|
+
const root = new ProjectRoot().path;
|
|
638
|
+
const route = node_path.join(root, nextAppFolder(root), ...name.folders, name.folderName, 'page.tsx');
|
|
639
|
+
const relativeRoute = node_path.relative(root, route).split(node_path.sep).join('/');
|
|
640
|
+
const routeFile = new File(route);
|
|
641
|
+
if (routeFile.exists) return void report(`${relativeRoute} already exists: render ${name.ClassName}Page there yourself.`);
|
|
642
|
+
routeFile.data = nextRouteContent(name.ClassName, relativeImport(route, pageFile.path.replace(/\.tsx$/, '')));
|
|
643
|
+
};
|
|
644
|
+
const scaffoldReactPage = async (presentationReactFolder)=>{
|
|
645
|
+
const name = await interaction_input({
|
|
646
|
+
key: 'name',
|
|
647
|
+
message: 'Provide name (folders split by "/"):',
|
|
648
|
+
validate: NestedName.validate
|
|
649
|
+
});
|
|
650
|
+
const nestedName = new NestedName(name);
|
|
651
|
+
const { folders, ClassName, fileName } = nestedName;
|
|
652
|
+
const pageFile = presentationReactFolder.subitem([
|
|
653
|
+
'pages',
|
|
654
|
+
...folders
|
|
655
|
+
]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
|
|
656
|
+
if (usesNext()) scaffoldNextRoute(nestedName, pageFile);
|
|
657
|
+
};
|
|
658
|
+
const openapiScriptPath = "scripts/generate-openapi.ts";
|
|
659
|
+
const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
|
|
660
|
+
const extractorPackages = [
|
|
661
|
+
'ts-morph',
|
|
662
|
+
'@microsoft/tsdoc'
|
|
663
|
+
];
|
|
664
|
+
const swaggerPagePath = (rootFolder)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/pages/swagger-page.tsx');
|
|
665
|
+
const swaggerPage = (rootFolder, outputPath)=>{
|
|
666
|
+
const specImport = node_path.posix.relative(node_path.posix.dirname(swaggerPagePath(rootFolder)), outputPath);
|
|
667
|
+
return reactPageContent('Swagger', {
|
|
668
|
+
imports: [
|
|
669
|
+
"import 'swagger-ui-react/swagger-ui.css'",
|
|
670
|
+
"import SwaggerUI from 'swagger-ui-react'",
|
|
671
|
+
`import spec from '${specImport.startsWith('.') ? specImport : `./${specImport}`}' with { type: 'json' }`
|
|
672
|
+
],
|
|
673
|
+
body: '<SwaggerUI displayOperationId spec={spec} />'
|
|
674
|
+
});
|
|
675
|
+
};
|
|
676
|
+
const openapiScripts = {
|
|
677
|
+
openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
|
|
678
|
+
};
|
|
679
|
+
const splitPath = (value)=>value.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
|
|
680
|
+
const apiTitle = (packageName)=>{
|
|
681
|
+
const words = String(packageName ?? '').replace(/^@[^/]*\//, '').split(/[^a-zA-Z0-9]+/).filter((word)=>!!word).map((word)=>word[0].toUpperCase() + word.slice(1));
|
|
682
|
+
return [
|
|
683
|
+
...words,
|
|
684
|
+
'API'
|
|
685
|
+
].join(' ');
|
|
686
|
+
};
|
|
687
|
+
const openapiGenerator = (rootFolder, title, routePrefix, outputPath, withExtractor = false)=>{
|
|
688
|
+
const restFolder = node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/rest');
|
|
689
|
+
const restImport = node_path.posix.relative(node_path.posix.dirname(openapiScriptPath), restFolder);
|
|
690
|
+
const prefixSegments = splitPath(routePrefix);
|
|
691
|
+
const apiRoutePrefix = prefixSegments.length ? `\n apiRoutePrefix: [${prefixSegments.map((segment)=>`'${segment}'`).join(', ')}],` : '';
|
|
692
|
+
const extractorImport = `./${node_path.posix.relative(node_path.posix.dirname(openapiScriptPath), openapiExtractorPath.replace(/\.ts$/, ''))}`;
|
|
693
|
+
const handlers = withExtractor ? `
|
|
694
|
+
const extractOpenApiDataFromEndpointLogic =
|
|
695
|
+
createOpenApiDataFromEndpointLogicExtractor();
|
|
696
|
+
|
|
697
|
+
const handlers = restHandlers.map((x) => ({
|
|
698
|
+
...x,
|
|
699
|
+
metadata: {
|
|
700
|
+
...x.metadata,
|
|
701
|
+
openApiMetadata: {
|
|
702
|
+
...extractOpenApiDataFromEndpointLogic(x.metadata.route),
|
|
703
|
+
...(x.metadata.openApiMetadata ?? {})
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
}));
|
|
707
|
+
` : '';
|
|
708
|
+
return `import { generateOpenAPI } from '@domain-first/handlers-rest';
|
|
709
|
+
import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}';${withExtractor ? `\nimport { createOpenApiDataFromEndpointLogicExtractor } from '${extractorImport}';` : ''}
|
|
710
|
+
${handlers}
|
|
711
|
+
generateOpenAPI(${withExtractor ? 'handlers' : 'restHandlers'}, {
|
|
712
|
+
document: { info: { title: '${title}', version: '1.0.0' } },${apiRoutePrefix}
|
|
713
|
+
outputFile: { path: '${outputPath}' }
|
|
714
|
+
});
|
|
715
|
+
`;
|
|
716
|
+
};
|
|
717
|
+
const addOpenapi = async ()=>{
|
|
718
|
+
const { rootFolder } = ConfigFile.Instance.data.project;
|
|
719
|
+
const root = new ProjectRoot().path;
|
|
720
|
+
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
1039
721
|
const manifest = JSON.parse(manifestFile.data);
|
|
1040
722
|
const dependencies = {
|
|
1041
723
|
...manifest.dependencies,
|
|
1042
724
|
...manifest.devDependencies
|
|
1043
725
|
};
|
|
1044
|
-
const
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
726
|
+
const routePrefix = await interaction_input({
|
|
727
|
+
key: 'routePrefix',
|
|
728
|
+
message: 'Route prefix the REST handlers are served under:',
|
|
729
|
+
default: '/api'
|
|
730
|
+
});
|
|
731
|
+
const outputPath = await interaction_input({
|
|
732
|
+
key: 'openapiPath',
|
|
733
|
+
message: 'OpenAPI document path:',
|
|
734
|
+
default: defaultOpenapiPath(usesNext()),
|
|
735
|
+
validate: (value)=>splitPath(value).length ? true : 'Path is required'
|
|
736
|
+
});
|
|
737
|
+
const withExtractor = await interaction_confirm({
|
|
738
|
+
key: 'withExtractor',
|
|
739
|
+
message: "Fill operationId, summary and description from the endpoint logic TSDoc?",
|
|
1053
740
|
default: true
|
|
1054
741
|
});
|
|
1055
|
-
const
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
742
|
+
const withSwaggerPage = Boolean(ConfigFile.Instance.data.frontend?.react) && await interaction_confirm({
|
|
743
|
+
key: 'swaggerPage',
|
|
744
|
+
message: 'Add a Swagger UI page?',
|
|
745
|
+
default: true
|
|
746
|
+
});
|
|
747
|
+
const selected = await addPackageScripts(manifestFile, openapiScripts);
|
|
748
|
+
if (withExtractor) {
|
|
749
|
+
const extractorFile = new File(node_path.join(root, openapiExtractorPath));
|
|
750
|
+
const extractor = openapiExtractor(rootFolder);
|
|
751
|
+
if (!extractorFile.exists || extractorFile.data !== extractor) extractorFile.data = extractor;
|
|
1062
752
|
}
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
const relativeFolder = node_path.relative(root, prismaFolder).split(node_path.sep).join('/');
|
|
753
|
+
const generatorFile = new File(node_path.join(root, openapiScriptPath));
|
|
754
|
+
const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
|
|
755
|
+
if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
|
|
756
|
+
if (withSwaggerPage) {
|
|
757
|
+
const pageFile = new File(node_path.join(root, swaggerPagePath(rootFolder)));
|
|
758
|
+
const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'));
|
|
759
|
+
if (!pageFile.exists || pageFile.data !== page) pageFile.data = page;
|
|
760
|
+
}
|
|
761
|
+
const resolveJsonModule = withSwaggerPage ? compilerOption(node_path.join(root, 'tsconfig.json'), 'resolveJsonModule') : true;
|
|
762
|
+
const hasRestHandlers = new File(node_path.join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
|
|
763
|
+
const missingExtractorPackages = withExtractor ? extractorPackages.filter((name)=>!dependencies[name]) : [];
|
|
1075
764
|
return [
|
|
1076
|
-
...
|
|
1077
|
-
|
|
1078
|
-
|
|
765
|
+
...dependencies['@domain-first/handlers-rest'] ? [] : [
|
|
766
|
+
'npm install @domain-first/handlers-rest'
|
|
767
|
+
],
|
|
768
|
+
...dependencies.tsx ? [] : [
|
|
769
|
+
'npm install --save-dev tsx'
|
|
770
|
+
],
|
|
771
|
+
...missingExtractorPackages.length ? [
|
|
772
|
+
`npm install --save-dev ${missingExtractorPackages.join(' ')}`
|
|
773
|
+
] : [],
|
|
774
|
+
...withSwaggerPage && !dependencies['swagger-ui-react'] ? [
|
|
775
|
+
'npm install swagger-ui-react'
|
|
776
|
+
] : [],
|
|
777
|
+
...withSwaggerPage && !dependencies['@types/swagger-ui-react'] ? [
|
|
778
|
+
'npm install --save-dev @types/swagger-ui-react'
|
|
779
|
+
] : [],
|
|
780
|
+
...true === resolveJsonModule || null === resolveJsonModule ? [] : [
|
|
781
|
+
'set "resolveJsonModule": true in compilerOptions of tsconfig.json — the Swagger UI page imports the OpenAPI document as JSON'
|
|
782
|
+
],
|
|
1079
783
|
...describeScripts(selected, {
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
784
|
+
openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
|
|
785
|
+
}),
|
|
786
|
+
...withSwaggerPage ? [
|
|
787
|
+
`SwaggerPage from ${swaggerPagePath(rootFolder)} shows ${splitPath(outputPath).join('/')} once it is generated — render it on a route of your app`
|
|
788
|
+
] : [],
|
|
789
|
+
...hasRestHandlers ? [] : [
|
|
790
|
+
`restHandlers appear in ${node_path.posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
|
|
791
|
+
]
|
|
1084
792
|
];
|
|
1085
793
|
};
|
|
1086
|
-
const
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
'
|
|
1091
|
-
|
|
1092
|
-
commands: 'Commands',
|
|
1093
|
-
'use-cases': 'Use cases',
|
|
1094
|
-
'infrastructure-services': 'Infrastructure services',
|
|
1095
|
-
'presentation-services': 'Presentation services'
|
|
794
|
+
const addGitignoreEntry = (root, entry)=>{
|
|
795
|
+
const gitignore = new File(node_path.join(root, '.gitignore'));
|
|
796
|
+
const ignored = gitignore.exists ? gitignore.data : '';
|
|
797
|
+
if (ignored.split(/\r?\n/).includes(entry)) return;
|
|
798
|
+
const newline = ignored.includes('\r\n') ? '\r\n' : '\n';
|
|
799
|
+
gitignore.update(`${ignored}${ignored && !ignored.endsWith('\n') ? newline : ''}${entry}${newline}`);
|
|
1096
800
|
};
|
|
1097
|
-
const
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
...suggested.map((x)=>({
|
|
1101
|
-
name: x.label,
|
|
1102
|
-
value: x,
|
|
1103
|
-
checked: true
|
|
1104
|
-
}))
|
|
1105
|
-
] : [];
|
|
1106
|
-
const kinds = [
|
|
1107
|
-
...new Set([
|
|
1108
|
-
...Object.keys(kindTitles),
|
|
1109
|
-
...items.map((x)=>x.module.kind)
|
|
1110
|
-
])
|
|
1111
|
-
];
|
|
1112
|
-
return [
|
|
1113
|
-
...suggestedChoices,
|
|
1114
|
-
...kinds.flatMap((kind)=>{
|
|
1115
|
-
const group = items.filter((x)=>x.module.kind === kind && !suggested.includes(x));
|
|
1116
|
-
return group.length ? [
|
|
1117
|
-
new Separator(`── ${kindTitles[kind] ?? kind}`),
|
|
1118
|
-
...group.map((x)=>({
|
|
1119
|
-
name: x.label,
|
|
1120
|
-
value: x
|
|
1121
|
-
}))
|
|
1122
|
-
] : [];
|
|
1123
|
-
})
|
|
1124
|
-
];
|
|
1125
|
-
};
|
|
1126
|
-
const groupedPageSize = 20;
|
|
1127
|
-
const dependencyOptions = (boundedContextFolder)=>{
|
|
1128
|
-
const sharedFolder = new Folder(new ProjectRoot().path).subitem([
|
|
1129
|
-
ConfigFile.Instance.data.project.rootFolder,
|
|
1130
|
-
'shared-kernel'
|
|
1131
|
-
]);
|
|
1132
|
-
const isShared = sharedFolder.path === boundedContextFolder.path;
|
|
1133
|
-
const contextsFolder = new Folder(new ProjectRoot().path).subitem([
|
|
1134
|
-
ConfigFile.Instance.data.project.rootFolder,
|
|
1135
|
-
'bounded-contexts'
|
|
1136
|
-
]);
|
|
1137
|
-
return [
|
|
1138
|
-
...findWiredModules(boundedContextFolder.path).map((x)=>({
|
|
1139
|
-
module: x,
|
|
1140
|
-
label: x.typeName
|
|
1141
|
-
})),
|
|
1142
|
-
...isShared ? [] : findWiredModules(sharedFolder.path).map((x)=>({
|
|
1143
|
-
module: x,
|
|
1144
|
-
label: `${x.typeName} (shared-kernel)`
|
|
1145
|
-
})),
|
|
1146
|
-
...isShared ? [] : contextsFolder.content.subfolderNames.filter((name)=>name !== boundedContextFolder.name).sort().flatMap((name)=>findWiredModules(contextsFolder.subitem([
|
|
1147
|
-
name
|
|
1148
|
-
]).path).map((module)=>({
|
|
1149
|
-
module,
|
|
1150
|
-
label: `${module.typeName} (${name})`
|
|
1151
|
-
})))
|
|
1152
|
-
];
|
|
1153
|
-
};
|
|
1154
|
-
const promptDependencies = async (boundedContextFolder, consumer, implementations = consumer.implementations, customWiring)=>{
|
|
1155
|
-
const options = dependencyOptions(boundedContextFolder);
|
|
1156
|
-
let asked = false;
|
|
1157
|
-
for (const implementation of implementations){
|
|
1158
|
-
const available = availableDependencies(consumer, implementation, options.map((x)=>x.module));
|
|
1159
|
-
const candidates = options.filter((x)=>available.includes(x.module));
|
|
1160
|
-
if (!candidates.length) continue;
|
|
1161
|
-
asked = true;
|
|
1162
|
-
const type = wiring_implementationType(consumer, implementation);
|
|
1163
|
-
const suggested = type ? candidates.filter((x)=>isSuggestedFor(x.module, type)) : [];
|
|
1164
|
-
const dependencies = await interaction_checkbox({
|
|
1165
|
-
key: `dependencies.${implementation.className}`,
|
|
1166
|
-
id: (value)=>moduleId(value.module),
|
|
1167
|
-
message: consumer.branched ? `Dependencies for ${implementation.className}:` : 'Dependencies:',
|
|
1168
|
-
choices: groupedChoices(candidates, suggested),
|
|
1169
|
-
pageSize: groupedPageSize,
|
|
1170
|
-
loop: false
|
|
1171
|
-
});
|
|
1172
|
-
const defaultWired = dependencies.map((x)=>x.module).filter((x)=>!customWiring?.(implementation, x));
|
|
1173
|
-
if (defaultWired.length) wireDependencies(consumer, implementation, defaultWired);
|
|
1174
|
-
}
|
|
1175
|
-
return asked;
|
|
1176
|
-
};
|
|
1177
|
-
const wireNewModuleDependencies = async (boundedContextFolder, wireFile, customWiring)=>{
|
|
1178
|
-
const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
|
|
1179
|
-
if (consumer) await promptDependencies(boundedContextFolder, consumer, consumer.implementations, customWiring);
|
|
1180
|
-
};
|
|
1181
|
-
const wireNewImplementationDependencies = async (boundedContextFolder, wireFile, className, customWiring)=>{
|
|
1182
|
-
const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
|
|
1183
|
-
const implementation = consumer?.implementations.find((x)=>x.className === className);
|
|
1184
|
-
if (consumer && implementation) await promptDependencies(boundedContextFolder, consumer, [
|
|
1185
|
-
implementation
|
|
1186
|
-
], customWiring);
|
|
1187
|
-
};
|
|
1188
|
-
const wireDependency = async (boundedContextFolder)=>{
|
|
1189
|
-
const modules = findWiredModules(boundedContextFolder.path);
|
|
1190
|
-
if (!modules.length) return void report('No wired modules here yet.');
|
|
1191
|
-
const { module: consumer, implementation } = await interaction_select({
|
|
1192
|
-
key: 'module',
|
|
1193
|
-
id: (value)=>`${moduleId(value.module)}:${value.implementation.className}`,
|
|
1194
|
-
message: 'Module:',
|
|
1195
|
-
choices: groupedChoices(modules.flatMap((x)=>x.implementations.map((implementation)=>{
|
|
1196
|
-
const type = wiring_implementationType(x, implementation);
|
|
1197
|
-
return {
|
|
1198
|
-
module: x,
|
|
1199
|
-
label: type ? `${x.typeName} (${type})` : x.typeName,
|
|
1200
|
-
implementation
|
|
1201
|
-
};
|
|
1202
|
-
}))),
|
|
1203
|
-
pageSize: groupedPageSize,
|
|
1204
|
-
loop: false
|
|
801
|
+
const dataLayerFolder = (rootFolder, target)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'hooks' === target ? 'presentation/react/data-layer' : 'presentation/data-layer');
|
|
802
|
+
const orvalScripts = (rootFolder, targets)=>({
|
|
803
|
+
'client:orval': targets.map((target)=>`orval --config ${JSON.stringify(`${dataLayerFolder(rootFolder, target)}/orval.config.ts`)}`).join(' && ')
|
|
1205
804
|
});
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
'
|
|
1214
|
-
'
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
id: (value)=>moduleId(value.module),
|
|
1222
|
-
message: 'Handler:',
|
|
1223
|
-
choices: groupedChoices(handlers),
|
|
1224
|
-
pageSize: groupedPageSize,
|
|
1225
|
-
loop: false
|
|
1226
|
-
})).module : void 0;
|
|
1227
|
-
};
|
|
1228
|
-
const createPresentationService = (boundedContextFolder, name, classFile)=>{
|
|
1229
|
-
const naming = new UnknownFormatNaming(name);
|
|
1230
|
-
const className = `${naming.ClassName}PresentationService`;
|
|
1231
|
-
const scaffoldUnitTests = Boolean(ConfigFile.backend.testingLibrary);
|
|
1232
|
-
const withWiring = ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
|
|
1233
|
-
const wiringFolder = boundedContextFolder.subitem([
|
|
1234
|
-
'wiring',
|
|
1235
|
-
'presentation-services'
|
|
1236
|
-
]);
|
|
1237
|
-
const presentationServicesFolder = boundedContextFolder.subitem([
|
|
1238
|
-
'presentation',
|
|
1239
|
-
'services'
|
|
1240
|
-
]);
|
|
1241
|
-
presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.ts`, classFile?.(className) ?? `
|
|
1242
|
-
export class ${className} {
|
|
805
|
+
const orvalConfig = (rootFolder, openapiPath, withNext, target = 'hooks', mutatorPath = './api-client/mutator.ts')=>{
|
|
806
|
+
const inputPath = node_path.posix.relative(dataLayerFolder(rootFolder, target), openapiPath);
|
|
807
|
+
const baseUrl = withNext ? `
|
|
808
|
+
baseUrl: {
|
|
809
|
+
runtime: 'process.env.NEXT_PUBLIC_API_BASE_URL ?? ""'
|
|
810
|
+
},` : '';
|
|
811
|
+
const client = 'hooks' === target ? `
|
|
812
|
+
client: 'react-query',
|
|
813
|
+
httpClient: 'fetch',` : `
|
|
814
|
+
client: 'fetch',`;
|
|
815
|
+
const query = 'hooks' === target ? `,
|
|
816
|
+
query: {
|
|
817
|
+
version: 5
|
|
818
|
+
}` : '';
|
|
819
|
+
return `import { defineConfig } from 'orval';
|
|
1243
820
|
|
|
821
|
+
export default defineConfig({
|
|
822
|
+
api: {
|
|
823
|
+
input: '${inputPath.startsWith('.') ? inputPath : `./${inputPath}`}',
|
|
824
|
+
output: {
|
|
825
|
+
mode: 'tags-split',
|
|
826
|
+
target: './orval',
|
|
827
|
+
schemas: './orval/model',${client}${baseUrl}
|
|
828
|
+
clean: true,
|
|
829
|
+
override: {
|
|
830
|
+
mutator: {
|
|
831
|
+
path: '${mutatorPath}',
|
|
832
|
+
name: 'customInstance'
|
|
833
|
+
},
|
|
834
|
+
fetch: {
|
|
835
|
+
includeHttpResponseReturnType: false
|
|
836
|
+
}${query}
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
});
|
|
841
|
+
`;
|
|
842
|
+
};
|
|
843
|
+
const orvalMutator = `/** Error of the generated requests, with the parsed response body. */
|
|
844
|
+
export class ApiError<Body = unknown> extends Error {
|
|
845
|
+
constructor(
|
|
846
|
+
public readonly status: number,
|
|
847
|
+
public readonly body: Body
|
|
848
|
+
) {
|
|
849
|
+
super(\`API error \${status}\`);
|
|
850
|
+
this.name = 'ApiError';
|
|
851
|
+
}
|
|
1244
852
|
}
|
|
1245
|
-
`.trim());
|
|
1246
|
-
if (scaffoldUnitTests) presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.spec.ts`, `
|
|
1247
|
-
import { describe, test, expect, beforeEach } from '${ConfigFile.backend.testingLibrary}'
|
|
1248
|
-
${withWiring ? `import { type ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'
|
|
1249
|
-
import { wire${naming.ClassName}PresentationService } from '../../wiring/presentation-services/wire-${naming.fileName}-presentation-service'` : `import { ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'`}
|
|
1250
853
|
|
|
1251
|
-
|
|
854
|
+
/** Error type of the generated requests, typed per endpoint by Orval. */
|
|
855
|
+
export type ErrorType<Body> = ApiError<Body>;
|
|
1252
856
|
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
857
|
+
/** Every generated request goes through here: add auth headers, token refresh, logging. */
|
|
858
|
+
export const customInstance = async <T>(
|
|
859
|
+
url: string,
|
|
860
|
+
init?: RequestInit
|
|
861
|
+
): Promise<T> => {
|
|
862
|
+
const response = await fetch(url, init);
|
|
863
|
+
const text = await response.text();
|
|
864
|
+
const body = text ? JSON.parse(text) : undefined;
|
|
1256
865
|
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
})
|
|
1261
|
-
})
|
|
1262
|
-
`.trim());
|
|
1263
|
-
if (withWiring) return wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
|
|
1264
|
-
import { wireClass } from '@domain-first/wire'
|
|
1265
|
-
import { ${naming.ClassName}PresentationService } from '../../presentation/services/${naming.fileName}-presentation-service'
|
|
866
|
+
if (!response.ok) {
|
|
867
|
+
throw new ApiError(response.status, body);
|
|
868
|
+
}
|
|
1266
869
|
|
|
1267
|
-
|
|
1268
|
-
${naming.ClassName}PresentationService,
|
|
1269
|
-
[]
|
|
1270
|
-
)
|
|
1271
|
-
`.trim());
|
|
1272
|
-
};
|
|
1273
|
-
const scaffoldNewPresentationService = async (boundedContextFolder)=>{
|
|
1274
|
-
const name = await interaction_input({
|
|
1275
|
-
key: 'name',
|
|
1276
|
-
message: 'Name: '
|
|
1277
|
-
});
|
|
1278
|
-
const wireFile = createPresentationService(boundedContextFolder, name);
|
|
1279
|
-
if (wireFile) await wireNewModuleDependencies(boundedContextFolder, wireFile);
|
|
870
|
+
return body as T;
|
|
1280
871
|
};
|
|
1281
|
-
|
|
1282
|
-
const
|
|
1283
|
-
const adapter = withNextAdapter ? 'nextAdapter' : 'adapter';
|
|
1284
|
-
return `
|
|
1285
|
-
import {
|
|
1286
|
-
${withNextAdapter ? '' : ' type Adapter,\n'} type EndpointGenerator,
|
|
1287
|
-
createEndpoint,
|
|
1288
|
-
invalidRequest
|
|
1289
|
-
} from '@domain-first/handlers-rest'
|
|
1290
|
-
${withNextAdapter ? "import { nextAdapter } from '@domain-first/handlers-next'" : `
|
|
1291
|
-
/**
|
|
1292
|
-
* The adapter of your HTTP framework.
|
|
1293
|
-
*/
|
|
1294
|
-
const adapter = undefined as unknown as Adapter<any[], any>`}
|
|
872
|
+
`;
|
|
873
|
+
const queryProvider = `'use client';
|
|
1295
874
|
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
return createEndpoint({
|
|
1299
|
-
errors: [invalidRequest()]
|
|
1300
|
-
})(${adapter}) as EndpointGenerator
|
|
1301
|
-
}
|
|
1302
|
-
}
|
|
1303
|
-
`.trim();
|
|
1304
|
-
});
|
|
1305
|
-
const findRestEndpointGenerator = (sharedFolder)=>{
|
|
1306
|
-
const typeFile = node_path.join(sharedFolder.path, 'presentation', 'services', `${rest_endpoint_generator_name}-presentation-service.ts`);
|
|
1307
|
-
if (!new File(typeFile).exists) return;
|
|
1308
|
-
return {
|
|
1309
|
-
typeName: 'RestEndpointGeneratorPresentationService',
|
|
1310
|
-
typeFile,
|
|
1311
|
-
wireName: 'wireRestEndpointGeneratorPresentationService',
|
|
1312
|
-
wireFile: node_path.join(sharedFolder.path, 'wiring', 'presentation-services', `wire-${rest_endpoint_generator_name}-presentation-service.ts`)
|
|
1313
|
-
};
|
|
1314
|
-
};
|
|
1315
|
-
const nextRoutePath = (root)=>node_path.posix.join(nextAppFolder(root), 'api/[...path]/route.ts');
|
|
1316
|
-
const nextRoute = (restHandlersImport)=>`
|
|
1317
|
-
import { nextEndpoints } from '@domain-first/handlers-next'
|
|
1318
|
-
${restHandlersImport ? `import { restHandlers } from '${restHandlersImport}'
|
|
1319
|
-
|
|
1320
|
-
const handler = nextEndpoints(restHandlers)` : `
|
|
1321
|
-
/**
|
|
1322
|
-
* Pass the endpoints' handle here; their paths are relative to this route's folder.
|
|
1323
|
-
*/
|
|
1324
|
-
const handler = nextEndpoints([])`}
|
|
1325
|
-
|
|
1326
|
-
export const GET = handler
|
|
1327
|
-
export const POST = handler
|
|
1328
|
-
export const PUT = handler
|
|
1329
|
-
export const PATCH = handler
|
|
1330
|
-
export const DELETE = handler
|
|
1331
|
-
`.trim();
|
|
1332
|
-
const rest_endpoint_generator_scaffoldNextRoute = (root)=>{
|
|
1333
|
-
const { rootFolder } = ConfigFile.Instance.data.project;
|
|
1334
|
-
const { domainFirstPackages } = ConfigFile.backend;
|
|
1335
|
-
const routePath = nextRoutePath(root);
|
|
1336
|
-
const routeFile = node_path.join(root, routePath);
|
|
1337
|
-
if (new File(routeFile).exists) return [];
|
|
1338
|
-
if (!domainFirstPackages.includes('@domain-first/wire')) {
|
|
1339
|
-
new File(routeFile).data = nextRoute(void 0);
|
|
1340
|
-
return [];
|
|
1341
|
-
}
|
|
1342
|
-
const restFolder = new Folder(root).subitem([
|
|
1343
|
-
rootFolder,
|
|
1344
|
-
'presentation',
|
|
1345
|
-
'rest'
|
|
1346
|
-
]);
|
|
1347
|
-
new File(routeFile).data = nextRoute(relativeImport(routeFile, restFolder.path));
|
|
1348
|
-
return new File(node_path.join(restFolder.path, 'index.ts')).exists ? [] : [
|
|
1349
|
-
`${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`
|
|
1350
|
-
];
|
|
1351
|
-
};
|
|
1352
|
-
const askNextAdapter = async ({ nextSelected } = {})=>(nextSelected ?? usesNext()) && await interaction_confirm({
|
|
1353
|
-
key: 'nextAdapter',
|
|
1354
|
-
message: 'Use @domain-first/handlers-next for REST endpoints'
|
|
1355
|
-
});
|
|
1356
|
-
const scaffoldRestEndpointGeneratorFiles = ({ withNextAdapter })=>{
|
|
1357
|
-
const root = new ProjectRoot().path;
|
|
1358
|
-
const generatorExisted = restEndpointGeneratorApplied();
|
|
1359
|
-
const routeNotes = withoutOverwrites(()=>{
|
|
1360
|
-
scaffoldRestEndpointGenerator(new Folder(root).subitem([
|
|
1361
|
-
ConfigFile.Instance.data.project.rootFolder,
|
|
1362
|
-
'shared-kernel'
|
|
1363
|
-
]), {
|
|
1364
|
-
withNextAdapter
|
|
1365
|
-
});
|
|
1366
|
-
return withNextAdapter ? rest_endpoint_generator_scaffoldNextRoute(root) : [];
|
|
1367
|
-
});
|
|
1368
|
-
if (!withNextAdapter) return [];
|
|
1369
|
-
return [
|
|
1370
|
-
...missingPackages([
|
|
1371
|
-
'@domain-first/handlers-next'
|
|
1372
|
-
]),
|
|
1373
|
-
...routeNotes,
|
|
1374
|
-
...generatorExisted ? [
|
|
1375
|
-
'the existing endpoint generator was kept — pass nextAdapter from @domain-first/handlers-next to its createEndpoint calls'
|
|
1376
|
-
] : []
|
|
1377
|
-
];
|
|
1378
|
-
};
|
|
1379
|
-
const addRestEndpointGenerator = async ()=>scaffoldRestEndpointGeneratorFiles({
|
|
1380
|
-
withNextAdapter: await askNextAdapter()
|
|
1381
|
-
});
|
|
1382
|
-
const restEndpointGeneratorApplied = ()=>Boolean(findRestEndpointGenerator(new Folder(new ProjectRoot().path).subitem([
|
|
1383
|
-
ConfigFile.Instance.data.project.rootFolder,
|
|
1384
|
-
'shared-kernel'
|
|
1385
|
-
])));
|
|
1386
|
-
const storybookFrameworkPackage = '@storybook/react-vite';
|
|
1387
|
-
const storybookFiles = (relativeProjectRoot)=>({
|
|
1388
|
-
'main.ts': `import { resolve } from 'node:path';
|
|
1389
|
-
import react from '@vitejs/plugin-react';
|
|
1390
|
-
import type { StorybookConfig } from '${storybookFrameworkPackage}';
|
|
1391
|
-
|
|
1392
|
-
const projectRoot = resolve(import.meta.dirname, ${JSON.stringify(relativeProjectRoot)});
|
|
1393
|
-
|
|
1394
|
-
const config: StorybookConfig = {
|
|
1395
|
-
stories: ['../**/*.mdx', '../**/*.stories.@(ts|tsx)'],
|
|
1396
|
-
framework: {
|
|
1397
|
-
name: '${storybookFrameworkPackage}',
|
|
1398
|
-
options: {}
|
|
1399
|
-
},
|
|
1400
|
-
core: {
|
|
1401
|
-
disableTelemetry: true
|
|
1402
|
-
},
|
|
1403
|
-
async viteFinal(viteConfig) {
|
|
1404
|
-
const { mergeConfig } = await import('vite');
|
|
1405
|
-
|
|
1406
|
-
return mergeConfig(viteConfig, {
|
|
1407
|
-
plugins: [react()],
|
|
1408
|
-
resolve: {
|
|
1409
|
-
alias: {
|
|
1410
|
-
'@': projectRoot
|
|
1411
|
-
}
|
|
1412
|
-
}
|
|
1413
|
-
});
|
|
1414
|
-
}
|
|
1415
|
-
};
|
|
875
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
|
876
|
+
import { type FC, type ReactNode, useState } from 'react';
|
|
1416
877
|
|
|
1417
|
-
export
|
|
1418
|
-
|
|
1419
|
-
|
|
878
|
+
export const QueryProvider: FC<{ children: ReactNode }> = ({ children }) => {
|
|
879
|
+
// One client per browser session; a module-level client would be shared between requests on the server
|
|
880
|
+
const [queryClient] = useState(() => new QueryClient());
|
|
1420
881
|
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
date: /Date$/i
|
|
1427
|
-
}
|
|
1428
|
-
}
|
|
1429
|
-
}
|
|
882
|
+
return (
|
|
883
|
+
<QueryClientProvider client={queryClient}>
|
|
884
|
+
{children}
|
|
885
|
+
</QueryClientProvider>
|
|
886
|
+
);
|
|
1430
887
|
};
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
const folder = node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react');
|
|
1437
|
-
const quote = (value)=>JSON.stringify(value);
|
|
1438
|
-
return {
|
|
1439
|
-
storybook: `storybook dev -p 6006 -c ${quote(`${folder}/.storybook`)}`,
|
|
1440
|
-
'build-storybook': `storybook build -c ${quote(`${folder}/.storybook`)} -o ${quote(`${folder}/storybook-static`)}`
|
|
1441
|
-
};
|
|
888
|
+
`;
|
|
889
|
+
const openapiOutputPath = (root)=>{
|
|
890
|
+
const generator = new File(node_path.join(root, openapiScriptPath));
|
|
891
|
+
if (!generator.exists) return;
|
|
892
|
+
return generator.data.match(/outputFile:\s*{\s*path:\s*'([^']+)'/)?.[1];
|
|
1442
893
|
};
|
|
1443
|
-
const
|
|
1444
|
-
const
|
|
1445
|
-
|
|
1446
|
-
key: 'configureReact',
|
|
1447
|
-
requestRequired: true,
|
|
1448
|
-
message: `Configure React scaffolding with ${storybookFrameworkPackage}?`,
|
|
1449
|
-
default: false
|
|
1450
|
-
})) return [];
|
|
894
|
+
const addOrval = async ()=>{
|
|
895
|
+
const { project: { rootFolder }, frontend } = ConfigFile.Instance.data;
|
|
896
|
+
const useReact = Boolean(frontend?.react);
|
|
1451
897
|
const root = new ProjectRoot().path;
|
|
1452
898
|
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
1453
899
|
const manifest = JSON.parse(manifestFile.data);
|
|
1454
|
-
const selected = await addPackageScripts(manifestFile, storybookScripts(config.project.rootFolder));
|
|
1455
|
-
const folder = new Folder(root).subitem([
|
|
1456
|
-
config.project.rootFolder,
|
|
1457
|
-
'presentation',
|
|
1458
|
-
'react',
|
|
1459
|
-
'.storybook'
|
|
1460
|
-
]);
|
|
1461
|
-
for (const [name, content] of Object.entries(storybookFiles(node_path.relative(folder.path, root).split(node_path.sep).join('/')))){
|
|
1462
|
-
const file = new File(node_path.join(folder.path, name));
|
|
1463
|
-
if (!file.exists || file.data !== content) file.data = content;
|
|
1464
|
-
}
|
|
1465
|
-
if (!config.frontend?.react || config.frontend?.react?.storybookFramework !== storybookFrameworkPackage) ConfigFile.update({
|
|
1466
|
-
frontend: {
|
|
1467
|
-
...config.frontend,
|
|
1468
|
-
react: {
|
|
1469
|
-
...config.frontend?.react,
|
|
1470
|
-
storybookFramework: storybookFrameworkPackage
|
|
1471
|
-
}
|
|
1472
|
-
}
|
|
1473
|
-
});
|
|
1474
|
-
const buildFolder = node_path.posix.join(config.project.rootFolder.replaceAll('\\', '/'), 'presentation/react/storybook-static');
|
|
1475
|
-
addGitignoreEntry(root, `/${buildFolder}/`);
|
|
1476
900
|
const dependencies = {
|
|
1477
901
|
...manifest.dependencies,
|
|
1478
902
|
...manifest.devDependencies
|
|
1479
903
|
};
|
|
1480
|
-
const
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
'
|
|
1484
|
-
'
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
904
|
+
const withNext = usesNext();
|
|
905
|
+
const generatedOpenapiPath = openapiOutputPath(root);
|
|
906
|
+
const openapiPath = await interaction_input({
|
|
907
|
+
key: 'openapiPath',
|
|
908
|
+
message: 'OpenAPI document path:',
|
|
909
|
+
default: generatedOpenapiPath ?? defaultOpenapiPath(withNext),
|
|
910
|
+
validate: (value)=>value.trim() ? true : 'Path is required'
|
|
911
|
+
});
|
|
912
|
+
const targets = useReact ? await interaction_checkbox({
|
|
913
|
+
key: 'targets',
|
|
914
|
+
message: 'Generate:',
|
|
915
|
+
choices: [
|
|
916
|
+
{
|
|
917
|
+
name: 'React Query hooks',
|
|
918
|
+
value: 'hooks',
|
|
919
|
+
checked: true
|
|
920
|
+
},
|
|
921
|
+
{
|
|
922
|
+
name: 'Typed API client',
|
|
923
|
+
value: 'client'
|
|
924
|
+
}
|
|
925
|
+
],
|
|
926
|
+
required: true
|
|
927
|
+
}) : [
|
|
928
|
+
'client'
|
|
1501
929
|
];
|
|
1502
|
-
|
|
1503
|
-
const
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
'
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
930
|
+
const selected = await addPackageScripts(manifestFile, orvalScripts(rootFolder, targets));
|
|
931
|
+
const document = node_path.posix.normalize(openapiPath.trim().replaceAll('\\', '/'));
|
|
932
|
+
const withClient = targets.includes('client');
|
|
933
|
+
for (const target of targets){
|
|
934
|
+
const dataLayer = dataLayerFolder(rootFolder, target);
|
|
935
|
+
const sharedMutator = 'hooks' === target && withClient;
|
|
936
|
+
const mutatorPath = sharedMutator ? `${node_path.posix.relative(dataLayer, dataLayerFolder(rootFolder, 'client'))}/api-client/mutator.ts` : void 0;
|
|
937
|
+
const configFile = new File(node_path.join(root, dataLayer, 'orval.config.ts'));
|
|
938
|
+
const content = orvalConfig(rootFolder, document, withNext, target, mutatorPath);
|
|
939
|
+
if (!configFile.exists || configFile.data !== content) configFile.data = content;
|
|
940
|
+
for (const [name, fileContent] of [
|
|
941
|
+
...sharedMutator ? [] : [
|
|
942
|
+
[
|
|
943
|
+
'api-client/mutator.ts',
|
|
944
|
+
orvalMutator
|
|
945
|
+
]
|
|
946
|
+
],
|
|
947
|
+
...'hooks' === target ? [
|
|
948
|
+
[
|
|
949
|
+
'query-provider.tsx',
|
|
950
|
+
queryProvider
|
|
951
|
+
]
|
|
952
|
+
] : []
|
|
953
|
+
]){
|
|
954
|
+
const file = new File(node_path.join(root, dataLayer, name));
|
|
955
|
+
if (!file.exists) file.data = fileContent;
|
|
956
|
+
}
|
|
957
|
+
addGitignoreEntry(root, `/${dataLayer}/orval/`);
|
|
958
|
+
}
|
|
959
|
+
const generated = targets.map((target)=>'hooks' === target ? `React Query hooks in ${dataLayerFolder(rootFolder, 'hooks')}/orval` : `a typed API client in ${dataLayerFolder(rootFolder, 'client')}/orval`);
|
|
960
|
+
const missing = (names)=>names.filter((name)=>!dependencies[name]);
|
|
961
|
+
const runtime = missing(targets.includes('hooks') ? [
|
|
962
|
+
'@tanstack/react-query'
|
|
963
|
+
] : []);
|
|
964
|
+
const development = missing([
|
|
965
|
+
'orval'
|
|
966
|
+
]);
|
|
967
|
+
return [
|
|
968
|
+
...runtime.length ? [
|
|
969
|
+
`npm install ${runtime.join(' ')}`
|
|
1530
970
|
] : [],
|
|
1531
|
-
...
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
/**
|
|
1546
|
-
* The branch this process runs in. Write how it is selected:
|
|
1547
|
-
* until then, this function doesn't compile.
|
|
1548
|
-
*/
|
|
1549
|
-
const currentBranch = (): EnvBranch => {
|
|
1550
|
-
}
|
|
1551
|
-
|
|
1552
|
-
export const envBranchedWire = branchedWire(currentBranch)`;
|
|
971
|
+
...development.length ? [
|
|
972
|
+
`npm install --save-dev ${development.join(' ')}`
|
|
973
|
+
] : [],
|
|
974
|
+
...describeScripts(selected, {
|
|
975
|
+
'client:orval': `generate ${generated.join(' and ')} from ${openapiPath.trim()}`
|
|
976
|
+
}),
|
|
977
|
+
...targets.includes('hooks') ? [
|
|
978
|
+
`Wrap your app in QueryProvider from ${dataLayerFolder(rootFolder, 'hooks')}/query-provider.tsx`
|
|
979
|
+
] : [],
|
|
980
|
+
...generatedOpenapiPath ? [] : [
|
|
981
|
+
'npx df-integration → OpenAPI generates the OpenAPI document the client is built from'
|
|
982
|
+
]
|
|
983
|
+
];
|
|
1553
984
|
};
|
|
1554
|
-
const
|
|
1555
|
-
|
|
1556
|
-
'test:integration': `vitest run --config ${integrationFolder}/vitest.config.ts --reporter=dot --silent=passed-only`
|
|
985
|
+
const playwrightScripts = {
|
|
986
|
+
'test:e2e': 'playwright test'
|
|
1557
987
|
};
|
|
1558
|
-
const
|
|
1559
|
-
const server = inlineHandlersNext ? `,
|
|
1560
|
-
server: {
|
|
1561
|
-
deps: {
|
|
1562
|
-
// Imports \`next/headers\` without an extension, which only a bundler can resolve
|
|
1563
|
-
inline: ['@domain-first/handlers-next']
|
|
1564
|
-
}
|
|
1565
|
-
}` : '';
|
|
1566
|
-
return `import { fileURLToPath } from 'node:url';
|
|
1567
|
-
import { defineConfig } from 'vitest/config';
|
|
988
|
+
const playwrightConfig = `import { defineConfig, devices } from '@playwright/test';
|
|
1568
989
|
|
|
1569
|
-
// Runs specs from this folder against PostgreSQL in a container, see global-setup.ts.
|
|
1570
990
|
export default defineConfig({
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
991
|
+
testDir: './specs/e2e',
|
|
992
|
+
fullyParallel: true,
|
|
993
|
+
forbidOnly: !!process.env.CI,
|
|
994
|
+
retries: process.env.CI ? 2 : 0,
|
|
995
|
+
workers: process.env.CI ? 1 : undefined,
|
|
996
|
+
reporter: 'html',
|
|
997
|
+
use: {
|
|
998
|
+
baseURL: 'http://localhost:3000',
|
|
999
|
+
trace: 'on-first-retry',
|
|
1000
|
+
screenshot: 'only-on-failure',
|
|
1001
|
+
video: 'retain-on-failure'
|
|
1575
1002
|
},
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1003
|
+
|
|
1004
|
+
projects: [
|
|
1005
|
+
{
|
|
1006
|
+
name: 'chromium',
|
|
1007
|
+
use: { ...devices['Desktop Chrome'] }
|
|
1008
|
+
},
|
|
1009
|
+
{
|
|
1010
|
+
name: 'firefox',
|
|
1011
|
+
use: { ...devices['Desktop Firefox'] }
|
|
1012
|
+
},
|
|
1013
|
+
{
|
|
1014
|
+
name: 'webkit',
|
|
1015
|
+
use: { ...devices['Desktop Safari'] }
|
|
1016
|
+
},
|
|
1017
|
+
{
|
|
1018
|
+
name: 'Mobile Chrome',
|
|
1019
|
+
use: { ...devices['Pixel 5'] }
|
|
1020
|
+
},
|
|
1021
|
+
{
|
|
1022
|
+
name: 'Mobile Safari',
|
|
1023
|
+
use: { ...devices['iPhone 12'] }
|
|
1024
|
+
}
|
|
1025
|
+
],
|
|
1026
|
+
|
|
1027
|
+
webServer: {
|
|
1028
|
+
// Playwright only stops the dev server on a clean shutdown. If its process dies any other
|
|
1029
|
+
// way (SIGHUP, SIGKILL), the dev server lives on in its own process group, so it is killed
|
|
1030
|
+
// as soon as Playwright is gone.
|
|
1031
|
+
command:
|
|
1032
|
+
process.platform === 'win32'
|
|
1033
|
+
? 'npm run dev'
|
|
1034
|
+
: \`npm run dev & while kill -0 \${process.pid} 2>/dev/null && kill -0 $! 2>/dev/null; do sleep 1; done; kill 0\`,
|
|
1035
|
+
url: 'http://localhost:3000',
|
|
1036
|
+
timeout: 120000,
|
|
1037
|
+
reuseExistingServer: !process.env.CI
|
|
1584
1038
|
}
|
|
1585
1039
|
});
|
|
1586
1040
|
`;
|
|
1587
|
-
};
|
|
1588
|
-
const testcontainersGlobalSetup = (migrationCommand)=>{
|
|
1589
|
-
const migrations = migrationCommand ? `
|
|
1590
|
-
// dotenv in the Prisma config does not override an already set variable
|
|
1591
|
-
execSync(${JSON.stringify(migrationCommand)}, {
|
|
1592
|
-
cwd: project.config.root,
|
|
1593
|
-
env: { ...process.env, DATABASE_URL: databaseUrl },
|
|
1594
|
-
// On failure the error carries the command's output
|
|
1595
|
-
stdio: 'pipe'
|
|
1596
|
-
});
|
|
1597
|
-
` : `
|
|
1598
|
-
// Apply your migrations to databaseUrl here.
|
|
1599
|
-
`;
|
|
1600
|
-
return `${migrationCommand ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
|
|
1601
|
-
import type { TestProject } from 'vitest/node';
|
|
1602
|
-
|
|
1603
|
-
declare module 'vitest' {
|
|
1604
|
-
export interface ProvidedContext {
|
|
1605
|
-
databaseUrl: string;
|
|
1606
|
-
}
|
|
1607
|
-
}
|
|
1608
|
-
|
|
1609
|
-
const POSTGRES_IMAGE = 'postgres:15';
|
|
1610
|
-
const POSTGRES_PORT = 5432;
|
|
1611
|
-
const POSTGRES_USER = 'test';
|
|
1612
|
-
const POSTGRES_PASSWORD = 'test';
|
|
1613
|
-
const POSTGRES_DB = 'test';
|
|
1614
|
-
|
|
1615
|
-
export default async function setup(project: TestProject) {
|
|
1616
|
-
const container = await new GenericContainer(POSTGRES_IMAGE)
|
|
1617
|
-
.withEnvironment({ POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB })
|
|
1618
|
-
.withExposedPorts(POSTGRES_PORT)
|
|
1619
|
-
// During init PostgreSQL listens on a unix socket only and restarts,
|
|
1620
|
-
// so checking over TCP passes once the final server is up
|
|
1621
|
-
.withHealthCheck({
|
|
1622
|
-
test: [
|
|
1623
|
-
'CMD-SHELL',
|
|
1624
|
-
\`pg_isready --host localhost --username \${POSTGRES_USER} --dbname \${POSTGRES_DB}\`
|
|
1625
|
-
],
|
|
1626
|
-
interval: 250,
|
|
1627
|
-
timeout: 1000,
|
|
1628
|
-
retries: 1000
|
|
1629
|
-
})
|
|
1630
|
-
.withWaitStrategy(Wait.forHealthCheck())
|
|
1631
|
-
.withStartupTimeout(120_000)
|
|
1632
|
-
.start();
|
|
1633
|
-
|
|
1634
|
-
const databaseUrl = \`postgresql://\${POSTGRES_USER}:\${POSTGRES_PASSWORD}@\${container.getHost()}:\${container.getMappedPort(POSTGRES_PORT)}/\${POSTGRES_DB}\`;
|
|
1635
|
-
${migrations}
|
|
1636
|
-
project.provide('databaseUrl', databaseUrl);
|
|
1041
|
+
const exampleSpec = `import { expect, test } from '@playwright/test';
|
|
1637
1042
|
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
}
|
|
1043
|
+
test.describe('home page', () => {
|
|
1044
|
+
test('opens the home page', async ({ page, baseURL }) => {
|
|
1045
|
+
await page.goto('/');
|
|
1046
|
+
await expect(page).toHaveURL(\`\${baseURL}/\`);
|
|
1047
|
+
});
|
|
1048
|
+
});
|
|
1642
1049
|
`;
|
|
1643
|
-
|
|
1644
|
-
const testcontainersSetupEnv = `import 'dotenv/config';
|
|
1645
|
-
import { inject } from 'vitest';
|
|
1646
|
-
|
|
1647
|
-
// Runs before each spec's imports: development implementations get the .env
|
|
1648
|
-
// config, and DATABASE_URL points to the container instead of the one from .env.
|
|
1649
|
-
if (process.env.NODE_ENV !== 'development') {
|
|
1650
|
-
throw new Error(
|
|
1651
|
-
\`Integration specs need NODE_ENV=development to wire development implementations, got "\${process.env.NODE_ENV}"\`
|
|
1652
|
-
);
|
|
1653
|
-
}
|
|
1050
|
+
const exampleReadme = `# Home page e2e cases
|
|
1654
1051
|
|
|
1655
|
-
|
|
1656
|
-
`;
|
|
1657
|
-
const testcontainers_exampleSpec = `import { expect, inject, test } from 'vitest';
|
|
1052
|
+
## User Stories
|
|
1658
1053
|
|
|
1659
|
-
|
|
1660
|
-
expect(process.env.DATABASE_URL).toBe(inject('databaseUrl'));
|
|
1661
|
-
});
|
|
1054
|
+
1. Guest opens \`/\` and stays on the home page.
|
|
1662
1055
|
`;
|
|
1663
|
-
const
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
}).replace('// Playwright runs end-to-end specs\n', '// Playwright runs end-to-end specs, test:integration runs integration ones\n');
|
|
1672
|
-
};
|
|
1673
|
-
const testcontainers_stageFile = (filePath, content)=>{
|
|
1674
|
-
const file = new File(filePath);
|
|
1675
|
-
if (!file.exists || file.data !== content) file.data = content;
|
|
1676
|
-
};
|
|
1677
|
-
const addTestcontainers = async ()=>{
|
|
1678
|
-
const config = ConfigFile.Instance.data;
|
|
1056
|
+
const gitignoreEntries = [
|
|
1057
|
+
'/test-results/',
|
|
1058
|
+
'/playwright-report/',
|
|
1059
|
+
'/blob-report/',
|
|
1060
|
+
'/playwright/.cache/',
|
|
1061
|
+
'/playwright/.auth/'
|
|
1062
|
+
];
|
|
1063
|
+
const addPlaywright = async ()=>{
|
|
1679
1064
|
const root = new ProjectRoot().path;
|
|
1680
1065
|
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
1681
1066
|
const manifest = JSON.parse(manifestFile.data);
|
|
@@ -1683,96 +1068,104 @@ const addTestcontainers = async ()=>{
|
|
|
1683
1068
|
...manifest.dependencies,
|
|
1684
1069
|
...manifest.devDependencies
|
|
1685
1070
|
};
|
|
1686
|
-
const selected = await addPackageScripts(manifestFile,
|
|
1687
|
-
const
|
|
1688
|
-
|
|
1689
|
-
const
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
}
|
|
1071
|
+
const selected = await addPackageScripts(manifestFile, playwrightScripts);
|
|
1072
|
+
const configFile = new File(node_path.join(root, 'playwright.config.ts'));
|
|
1073
|
+
if (!configFile.exists || configFile.data !== playwrightConfig) configFile.data = playwrightConfig;
|
|
1074
|
+
const exampleFolder = node_path.join(root, 'specs/e2e/home');
|
|
1075
|
+
for (const [name, content] of [
|
|
1076
|
+
[
|
|
1077
|
+
'home.e2e.spec.ts',
|
|
1078
|
+
exampleSpec
|
|
1079
|
+
],
|
|
1080
|
+
[
|
|
1081
|
+
'README.MD',
|
|
1082
|
+
exampleReadme
|
|
1083
|
+
]
|
|
1084
|
+
]){
|
|
1085
|
+
const file = new File(node_path.join(exampleFolder, name));
|
|
1086
|
+
if (!file.exists) file.data = content;
|
|
1703
1087
|
}
|
|
1704
|
-
const
|
|
1705
|
-
'vitest',
|
|
1706
|
-
'testcontainers',
|
|
1707
|
-
'dotenv'
|
|
1708
|
-
].filter((name)=>!dependencies[name]);
|
|
1088
|
+
for (const entry of gitignoreEntries)addGitignoreEntry(root, entry);
|
|
1709
1089
|
return [
|
|
1710
|
-
...
|
|
1711
|
-
|
|
1712
|
-
] : [],
|
|
1713
|
-
`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.`,
|
|
1714
|
-
...migrationCommand ? [] : [
|
|
1715
|
-
`Apply your migrations in ${integrationFolder}/global-setup.ts.`
|
|
1716
|
-
],
|
|
1717
|
-
...excludedFromUnitTests ? [] : [
|
|
1718
|
-
`Add '${integrationFolder}/**' to test.exclude in vitest.config.ts, so unit tests skip integration specs.`
|
|
1090
|
+
...dependencies['@playwright/test'] ? [] : [
|
|
1091
|
+
'npm install --save-dev @playwright/test'
|
|
1719
1092
|
],
|
|
1720
|
-
|
|
1721
|
-
`${integrationFolder} runs with NODE_ENV=development and ${integrationFolder}/setup-env.ts requires it, but your envBranchedWire branches are custom: make currentBranch in shared-kernel/wiring/env-branched-wire.ts return the branch for integration specs, and adjust setup-env.ts.`
|
|
1722
|
-
] : [],
|
|
1723
|
-
'Docker must be running for integration specs.',
|
|
1093
|
+
'npx playwright install --with-deps',
|
|
1724
1094
|
...describeScripts(selected, {
|
|
1725
|
-
'test:
|
|
1095
|
+
'test:e2e': 'start the dev server and run end-to-end specs from specs/e2e'
|
|
1726
1096
|
})
|
|
1727
1097
|
];
|
|
1728
1098
|
};
|
|
1729
|
-
const
|
|
1730
|
-
|
|
1731
|
-
'
|
|
1099
|
+
const prisma_runtimePackages = [
|
|
1100
|
+
'@prisma/orm-postgres',
|
|
1101
|
+
'temporal-polyfill',
|
|
1102
|
+
'dotenv'
|
|
1103
|
+
];
|
|
1104
|
+
const prisma_developmentPackages = [
|
|
1105
|
+
'prisma',
|
|
1106
|
+
'@prisma/cli-engine'
|
|
1107
|
+
];
|
|
1108
|
+
const prismaScripts = (rootFolder)=>{
|
|
1109
|
+
const config = JSON.stringify(node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'shared-kernel/infrastructure/prisma/prisma.config.ts'));
|
|
1110
|
+
const emit = `prisma contract emit --config ${config}`;
|
|
1111
|
+
return {
|
|
1112
|
+
'prisma:emit': emit,
|
|
1113
|
+
'prisma:migration:plan': `${emit} && prisma migration plan --config ${config}`,
|
|
1114
|
+
'prisma:migration:apply': `prisma db migrate --advance-ref db --config ${config}`
|
|
1115
|
+
};
|
|
1732
1116
|
};
|
|
1733
|
-
const
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
server: {
|
|
1737
|
-
deps: {
|
|
1738
|
-
// Imports \`next/headers\` without an extension, which only a bundler can resolve
|
|
1739
|
-
inline: ['@domain-first/handlers-next']
|
|
1740
|
-
}
|
|
1741
|
-
}` : '';
|
|
1742
|
-
return `import { configDefaults, defineConfig } from 'vitest/config';
|
|
1117
|
+
const prismaConfig = `import 'dotenv/config';
|
|
1118
|
+
import { definePrismaConfig } from '@prisma/cli-engine';
|
|
1119
|
+
import { defineConfig as ormConfig } from '@prisma/orm-postgres/config';
|
|
1743
1120
|
|
|
1744
|
-
export default
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
provider: 'v8',
|
|
1753
|
-
include: [${folder('bounded-contexts/**/*.ts')}, ${folder('shared-kernel/**/*.ts')}],
|
|
1754
|
-
exclude: [
|
|
1755
|
-
'**/*.spec.ts',
|
|
1756
|
-
${folder('shared-kernel/infrastructure/**')},
|
|
1757
|
-
${folder('bounded-contexts/*/infrastructure/**')},
|
|
1758
|
-
${folder('bounded-contexts/*/presentation/rest/**')},
|
|
1759
|
-
${folder('shared-kernel/wiring/**')},
|
|
1760
|
-
${folder('bounded-contexts/*/wiring/**')}
|
|
1761
|
-
],
|
|
1762
|
-
reporter: [['text', { skipFull: true }], 'html']
|
|
1763
|
-
}${server}
|
|
1764
|
-
}
|
|
1121
|
+
export default definePrismaConfig({
|
|
1122
|
+
orm: ormConfig({
|
|
1123
|
+
contract: './contract.prisma',
|
|
1124
|
+
migrations: { dir: './migrations' },
|
|
1125
|
+
db: {
|
|
1126
|
+
connection: process.env.DATABASE_URL
|
|
1127
|
+
}
|
|
1128
|
+
})
|
|
1765
1129
|
});
|
|
1766
1130
|
`;
|
|
1131
|
+
const prismaService = `import 'temporal-polyfill/global';
|
|
1132
|
+
import postgres from '@prisma/orm-postgres/runtime';
|
|
1133
|
+
import type {} from 'temporal-polyfill/types/global';
|
|
1134
|
+
import type { Contract } from '../prisma/contract.d';
|
|
1135
|
+
import contractJson from '../prisma/contract.json' with { type: 'json' };
|
|
1136
|
+
|
|
1137
|
+
type PrismaClient = ReturnType<typeof postgres<Contract>>;
|
|
1138
|
+
|
|
1139
|
+
const globalForPrisma = globalThis as typeof globalThis & {
|
|
1140
|
+
prismaClient?: PrismaClient;
|
|
1767
1141
|
};
|
|
1768
|
-
|
|
1142
|
+
|
|
1143
|
+
// Reuse the client across development hot reloads.
|
|
1144
|
+
const prismaClient = globalForPrisma.prismaClient ??
|
|
1145
|
+
postgres<Contract>({ contractJson, url: process.env.DATABASE_URL });
|
|
1146
|
+
|
|
1147
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
1148
|
+
globalForPrisma.prismaClient = prismaClient;
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
export class PrismaInfrastructureService {
|
|
1152
|
+
readonly orm = prismaClient.orm.public;
|
|
1153
|
+
}
|
|
1154
|
+
`;
|
|
1155
|
+
const prismaWiring = `import { wireClass } from '@domain-first/wire';
|
|
1156
|
+
import { PrismaInfrastructureService } from '../../infrastructure/services/prisma-infrastructure-service';
|
|
1157
|
+
|
|
1158
|
+
export const wirePrismaInfrastructureService = wireClass(
|
|
1159
|
+
PrismaInfrastructureService,
|
|
1160
|
+
[]
|
|
1161
|
+
);
|
|
1162
|
+
`;
|
|
1163
|
+
const prisma_stageFile = (filePath, content)=>{
|
|
1164
|
+
const file = new File(filePath);
|
|
1165
|
+
if (!file.exists || file.data !== content) file.data = content;
|
|
1166
|
+
};
|
|
1167
|
+
const addPrisma = async ()=>{
|
|
1769
1168
|
const config = ConfigFile.Instance.data;
|
|
1770
|
-
if (ConfigFile.backend.testingLibrary && 'vitest' !== ConfigFile.backend.testingLibrary && !await interaction_confirm({
|
|
1771
|
-
key: 'replaceTestingLibrary',
|
|
1772
|
-
requestRequired: true,
|
|
1773
|
-
message: `Replace testing library "${ConfigFile.backend.testingLibrary}" with vitest for generated tests?`,
|
|
1774
|
-
default: false
|
|
1775
|
-
})) return [];
|
|
1776
1169
|
const root = new ProjectRoot().path;
|
|
1777
1170
|
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
1778
1171
|
const manifest = JSON.parse(manifestFile.data);
|
|
@@ -1780,228 +1173,465 @@ const addVitest = async ()=>{
|
|
|
1780
1173
|
...manifest.dependencies,
|
|
1781
1174
|
...manifest.devDependencies
|
|
1782
1175
|
};
|
|
1783
|
-
const
|
|
1784
|
-
const
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1176
|
+
const shared = node_path.resolve(root, config.project.rootFolder, 'shared-kernel');
|
|
1177
|
+
const prismaFolder = node_path.join(shared, 'infrastructure/prisma');
|
|
1178
|
+
if (dependencies['@prisma/client'] || dependencies.prisma && !/^[~^]?8\./.test(dependencies.prisma) || dependencies['@prisma/orm-mongo'] || dependencies['@prisma/orm-sqlite'] || [
|
|
1179
|
+
node_path.join(root, 'prisma/schema.prisma'),
|
|
1180
|
+
node_path.join(prismaFolder, 'schema.prisma')
|
|
1181
|
+
].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.');
|
|
1182
|
+
const withService = await interaction_confirm({
|
|
1183
|
+
key: 'withService',
|
|
1184
|
+
message: 'Create the Prisma infrastructure service in the Shared Kernel?',
|
|
1185
|
+
default: true
|
|
1792
1186
|
});
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1187
|
+
const selected = await addPackageScripts(manifestFile, prismaScripts(config.project.rootFolder));
|
|
1188
|
+
prisma_stageFile(node_path.join(prismaFolder, 'prisma.config.ts'), prismaConfig);
|
|
1189
|
+
const contract = new File(node_path.join(prismaFolder, 'contract.prisma'));
|
|
1190
|
+
if (!contract.exists) contract.data = '// use prisma-8\n\n// Add your application models here before running prisma:emit.\n';
|
|
1191
|
+
if (withService) {
|
|
1192
|
+
prisma_stageFile(node_path.join(shared, 'infrastructure/services/prisma-infrastructure-service.ts'), prismaService);
|
|
1193
|
+
if (ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) prisma_stageFile(node_path.join(shared, 'wiring/infrastructure-services/wire-prisma-infrastructure-service.ts'), prismaWiring);
|
|
1194
|
+
}
|
|
1195
|
+
for (const kind of [
|
|
1196
|
+
'repositories',
|
|
1197
|
+
'commands',
|
|
1198
|
+
'queries'
|
|
1199
|
+
])rememberImplementation(kind, 'primary', 'prisma');
|
|
1200
|
+
const install = (packages, dev)=>{
|
|
1201
|
+
const missing = packages.filter((name)=>!dependencies[name]);
|
|
1202
|
+
return missing.length ? [
|
|
1203
|
+
`npm install${dev ? ' --save-dev' : ''} ${missing.join(' ')}`
|
|
1204
|
+
] : [];
|
|
1205
|
+
};
|
|
1206
|
+
const relativeFolder = node_path.relative(root, prismaFolder).split(node_path.sep).join('/');
|
|
1798
1207
|
return [
|
|
1799
|
-
...
|
|
1800
|
-
|
|
1801
|
-
|
|
1208
|
+
...install(prisma_runtimePackages, false),
|
|
1209
|
+
...install(prisma_developmentPackages, true),
|
|
1210
|
+
`Add !${relativeFolder} in your linter, to ignore prisma files.`,
|
|
1802
1211
|
...describeScripts(selected, {
|
|
1803
|
-
|
|
1804
|
-
'
|
|
1212
|
+
'prisma:emit': 'emit contract.json and contract.d.ts from contract.prisma',
|
|
1213
|
+
'prisma:migration:plan': 'emit the contract and plan a migration',
|
|
1214
|
+
'prisma:migration:apply': 'apply planned migrations to the database in DATABASE_URL'
|
|
1805
1215
|
})
|
|
1806
1216
|
];
|
|
1807
1217
|
};
|
|
1808
|
-
const
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
}
|
|
1819
|
-
for (const name of match[2].trim().split(/\s+/))(match[1] ? development : runtime).add(name);
|
|
1820
|
-
}
|
|
1821
|
-
const devOnly = [
|
|
1822
|
-
...development
|
|
1823
|
-
].filter((name)=>!runtime.has(name));
|
|
1824
|
-
return [
|
|
1825
|
-
...runtime.size ? [
|
|
1826
|
-
`npm install ${[
|
|
1827
|
-
...runtime
|
|
1828
|
-
].join(' ')}`
|
|
1829
|
-
] : [],
|
|
1830
|
-
...devOnly.length ? [
|
|
1831
|
-
`npm install --save-dev ${devOnly.join(' ')}`
|
|
1832
|
-
] : [],
|
|
1833
|
-
...rest
|
|
1834
|
-
];
|
|
1218
|
+
const kindTitles = {
|
|
1219
|
+
repositories: 'Repositories',
|
|
1220
|
+
'domain-services': 'Domain services',
|
|
1221
|
+
'application-ports': 'Ports',
|
|
1222
|
+
'application-services': 'Application services',
|
|
1223
|
+
queries: 'Queries',
|
|
1224
|
+
commands: 'Commands',
|
|
1225
|
+
'use-cases': 'Use cases',
|
|
1226
|
+
'infrastructure-services': 'Infrastructure services',
|
|
1227
|
+
'presentation-services': 'Presentation services'
|
|
1835
1228
|
};
|
|
1836
|
-
const
|
|
1837
|
-
const
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1229
|
+
const groupedChoices = (items, suggested = [])=>{
|
|
1230
|
+
const suggestedChoices = suggested.length ? [
|
|
1231
|
+
new Separator('── Suggested'),
|
|
1232
|
+
...suggested.map((x)=>({
|
|
1233
|
+
name: x.label,
|
|
1234
|
+
value: x,
|
|
1235
|
+
checked: true
|
|
1236
|
+
}))
|
|
1237
|
+
] : [];
|
|
1238
|
+
const kinds = [
|
|
1239
|
+
...new Set([
|
|
1240
|
+
...Object.keys(kindTitles),
|
|
1241
|
+
...items.map((x)=>x.module.kind)
|
|
1242
|
+
])
|
|
1243
|
+
];
|
|
1244
|
+
return [
|
|
1245
|
+
...suggestedChoices,
|
|
1246
|
+
...kinds.flatMap((kind)=>{
|
|
1247
|
+
const group = items.filter((x)=>x.module.kind === kind && !suggested.includes(x));
|
|
1248
|
+
return group.length ? [
|
|
1249
|
+
new Separator(`── ${kindTitles[kind] ?? kind}`),
|
|
1250
|
+
...group.map((x)=>({
|
|
1251
|
+
name: x.label,
|
|
1252
|
+
value: x
|
|
1253
|
+
}))
|
|
1254
|
+
] : [];
|
|
1255
|
+
})
|
|
1256
|
+
];
|
|
1856
1257
|
};
|
|
1857
|
-
const
|
|
1858
|
-
|
|
1859
|
-
const
|
|
1860
|
-
|
|
1258
|
+
const groupedPageSize = 20;
|
|
1259
|
+
const dependencyOptions = (boundedContextFolder)=>{
|
|
1260
|
+
const sharedFolder = new Folder(new ProjectRoot().path).subitem([
|
|
1261
|
+
ConfigFile.Instance.data.project.rootFolder,
|
|
1262
|
+
'shared-kernel'
|
|
1263
|
+
]);
|
|
1264
|
+
const isShared = sharedFolder.path === boundedContextFolder.path;
|
|
1265
|
+
const contextsFolder = new Folder(new ProjectRoot().path).subitem([
|
|
1266
|
+
ConfigFile.Instance.data.project.rootFolder,
|
|
1267
|
+
'bounded-contexts'
|
|
1268
|
+
]);
|
|
1269
|
+
return [
|
|
1270
|
+
...findWiredModules(boundedContextFolder.path).map((x)=>({
|
|
1271
|
+
module: x,
|
|
1272
|
+
label: x.typeName
|
|
1273
|
+
})),
|
|
1274
|
+
...isShared ? [] : findWiredModules(sharedFolder.path).map((x)=>({
|
|
1275
|
+
module: x,
|
|
1276
|
+
label: `${x.typeName} (shared-kernel)`
|
|
1277
|
+
})),
|
|
1278
|
+
...isShared ? [] : contextsFolder.content.subfolderNames.filter((name)=>name !== boundedContextFolder.name).sort().flatMap((name)=>findWiredModules(contextsFolder.subitem([
|
|
1279
|
+
name
|
|
1280
|
+
]).path).map((module)=>({
|
|
1281
|
+
module,
|
|
1282
|
+
label: `${module.typeName} (${name})`
|
|
1283
|
+
})))
|
|
1284
|
+
];
|
|
1285
|
+
};
|
|
1286
|
+
const promptDependencies = async (boundedContextFolder, consumer, implementations = consumer.implementations, customWiring)=>{
|
|
1287
|
+
const options = dependencyOptions(boundedContextFolder);
|
|
1288
|
+
let asked = false;
|
|
1289
|
+
for (const implementation of implementations){
|
|
1290
|
+
const available = availableDependencies(consumer, implementation, options.map((x)=>x.module));
|
|
1291
|
+
const candidates = options.filter((x)=>available.includes(x.module));
|
|
1292
|
+
if (!candidates.length) continue;
|
|
1293
|
+
asked = true;
|
|
1294
|
+
const type = wiring_implementationType(consumer, implementation);
|
|
1295
|
+
const suggested = type ? candidates.filter((x)=>isSuggestedFor(x.module, type)) : [];
|
|
1296
|
+
const dependencies = await interaction_checkbox({
|
|
1297
|
+
key: `dependencies.${implementation.className}`,
|
|
1298
|
+
id: (value)=>moduleId(value.module),
|
|
1299
|
+
message: consumer.branched ? `Dependencies for ${implementation.className}:` : 'Dependencies:',
|
|
1300
|
+
choices: groupedChoices(candidates, suggested),
|
|
1301
|
+
pageSize: groupedPageSize,
|
|
1302
|
+
loop: false
|
|
1303
|
+
});
|
|
1304
|
+
const defaultWired = dependencies.map((x)=>x.module).filter((x)=>!customWiring?.(implementation, x));
|
|
1305
|
+
if (defaultWired.length) wireDependencies(consumer, implementation, defaultWired);
|
|
1306
|
+
}
|
|
1307
|
+
return asked;
|
|
1308
|
+
};
|
|
1309
|
+
const wireNewModuleDependencies = async (boundedContextFolder, wireFile, customWiring)=>{
|
|
1310
|
+
const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
|
|
1311
|
+
if (consumer) await promptDependencies(boundedContextFolder, consumer, consumer.implementations, customWiring);
|
|
1312
|
+
};
|
|
1313
|
+
const wireNewImplementationDependencies = async (boundedContextFolder, wireFile, className, customWiring)=>{
|
|
1314
|
+
const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
|
|
1315
|
+
const implementation = consumer?.implementations.find((x)=>x.className === className);
|
|
1316
|
+
if (consumer && implementation) await promptDependencies(boundedContextFolder, consumer, [
|
|
1317
|
+
implementation
|
|
1318
|
+
], customWiring);
|
|
1319
|
+
};
|
|
1320
|
+
const wireDependency = async (boundedContextFolder)=>{
|
|
1321
|
+
const modules = findWiredModules(boundedContextFolder.path);
|
|
1322
|
+
if (!modules.length) return void report('No wired modules here yet.');
|
|
1323
|
+
const { module: consumer, implementation } = await interaction_select({
|
|
1324
|
+
key: 'module',
|
|
1325
|
+
id: (value)=>`${moduleId(value.module)}:${value.implementation.className}`,
|
|
1326
|
+
message: 'Module:',
|
|
1327
|
+
choices: groupedChoices(modules.flatMap((x)=>x.implementations.map((implementation)=>{
|
|
1328
|
+
const type = wiring_implementationType(x, implementation);
|
|
1329
|
+
return {
|
|
1330
|
+
module: x,
|
|
1331
|
+
label: type ? `${x.typeName} (${type})` : x.typeName,
|
|
1332
|
+
implementation
|
|
1333
|
+
};
|
|
1334
|
+
}))),
|
|
1335
|
+
pageSize: groupedPageSize,
|
|
1336
|
+
loop: false
|
|
1861
1337
|
});
|
|
1862
|
-
if (
|
|
1863
|
-
|
|
1338
|
+
if (!await promptDependencies(boundedContextFolder, consumer, [
|
|
1339
|
+
implementation
|
|
1340
|
+
])) report('No dependencies available for this module.');
|
|
1341
|
+
};
|
|
1342
|
+
const promptEndpointHandler = async (boundedContextFolder)=>{
|
|
1343
|
+
const handlers = findWiredModules(boundedContextFolder.path).filter((x)=>[
|
|
1344
|
+
'queries',
|
|
1345
|
+
'commands',
|
|
1346
|
+
'use-cases'
|
|
1347
|
+
].includes(x.kind)).map((x)=>({
|
|
1348
|
+
module: x,
|
|
1349
|
+
label: x.typeName
|
|
1350
|
+
}));
|
|
1351
|
+
return handlers.length ? (await interaction_select({
|
|
1352
|
+
key: 'handler',
|
|
1353
|
+
id: (value)=>moduleId(value.module),
|
|
1354
|
+
message: 'Handler:',
|
|
1355
|
+
choices: groupedChoices(handlers),
|
|
1356
|
+
pageSize: groupedPageSize,
|
|
1357
|
+
loop: false
|
|
1358
|
+
})).module : void 0;
|
|
1359
|
+
};
|
|
1360
|
+
const createPresentationService = (boundedContextFolder, name, classFile)=>{
|
|
1361
|
+
const naming = new UnknownFormatNaming(name);
|
|
1362
|
+
const className = `${naming.ClassName}PresentationService`;
|
|
1363
|
+
const scaffoldUnitTests = Boolean(ConfigFile.backend.testingLibrary);
|
|
1364
|
+
const withWiring = ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
|
|
1365
|
+
const wiringFolder = boundedContextFolder.subitem([
|
|
1366
|
+
'wiring',
|
|
1367
|
+
'presentation-services'
|
|
1368
|
+
]);
|
|
1369
|
+
const presentationServicesFolder = boundedContextFolder.subitem([
|
|
1370
|
+
'presentation',
|
|
1371
|
+
'services'
|
|
1372
|
+
]);
|
|
1373
|
+
presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.ts`, classFile?.(className) ?? `
|
|
1374
|
+
export class ${className} {
|
|
1375
|
+
|
|
1376
|
+
}
|
|
1377
|
+
`.trim());
|
|
1378
|
+
if (scaffoldUnitTests) presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.spec.ts`, `
|
|
1379
|
+
import { describe, test, expect, beforeEach } from '${ConfigFile.backend.testingLibrary}'
|
|
1380
|
+
${withWiring ? `import { type ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'
|
|
1381
|
+
import { wire${naming.ClassName}PresentationService } from '../../wiring/presentation-services/wire-${naming.fileName}-presentation-service'` : `import { ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'`}
|
|
1382
|
+
|
|
1383
|
+
let ${naming.variableName}PresentationService: ${naming.ClassName}PresentationService
|
|
1384
|
+
|
|
1385
|
+
beforeEach(() => {
|
|
1386
|
+
${naming.variableName}PresentationService = ${withWiring ? `wire${naming.ClassName}PresentationService()` : `new ${naming.ClassName}PresentationService()`}
|
|
1387
|
+
})
|
|
1388
|
+
|
|
1389
|
+
describe('${naming.withSpaces}', () => {
|
|
1390
|
+
test('can be ${withWiring ? 'wired' : 'created'}', () => {
|
|
1391
|
+
expect(${naming.variableName}PresentationService).toBeDefined()
|
|
1392
|
+
})
|
|
1393
|
+
})
|
|
1394
|
+
`.trim());
|
|
1395
|
+
if (withWiring) return wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
|
|
1396
|
+
import { wireClass } from '@domain-first/wire'
|
|
1397
|
+
import { ${naming.ClassName}PresentationService } from '../../presentation/services/${naming.fileName}-presentation-service'
|
|
1398
|
+
|
|
1399
|
+
export const wire${naming.ClassName}PresentationService = wireClass(
|
|
1400
|
+
${naming.ClassName}PresentationService,
|
|
1401
|
+
[]
|
|
1402
|
+
)
|
|
1403
|
+
`.trim());
|
|
1404
|
+
};
|
|
1405
|
+
const scaffoldNewPresentationService = async (boundedContextFolder)=>{
|
|
1406
|
+
const name = await interaction_input({
|
|
1407
|
+
key: 'name',
|
|
1408
|
+
message: 'Name: '
|
|
1864
1409
|
});
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1410
|
+
const wireFile = createPresentationService(boundedContextFolder, name);
|
|
1411
|
+
if (wireFile) await wireNewModuleDependencies(boundedContextFolder, wireFile);
|
|
1412
|
+
};
|
|
1413
|
+
const rest_endpoint_generator_name = 'rest-endpoint-generator';
|
|
1414
|
+
const scaffoldRestEndpointGenerator = (sharedFolder, { withNextAdapter = false } = {})=>createPresentationService(sharedFolder, rest_endpoint_generator_name, (className)=>{
|
|
1415
|
+
const adapter = withNextAdapter ? 'nextAdapter' : 'adapter';
|
|
1416
|
+
return `
|
|
1417
|
+
import {
|
|
1418
|
+
${withNextAdapter ? '' : ' type Adapter,\n'} type EndpointGenerator,
|
|
1419
|
+
createEndpoint,
|
|
1420
|
+
invalidRequest
|
|
1421
|
+
} from '@domain-first/handlers-rest'
|
|
1422
|
+
${withNextAdapter ? "import { nextAdapter } from '@domain-first/handlers-next'" : `
|
|
1423
|
+
/**
|
|
1424
|
+
* The adapter of your HTTP framework.
|
|
1425
|
+
*/
|
|
1426
|
+
const adapter = undefined as unknown as Adapter<any[], any>`}
|
|
1427
|
+
|
|
1428
|
+
export class ${className} {
|
|
1429
|
+
get withoutGuards(): EndpointGenerator {
|
|
1430
|
+
return createEndpoint({
|
|
1431
|
+
errors: [invalidRequest()]
|
|
1432
|
+
})(${adapter}) as EndpointGenerator
|
|
1879
1433
|
}
|
|
1880
|
-
|
|
1881
|
-
|
|
1434
|
+
}
|
|
1435
|
+
`.trim();
|
|
1436
|
+
});
|
|
1437
|
+
const findRestEndpointGenerator = (sharedFolder)=>{
|
|
1438
|
+
const typeFile = node_path.join(sharedFolder.path, 'presentation', 'services', `${rest_endpoint_generator_name}-presentation-service.ts`);
|
|
1439
|
+
if (!new File(typeFile).exists) return;
|
|
1440
|
+
return {
|
|
1441
|
+
typeName: 'RestEndpointGeneratorPresentationService',
|
|
1442
|
+
typeFile,
|
|
1443
|
+
wireName: 'wireRestEndpointGeneratorPresentationService',
|
|
1444
|
+
wireFile: node_path.join(sharedFolder.path, 'wiring', 'presentation-services', `wire-${rest_endpoint_generator_name}-presentation-service.ts`)
|
|
1445
|
+
};
|
|
1882
1446
|
};
|
|
1883
|
-
const
|
|
1884
|
-
const
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
const
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
{
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1447
|
+
const nextRoutePath = (root)=>node_path.posix.join(nextAppFolder(root), 'api/[...path]/route.ts');
|
|
1448
|
+
const nextRoute = (restHandlersImport)=>`
|
|
1449
|
+
import { nextEndpoints } from '@domain-first/handlers-next'
|
|
1450
|
+
${restHandlersImport ? `import { restHandlers } from '${restHandlersImport}'
|
|
1451
|
+
|
|
1452
|
+
const handler = nextEndpoints(restHandlers)` : `
|
|
1453
|
+
/**
|
|
1454
|
+
* Pass the endpoints' handle here; their paths are relative to this route's folder.
|
|
1455
|
+
*/
|
|
1456
|
+
const handler = nextEndpoints([])`}
|
|
1457
|
+
|
|
1458
|
+
export const GET = handler
|
|
1459
|
+
export const POST = handler
|
|
1460
|
+
export const PUT = handler
|
|
1461
|
+
export const PATCH = handler
|
|
1462
|
+
export const DELETE = handler
|
|
1463
|
+
`.trim();
|
|
1464
|
+
const rest_endpoint_generator_scaffoldNextRoute = (root)=>{
|
|
1465
|
+
const { rootFolder } = ConfigFile.Instance.data.project;
|
|
1466
|
+
const { domainFirstPackages } = ConfigFile.backend;
|
|
1467
|
+
const routePath = nextRoutePath(root);
|
|
1468
|
+
const routeFile = node_path.join(root, routePath);
|
|
1469
|
+
if (new File(routeFile).exists) return [];
|
|
1470
|
+
if (!domainFirstPackages.includes('@domain-first/wire')) {
|
|
1471
|
+
new File(routeFile).data = nextRoute(void 0);
|
|
1472
|
+
return [];
|
|
1473
|
+
}
|
|
1474
|
+
const restFolder = new Folder(root).subitem([
|
|
1475
|
+
rootFolder,
|
|
1476
|
+
'presentation',
|
|
1477
|
+
'rest'
|
|
1478
|
+
]);
|
|
1479
|
+
new File(routeFile).data = nextRoute(relativeImport(routeFile, restFolder.path));
|
|
1480
|
+
return new File(node_path.join(restFolder.path, 'index.ts')).exists ? [] : [
|
|
1481
|
+
`${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`
|
|
1482
|
+
];
|
|
1483
|
+
};
|
|
1484
|
+
const askNextAdapter = async ({ nextSelected } = {})=>(nextSelected ?? usesNext()) && await interaction_confirm({
|
|
1485
|
+
key: 'nextAdapter',
|
|
1486
|
+
message: 'Use @domain-first/handlers-next for REST endpoints'
|
|
1487
|
+
});
|
|
1488
|
+
const scaffoldRestEndpointGeneratorFiles = ({ withNextAdapter })=>{
|
|
1489
|
+
const root = new ProjectRoot().path;
|
|
1490
|
+
const generatorExisted = restEndpointGeneratorApplied();
|
|
1491
|
+
const routeNotes = withoutOverwrites(()=>{
|
|
1492
|
+
scaffoldRestEndpointGenerator(new Folder(root).subitem([
|
|
1493
|
+
ConfigFile.Instance.data.project.rootFolder,
|
|
1494
|
+
'shared-kernel'
|
|
1495
|
+
]), {
|
|
1496
|
+
withNextAdapter
|
|
1497
|
+
});
|
|
1498
|
+
return withNextAdapter ? rest_endpoint_generator_scaffoldNextRoute(root) : [];
|
|
1499
|
+
});
|
|
1500
|
+
if (!withNextAdapter) return [];
|
|
1501
|
+
return [
|
|
1502
|
+
...missingPackages([
|
|
1503
|
+
'@domain-first/handlers-next'
|
|
1504
|
+
]),
|
|
1505
|
+
...routeNotes,
|
|
1506
|
+
...generatorExisted ? [
|
|
1507
|
+
'the existing endpoint generator was kept — pass nextAdapter from @domain-first/handlers-next to its createEndpoint calls'
|
|
1508
|
+
] : []
|
|
1509
|
+
];
|
|
1510
|
+
};
|
|
1511
|
+
const addRestEndpointGenerator = async ()=>scaffoldRestEndpointGeneratorFiles({
|
|
1512
|
+
withNextAdapter: await askNextAdapter()
|
|
1513
|
+
});
|
|
1514
|
+
const restEndpointGeneratorApplied = ()=>Boolean(findRestEndpointGenerator(new Folder(new ProjectRoot().path).subitem([
|
|
1515
|
+
ConfigFile.Instance.data.project.rootFolder,
|
|
1516
|
+
'shared-kernel'
|
|
1517
|
+
])));
|
|
1518
|
+
const storybookFrameworkPackage = '@storybook/react-vite';
|
|
1519
|
+
const storybookFiles = (relativeProjectRoot)=>({
|
|
1520
|
+
'main.ts': `import { resolve } from 'node:path';
|
|
1521
|
+
import react from '@vitejs/plugin-react';
|
|
1522
|
+
import type { StorybookConfig } from '${storybookFrameworkPackage}';
|
|
1523
|
+
|
|
1524
|
+
const projectRoot = resolve(import.meta.dirname, ${JSON.stringify(relativeProjectRoot)});
|
|
1525
|
+
|
|
1526
|
+
const config: StorybookConfig = {
|
|
1527
|
+
stories: ['../**/*.mdx', '../**/*.stories.@(ts|tsx)'],
|
|
1528
|
+
framework: {
|
|
1529
|
+
name: '${storybookFrameworkPackage}',
|
|
1530
|
+
options: {}
|
|
1947
1531
|
},
|
|
1948
|
-
{
|
|
1949
|
-
|
|
1950
|
-
name: 'OpenAPI',
|
|
1951
|
-
group: 'backend',
|
|
1952
|
-
run: addOpenapi,
|
|
1953
|
-
available: ()=>withHandlersRest(),
|
|
1954
|
-
applied: ()=>created(openapiScriptPath)
|
|
1532
|
+
core: {
|
|
1533
|
+
disableTelemetry: true
|
|
1955
1534
|
},
|
|
1956
|
-
{
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1535
|
+
async viteFinal(viteConfig) {
|
|
1536
|
+
const { mergeConfig } = await import('vite');
|
|
1537
|
+
|
|
1538
|
+
return mergeConfig(viteConfig, {
|
|
1539
|
+
plugins: [react()],
|
|
1540
|
+
resolve: {
|
|
1541
|
+
alias: {
|
|
1542
|
+
'@': projectRoot
|
|
1543
|
+
}
|
|
1544
|
+
}
|
|
1545
|
+
});
|
|
1963
1546
|
}
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1547
|
+
};
|
|
1548
|
+
|
|
1549
|
+
export default config;
|
|
1550
|
+
`,
|
|
1551
|
+
'preview.ts': `import type { Preview } from '${storybookFrameworkPackage}';
|
|
1552
|
+
|
|
1553
|
+
const preview: Preview = {
|
|
1554
|
+
parameters: {
|
|
1555
|
+
controls: {
|
|
1556
|
+
matchers: {
|
|
1557
|
+
color: /(background|color)$/i,
|
|
1558
|
+
date: /Date$/i
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
};
|
|
1563
|
+
|
|
1564
|
+
export default preview;
|
|
1565
|
+
`
|
|
1566
|
+
});
|
|
1567
|
+
const storybookScripts = (rootFolder)=>{
|
|
1568
|
+
const folder = node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react');
|
|
1569
|
+
const quote = (value)=>JSON.stringify(value);
|
|
1570
|
+
return {
|
|
1571
|
+
storybook: `storybook dev -p 6006 -c ${quote(`${folder}/.storybook`)}`,
|
|
1572
|
+
'build-storybook': `storybook build -c ${quote(`${folder}/.storybook`)} -o ${quote(`${folder}/storybook-static`)}`
|
|
1982
1573
|
};
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1574
|
+
};
|
|
1575
|
+
const addStorybook = async ()=>{
|
|
1576
|
+
const config = ConfigFile.Instance.data;
|
|
1577
|
+
if ((!config.frontend?.react || config.frontend?.react?.storybookFramework && config.frontend?.react?.storybookFramework !== storybookFrameworkPackage) && !await interaction_confirm({
|
|
1578
|
+
key: 'configureReact',
|
|
1579
|
+
requestRequired: true,
|
|
1580
|
+
message: `Configure React scaffolding with ${storybookFrameworkPackage}?`,
|
|
1581
|
+
default: false
|
|
1582
|
+
})) return [];
|
|
1583
|
+
const root = new ProjectRoot().path;
|
|
1584
|
+
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
1585
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
1586
|
+
const selected = await addPackageScripts(manifestFile, storybookScripts(config.project.rootFolder));
|
|
1587
|
+
const folder = new Folder(root).subitem([
|
|
1588
|
+
config.project.rootFolder,
|
|
1589
|
+
'presentation',
|
|
1590
|
+
'react',
|
|
1591
|
+
'.storybook'
|
|
1592
|
+
]);
|
|
1593
|
+
for (const [name, content] of Object.entries(storybookFiles(node_path.relative(folder.path, root).split(node_path.sep).join('/')))){
|
|
1594
|
+
const file = new File(node_path.join(folder.path, name));
|
|
1595
|
+
if (!file.exists || file.data !== content) file.data = content;
|
|
1596
|
+
}
|
|
1597
|
+
if (!config.frontend?.react || config.frontend?.react?.storybookFramework !== storybookFrameworkPackage) ConfigFile.update({
|
|
1598
|
+
frontend: {
|
|
1599
|
+
...config.frontend,
|
|
1600
|
+
react: {
|
|
1601
|
+
...config.frontend?.react,
|
|
1602
|
+
storybookFramework: storybookFrameworkPackage
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
});
|
|
1606
|
+
const buildFolder = node_path.posix.join(config.project.rootFolder.replaceAll('\\', '/'), 'presentation/react/storybook-static');
|
|
1607
|
+
addGitignoreEntry(root, `/${buildFolder}/`);
|
|
1608
|
+
const dependencies = {
|
|
1609
|
+
...manifest.dependencies,
|
|
1610
|
+
...manifest.devDependencies
|
|
1611
|
+
};
|
|
1612
|
+
const missing = [
|
|
1613
|
+
'storybook',
|
|
1614
|
+
storybookFrameworkPackage,
|
|
1615
|
+
'vite',
|
|
1616
|
+
'@vitejs/plugin-react'
|
|
1617
|
+
].filter((name)=>!dependencies[name]);
|
|
1618
|
+
const missingReact = [
|
|
1619
|
+
'react',
|
|
1620
|
+
'react-dom'
|
|
1621
|
+
].filter((name)=>!dependencies[name]);
|
|
1622
|
+
return [
|
|
1623
|
+
...missing.length ? [
|
|
1624
|
+
`npm install --save-dev ${missing.join(' ')}`
|
|
1625
|
+
] : [],
|
|
1626
|
+
...missingReact.length ? [
|
|
1627
|
+
`npm install ${missingReact.join(' ')}`
|
|
1628
|
+
] : [],
|
|
1629
|
+
...describeScripts(selected, {
|
|
1630
|
+
storybook: 'start Storybook on http://localhost:6006',
|
|
1631
|
+
'build-storybook': `build static Storybook into ${buildFolder}`
|
|
1632
|
+
})
|
|
1986
1633
|
];
|
|
1987
|
-
const selected = await interaction_checkbox({
|
|
1988
|
-
key: 'integrations',
|
|
1989
|
-
id: (integration)=>integration.id,
|
|
1990
|
-
message: 'Integrations:',
|
|
1991
|
-
choices,
|
|
1992
|
-
pageSize: choices.length
|
|
1993
|
-
});
|
|
1994
|
-
const nextSteps = [];
|
|
1995
|
-
for (const integration of integrations.filter((value)=>selected.includes(value)))nextSteps.push(...await integration.run());
|
|
1996
|
-
if (save && await savePendingChanges()) printNextSteps(nextSteps);
|
|
1997
|
-
return nextSteps;
|
|
1998
1634
|
};
|
|
1999
|
-
const integrationDescriptions = ()=>integrations.map((integration)=>({
|
|
2000
|
-
id: integration.id,
|
|
2001
|
-
name: integration.name,
|
|
2002
|
-
group: integration.group,
|
|
2003
|
-
available: ('backend' !== integration.group || Boolean(ConfigFile.Instance.data.backend)) && (integration.available?.() ?? true)
|
|
2004
|
-
}));
|
|
2005
1635
|
const serviceLayout = (layer)=>({
|
|
2006
1636
|
title: `${layer[0].toUpperCase()}${layer.slice(1)} services`,
|
|
2007
1637
|
core: (ClassName)=>`${ClassName}${layer[0].toUpperCase()}${layer.slice(1)}Service`,
|
|
@@ -2099,6 +1729,38 @@ const kindLayouts = {
|
|
|
2099
1729
|
sharedKernel: true
|
|
2100
1730
|
}
|
|
2101
1731
|
};
|
|
1732
|
+
const integrationSpecsFolder = 'specs/integration';
|
|
1733
|
+
const projectRootOf = (folder)=>{
|
|
1734
|
+
let current = folder;
|
|
1735
|
+
while(true){
|
|
1736
|
+
if (node_fs.existsSync(node_path.join(current, 'package.json'))) return current;
|
|
1737
|
+
const parent = node_path.dirname(current);
|
|
1738
|
+
if (parent === current) return;
|
|
1739
|
+
current = parent;
|
|
1740
|
+
}
|
|
1741
|
+
};
|
|
1742
|
+
const integrationSpecFile = (unit, label)=>{
|
|
1743
|
+
const layout = kindLayouts[unit.kind];
|
|
1744
|
+
const place = {
|
|
1745
|
+
ownerPath: unit.ownerPath,
|
|
1746
|
+
name: unit.name
|
|
1747
|
+
};
|
|
1748
|
+
const source = void 0 === label ? 'infrastructure-service' === unit.kind ? layout.files(place, [])[0] : void 0 : layout.implementations ? layout.files(place, [
|
|
1749
|
+
label
|
|
1750
|
+
]).find((file)=>file.startsWith(`${layout.implementations}/${label}/`)) : void 0;
|
|
1751
|
+
const projectRoot = projectRootOf(unit.ownerPath);
|
|
1752
|
+
if (!source || !projectRoot) return;
|
|
1753
|
+
return node_path.join(projectRoot, integrationSpecsFolder, node_path.basename(unit.ownerPath), source.slice(15).replace(/\.ts$/, '.spec.ts'));
|
|
1754
|
+
};
|
|
1755
|
+
const integrationSpecSubjects = (unit)=>'infrastructure-service' === unit.kind ? [
|
|
1756
|
+
void 0
|
|
1757
|
+
] : unit.labels;
|
|
1758
|
+
const integrationSpecsStop = (file)=>{
|
|
1759
|
+
const projectRoot = projectRootOf(node_path.dirname(file));
|
|
1760
|
+
if (!projectRoot) return;
|
|
1761
|
+
const folder = node_path.join(projectRoot, integrationSpecsFolder);
|
|
1762
|
+
return file.startsWith(`${folder}${node_path.sep}`) ? folder : void 0;
|
|
1763
|
+
};
|
|
2102
1764
|
const subfolders = (folder)=>node_fs.existsSync(folder) ? node_fs.readdirSync(folder, {
|
|
2103
1765
|
withFileTypes: true
|
|
2104
1766
|
}).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name).sort() : [];
|
|
@@ -2152,386 +1814,1093 @@ const unitMoves = (unit, target)=>{
|
|
|
2152
1814
|
const oldPath = node_path.join(unit.ownerPath, file);
|
|
2153
1815
|
if (node_fs.existsSync(oldPath)) moves.set(oldPath, node_path.join(target.ownerPath, to[index]));
|
|
2154
1816
|
});
|
|
1817
|
+
for (const label of integrationSpecSubjects(unit)){
|
|
1818
|
+
const oldSpec = integrationSpecFile(unit, label);
|
|
1819
|
+
const newSpec = integrationSpecFile({
|
|
1820
|
+
kind: unit.kind,
|
|
1821
|
+
name: target.name,
|
|
1822
|
+
ownerPath: target.ownerPath
|
|
1823
|
+
}, label);
|
|
1824
|
+
if (oldSpec && newSpec && node_fs.existsSync(oldSpec)) moves.set(oldSpec, newSpec);
|
|
1825
|
+
}
|
|
2155
1826
|
if ('aggregate' === unit.kind) {
|
|
2156
1827
|
const oldFolder = node_path.join(unit.ownerPath, 'domain/aggregates', unit.name);
|
|
2157
1828
|
const newFolder = node_path.join(target.ownerPath, 'domain/aggregates', target.name);
|
|
2158
1829
|
const own = new Set(aggregateOwnFiles(unit.name).map((file)=>node_path.join(oldFolder, file)));
|
|
2159
1830
|
for (const file of walk(oldFolder))if (!own.has(file)) moves.set(file, node_path.join(newFolder, node_path.relative(oldFolder, file)));
|
|
2160
1831
|
}
|
|
2161
|
-
return moves;
|
|
2162
|
-
};
|
|
2163
|
-
const validateBackendMove = (unit, target, sharedKernelPath)=>{
|
|
2164
|
-
if (!kebabName.test(target.name)) return 'Use kebab-case: lowercase words split by "-", e.g. place-order';
|
|
2165
|
-
if (target.ownerPath === sharedKernelPath && !kindLayouts[unit.kind].sharedKernel) return `${kindLayouts[unit.kind].title} are not part of the Shared Kernel`;
|
|
2166
|
-
if (target.ownerPath === unit.ownerPath && target.name === unit.name && target.aggregate === unit.aggregate) return 'Nothing to change: enter a new name or pick another place';
|
|
2167
|
-
for (const [from, to] of unitMoves(unit, target))if (to !== from && node_fs.existsSync(to)) return `${node_path.relative(target.ownerPath, to)} already exists`;
|
|
2168
|
-
return true;
|
|
2169
|
-
};
|
|
2170
|
-
const ownerOf = (rootFolderPath, file)=>{
|
|
2171
|
-
const [area, context] = node_path.relative(rootFolderPath, file).split(node_path.sep);
|
|
2172
|
-
if ('bounded-contexts' === area && context) return {
|
|
2173
|
-
context,
|
|
2174
|
-
path: node_path.join(rootFolderPath, area, context)
|
|
1832
|
+
return moves;
|
|
1833
|
+
};
|
|
1834
|
+
const validateBackendMove = (unit, target, sharedKernelPath)=>{
|
|
1835
|
+
if (!kebabName.test(target.name)) return 'Use kebab-case: lowercase words split by "-", e.g. place-order';
|
|
1836
|
+
if (target.ownerPath === sharedKernelPath && !kindLayouts[unit.kind].sharedKernel) return `${kindLayouts[unit.kind].title} are not part of the Shared Kernel`;
|
|
1837
|
+
if (target.ownerPath === unit.ownerPath && target.name === unit.name && target.aggregate === unit.aggregate) return 'Nothing to change: enter a new name or pick another place';
|
|
1838
|
+
for (const [from, to] of unitMoves(unit, target))if (to !== from && node_fs.existsSync(to)) return `${node_path.relative(target.ownerPath, to)} already exists`;
|
|
1839
|
+
return true;
|
|
1840
|
+
};
|
|
1841
|
+
const ownerOf = (rootFolderPath, file)=>{
|
|
1842
|
+
const [area, context] = node_path.relative(rootFolderPath, file).split(node_path.sep);
|
|
1843
|
+
if ('bounded-contexts' === area && context) return {
|
|
1844
|
+
context,
|
|
1845
|
+
path: node_path.join(rootFolderPath, area, context)
|
|
1846
|
+
};
|
|
1847
|
+
if ('shared-kernel' === area) return {
|
|
1848
|
+
context: void 0,
|
|
1849
|
+
path: node_path.join(rootFolderPath, area)
|
|
1850
|
+
};
|
|
1851
|
+
};
|
|
1852
|
+
const inMemoryDbFile = (rootFolderPath)=>node_path.join(rootFolderPath, 'shared-kernel/infrastructure/services/in-memory-db-infrastructure-service.ts');
|
|
1853
|
+
const isolationAllows = (rootFolderPath, from, to)=>{
|
|
1854
|
+
const fromOwner = ownerOf(rootFolderPath, from);
|
|
1855
|
+
const toOwner = ownerOf(rootFolderPath, to);
|
|
1856
|
+
if (!fromOwner || !toOwner?.context) return true;
|
|
1857
|
+
if (fromOwner.context) return fromOwner.context === toOwner.context || true === crossContextImportAllowed(from, to);
|
|
1858
|
+
const inside = (folder)=>to === node_path.join(toOwner.path, folder) || to.startsWith(node_path.join(toOwner.path, folder) + node_path.sep);
|
|
1859
|
+
return inside('domain/errors') || from.replace(codeExtension, '') === inMemoryDbFile(rootFolderPath).replace(codeExtension, '') && inside('domain');
|
|
1860
|
+
};
|
|
1861
|
+
const moveBackendUnit = (projectRoot, rootFolderPath, unit, target)=>{
|
|
1862
|
+
const layout = kindLayouts[unit.kind];
|
|
1863
|
+
const moves = unitMoves(unit, target);
|
|
1864
|
+
const withoutExtension = new Map([
|
|
1865
|
+
...moves
|
|
1866
|
+
].map(([from, to])=>[
|
|
1867
|
+
from.replace(codeExtension, ''),
|
|
1868
|
+
to.replace(codeExtension, '')
|
|
1869
|
+
]));
|
|
1870
|
+
const folders = 'aggregate' === unit.kind ? [
|
|
1871
|
+
[
|
|
1872
|
+
node_path.join(unit.ownerPath, 'domain/aggregates', unit.name),
|
|
1873
|
+
node_path.join(target.ownerPath, 'domain/aggregates', target.name)
|
|
1874
|
+
]
|
|
1875
|
+
] : [];
|
|
1876
|
+
const movedPath = (candidate)=>{
|
|
1877
|
+
const extension = candidate.match(codeExtension)?.[0];
|
|
1878
|
+
if (extension) return moves.get(candidate);
|
|
1879
|
+
return withoutExtension.get(candidate) ?? folders.find(([from])=>from === candidate)?.[1];
|
|
1880
|
+
};
|
|
1881
|
+
const { codeFiles, importsOf, resolve } = projectImports(projectRoot);
|
|
1882
|
+
const oldNaming = new UnknownFormatNaming(unit.name);
|
|
1883
|
+
const newNaming = new UnknownFormatNaming(target.name);
|
|
1884
|
+
const leavesAggregate = !!unit.aggregate && (unit.aggregate !== target.aggregate || unit.ownerPath !== target.ownerPath);
|
|
1885
|
+
const oldAggregateFolder = unit.aggregate && node_path.join(unit.ownerPath, 'domain/aggregates', unit.aggregate);
|
|
1886
|
+
const isOldBarrel = (resolved)=>!!oldAggregateFolder && (resolved === oldAggregateFolder || resolved === node_path.join(oldAggregateFolder, 'index'));
|
|
1887
|
+
const mainFile = [
|
|
1888
|
+
...moves.keys()
|
|
1889
|
+
][0];
|
|
1890
|
+
const newMainFile = moves.get(mainFile);
|
|
1891
|
+
const namedImports = /import\s+(type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\3;?/g;
|
|
1892
|
+
const barrelImporters = leavesAggregate ? [
|
|
1893
|
+
...codeFiles
|
|
1894
|
+
].filter(([file, content])=>!moves.has(file) && [
|
|
1895
|
+
...content.matchAll(namedImports)
|
|
1896
|
+
].some(([, , names, , specifier])=>isOldBarrel(resolve(specifier, file)?.resolved) && new RegExp(`(?<![\\w$])${oldNaming.ClassName}(?![\\w$])`).test(names))) : [];
|
|
1897
|
+
const violations = [];
|
|
1898
|
+
const relative = (file)=>toPosix(node_path.relative(projectRoot, file));
|
|
1899
|
+
for (const file of codeFiles.keys()){
|
|
1900
|
+
const from = moves.get(file) ?? file;
|
|
1901
|
+
for (const imported of importsOf(file)){
|
|
1902
|
+
const to = movedPath(imported);
|
|
1903
|
+
if (moves.has(file) || to) {
|
|
1904
|
+
if (!isolationAllows(rootFolderPath, from, to ?? imported)) violations.push([
|
|
1905
|
+
relative(from),
|
|
1906
|
+
relative(to ?? imported)
|
|
1907
|
+
]);
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
for (const [file] of barrelImporters)if (!isolationAllows(rootFolderPath, file, newMainFile)) violations.push([
|
|
1912
|
+
relative(file),
|
|
1913
|
+
relative(newMainFile)
|
|
1914
|
+
]);
|
|
1915
|
+
if (violations.length) return {
|
|
1916
|
+
violations
|
|
1917
|
+
};
|
|
1918
|
+
const word = (form)=>`(?<![\\w$])${escapeRegExp(form)}(?![\\w$])`;
|
|
1919
|
+
const oldCore = layout.core(oldNaming.ClassName);
|
|
1920
|
+
const newCore = layout.core(newNaming.ClassName);
|
|
1921
|
+
const labelNames = unit.labels.map((label)=>new UnknownFormatNaming(label).ClassName);
|
|
1922
|
+
const prefixes = [
|
|
1923
|
+
...labelNames,
|
|
1924
|
+
...layout.wired ? [
|
|
1925
|
+
'wire',
|
|
1926
|
+
...labelNames.map((label)=>`wire${label}`)
|
|
1927
|
+
] : []
|
|
1928
|
+
];
|
|
1929
|
+
const renames = [
|
|
1930
|
+
{
|
|
1931
|
+
pattern: new RegExp(`(?<![\\w$])(${prefixes.map(escapeRegExp).join('|')})?${escapeRegExp(oldCore)}(?![\\w$])`, 'g'),
|
|
1932
|
+
to: `$1${newCore}`
|
|
1933
|
+
},
|
|
1934
|
+
{
|
|
1935
|
+
pattern: new RegExp(word(lowerFirst(oldCore)), 'g'),
|
|
1936
|
+
to: lowerFirst(newCore)
|
|
1937
|
+
},
|
|
1938
|
+
{
|
|
1939
|
+
pattern: new RegExp(`(describe\\(\\s*['"\`])${escapeRegExp(oldNaming.withSpaces)}(?=[ '"\`])`, 'g'),
|
|
1940
|
+
to: `$1${newNaming.withSpaces}`,
|
|
1941
|
+
movedOnly: true
|
|
1942
|
+
}
|
|
1943
|
+
];
|
|
1944
|
+
if ('aggregate' === unit.kind) renames.push({
|
|
1945
|
+
pattern: new RegExp(word(oldNaming.ClassName), 'g'),
|
|
1946
|
+
to: newNaming.ClassName
|
|
1947
|
+
}, {
|
|
1948
|
+
pattern: new RegExp(word(oldNaming.variableName), 'g'),
|
|
1949
|
+
to: newNaming.variableName,
|
|
1950
|
+
movedOnly: true
|
|
1951
|
+
});
|
|
1952
|
+
if ('entity' === unit.kind || 'value-object' === unit.kind) renames.push({
|
|
1953
|
+
pattern: new RegExp(word(oldNaming.variableName), 'g'),
|
|
1954
|
+
to: newNaming.variableName,
|
|
1955
|
+
movedOnly: true
|
|
1956
|
+
});
|
|
1957
|
+
const oldSection = new UnknownFormatNaming(plural(unit.name));
|
|
1958
|
+
const newSection = new UnknownFormatNaming(plural(target.name));
|
|
1959
|
+
const renamesSection = 'aggregate' === unit.kind && unit.name !== target.name;
|
|
1960
|
+
const everyFile = (content)=>renamesSection ? content.replace(new RegExp(`(InMemoryDbInfrastructureService\\[\\s*['"])${oldSection.variableName}(?=['"]\\s*\\])`, 'g'), `$1${newSection.variableName}`).replace(new RegExp(`(inMemoryDbInfrastructureService\\s*\\.\\s*)${oldSection.variableName}(?![\\w$])`, 'g'), `$1${newSection.variableName}`).replace(new RegExp(`(?<![\\w$.])${oldSection.variableName}(\\s*=\\s*this\\.section<[^>]*>\\(\\s*['"])${oldSection.fileName.toUpperCase()}(?=['"])`, 'g'), `${newSection.variableName}$1${newSection.fileName.toUpperCase()}`) : content;
|
|
1961
|
+
const plan = stageModuleMove({
|
|
1962
|
+
projectRoot,
|
|
1963
|
+
stopAt: rootFolderPath,
|
|
1964
|
+
stopAtFor: integrationSpecsStop,
|
|
1965
|
+
moves,
|
|
1966
|
+
movedPath,
|
|
1967
|
+
rename: (content, { moved })=>renames.reduce((result, { pattern, to, movedOnly })=>movedOnly && !moved ? result : result.replace(pattern, to), content),
|
|
1968
|
+
everyFile
|
|
1969
|
+
});
|
|
1970
|
+
if (leavesAggregate && oldAggregateFolder) {
|
|
1971
|
+
const indexFile = new File(node_path.join(oldAggregateFolder, 'index.ts'));
|
|
1972
|
+
const exportLine = /^export\s+\*\s+from\s+(['"])([^'"\n]+)\1;?\s*$/;
|
|
1973
|
+
indexFile.update(indexFile.data.split('\n').filter((line)=>{
|
|
1974
|
+
const specifier = line.match(exportLine)?.[2];
|
|
1975
|
+
return !specifier || node_path.resolve(node_path.dirname(indexFile.path), specifier) !== newMainFile.replace(codeExtension, '');
|
|
1976
|
+
}).join('\n'));
|
|
1977
|
+
if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
|
|
1978
|
+
for (const [file] of barrelImporters){
|
|
1979
|
+
const importer = new File(file);
|
|
1980
|
+
let content = importer.data;
|
|
1981
|
+
for (const match of content.matchAll(namedImports)){
|
|
1982
|
+
const [statement, typeOnly = '', names, quote, specifier] = match;
|
|
1983
|
+
if (!isOldBarrel(resolve(specifier, file)?.resolved)) continue;
|
|
1984
|
+
const items = names.split(',').map((item)=>item.trim()).filter((item)=>!!item);
|
|
1985
|
+
const own = new RegExp(`^(?:type\\s+)?${newNaming.ClassName}(?:\\s+as\\s+[\\w$]+)?$`);
|
|
1986
|
+
const moved = items.filter((item)=>own.test(item));
|
|
1987
|
+
if (!moved.length) continue;
|
|
1988
|
+
const rest = items.filter((item)=>!own.test(item));
|
|
1989
|
+
const direct = `import ${typeOnly}{ ${moved.join(', ')} } from ${quote}${projectRelative(file, newMainFile)}${quote}`;
|
|
1990
|
+
content = content.replace(statement, rest.length ? `import ${typeOnly}{ ${rest.join(', ')} } from ${quote}${specifier}${quote}\n${direct}` : direct);
|
|
1991
|
+
}
|
|
1992
|
+
importer.update(content);
|
|
1993
|
+
}
|
|
1994
|
+
}
|
|
1995
|
+
if (target.aggregate && (target.aggregate !== unit.aggregate || target.ownerPath !== unit.ownerPath)) {
|
|
1996
|
+
const kindFolder = 'entity' === unit.kind ? 'entities' : 'value-objects';
|
|
1997
|
+
const indexFile = new File(node_path.join(target.ownerPath, 'domain/aggregates', target.aggregate, 'index.ts'));
|
|
1998
|
+
indexFile.addLineIfMissing(`export * from './${kindFolder}/${target.name}.${unit.kind}'`);
|
|
1999
|
+
if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
|
|
2000
|
+
}
|
|
2001
|
+
return plan;
|
|
2002
|
+
};
|
|
2003
|
+
const projectRelative = (fromFile, toFile)=>{
|
|
2004
|
+
const relative = toPosix(node_path.relative(node_path.dirname(fromFile), toFile.replace(codeExtension, '')));
|
|
2005
|
+
return relative.startsWith('.') ? relative : `./${relative}`;
|
|
2006
|
+
};
|
|
2007
|
+
const importSpecifier = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|\bimport\s+)(['"])([^'"\n]+)\1/g;
|
|
2008
|
+
const importLine = /^\s*(?:import|export)\b[^'"\n]*\bfrom\s*(['"])([^'"\n]+)\1;?\s*$/;
|
|
2009
|
+
const deleteBackendUnit = (projectRoot, rootFolderPath, unit)=>{
|
|
2010
|
+
const files = [
|
|
2011
|
+
...unitMoves(unit, unit).keys()
|
|
2012
|
+
];
|
|
2013
|
+
const fileSet = new Set(files);
|
|
2014
|
+
const stems = new Set(files.map((file)=>file.replace(codeExtension, '')));
|
|
2015
|
+
const aggregateFolder = 'aggregate' === unit.kind ? node_path.join(unit.ownerPath, 'domain/aggregates', unit.name) : void 0;
|
|
2016
|
+
const parentAggregate = unit.aggregate ? node_path.join(unit.ownerPath, 'domain/aggregates', unit.aggregate) : void 0;
|
|
2017
|
+
const isUnit = (resolved)=>stems.has(resolved) || !!aggregateFolder && (resolved === aggregateFolder || resolved.startsWith(`${aggregateFolder}${node_path.sep}`));
|
|
2018
|
+
const isParentBarrel = (resolved)=>!!parentAggregate && (resolved === parentAggregate || resolved === node_path.join(parentAggregate, 'index'));
|
|
2019
|
+
const { codeFiles, resolve } = projectImports(projectRoot);
|
|
2020
|
+
const resolved = (specifier, file)=>resolve(specifier, file)?.resolved;
|
|
2021
|
+
const withoutUnitImports = (content, file)=>content.split('\n').filter((line)=>{
|
|
2022
|
+
const specifier = line.match(importLine)?.[2];
|
|
2023
|
+
const target = specifier && resolved(specifier, file);
|
|
2024
|
+
return !(target && isUnit(target));
|
|
2025
|
+
}).join('\n');
|
|
2026
|
+
const cleaned = new Map();
|
|
2027
|
+
const inMemoryDb = inMemoryDbFile(rootFolderPath);
|
|
2028
|
+
if ('aggregate' === unit.kind && codeFiles.has(inMemoryDb)) {
|
|
2029
|
+
const section = new UnknownFormatNaming(plural(unit.name));
|
|
2030
|
+
const original = codeFiles.get(inMemoryDb);
|
|
2031
|
+
const content = withoutUnitImports(original.replace(new RegExp(`^[ \\t]*${escapeRegExp(section.variableName)}\\s*=\\s*this\\.section<[^\\n]*\\n?`, 'm'), ''), inMemoryDb);
|
|
2032
|
+
if (content !== original) cleaned.set(inMemoryDb, content);
|
|
2033
|
+
}
|
|
2034
|
+
if (parentAggregate) {
|
|
2035
|
+
const index = node_path.join(parentAggregate, 'index.ts');
|
|
2036
|
+
const original = codeFiles.get(index);
|
|
2037
|
+
if (void 0 !== original) {
|
|
2038
|
+
const content = withoutUnitImports(original, index);
|
|
2039
|
+
if (content !== original) cleaned.set(index, content);
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
const ClassName = new UnknownFormatNaming(unit.name).ClassName;
|
|
2043
|
+
const namedImports = /import\s+(?:type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\2/g;
|
|
2044
|
+
const usedBy = [];
|
|
2045
|
+
const relative = (file)=>toPosix(node_path.relative(projectRoot, file));
|
|
2046
|
+
for (const [file, original] of codeFiles){
|
|
2047
|
+
if (fileSet.has(file)) continue;
|
|
2048
|
+
const content = cleaned.get(file) ?? original;
|
|
2049
|
+
for (const [, , specifier] of content.matchAll(importSpecifier)){
|
|
2050
|
+
const target = resolved(specifier, file);
|
|
2051
|
+
if (target && isUnit(target)) usedBy.push([
|
|
2052
|
+
relative(file),
|
|
2053
|
+
relative(target)
|
|
2054
|
+
]);
|
|
2055
|
+
}
|
|
2056
|
+
for (const [, names, , specifier] of content.matchAll(namedImports)){
|
|
2057
|
+
const target = resolved(specifier, file);
|
|
2058
|
+
if (target && isParentBarrel(target) && new RegExp(`(?<![\\w$])${ClassName}(?![\\w$])`).test(names)) usedBy.push([
|
|
2059
|
+
relative(file),
|
|
2060
|
+
`${relative(target)} (${ClassName})`
|
|
2061
|
+
]);
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
if (usedBy.length) return {
|
|
2065
|
+
usedBy
|
|
2175
2066
|
};
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2067
|
+
for (const file of files)new File(file).delete(integrationSpecsStop(file) ?? rootFolderPath);
|
|
2068
|
+
for (const [file, content] of cleaned)new File(file).update(content);
|
|
2069
|
+
return {
|
|
2070
|
+
deleted: files,
|
|
2071
|
+
updated: [
|
|
2072
|
+
...cleaned.keys()
|
|
2073
|
+
]
|
|
2179
2074
|
};
|
|
2180
2075
|
};
|
|
2181
|
-
const
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2076
|
+
const contractKinds = [
|
|
2077
|
+
'aggregate',
|
|
2078
|
+
'command',
|
|
2079
|
+
'query',
|
|
2080
|
+
'port'
|
|
2081
|
+
];
|
|
2082
|
+
const implementations_withWiring = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
|
|
2083
|
+
const withHandlers = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers');
|
|
2084
|
+
const contractFile = (unit)=>'aggregate' === unit.kind ? `domain/aggregates/${unit.name}/${unit.name}-repository.ts` : kindLayouts[unit.kind].files(unit, [])[0];
|
|
2085
|
+
const findContracts = (ownerPath)=>findBackendUnits(ownerPath).filter((unit)=>contractKinds.includes(unit.kind) && node_fs.existsSync(node_path.join(ownerPath, contractFile(unit))));
|
|
2086
|
+
const implementationWireName = (label)=>`wire${new UnknownFormatNaming(label).ClassName}Implementation`;
|
|
2087
|
+
const contractClassName = (unit)=>kindLayouts[unit.kind].core(new UnknownFormatNaming(unit.name).ClassName);
|
|
2088
|
+
const implementationClassName = (unit, label)=>`${new UnknownFormatNaming(label).ClassName}${contractClassName(unit)}`;
|
|
2089
|
+
const implementationFile = (unit, label)=>{
|
|
2090
|
+
const { implementations } = kindLayouts[unit.kind];
|
|
2091
|
+
return kindLayouts[unit.kind].files(unit, [
|
|
2092
|
+
label
|
|
2093
|
+
]).find((file)=>file.startsWith(`${implementations}/`));
|
|
2189
2094
|
};
|
|
2190
|
-
const
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
const movedPath = (candidate)=>{
|
|
2206
|
-
const extension = candidate.match(codeExtension)?.[0];
|
|
2207
|
-
if (extension) return moves.get(candidate);
|
|
2208
|
-
return withoutExtension.get(candidate) ?? folders.find(([from])=>from === candidate)?.[1];
|
|
2209
|
-
};
|
|
2210
|
-
const { codeFiles, importsOf, resolve } = projectImports(projectRoot);
|
|
2211
|
-
const oldNaming = new UnknownFormatNaming(unit.name);
|
|
2212
|
-
const newNaming = new UnknownFormatNaming(target.name);
|
|
2213
|
-
const leavesAggregate = !!unit.aggregate && (unit.aggregate !== target.aggregate || unit.ownerPath !== target.ownerPath);
|
|
2214
|
-
const oldAggregateFolder = unit.aggregate && node_path.join(unit.ownerPath, 'domain/aggregates', unit.aggregate);
|
|
2215
|
-
const isOldBarrel = (resolved)=>!!oldAggregateFolder && (resolved === oldAggregateFolder || resolved === node_path.join(oldAggregateFolder, 'index'));
|
|
2216
|
-
const mainFile = [
|
|
2217
|
-
...moves.keys()
|
|
2218
|
-
][0];
|
|
2219
|
-
const newMainFile = moves.get(mainFile);
|
|
2220
|
-
const namedImports = /import\s+(type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\3;?/g;
|
|
2221
|
-
const barrelImporters = leavesAggregate ? [
|
|
2222
|
-
...codeFiles
|
|
2223
|
-
].filter(([file, content])=>!moves.has(file) && [
|
|
2224
|
-
...content.matchAll(namedImports)
|
|
2225
|
-
].some(([, , names, , specifier])=>isOldBarrel(resolve(specifier, file)?.resolved) && new RegExp(`(?<![\\w$])${oldNaming.ClassName}(?![\\w$])`).test(names))) : [];
|
|
2226
|
-
const violations = [];
|
|
2227
|
-
const relative = (file)=>toPosix(node_path.relative(projectRoot, file));
|
|
2228
|
-
for (const file of codeFiles.keys()){
|
|
2229
|
-
const from = moves.get(file) ?? file;
|
|
2230
|
-
for (const imported of importsOf(file)){
|
|
2231
|
-
const to = movedPath(imported);
|
|
2232
|
-
if (moves.has(file) || to) {
|
|
2233
|
-
if (!isolationAllows(rootFolderPath, from, to ?? imported)) violations.push([
|
|
2234
|
-
relative(from),
|
|
2235
|
-
relative(to ?? imported)
|
|
2236
|
-
]);
|
|
2237
|
-
}
|
|
2095
|
+
const contractWireFile = (unit)=>kindLayouts[unit.kind].files(unit, []).find((file)=>file.startsWith('wiring/'));
|
|
2096
|
+
const handlerImplementation = (ContractName, ClassName, contractImport)=>withHandlers() ? `
|
|
2097
|
+
import { defineHandler } from '@domain-first/handlers'
|
|
2098
|
+
import { ${ContractName} } from '${contractImport}'
|
|
2099
|
+
|
|
2100
|
+
export class ${ClassName} extends ${ContractName} {
|
|
2101
|
+
constructor() {
|
|
2102
|
+
super()
|
|
2103
|
+
}
|
|
2104
|
+
|
|
2105
|
+
handle = defineHandler({
|
|
2106
|
+
inputSchema: ${ContractName}.inputSchema,
|
|
2107
|
+
outputSchema: ${ContractName}.outputSchema,
|
|
2108
|
+
handler: async (input) => {
|
|
2109
|
+
return {}
|
|
2238
2110
|
}
|
|
2111
|
+
})
|
|
2112
|
+
}
|
|
2113
|
+
`.trim() : `
|
|
2114
|
+
import { ${ContractName} } from '${contractImport}'
|
|
2115
|
+
|
|
2116
|
+
export class ${ClassName} extends ${ContractName} {
|
|
2117
|
+
constructor() {
|
|
2118
|
+
super()
|
|
2239
2119
|
}
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
const newCore = layout.core(newNaming.ClassName);
|
|
2250
|
-
const prefixes = [
|
|
2251
|
-
...unit.labels.map((label)=>new UnknownFormatNaming(label).ClassName),
|
|
2252
|
-
...layout.wired ? [
|
|
2253
|
-
'wire'
|
|
2254
|
-
] : []
|
|
2120
|
+
}
|
|
2121
|
+
`.trim();
|
|
2122
|
+
const createImplementation = (ownerFolder, unit, label)=>{
|
|
2123
|
+
const naming = new UnknownFormatNaming(unit.name);
|
|
2124
|
+
const ContractName = contractClassName(unit);
|
|
2125
|
+
const className = implementationClassName(unit, label);
|
|
2126
|
+
const [folder, fileName] = [
|
|
2127
|
+
node_path.dirname(implementationFile(unit, label)),
|
|
2128
|
+
node_path.basename(implementationFile(unit, label))
|
|
2255
2129
|
];
|
|
2256
|
-
const
|
|
2257
|
-
|
|
2258
|
-
|
|
2259
|
-
|
|
2260
|
-
|
|
2261
|
-
|
|
2262
|
-
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2130
|
+
const implementationFolder = ownerFolder.subitem(folder.split('/'));
|
|
2131
|
+
const inMemoryDb = !implementations_withWiring() && usesInMemoryDb(label);
|
|
2132
|
+
switch(unit.kind){
|
|
2133
|
+
case 'aggregate':
|
|
2134
|
+
{
|
|
2135
|
+
const contractImport = `../../../domain/aggregates/${unit.name}`;
|
|
2136
|
+
if (inMemoryDb) {
|
|
2137
|
+
const section = addInMemoryDbSection(naming, ownerFolder.subitem([
|
|
2138
|
+
'domain',
|
|
2139
|
+
'aggregates',
|
|
2140
|
+
unit.name
|
|
2141
|
+
]).path);
|
|
2142
|
+
const file = implementationFolder.createFile(fileName, `
|
|
2143
|
+
${inMemoryDbTypeImport(implementationFolder.subitem([
|
|
2144
|
+
fileName
|
|
2145
|
+
]).path)}
|
|
2146
|
+
import { ${ContractName} } from '${contractImport}'
|
|
2147
|
+
|
|
2148
|
+
export class ${className} implements ${ContractName} {
|
|
2149
|
+
${inMemoryDbSectionMembers(section, false)}
|
|
2150
|
+
}
|
|
2151
|
+
`.trim());
|
|
2152
|
+
return {
|
|
2153
|
+
file,
|
|
2154
|
+
className
|
|
2155
|
+
};
|
|
2156
|
+
}
|
|
2157
|
+
const file = implementationFolder.createFile(fileName, `
|
|
2158
|
+
import { ${ContractName} } from '${contractImport}'
|
|
2159
|
+
|
|
2160
|
+
export class ${className} implements ${ContractName} {
|
|
2161
|
+
constructor() {}
|
|
2162
|
+
}
|
|
2163
|
+
|
|
2164
|
+
`.trim());
|
|
2165
|
+
return {
|
|
2166
|
+
file,
|
|
2167
|
+
className
|
|
2168
|
+
};
|
|
2169
|
+
}
|
|
2170
|
+
case 'command':
|
|
2171
|
+
case 'query':
|
|
2172
|
+
{
|
|
2173
|
+
const folderName = 'command' === unit.kind ? 'commands' : 'queries';
|
|
2174
|
+
const file = implementationFolder.createFile(fileName, handlerImplementation(ContractName, className, `../../../application/${folderName}/${naming.fileName}-${unit.kind}`));
|
|
2175
|
+
if (inMemoryDb) injectInMemoryDb(file, className);
|
|
2176
|
+
return {
|
|
2177
|
+
file,
|
|
2178
|
+
className
|
|
2179
|
+
};
|
|
2180
|
+
}
|
|
2181
|
+
case 'port':
|
|
2182
|
+
{
|
|
2183
|
+
const file = implementationFolder.createFile(fileName, `
|
|
2184
|
+
import { ${ContractName} } from '../../../application/ports/${naming.fileName}'
|
|
2185
|
+
|
|
2186
|
+
export class ${className} extends ${ContractName} {
|
|
2187
|
+
|
|
2188
|
+
}
|
|
2189
|
+
`.trim());
|
|
2190
|
+
return {
|
|
2191
|
+
file,
|
|
2192
|
+
className
|
|
2193
|
+
};
|
|
2194
|
+
}
|
|
2195
|
+
default:
|
|
2196
|
+
throw new Error(`${unit.kind} has no implementations`);
|
|
2197
|
+
}
|
|
2198
|
+
};
|
|
2199
|
+
const inMemoryRepositoryWiring = (ownerFolder, unit, wireFile)=>(implementation, dependency)=>{
|
|
2200
|
+
if ('aggregate' !== unit.kind || !isInMemoryDb(dependency)) return false;
|
|
2201
|
+
keepInMemoryDbSection(new File(implementation.file), addInMemoryDbSection(new UnknownFormatNaming(unit.name), ownerFolder.subitem([
|
|
2202
|
+
'domain',
|
|
2203
|
+
'aggregates',
|
|
2204
|
+
unit.name
|
|
2205
|
+
]).path));
|
|
2206
|
+
wireInMemoryDb(wireFile, implementation.className);
|
|
2207
|
+
return true;
|
|
2208
|
+
};
|
|
2209
|
+
const integration_tests_withWiring = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
|
|
2210
|
+
const integrationSpecsAvailable = ()=>integration_tests_withWiring() && new File(node_path.join(new ProjectRoot().path, integrationSpecsFolder, 'vitest.config.ts')).exists;
|
|
2211
|
+
const systemImplementationTypes = new Set([
|
|
2212
|
+
inMemoryImplementationType,
|
|
2213
|
+
crossContextImplementation
|
|
2214
|
+
]);
|
|
2215
|
+
const integrationTestTypes = ()=>ConfigFile.backend.implementations?.integrationTests ?? [];
|
|
2216
|
+
const setIntegrationTestTypes = (types)=>{
|
|
2217
|
+
const backend = ConfigFile.backend;
|
|
2218
|
+
ConfigFile.update({
|
|
2219
|
+
backend: {
|
|
2220
|
+
...backend,
|
|
2221
|
+
implementations: {
|
|
2222
|
+
...backend.implementations,
|
|
2223
|
+
integrationTests: [
|
|
2224
|
+
...new Set(types)
|
|
2225
|
+
]
|
|
2226
|
+
}
|
|
2269
2227
|
}
|
|
2270
|
-
];
|
|
2271
|
-
if ('aggregate' === unit.kind) renames.push({
|
|
2272
|
-
pattern: new RegExp(word(oldNaming.ClassName), 'g'),
|
|
2273
|
-
to: newNaming.ClassName
|
|
2274
|
-
}, {
|
|
2275
|
-
pattern: new RegExp(word(oldNaming.variableName), 'g'),
|
|
2276
|
-
to: newNaming.variableName,
|
|
2277
|
-
movedOnly: true
|
|
2278
2228
|
});
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
|
|
2229
|
+
};
|
|
2230
|
+
const importPath = (fromFile, toFile)=>{
|
|
2231
|
+
const relative = node_path.relative(node_path.dirname(fromFile), toFile).replace(/\.ts$/, '').split(node_path.sep).join('/');
|
|
2232
|
+
return relative.startsWith('.') ? relative : `./${relative}`;
|
|
2233
|
+
};
|
|
2234
|
+
const exportImplementationWire = (wireFile, label)=>{
|
|
2235
|
+
if (!wireFile.exists) return false;
|
|
2236
|
+
const name = implementationWireName(label);
|
|
2237
|
+
const declaration = new RegExp(`^(export\\s+)?const\\s+${name}\\b`, 'm');
|
|
2238
|
+
const match = wireFile.data.match(declaration);
|
|
2239
|
+
if (!match) return false;
|
|
2240
|
+
if (!match[1]) wireFile.update(wireFile.data.replace(declaration, `export const ${name}`));
|
|
2241
|
+
return true;
|
|
2242
|
+
};
|
|
2243
|
+
const renderSpec = ({ title, className, classFile, wireImport, wireFile, factory, specPath })=>`
|
|
2244
|
+
import { describe, test, expect } from 'vitest'
|
|
2245
|
+
import { ${className} } from '${importPath(specPath, classFile)}'
|
|
2246
|
+
import { ${wireImport} } from '${importPath(specPath, wireFile)}'
|
|
2247
|
+
|
|
2248
|
+
describe('${title}', () => {
|
|
2249
|
+
test('can be wired', () => {
|
|
2250
|
+
expect(${factory}()).toBeInstanceOf(${className})
|
|
2251
|
+
})
|
|
2252
|
+
|
|
2253
|
+
test.todo('works against the infrastructure')
|
|
2254
|
+
})
|
|
2255
|
+
`.trimStart();
|
|
2256
|
+
const scaffoldIntegrationSpec = (unit, label)=>{
|
|
2257
|
+
const specPath = integrationSpecFile(unit, label);
|
|
2258
|
+
if (!specPath) return;
|
|
2259
|
+
const spec = new File(specPath);
|
|
2260
|
+
if (spec.exists) return;
|
|
2261
|
+
const layout = kindLayouts[unit.kind];
|
|
2262
|
+
const naming = new UnknownFormatNaming(unit.name);
|
|
2263
|
+
const core = layout.core(naming.ClassName);
|
|
2264
|
+
const files = layout.files({
|
|
2265
|
+
ownerPath: unit.ownerPath,
|
|
2266
|
+
name: unit.name
|
|
2267
|
+
}, void 0 === label ? [] : [
|
|
2268
|
+
label
|
|
2269
|
+
]);
|
|
2270
|
+
const wireFile = new File(node_path.join(unit.ownerPath, files.find((file)=>file.startsWith('wiring/'))));
|
|
2271
|
+
if (void 0 === label) {
|
|
2272
|
+
const factory = `wire${core}`;
|
|
2273
|
+
spec.data = renderSpec({
|
|
2274
|
+
title: naming.withSpaces,
|
|
2275
|
+
className: core,
|
|
2276
|
+
classFile: node_path.join(unit.ownerPath, files[0]),
|
|
2277
|
+
wireImport: factory,
|
|
2278
|
+
wireFile: wireFile.path,
|
|
2279
|
+
factory,
|
|
2280
|
+
specPath
|
|
2281
|
+
});
|
|
2282
|
+
return spec;
|
|
2283
|
+
}
|
|
2284
|
+
const className = `${new UnknownFormatNaming(label).ClassName}${core}`;
|
|
2285
|
+
if (!exportImplementationWire(wireFile, label)) return void report(`No integration spec for ${className}: ${wireFile.path} has no ${implementationWireName(label)} factory.`);
|
|
2286
|
+
const factory = `wire${className}`;
|
|
2287
|
+
const wireImport = `${implementationWireName(label)} as ${factory}`;
|
|
2288
|
+
const title = 'aggregate' === unit.kind ? `${naming.withSpaces} repository` : 'port' === unit.kind ? naming.withSpaces : `${naming.withSpaces} ${unit.kind}`;
|
|
2289
|
+
spec.data = renderSpec({
|
|
2290
|
+
title: `${title} (${label})`,
|
|
2291
|
+
className,
|
|
2292
|
+
classFile: node_path.join(unit.ownerPath, files.find((file)=>file.startsWith(`${layout.implementations}/${label}/`))),
|
|
2293
|
+
wireImport,
|
|
2294
|
+
wireFile: wireFile.path,
|
|
2295
|
+
factory,
|
|
2296
|
+
specPath
|
|
2297
|
+
});
|
|
2298
|
+
return spec;
|
|
2299
|
+
};
|
|
2300
|
+
const unusedAnswer = ()=>new RequestError('UNUSED_PARAMETERS', 'implementation.integrationTests applies only to a newly entered primary implementation type, with the Testcontainers integration and wiring.', {
|
|
2301
|
+
fields: [
|
|
2302
|
+
'implementation.integrationTests'
|
|
2303
|
+
]
|
|
2283
2304
|
});
|
|
2284
|
-
|
|
2285
|
-
const
|
|
2286
|
-
const
|
|
2287
|
-
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
everyFile
|
|
2305
|
+
const wantsIntegrationTests = async (label, { entered, save })=>{
|
|
2306
|
+
const answer = isNonInteractive() ? answerFor('implementation')?.integrationTests : void 0;
|
|
2307
|
+
const applies = integrationSpecsAvailable() && entered && !systemImplementationTypes.has(label) && !integrationTestTypes().includes(label);
|
|
2308
|
+
if (!applies) {
|
|
2309
|
+
if (void 0 !== answer) throw unusedAnswer();
|
|
2310
|
+
return integrationSpecsAvailable() && integrationTestTypes().includes(label);
|
|
2311
|
+
}
|
|
2312
|
+
const wanted = isNonInteractive() ? answer ?? true : await interaction_confirm({
|
|
2313
|
+
message: `Generate integration tests for ${label} implementations?`,
|
|
2314
|
+
default: true
|
|
2295
2315
|
});
|
|
2296
|
-
if (
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2316
|
+
if (wanted && save) setIntegrationTestTypes([
|
|
2317
|
+
...integrationTestTypes(),
|
|
2318
|
+
label
|
|
2319
|
+
]);
|
|
2320
|
+
return wanted;
|
|
2321
|
+
};
|
|
2322
|
+
const wantsServiceIntegrationSpec = async ()=>integrationSpecsAvailable() && await interaction_confirm({
|
|
2323
|
+
key: 'integrationSpec',
|
|
2324
|
+
message: 'Generate an integration spec?',
|
|
2325
|
+
default: false
|
|
2326
|
+
});
|
|
2327
|
+
const defaultEnvBranches = {
|
|
2328
|
+
names: [
|
|
2329
|
+
'test',
|
|
2330
|
+
'development',
|
|
2331
|
+
'production'
|
|
2332
|
+
],
|
|
2333
|
+
test: 'test'
|
|
2334
|
+
};
|
|
2335
|
+
const wire_branches_envBranches = ()=>{
|
|
2336
|
+
const configured = ConfigFile.exists ? ConfigFile.Instance.data.backend?.envBranches : void 0;
|
|
2337
|
+
const { names, test } = configured ?? defaultEnvBranches;
|
|
2338
|
+
return {
|
|
2339
|
+
names,
|
|
2340
|
+
test,
|
|
2341
|
+
primary: names.filter((name)=>name !== test),
|
|
2342
|
+
custom: Boolean(configured)
|
|
2343
|
+
};
|
|
2344
|
+
};
|
|
2345
|
+
const offersTestImplementation = ()=>{
|
|
2346
|
+
const backend = ConfigFile.exists ? ConfigFile.Instance.data.backend : void 0;
|
|
2347
|
+
return !(backend?.domainFirstPackages.includes('@domain-first/wire') && backend.envBranches && void 0 === backend.envBranches.test);
|
|
2348
|
+
};
|
|
2349
|
+
const envBranchedWireArgument = (testWire, primaryWire)=>{
|
|
2350
|
+
const { test, primary } = wire_branches_envBranches();
|
|
2351
|
+
return `{\n${[
|
|
2352
|
+
...test ? [
|
|
2353
|
+
` ${test}: ${testWire}`
|
|
2354
|
+
] : [],
|
|
2355
|
+
...primary.map((name)=>` ${name}: ${primaryWire}`)
|
|
2356
|
+
].join(',\n')}\n}`;
|
|
2357
|
+
};
|
|
2358
|
+
const envBranchedWireSource = ()=>{
|
|
2359
|
+
const { names, custom } = wire_branches_envBranches();
|
|
2360
|
+
if (!custom) return `import { branchedWire } from '@domain-first/wire'
|
|
2361
|
+
|
|
2362
|
+
export const envBranchedWire = branchedWire(() => {
|
|
2363
|
+
return process.env.NODE_ENV ?? 'development' as 'test' | 'development' | 'production'
|
|
2364
|
+
});`;
|
|
2365
|
+
return `import { branchedWire } from '@domain-first/wire'
|
|
2366
|
+
|
|
2367
|
+
export type EnvBranch = ${names.map((name)=>`'${name}'`).join(' | ')}
|
|
2368
|
+
|
|
2369
|
+
/**
|
|
2370
|
+
* The branch this process runs in. Write how it is selected:
|
|
2371
|
+
* until then, this function doesn't compile.
|
|
2372
|
+
*/
|
|
2373
|
+
const currentBranch = (): EnvBranch => {
|
|
2374
|
+
}
|
|
2375
|
+
|
|
2376
|
+
export const envBranchedWire = branchedWire(currentBranch)`;
|
|
2377
|
+
};
|
|
2378
|
+
const integrationFolder = 'specs/integration';
|
|
2379
|
+
const testcontainersScripts = {
|
|
2380
|
+
'test:integration': `vitest run --config ${integrationFolder}/vitest.config.ts --reporter=dot --silent=passed-only`
|
|
2381
|
+
};
|
|
2382
|
+
const testcontainersVitestConfig = (inlineHandlersNext)=>{
|
|
2383
|
+
const server = inlineHandlersNext ? `,
|
|
2384
|
+
server: {
|
|
2385
|
+
deps: {
|
|
2386
|
+
// Imports \`next/headers\` without an extension, which only a bundler can resolve
|
|
2387
|
+
inline: ['@domain-first/handlers-next']
|
|
2317
2388
|
}
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2389
|
+
}` : '';
|
|
2390
|
+
return `import { fileURLToPath } from 'node:url';
|
|
2391
|
+
import { defineConfig } from 'vitest/config';
|
|
2392
|
+
|
|
2393
|
+
// Runs specs from this folder against PostgreSQL in a container, see global-setup.ts.
|
|
2394
|
+
export default defineConfig({
|
|
2395
|
+
// Paths below are relative to the project root, not this folder
|
|
2396
|
+
root: fileURLToPath(new URL('../..', import.meta.url)),
|
|
2397
|
+
resolve: {
|
|
2398
|
+
tsconfigPaths: true
|
|
2399
|
+
},
|
|
2400
|
+
test: {
|
|
2401
|
+
include: ['${integrationFolder}/**/*.spec.ts'],
|
|
2402
|
+
// Development implementations work with the real database
|
|
2403
|
+
env: { NODE_ENV: 'development' },
|
|
2404
|
+
globalSetup: ['${integrationFolder}/global-setup.ts'],
|
|
2405
|
+
setupFiles: ['${integrationFolder}/setup-env.ts'],
|
|
2406
|
+
// Pulling the image on the first run takes a while
|
|
2407
|
+
hookTimeout: 120_000${server}
|
|
2326
2408
|
}
|
|
2327
|
-
|
|
2409
|
+
});
|
|
2410
|
+
`;
|
|
2328
2411
|
};
|
|
2329
|
-
const
|
|
2330
|
-
const
|
|
2331
|
-
|
|
2412
|
+
const testcontainersGlobalSetup = (migrationCommands = [])=>{
|
|
2413
|
+
const migrations = migrationCommands.length ? `
|
|
2414
|
+
// dotenv in the ORM config does not override an already set variable
|
|
2415
|
+
${migrationCommands.map((command)=>` execSync(${JSON.stringify(command)}, {
|
|
2416
|
+
cwd: project.config.root,
|
|
2417
|
+
env: { ...process.env, DATABASE_URL: databaseUrl },
|
|
2418
|
+
// On failure the error carries the command's output
|
|
2419
|
+
stdio: 'pipe'
|
|
2420
|
+
});
|
|
2421
|
+
`).join('')}` : `
|
|
2422
|
+
// Apply your migrations to databaseUrl here.
|
|
2423
|
+
`;
|
|
2424
|
+
return `${migrationCommands.length ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
|
|
2425
|
+
import type { TestProject } from 'vitest/node';
|
|
2426
|
+
|
|
2427
|
+
declare module 'vitest' {
|
|
2428
|
+
export interface ProvidedContext {
|
|
2429
|
+
databaseUrl: string;
|
|
2430
|
+
}
|
|
2431
|
+
}
|
|
2432
|
+
|
|
2433
|
+
const POSTGRES_IMAGE = 'postgres:15';
|
|
2434
|
+
const POSTGRES_PORT = 5432;
|
|
2435
|
+
const POSTGRES_USER = 'test';
|
|
2436
|
+
const POSTGRES_PASSWORD = 'test';
|
|
2437
|
+
const POSTGRES_DB = 'test';
|
|
2438
|
+
|
|
2439
|
+
export default async function setup(project: TestProject) {
|
|
2440
|
+
const container = await new GenericContainer(POSTGRES_IMAGE)
|
|
2441
|
+
.withEnvironment({ POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB })
|
|
2442
|
+
.withExposedPorts(POSTGRES_PORT)
|
|
2443
|
+
// During init PostgreSQL listens on a unix socket only and restarts,
|
|
2444
|
+
// so checking over TCP passes once the final server is up
|
|
2445
|
+
.withHealthCheck({
|
|
2446
|
+
test: [
|
|
2447
|
+
'CMD-SHELL',
|
|
2448
|
+
\`pg_isready --host localhost --username \${POSTGRES_USER} --dbname \${POSTGRES_DB}\`
|
|
2449
|
+
],
|
|
2450
|
+
interval: 250,
|
|
2451
|
+
timeout: 1000,
|
|
2452
|
+
retries: 1000
|
|
2453
|
+
})
|
|
2454
|
+
.withWaitStrategy(Wait.forHealthCheck())
|
|
2455
|
+
.withStartupTimeout(120_000)
|
|
2456
|
+
.start();
|
|
2457
|
+
|
|
2458
|
+
const databaseUrl = \`postgresql://\${POSTGRES_USER}:\${POSTGRES_PASSWORD}@\${container.getHost()}:\${container.getMappedPort(POSTGRES_PORT)}/\${POSTGRES_DB}\`;
|
|
2459
|
+
${migrations}
|
|
2460
|
+
project.provide('databaseUrl', databaseUrl);
|
|
2461
|
+
|
|
2462
|
+
return async () => {
|
|
2463
|
+
await container.stop();
|
|
2464
|
+
};
|
|
2465
|
+
}
|
|
2466
|
+
`;
|
|
2332
2467
|
};
|
|
2333
|
-
const
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2353
|
-
const
|
|
2354
|
-
if (
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
const
|
|
2358
|
-
|
|
2468
|
+
const testcontainersSetupEnv = `import 'dotenv/config';
|
|
2469
|
+
import { inject } from 'vitest';
|
|
2470
|
+
|
|
2471
|
+
// Runs before each spec's imports: development implementations get the .env
|
|
2472
|
+
// config, and DATABASE_URL points to the container instead of the one from .env.
|
|
2473
|
+
if (process.env.NODE_ENV !== 'development') {
|
|
2474
|
+
throw new Error(
|
|
2475
|
+
\`Integration specs need NODE_ENV=development to wire development implementations, got "\${process.env.NODE_ENV}"\`
|
|
2476
|
+
);
|
|
2477
|
+
}
|
|
2478
|
+
|
|
2479
|
+
process.env.DATABASE_URL = inject('databaseUrl');
|
|
2480
|
+
`;
|
|
2481
|
+
const testcontainers_exampleSpec = `import { expect, inject, test } from 'vitest';
|
|
2482
|
+
|
|
2483
|
+
test('connects to the database in the container', () => {
|
|
2484
|
+
expect(process.env.DATABASE_URL).toBe(inject('databaseUrl'));
|
|
2485
|
+
});
|
|
2486
|
+
`;
|
|
2487
|
+
const excludeFromUnitTests = (content)=>{
|
|
2488
|
+
const exclude = /(exclude:\s*\[\s*\.\.\.configDefaults\.exclude\b[^\]]*?)(,?)(\s*)\]/;
|
|
2489
|
+
if (!exclude.test(content)) return;
|
|
2490
|
+
const entry = `'${integrationFolder}/**'`;
|
|
2491
|
+
return content.replace(exclude, (_, items, comma, whitespace)=>{
|
|
2492
|
+
const indent = whitespace.includes('\n') ? /\n([ \t]*)[^\n]*$/.exec(items)?.[1] : void 0;
|
|
2493
|
+
const separator = void 0 === indent ? ', ' : `,\n${indent}`;
|
|
2494
|
+
return `${items}${separator}${entry}${comma}${whitespace}]`;
|
|
2495
|
+
}).replace('// Playwright runs end-to-end specs\n', '// Playwright runs end-to-end specs, test:integration runs integration ones\n');
|
|
2496
|
+
};
|
|
2497
|
+
const testcontainers_stageFile = (filePath, content)=>{
|
|
2498
|
+
const file = new File(filePath);
|
|
2499
|
+
if (!file.exists || file.data !== content) file.data = content;
|
|
2500
|
+
};
|
|
2501
|
+
const configureIntegrationTests = async (root)=>{
|
|
2502
|
+
if (!ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) return;
|
|
2503
|
+
const kindsOf = new Map();
|
|
2504
|
+
for (const kind of implementationKinds)for (const label of savedImplementations(kind, 'primary'))if (!systemImplementationTypes.has(label)) kindsOf.set(label, [
|
|
2505
|
+
...kindsOf.get(label) ?? [],
|
|
2506
|
+
kind
|
|
2507
|
+
]);
|
|
2508
|
+
const current = integrationTestTypes();
|
|
2509
|
+
if (kindsOf.size) {
|
|
2510
|
+
const selected = await interaction_checkbox({
|
|
2511
|
+
key: 'integrationTestTypes',
|
|
2512
|
+
message: 'Integration tests for implementation types:',
|
|
2513
|
+
choices: [
|
|
2514
|
+
...kindsOf
|
|
2515
|
+
].map(([value, kinds])=>({
|
|
2516
|
+
name: `${value} (${kinds.join(', ')})`,
|
|
2517
|
+
value,
|
|
2518
|
+
checked: current.includes(value)
|
|
2519
|
+
}))
|
|
2520
|
+
});
|
|
2521
|
+
const kept = current.filter((label)=>!kindsOf.has(label));
|
|
2522
|
+
const next = [
|
|
2523
|
+
...selected,
|
|
2524
|
+
...kept
|
|
2525
|
+
];
|
|
2526
|
+
if (next.length !== current.length || next.some((label)=>!current.includes(label))) setIntegrationTestTypes(next);
|
|
2359
2527
|
}
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2528
|
+
const types = integrationTestTypes();
|
|
2529
|
+
if (!types.length) return;
|
|
2530
|
+
const testBranch = wire_branches_envBranches().test;
|
|
2531
|
+
const source = new Folder(root).subitem([
|
|
2532
|
+
ConfigFile.Instance.data.project.rootFolder
|
|
2533
|
+
]);
|
|
2534
|
+
const owners = [
|
|
2535
|
+
source.subitem([
|
|
2536
|
+
'shared-kernel'
|
|
2537
|
+
]),
|
|
2538
|
+
...source.subitem([
|
|
2539
|
+
'bounded-contexts'
|
|
2540
|
+
]).content.subfolderNames.sort().map((name)=>source.subitem([
|
|
2541
|
+
'bounded-contexts',
|
|
2542
|
+
name
|
|
2543
|
+
]))
|
|
2544
|
+
];
|
|
2545
|
+
for (const owner of owners)for (const unit of findContracts(owner.path)){
|
|
2546
|
+
const wireFile = new File(node_path.join(owner.path, contractWireFile(unit)));
|
|
2547
|
+
if (!wireFile.exists) continue;
|
|
2548
|
+
let wired;
|
|
2549
|
+
try {
|
|
2550
|
+
wired = wireBranches(wireFile.data, `wire${contractClassName(unit)}`);
|
|
2551
|
+
} catch {
|
|
2552
|
+
continue;
|
|
2366
2553
|
}
|
|
2554
|
+
const primaryWires = new Set([
|
|
2555
|
+
...wired
|
|
2556
|
+
].filter(([branch])=>branch !== testBranch).map(([, wire])=>wire));
|
|
2557
|
+
for (const label of unit.labels)if (types.includes(label) && primaryWires.has(implementationWireName(label))) scaffoldIntegrationSpec(unit, label);
|
|
2367
2558
|
}
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
const
|
|
2371
|
-
const
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2559
|
+
};
|
|
2560
|
+
const addTestcontainers = async ()=>{
|
|
2561
|
+
const config = ConfigFile.Instance.data;
|
|
2562
|
+
const root = new ProjectRoot().path;
|
|
2563
|
+
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
2564
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
2565
|
+
const dependencies = {
|
|
2566
|
+
...manifest.dependencies,
|
|
2567
|
+
...manifest.devDependencies
|
|
2568
|
+
};
|
|
2569
|
+
const selected = await addPackageScripts(manifestFile, testcontainersScripts);
|
|
2570
|
+
const presetExists = (relativePath)=>new File(node_path.resolve(root, relativePath)).exists;
|
|
2571
|
+
const migrationCommands = [
|
|
2572
|
+
...presetExists(node_path.join(config.project.rootFolder, 'shared-kernel/infrastructure/prisma/prisma.config.ts')) ? [
|
|
2573
|
+
`npx ${prismaScripts(config.project.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}`
|
|
2574
|
+
] : [],
|
|
2575
|
+
...presetExists(drizzleConfigPath(config.project.rootFolder)) ? [
|
|
2576
|
+
`npx ${drizzleScripts(config.project.rootFolder)['drizzle:migrate']}`
|
|
2577
|
+
] : []
|
|
2578
|
+
];
|
|
2579
|
+
const folder = node_path.join(root, integrationFolder);
|
|
2580
|
+
testcontainers_stageFile(node_path.join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
|
|
2581
|
+
testcontainers_stageFile(node_path.join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommands));
|
|
2582
|
+
testcontainers_stageFile(node_path.join(folder, 'setup-env.ts'), testcontainersSetupEnv);
|
|
2583
|
+
const example = new File(node_path.join(folder, 'database/database.spec.ts'));
|
|
2584
|
+
if (!example.exists) example.data = testcontainers_exampleSpec;
|
|
2585
|
+
const unitConfig = new File(node_path.join(root, 'vitest.config.ts'));
|
|
2586
|
+
let excludedFromUnitTests = !unitConfig.exists || unitConfig.data.includes(integrationFolder);
|
|
2587
|
+
if (!excludedFromUnitTests) {
|
|
2588
|
+
const excluded = excludeFromUnitTests(unitConfig.data);
|
|
2589
|
+
if (excluded) {
|
|
2590
|
+
unitConfig.update(excluded);
|
|
2591
|
+
excludedFromUnitTests = true;
|
|
2388
2592
|
}
|
|
2389
2593
|
}
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
]
|
|
2400
|
-
|
|
2594
|
+
await configureIntegrationTests(root);
|
|
2595
|
+
const missing = [
|
|
2596
|
+
'vitest',
|
|
2597
|
+
'testcontainers',
|
|
2598
|
+
'dotenv'
|
|
2599
|
+
].filter((name)=>!dependencies[name]);
|
|
2600
|
+
return [
|
|
2601
|
+
...missing.length ? [
|
|
2602
|
+
`npm install --save-dev ${missing.join(' ')}`
|
|
2603
|
+
] : [],
|
|
2604
|
+
`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.`,
|
|
2605
|
+
...migrationCommands.length ? [] : [
|
|
2606
|
+
`Apply your migrations in ${integrationFolder}/global-setup.ts.`
|
|
2607
|
+
],
|
|
2608
|
+
...excludedFromUnitTests ? [] : [
|
|
2609
|
+
`Add '${integrationFolder}/**' to test.exclude in vitest.config.ts, so unit tests skip integration specs.`
|
|
2610
|
+
],
|
|
2611
|
+
...wire_branches_envBranches().custom ? [
|
|
2612
|
+
`${integrationFolder} runs with NODE_ENV=development and ${integrationFolder}/setup-env.ts requires it, but your envBranchedWire branches are custom: make currentBranch in shared-kernel/wiring/env-branched-wire.ts return the branch for integration specs, and adjust setup-env.ts.`
|
|
2613
|
+
] : [],
|
|
2614
|
+
'Docker must be running for integration specs.',
|
|
2615
|
+
...describeScripts(selected, {
|
|
2616
|
+
'test:integration': `run integration specs from ${integrationFolder} against PostgreSQL in a container`
|
|
2617
|
+
})
|
|
2618
|
+
];
|
|
2401
2619
|
};
|
|
2402
|
-
const
|
|
2403
|
-
'
|
|
2404
|
-
'
|
|
2405
|
-
'query',
|
|
2406
|
-
'port'
|
|
2407
|
-
];
|
|
2408
|
-
const implementations_withWiring = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
|
|
2409
|
-
const withHandlers = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers');
|
|
2410
|
-
const contractFile = (unit)=>'aggregate' === unit.kind ? `domain/aggregates/${unit.name}/${unit.name}-repository.ts` : kindLayouts[unit.kind].files(unit, [])[0];
|
|
2411
|
-
const findContracts = (ownerPath)=>findBackendUnits(ownerPath).filter((unit)=>contractKinds.includes(unit.kind) && node_fs.existsSync(node_path.join(ownerPath, contractFile(unit))));
|
|
2412
|
-
const implementationWireName = (label)=>`wire${new UnknownFormatNaming(label).ClassName}Implementation`;
|
|
2413
|
-
const contractClassName = (unit)=>kindLayouts[unit.kind].core(new UnknownFormatNaming(unit.name).ClassName);
|
|
2414
|
-
const implementationClassName = (unit, label)=>`${new UnknownFormatNaming(label).ClassName}${contractClassName(unit)}`;
|
|
2415
|
-
const implementationFile = (unit, label)=>{
|
|
2416
|
-
const { implementations } = kindLayouts[unit.kind];
|
|
2417
|
-
return kindLayouts[unit.kind].files(unit, [
|
|
2418
|
-
label
|
|
2419
|
-
]).find((file)=>file.startsWith(`${implementations}/`));
|
|
2620
|
+
const vitestScripts = {
|
|
2621
|
+
test: 'vitest run --reporter=dot --silent=passed-only',
|
|
2622
|
+
'test:coverage': 'vitest run --coverage --reporter=dot --silent=passed-only'
|
|
2420
2623
|
};
|
|
2421
|
-
const
|
|
2422
|
-
const
|
|
2423
|
-
|
|
2424
|
-
|
|
2624
|
+
const vitestConfig = (rootFolder, inlineHandlersNext)=>{
|
|
2625
|
+
const folder = (subpath)=>JSON.stringify(node_path.posix.join(rootFolder.replaceAll('\\', '/'), subpath));
|
|
2626
|
+
const server = inlineHandlersNext ? `,
|
|
2627
|
+
server: {
|
|
2628
|
+
deps: {
|
|
2629
|
+
// Imports \`next/headers\` without an extension, which only a bundler can resolve
|
|
2630
|
+
inline: ['@domain-first/handlers-next']
|
|
2631
|
+
}
|
|
2632
|
+
}` : '';
|
|
2633
|
+
return `import { configDefaults, defineConfig } from 'vitest/config';
|
|
2425
2634
|
|
|
2426
|
-
export
|
|
2427
|
-
|
|
2428
|
-
|
|
2635
|
+
export default defineConfig({
|
|
2636
|
+
resolve: {
|
|
2637
|
+
tsconfigPaths: true
|
|
2638
|
+
},
|
|
2639
|
+
test: {
|
|
2640
|
+
// Playwright runs end-to-end specs, test:integration runs integration ones
|
|
2641
|
+
exclude: [...configDefaults.exclude, 'specs/e2e/**', 'specs/integration/**'],
|
|
2642
|
+
coverage: {
|
|
2643
|
+
provider: 'v8',
|
|
2644
|
+
include: [${folder('bounded-contexts/**/*.ts')}, ${folder('shared-kernel/**/*.ts')}],
|
|
2645
|
+
exclude: [
|
|
2646
|
+
'**/*.spec.ts',
|
|
2647
|
+
${folder('shared-kernel/infrastructure/**')},
|
|
2648
|
+
${folder('bounded-contexts/*/infrastructure/**')},
|
|
2649
|
+
${folder('bounded-contexts/*/presentation/rest/**')},
|
|
2650
|
+
${folder('shared-kernel/wiring/**')},
|
|
2651
|
+
${folder('bounded-contexts/*/wiring/**')}
|
|
2652
|
+
],
|
|
2653
|
+
reporter: [['text', { skipFull: true }], 'html']
|
|
2654
|
+
}${server}
|
|
2429
2655
|
}
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2656
|
+
});
|
|
2657
|
+
`;
|
|
2658
|
+
};
|
|
2659
|
+
const addVitest = async ()=>{
|
|
2660
|
+
const config = ConfigFile.Instance.data;
|
|
2661
|
+
if (ConfigFile.backend.testingLibrary && 'vitest' !== ConfigFile.backend.testingLibrary && !await interaction_confirm({
|
|
2662
|
+
key: 'replaceTestingLibrary',
|
|
2663
|
+
requestRequired: true,
|
|
2664
|
+
message: `Replace testing library "${ConfigFile.backend.testingLibrary}" with vitest for generated tests?`,
|
|
2665
|
+
default: false
|
|
2666
|
+
})) return [];
|
|
2667
|
+
const root = new ProjectRoot().path;
|
|
2668
|
+
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
2669
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
2670
|
+
const dependencies = {
|
|
2671
|
+
...manifest.dependencies,
|
|
2672
|
+
...manifest.devDependencies
|
|
2673
|
+
};
|
|
2674
|
+
const selected = await addPackageScripts(manifestFile, vitestScripts);
|
|
2675
|
+
const configFile = new File(node_path.join(root, 'vitest.config.ts'));
|
|
2676
|
+
const content = vitestConfig(config.project.rootFolder, Boolean(dependencies['@domain-first/handlers-next']));
|
|
2677
|
+
if (!configFile.exists || configFile.data !== content) configFile.data = content;
|
|
2678
|
+
if ('vitest' !== ConfigFile.backend.testingLibrary) ConfigFile.update({
|
|
2679
|
+
backend: {
|
|
2680
|
+
...ConfigFile.backend,
|
|
2681
|
+
testingLibrary: 'vitest'
|
|
2682
|
+
}
|
|
2683
|
+
});
|
|
2684
|
+
addGitignoreEntry(root, '/coverage/');
|
|
2685
|
+
const missing = [
|
|
2686
|
+
'vitest',
|
|
2687
|
+
'@vitest/coverage-v8'
|
|
2688
|
+
].filter((name)=>!dependencies[name]);
|
|
2689
|
+
return [
|
|
2690
|
+
...missing.length ? [
|
|
2691
|
+
`npm install --save-dev ${missing.join(' ')}`
|
|
2692
|
+
] : [],
|
|
2693
|
+
...describeScripts(selected, {
|
|
2694
|
+
test: 'run unit tests',
|
|
2695
|
+
'test:coverage': 'run unit tests with a V8 coverage report in coverage/'
|
|
2696
|
+
})
|
|
2697
|
+
];
|
|
2698
|
+
};
|
|
2699
|
+
const installCommand = /^\s*npm (?:i|install)((?:\s+(?:--save-dev|-D))?)\s+(.+)$/;
|
|
2700
|
+
const mergeInstallCommands = (commands)=>{
|
|
2701
|
+
const runtime = new Set();
|
|
2702
|
+
const development = new Set();
|
|
2703
|
+
const rest = [];
|
|
2704
|
+
for (const command of commands){
|
|
2705
|
+
const match = installCommand.exec(command);
|
|
2706
|
+
if (!match) {
|
|
2707
|
+
rest.push(command);
|
|
2708
|
+
continue;
|
|
2709
|
+
}
|
|
2710
|
+
for (const name of match[2].trim().split(/\s+/))(match[1] ? development : runtime).add(name);
|
|
2711
|
+
}
|
|
2712
|
+
const devOnly = [
|
|
2713
|
+
...development
|
|
2714
|
+
].filter((name)=>!runtime.has(name));
|
|
2715
|
+
return [
|
|
2716
|
+
...runtime.size ? [
|
|
2717
|
+
`npm install ${[
|
|
2718
|
+
...runtime
|
|
2719
|
+
].join(' ')}`
|
|
2720
|
+
] : [],
|
|
2721
|
+
...devOnly.length ? [
|
|
2722
|
+
`npm install --save-dev ${devOnly.join(' ')}`
|
|
2723
|
+
] : [],
|
|
2724
|
+
...rest
|
|
2725
|
+
];
|
|
2726
|
+
};
|
|
2727
|
+
const printNextSteps = (nextSteps)=>{
|
|
2728
|
+
const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
|
|
2729
|
+
const commands = mergeInstallCommands(nextSteps.filter(isCommand));
|
|
2730
|
+
const notes = nextSteps.filter((line)=>!isCommand(line));
|
|
2731
|
+
const sections = [];
|
|
2732
|
+
if (commands.length) sections.push([
|
|
2733
|
+
'Run this command to install the required dependencies:',
|
|
2734
|
+
styleText([
|
|
2735
|
+
'bold',
|
|
2736
|
+
'cyan'
|
|
2737
|
+
], commands.join(' && '))
|
|
2738
|
+
].join('\n'));
|
|
2739
|
+
if (notes.length) sections.push([
|
|
2740
|
+
'Additional information:',
|
|
2741
|
+
...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + styleText([
|
|
2742
|
+
'bold',
|
|
2743
|
+
'cyan'
|
|
2744
|
+
], path)))
|
|
2745
|
+
].join('\n'));
|
|
2746
|
+
if (sections.length) console.log(sections.join('\n\n'));
|
|
2747
|
+
};
|
|
2748
|
+
const savePendingChanges = async ()=>{
|
|
2749
|
+
assertAnswersConsumed();
|
|
2750
|
+
const overwrittenFiles = filesToOverwrite({
|
|
2751
|
+
changedOnly: isNonInteractive()
|
|
2752
|
+
});
|
|
2753
|
+
if (isNonInteractive() && overwrittenFiles.length && !answerFor('overwrite', false)) throw new RequestError('OVERWRITE_REQUIRED', 'Set overwrite to true to replace existing files.', {
|
|
2754
|
+
files: overwrittenFiles.map((file)=>node_path.relative(new ProjectRoot().path, file).split(node_path.sep).join('/'))
|
|
2755
|
+
});
|
|
2756
|
+
if (overwrittenFiles.length) {
|
|
2757
|
+
const root = new ProjectRoot().path;
|
|
2758
|
+
report('These files already exist and will be overwritten:');
|
|
2759
|
+
for (const filePath of overwrittenFiles)report(` ${node_path.relative(root, filePath)}`);
|
|
2760
|
+
const overwrite = await interaction_confirm({
|
|
2761
|
+
key: 'overwrite',
|
|
2762
|
+
message: 'Overwrite them?',
|
|
2763
|
+
default: false
|
|
2764
|
+
});
|
|
2765
|
+
if (!overwrite) {
|
|
2766
|
+
discardPendingChanges();
|
|
2767
|
+
report('Cancelled: nothing was written.');
|
|
2768
|
+
return false;
|
|
2436
2769
|
}
|
|
2437
|
-
})
|
|
2438
|
-
}
|
|
2439
|
-
`.trim() : `
|
|
2440
|
-
import { ${ContractName} } from '${contractImport}'
|
|
2441
|
-
|
|
2442
|
-
export class ${ClassName} extends ${ContractName} {
|
|
2443
|
-
constructor() {
|
|
2444
|
-
super()
|
|
2445
|
-
}
|
|
2446
|
-
}
|
|
2447
|
-
`.trim();
|
|
2448
|
-
const createImplementation = (ownerFolder, unit, label)=>{
|
|
2449
|
-
const naming = new UnknownFormatNaming(unit.name);
|
|
2450
|
-
const ContractName = contractClassName(unit);
|
|
2451
|
-
const className = implementationClassName(unit, label);
|
|
2452
|
-
const [folder, fileName] = [
|
|
2453
|
-
node_path.dirname(implementationFile(unit, label)),
|
|
2454
|
-
node_path.basename(implementationFile(unit, label))
|
|
2455
|
-
];
|
|
2456
|
-
const implementationFolder = ownerFolder.subitem(folder.split('/'));
|
|
2457
|
-
const inMemoryDb = !implementations_withWiring() && usesInMemoryDb(label);
|
|
2458
|
-
switch(unit.kind){
|
|
2459
|
-
case 'aggregate':
|
|
2460
|
-
{
|
|
2461
|
-
const contractImport = `../../../domain/aggregates/${unit.name}`;
|
|
2462
|
-
if (inMemoryDb) {
|
|
2463
|
-
const section = addInMemoryDbSection(naming, ownerFolder.subitem([
|
|
2464
|
-
'domain',
|
|
2465
|
-
'aggregates',
|
|
2466
|
-
unit.name
|
|
2467
|
-
]).path);
|
|
2468
|
-
const file = implementationFolder.createFile(fileName, `
|
|
2469
|
-
${inMemoryDbTypeImport(implementationFolder.subitem([
|
|
2470
|
-
fileName
|
|
2471
|
-
]).path)}
|
|
2472
|
-
import { ${ContractName} } from '${contractImport}'
|
|
2473
|
-
|
|
2474
|
-
export class ${className} implements ${ContractName} {
|
|
2475
|
-
${inMemoryDbSectionMembers(section, false)}
|
|
2476
|
-
}
|
|
2477
|
-
`.trim());
|
|
2478
|
-
return {
|
|
2479
|
-
file,
|
|
2480
|
-
className
|
|
2481
|
-
};
|
|
2482
|
-
}
|
|
2483
|
-
const file = implementationFolder.createFile(fileName, `
|
|
2484
|
-
import { ${ContractName} } from '${contractImport}'
|
|
2485
|
-
|
|
2486
|
-
export class ${className} implements ${ContractName} {
|
|
2487
|
-
constructor() {}
|
|
2488
|
-
}
|
|
2489
|
-
|
|
2490
|
-
`.trim());
|
|
2491
|
-
return {
|
|
2492
|
-
file,
|
|
2493
|
-
className
|
|
2494
|
-
};
|
|
2495
|
-
}
|
|
2496
|
-
case 'command':
|
|
2497
|
-
case 'query':
|
|
2498
|
-
{
|
|
2499
|
-
const folderName = 'command' === unit.kind ? 'commands' : 'queries';
|
|
2500
|
-
const file = implementationFolder.createFile(fileName, handlerImplementation(ContractName, className, `../../../application/${folderName}/${naming.fileName}-${unit.kind}`));
|
|
2501
|
-
if (inMemoryDb) injectInMemoryDb(file, className);
|
|
2502
|
-
return {
|
|
2503
|
-
file,
|
|
2504
|
-
className
|
|
2505
|
-
};
|
|
2506
|
-
}
|
|
2507
|
-
case 'port':
|
|
2508
|
-
{
|
|
2509
|
-
const file = implementationFolder.createFile(fileName, `
|
|
2510
|
-
import { ${ContractName} } from '../../../application/ports/${naming.fileName}'
|
|
2511
|
-
|
|
2512
|
-
export class ${className} extends ${ContractName} {
|
|
2513
|
-
|
|
2514
|
-
}
|
|
2515
|
-
`.trim());
|
|
2516
|
-
return {
|
|
2517
|
-
file,
|
|
2518
|
-
className
|
|
2519
|
-
};
|
|
2520
|
-
}
|
|
2521
|
-
default:
|
|
2522
|
-
throw new Error(`${unit.kind} has no implementations`);
|
|
2523
2770
|
}
|
|
2771
|
+
writePendingChanges();
|
|
2772
|
+
return true;
|
|
2524
2773
|
};
|
|
2525
|
-
const
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
|
|
2529
|
-
|
|
2530
|
-
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
|
|
2774
|
+
const withHandlersRest = ()=>ConfigFile.Instance.data.backend?.domainFirstPackages.includes('@domain-first/handlers-rest') ?? false;
|
|
2775
|
+
const created = (...segments)=>new File(node_path.join(new ProjectRoot().path, ...segments)).exists;
|
|
2776
|
+
const createdInRoot = (...segments)=>created(ConfigFile.Instance.data.project.rootFolder, ...segments);
|
|
2777
|
+
const integrationIds = [
|
|
2778
|
+
'storybook',
|
|
2779
|
+
'rest-endpoint-generator',
|
|
2780
|
+
'in-memory-db',
|
|
2781
|
+
'prisma',
|
|
2782
|
+
'drizzle',
|
|
2783
|
+
'vitest',
|
|
2784
|
+
'playwright',
|
|
2785
|
+
'testcontainers',
|
|
2786
|
+
'openapi',
|
|
2787
|
+
'orval'
|
|
2788
|
+
];
|
|
2789
|
+
const integrations = [
|
|
2790
|
+
{
|
|
2791
|
+
id: 'storybook',
|
|
2792
|
+
name: 'Storybook (React + Vite)',
|
|
2793
|
+
group: 'frontend',
|
|
2794
|
+
run: addStorybook,
|
|
2795
|
+
applied: ()=>createdInRoot('presentation/react/.storybook/main.ts')
|
|
2796
|
+
},
|
|
2797
|
+
{
|
|
2798
|
+
id: 'rest-endpoint-generator',
|
|
2799
|
+
name: 'REST endpoint generator',
|
|
2800
|
+
group: 'backend',
|
|
2801
|
+
run: addRestEndpointGenerator,
|
|
2802
|
+
available: ()=>withHandlersRest(),
|
|
2803
|
+
applied: restEndpointGeneratorApplied
|
|
2804
|
+
},
|
|
2805
|
+
{
|
|
2806
|
+
id: 'in-memory-db',
|
|
2807
|
+
name: 'In-memory DB',
|
|
2808
|
+
group: 'backend',
|
|
2809
|
+
run: addInMemoryDb,
|
|
2810
|
+
applied: inMemoryDbApplied
|
|
2811
|
+
},
|
|
2812
|
+
{
|
|
2813
|
+
id: 'prisma',
|
|
2814
|
+
name: 'Prisma 8 (PostgreSQL, RC)',
|
|
2815
|
+
group: 'backend',
|
|
2816
|
+
run: addPrisma,
|
|
2817
|
+
applied: ()=>createdInRoot('shared-kernel/infrastructure/prisma/prisma.config.ts')
|
|
2818
|
+
},
|
|
2819
|
+
{
|
|
2820
|
+
id: 'drizzle',
|
|
2821
|
+
name: 'Drizzle (PostgreSQL)',
|
|
2822
|
+
group: 'backend',
|
|
2823
|
+
run: addDrizzle,
|
|
2824
|
+
applied: ()=>created(drizzleConfigPath(ConfigFile.Instance.data.project.rootFolder))
|
|
2825
|
+
},
|
|
2826
|
+
{
|
|
2827
|
+
id: 'vitest',
|
|
2828
|
+
name: 'Vitest',
|
|
2829
|
+
group: 'backend',
|
|
2830
|
+
run: addVitest,
|
|
2831
|
+
applied: ()=>created('vitest.config.ts')
|
|
2832
|
+
},
|
|
2833
|
+
{
|
|
2834
|
+
id: 'playwright',
|
|
2835
|
+
name: 'Playwright',
|
|
2836
|
+
group: 'frontend',
|
|
2837
|
+
run: addPlaywright,
|
|
2838
|
+
applied: ()=>created('playwright.config.ts')
|
|
2839
|
+
},
|
|
2840
|
+
{
|
|
2841
|
+
id: 'testcontainers',
|
|
2842
|
+
name: 'Integration tests (Testcontainers, PostgreSQL)',
|
|
2843
|
+
group: 'backend',
|
|
2844
|
+
run: addTestcontainers,
|
|
2845
|
+
applied: ()=>created('specs/integration/vitest.config.ts')
|
|
2846
|
+
},
|
|
2847
|
+
{
|
|
2848
|
+
id: 'openapi',
|
|
2849
|
+
name: 'OpenAPI',
|
|
2850
|
+
group: 'backend',
|
|
2851
|
+
run: addOpenapi,
|
|
2852
|
+
available: ()=>withHandlersRest(),
|
|
2853
|
+
applied: ()=>created(openapiScriptPath)
|
|
2854
|
+
},
|
|
2855
|
+
{
|
|
2856
|
+
id: 'orval',
|
|
2857
|
+
name: 'Orval (API client)',
|
|
2858
|
+
group: 'frontend',
|
|
2859
|
+
run: addOrval,
|
|
2860
|
+
available: ()=>withHandlersRest(),
|
|
2861
|
+
applied: ()=>createdInRoot('presentation/react/data-layer/orval.config.ts') || createdInRoot('presentation/data-layer/orval.config.ts')
|
|
2862
|
+
}
|
|
2863
|
+
];
|
|
2864
|
+
const addIntegration = async ({ save = true } = {})=>{
|
|
2865
|
+
const available = integrations.filter(({ group, available })=>('backend' !== group || Boolean(ConfigFile.Instance.data.backend)) && (available?.() ?? true)).map((value)=>({
|
|
2866
|
+
value,
|
|
2867
|
+
applied: value.applied()
|
|
2868
|
+
}));
|
|
2869
|
+
const section = (title, applied)=>{
|
|
2870
|
+
const items = [
|
|
2871
|
+
'backend',
|
|
2872
|
+
'frontend'
|
|
2873
|
+
].flatMap((group)=>available.filter((item)=>item.applied === applied && item.value.group === group));
|
|
2874
|
+
return items.length ? [
|
|
2875
|
+
new Separator(title),
|
|
2876
|
+
...items.map(({ value })=>({
|
|
2877
|
+
name: `${value.name} · ${value.group}`,
|
|
2878
|
+
value
|
|
2879
|
+
}))
|
|
2880
|
+
] : [];
|
|
2534
2881
|
};
|
|
2882
|
+
const choices = [
|
|
2883
|
+
...section('New integrations', false),
|
|
2884
|
+
...section('Already applied (select to reapply)', true)
|
|
2885
|
+
];
|
|
2886
|
+
const selected = await interaction_checkbox({
|
|
2887
|
+
key: 'integrations',
|
|
2888
|
+
id: (integration)=>integration.id,
|
|
2889
|
+
message: 'Integrations:',
|
|
2890
|
+
choices,
|
|
2891
|
+
pageSize: choices.length
|
|
2892
|
+
});
|
|
2893
|
+
const nextSteps = [];
|
|
2894
|
+
for (const integration of integrations.filter((value)=>selected.includes(value)))nextSteps.push(...await integration.run());
|
|
2895
|
+
if (save && await savePendingChanges()) printNextSteps(nextSteps);
|
|
2896
|
+
return nextSteps;
|
|
2897
|
+
};
|
|
2898
|
+
const integrationDescriptions = ()=>integrations.map((integration)=>({
|
|
2899
|
+
id: integration.id,
|
|
2900
|
+
name: integration.name,
|
|
2901
|
+
group: integration.group,
|
|
2902
|
+
available: ('backend' !== integration.group || Boolean(ConfigFile.Instance.data.backend)) && (integration.available?.() ?? true)
|
|
2903
|
+
}));
|
|
2535
2904
|
const reactKindLayouts = {
|
|
2536
2905
|
page: {
|
|
2537
2906
|
folder: 'pages',
|
|
@@ -3372,16 +3741,23 @@ const promptImplementationType = async (message, kind, { existing = [], purpose
|
|
|
3372
3741
|
if (!implementation) throw new RequestError('MISSING_PARAMETER', `Provide ${key}.`, {
|
|
3373
3742
|
field: key
|
|
3374
3743
|
});
|
|
3744
|
+
if ('test' === purpose && void 0 !== implementation.integrationTests) throw new RequestError('UNUSED_PARAMETERS', 'Test implementations get no integration specs.', {
|
|
3745
|
+
fields: [
|
|
3746
|
+
`${key}.integrationTests`
|
|
3747
|
+
]
|
|
3748
|
+
});
|
|
3375
3749
|
const valid = validateLabel(implementation.type);
|
|
3376
3750
|
if (true !== valid) throw new RequestError('INVALID_IMPLEMENTATION', valid, {
|
|
3377
3751
|
field: key
|
|
3378
3752
|
});
|
|
3379
3753
|
const label = implementation.type.trim();
|
|
3380
3754
|
const saveForFutureUse = implementation.save ?? false;
|
|
3755
|
+
const entered = !choices.some((choice)=>choice.value === label);
|
|
3381
3756
|
if (remember && saveForFutureUse && !system.some((choice)=>choice.value === label)) rememberImplementation(kind, 'all' === purpose ? 'primary' : purpose, label);
|
|
3382
3757
|
return {
|
|
3383
3758
|
label,
|
|
3384
|
-
saveForFutureUse
|
|
3759
|
+
saveForFutureUse,
|
|
3760
|
+
entered
|
|
3385
3761
|
};
|
|
3386
3762
|
}
|
|
3387
3763
|
const type = await interaction_select({
|
|
@@ -3397,7 +3773,8 @@ const promptImplementationType = async (message, kind, { existing = [], purpose
|
|
|
3397
3773
|
});
|
|
3398
3774
|
if ('string' == typeof type) return {
|
|
3399
3775
|
label: type,
|
|
3400
|
-
saveForFutureUse: true
|
|
3776
|
+
saveForFutureUse: true,
|
|
3777
|
+
entered: false
|
|
3401
3778
|
};
|
|
3402
3779
|
const saveForFutureUse = type !== enterImplementationTypeOnce;
|
|
3403
3780
|
const label = (await interaction_input({
|
|
@@ -3408,7 +3785,8 @@ const promptImplementationType = async (message, kind, { existing = [], purpose
|
|
|
3408
3785
|
if (saveForFutureUse && remember && !choices.some(({ value })=>value === label)) rememberImplementation(kind, 'all' === purpose ? 'primary' : purpose, label);
|
|
3409
3786
|
return {
|
|
3410
3787
|
label,
|
|
3411
|
-
saveForFutureUse
|
|
3788
|
+
saveForFutureUse,
|
|
3789
|
+
entered: !choices.some(({ value })=>value === label)
|
|
3412
3790
|
};
|
|
3413
3791
|
};
|
|
3414
3792
|
const scaffoldNewAggregateUseCase = async (boundedContextFolder)=>{
|
|
@@ -3454,7 +3832,12 @@ describe('${aggregateNaming.withSpaces}', () => {
|
|
|
3454
3832
|
if (withRepository) {
|
|
3455
3833
|
aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.ts`, `export abstract class ${aggregateNaming.ClassName}Repository { }`);
|
|
3456
3834
|
barrelFile.addLine(`export * from './${aggregateNaming.fileName}-repository'`);
|
|
3457
|
-
const
|
|
3835
|
+
const primary = await promptImplementationType('Repository infrastructure implementation type:', 'repositories');
|
|
3836
|
+
const infrastructureImplementationType = primary.label;
|
|
3837
|
+
const withIntegrationSpec = await wantsIntegrationTests(primary.label, {
|
|
3838
|
+
entered: primary.entered,
|
|
3839
|
+
save: primary.saveForFutureUse
|
|
3840
|
+
});
|
|
3458
3841
|
let addTestImplementation = false;
|
|
3459
3842
|
let testImplementationType = '';
|
|
3460
3843
|
addTestImplementation = offersTestImplementation() && await interaction_confirm({
|
|
@@ -3494,6 +3877,11 @@ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>
|
|
|
3494
3877
|
export const wire${aggregateNaming.ClassName}Repository = envBranchedWire(${envBranchedWireArgument(`wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation`, `wire${implementationNaming.ClassName}Implementation`)})
|
|
3495
3878
|
`.trim());
|
|
3496
3879
|
await wireNewModuleDependencies(boundedContextFolder, wireFile, inMemoryRepositoryWiring(boundedContextFolder, repository, wireFile));
|
|
3880
|
+
if (withIntegrationSpec) scaffoldIntegrationSpec({
|
|
3881
|
+
kind: 'aggregate',
|
|
3882
|
+
name: aggregateNaming.fileName,
|
|
3883
|
+
ownerPath: boundedContextFolder.path
|
|
3884
|
+
}, new UnknownFormatNaming(infrastructureImplementationType).fileName);
|
|
3497
3885
|
}
|
|
3498
3886
|
}
|
|
3499
3887
|
};
|
|
@@ -3517,9 +3905,14 @@ export abstract class ${naming.ClassName} {
|
|
|
3517
3905
|
}
|
|
3518
3906
|
`.trim());
|
|
3519
3907
|
const crossContext = hasNeighboringBoundedContext(boundedContextFolder.path);
|
|
3520
|
-
const
|
|
3908
|
+
const primary = await promptImplementationType('Adapter implementation type:', 'ports', {
|
|
3521
3909
|
crossContext
|
|
3522
3910
|
});
|
|
3911
|
+
const implementationType = primary.label;
|
|
3912
|
+
const withIntegrationSpec = await wantsIntegrationTests(primary.label, {
|
|
3913
|
+
entered: primary.entered,
|
|
3914
|
+
save: primary.saveForFutureUse
|
|
3915
|
+
});
|
|
3523
3916
|
const addTestImplementation = offersTestImplementation() && await interaction_confirm({
|
|
3524
3917
|
key: 'withTestImplementation',
|
|
3525
3918
|
message: 'With test implementation'
|
|
@@ -3560,6 +3953,11 @@ export const wire${naming.ClassName} = envBranchedWire(${envBranchedWireArgument
|
|
|
3560
3953
|
|
|
3561
3954
|
`.trim());
|
|
3562
3955
|
await wireNewModuleDependencies(boundedContextFolder, wireFile);
|
|
3956
|
+
if (withIntegrationSpec) scaffoldIntegrationSpec({
|
|
3957
|
+
kind: 'port',
|
|
3958
|
+
name: naming.fileName,
|
|
3959
|
+
ownerPath: boundedContextFolder.path
|
|
3960
|
+
}, new UnknownFormatNaming(implementationType).fileName);
|
|
3563
3961
|
}
|
|
3564
3962
|
};
|
|
3565
3963
|
const scaffoldNewApplicationService = async (boundedContextFolder)=>{
|
|
@@ -3638,7 +4036,12 @@ const scaffoldNewCommand = async (boundedContextFolder)=>{
|
|
|
3638
4036
|
message: 'Name: '
|
|
3639
4037
|
});
|
|
3640
4038
|
const naming = new UnknownFormatNaming(commandName);
|
|
3641
|
-
const
|
|
4039
|
+
const primary = await promptImplementationType('Command infrastructure implementation type:', 'commands');
|
|
4040
|
+
const implementationType = primary.label;
|
|
4041
|
+
const withIntegrationSpec = await wantsIntegrationTests(primary.label, {
|
|
4042
|
+
entered: primary.entered,
|
|
4043
|
+
save: primary.saveForFutureUse
|
|
4044
|
+
});
|
|
3642
4045
|
let addTestImplementation = false;
|
|
3643
4046
|
let testImplementationType = '';
|
|
3644
4047
|
addTestImplementation = offersTestImplementation() && await interaction_confirm({
|
|
@@ -3691,6 +4094,11 @@ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>
|
|
|
3691
4094
|
export const wire${naming.ClassName}Command = envBranchedWire(${envBranchedWireArgument(`wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation`, `wire${implementationNaming.ClassName}Implementation`)})
|
|
3692
4095
|
`.trim());
|
|
3693
4096
|
await wireNewModuleDependencies(boundedContextFolder, wireFile);
|
|
4097
|
+
if (withIntegrationSpec) scaffoldIntegrationSpec({
|
|
4098
|
+
kind: 'command',
|
|
4099
|
+
name: naming.fileName,
|
|
4100
|
+
ownerPath: boundedContextFolder.path
|
|
4101
|
+
}, new UnknownFormatNaming(implementationType).fileName);
|
|
3694
4102
|
}
|
|
3695
4103
|
};
|
|
3696
4104
|
const scaffold_new_domain_object_noAggregate = 'No aggregate';
|
|
@@ -4064,7 +4472,7 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
|
|
|
4064
4472
|
pageSize: 20
|
|
4065
4473
|
});
|
|
4066
4474
|
const kind = 'aggregate' === unit.kind ? 'repositories' : 'command' === unit.kind ? 'commands' : 'query' === unit.kind ? 'queries' : 'ports';
|
|
4067
|
-
const { label, saveForFutureUse } = await promptImplementationType('Implementation type:', kind, {
|
|
4475
|
+
const { label, saveForFutureUse, entered } = await promptImplementationType('Implementation type:', kind, {
|
|
4068
4476
|
existing: unit.labels,
|
|
4069
4477
|
purpose: 'all',
|
|
4070
4478
|
remember: false,
|
|
@@ -4078,12 +4486,23 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
|
|
|
4078
4486
|
if (branches.test && environments.includes(branches.test)) rememberImplementation(kind, 'test', label);
|
|
4079
4487
|
if (environments.some((environment)=>environment !== branches.test)) rememberImplementation(kind, 'primary', label);
|
|
4080
4488
|
};
|
|
4081
|
-
if (!ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire'))
|
|
4489
|
+
if (!ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) {
|
|
4490
|
+
rememberFor(branches.primary);
|
|
4491
|
+
await wantsIntegrationTests(label, {
|
|
4492
|
+
entered: false,
|
|
4493
|
+
save: false
|
|
4494
|
+
});
|
|
4495
|
+
return;
|
|
4496
|
+
}
|
|
4082
4497
|
const wireFile = new File(ownerFolder.path).subitem(contractWireFile(unit).split('/'));
|
|
4083
4498
|
const wireName = `wire${contractClassName(unit)}`;
|
|
4084
4499
|
const wired = branchesOf(wireFile, wireName);
|
|
4085
4500
|
if (!wired) {
|
|
4086
4501
|
rememberFor(branches.primary);
|
|
4502
|
+
await wantsIntegrationTests(label, {
|
|
4503
|
+
entered: false,
|
|
4504
|
+
save: false
|
|
4505
|
+
});
|
|
4087
4506
|
report(`${wireFile.path} has no ${wireName} = envBranchedWire({...}): wire ${className} there yourself.`);
|
|
4088
4507
|
return;
|
|
4089
4508
|
}
|
|
@@ -4112,6 +4531,11 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
|
|
|
4112
4531
|
required: true
|
|
4113
4532
|
});
|
|
4114
4533
|
rememberFor(chosenEnvironments);
|
|
4534
|
+
const primaryRole = chosenEnvironments.some((environment)=>environment !== branches.test);
|
|
4535
|
+
const withIntegrationSpec = await wantsIntegrationTests(label, {
|
|
4536
|
+
entered: primaryRole && entered,
|
|
4537
|
+
save: saveForFutureUse
|
|
4538
|
+
}) && primaryRole;
|
|
4115
4539
|
const before = readWiredModule(wireFile.path, ownerFolder.path);
|
|
4116
4540
|
wireFile.update(addBranchedImplementation(wireFile.data, wireName, {
|
|
4117
4541
|
importLine: `import { ${className} } from '${relativeImport(wireFile.path, file.path)}'`,
|
|
@@ -4120,6 +4544,7 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
|
|
|
4120
4544
|
environments: chosenEnvironments
|
|
4121
4545
|
}));
|
|
4122
4546
|
const after = readWiredModule(wireFile.path, ownerFolder.path);
|
|
4547
|
+
if (withIntegrationSpec) scaffoldIntegrationSpec(unit, label);
|
|
4123
4548
|
const unused = (before?.implementations ?? []).filter((x)=>!after?.implementations.some((y)=>y.className === x.className));
|
|
4124
4549
|
for (const implementation of unused)report(`${implementation.className} is no longer used in any environment.`);
|
|
4125
4550
|
await wireNewImplementationDependencies(ownerFolder, wireFile, className, inMemoryRepositoryWiring(ownerFolder, unit, wireFile));
|
|
@@ -4172,6 +4597,7 @@ const scaffoldNewInfrastructureService = async (boundedContextFolder)=>{
|
|
|
4172
4597
|
message: 'Name: '
|
|
4173
4598
|
});
|
|
4174
4599
|
const naming = new UnknownFormatNaming(name);
|
|
4600
|
+
const withIntegrationSpec = await wantsServiceIntegrationSpec();
|
|
4175
4601
|
const withWiring = ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
|
|
4176
4602
|
const wiringFolder = boundedContextFolder.subitem([
|
|
4177
4603
|
'wiring',
|
|
@@ -4197,6 +4623,11 @@ export const wire${naming.ClassName}InfrastructureService = wireClass(
|
|
|
4197
4623
|
)
|
|
4198
4624
|
`.trim());
|
|
4199
4625
|
await wireNewModuleDependencies(boundedContextFolder, wireFile);
|
|
4626
|
+
if (withIntegrationSpec) scaffoldIntegrationSpec({
|
|
4627
|
+
kind: 'infrastructure-service',
|
|
4628
|
+
name: naming.fileName,
|
|
4629
|
+
ownerPath: boundedContextFolder.path
|
|
4630
|
+
});
|
|
4200
4631
|
}
|
|
4201
4632
|
};
|
|
4202
4633
|
const scaffoldNewQuery = async (boundedContextFolder)=>{
|
|
@@ -4209,7 +4640,12 @@ const scaffoldNewQuery = async (boundedContextFolder)=>{
|
|
|
4209
4640
|
message: 'Name: '
|
|
4210
4641
|
});
|
|
4211
4642
|
const naming = new UnknownFormatNaming(queryName);
|
|
4212
|
-
const
|
|
4643
|
+
const primary = await promptImplementationType('Query infrastructure implementation type:', 'queries');
|
|
4644
|
+
const implementationType = primary.label;
|
|
4645
|
+
const withIntegrationSpec = await wantsIntegrationTests(primary.label, {
|
|
4646
|
+
entered: primary.entered,
|
|
4647
|
+
save: primary.saveForFutureUse
|
|
4648
|
+
});
|
|
4213
4649
|
let addTestImplementation = false;
|
|
4214
4650
|
let testImplementationType = '';
|
|
4215
4651
|
addTestImplementation = offersTestImplementation() && await interaction_confirm({
|
|
@@ -4262,6 +4698,11 @@ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>
|
|
|
4262
4698
|
export const wire${naming.ClassName}Query = envBranchedWire(${envBranchedWireArgument(`wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation`, `wire${implementationNaming.ClassName}Implementation`)})
|
|
4263
4699
|
`.trim());
|
|
4264
4700
|
await wireNewModuleDependencies(boundedContextFolder, wireFile);
|
|
4701
|
+
if (withIntegrationSpec) scaffoldIntegrationSpec({
|
|
4702
|
+
kind: 'query',
|
|
4703
|
+
name: naming.fileName,
|
|
4704
|
+
ownerPath: boundedContextFolder.path
|
|
4705
|
+
}, new UnknownFormatNaming(implementationType).fileName);
|
|
4265
4706
|
}
|
|
4266
4707
|
};
|
|
4267
4708
|
const scaffoldNewUseCase = async (boundedContextFolder)=>{
|
|
@@ -4522,4 +4963,4 @@ export const use${ClassName}UIModel = (widgetProps: Omit<${ClassName}WidgetProps
|
|
|
4522
4963
|
break;
|
|
4523
4964
|
}
|
|
4524
4965
|
};
|
|
4525
|
-
export { RequestError, addIntegration, assertAnswersConsumed, configurationSections, deleteBackendUnitUseCase, deleteReactModuleUseCase, findBackendUnits, findContracts, findReactModules, findRestEndpointGenerator, helperImplementationTypes, initializeUseCase, integrationDescriptions, integrationIds, moduleId, moveBackendUnitUseCase, moveReactModuleUseCase, printNextSteps, reactKindTitles, rootControllerChoice, runWithAnswers, savePendingChanges, savedImplementations, scaffoldNewAggregateUseCase, scaffoldNewApplicationPort, scaffoldNewApplicationService, scaffoldNewBoundedContextUseCase, scaffoldNewCommand, scaffoldNewDomainObject, scaffoldNewDomainService, scaffoldNewErrorUseCase, scaffoldNewHandlersRestEndpoint, scaffoldNewImplementation, scaffoldNewInfrastructureHelper, scaffoldNewInfrastructureService, scaffoldNewPresentationService, scaffoldNewQuery, scaffoldNewUseCase, scaffoldReactPage, scaffoldReactSharedHook, scaffoldReactUIKitComponent, scaffoldReactWidget, systemImplementationChoices, unitId, wireDependency };
|
|
4966
|
+
export { RequestError, addIntegration, assertAnswersConsumed, configurationSections, deleteBackendUnitUseCase, deleteReactModuleUseCase, findBackendUnits, findContracts, findReactModules, findRestEndpointGenerator, helperImplementationTypes, initializeUseCase, integrationDescriptions, integrationIds, integrationSpecFile, integrationSpecsAvailable, moduleId, moveBackendUnitUseCase, moveReactModuleUseCase, printNextSteps, reactKindTitles, rootControllerChoice, runWithAnswers, savePendingChanges, savedImplementations, scaffoldNewAggregateUseCase, scaffoldNewApplicationPort, scaffoldNewApplicationService, scaffoldNewBoundedContextUseCase, scaffoldNewCommand, scaffoldNewDomainObject, scaffoldNewDomainService, scaffoldNewErrorUseCase, scaffoldNewHandlersRestEndpoint, scaffoldNewImplementation, scaffoldNewInfrastructureHelper, scaffoldNewInfrastructureService, scaffoldNewPresentationService, scaffoldNewQuery, scaffoldNewUseCase, scaffoldReactPage, scaffoldReactSharedHook, scaffoldReactUIKitComponent, scaffoldReactWidget, systemImplementationChoices, unitId, wireDependency };
|