@domain-first/project-structure 5.1.2 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +18 -21
  2. package/dist/201.js +46 -35
  3. package/dist/287.js +3290 -0
  4. package/dist/config-file.d.ts +2 -2
  5. package/dist/dependency-rules.d.ts +1 -1
  6. package/dist/file-system.d.ts +5 -0
  7. package/dist/in-memory-db.d.ts +5 -0
  8. package/dist/index.cjs +195 -2156
  9. package/dist/index.js +9 -3169
  10. package/dist/init.cjs +868 -0
  11. package/dist/init.d.ts +2 -0
  12. package/dist/init.js +36 -0
  13. package/dist/integration.cjs +2063 -0
  14. package/dist/integration.d.ts +2 -0
  15. package/dist/integration.js +31 -0
  16. package/dist/integrations/in-memory-db.d.ts +6 -0
  17. package/dist/integrations/index.d.ts +2 -0
  18. package/dist/integrations/missing-domain-first-packages.d.ts +8 -0
  19. package/dist/integrations/orval.d.ts +7 -4
  20. package/dist/integrations/rest-endpoint-generator.d.ts +18 -0
  21. package/dist/integrations/rest-endpoint-generator.spec.d.ts +1 -0
  22. package/dist/lint.cjs +8 -8
  23. package/dist/lint.js +7 -7
  24. package/dist/print-next-steps.d.ts +9 -2
  25. package/dist/react.cjs +915 -0
  26. package/dist/react.d.ts +2 -0
  27. package/dist/react.js +73 -0
  28. package/dist/use-cases/add-integration-order.spec.d.ts +1 -0
  29. package/dist/use-cases/rest-endpoint-generator.d.ts +1 -1
  30. package/package.json +5 -2
  31. package/skills/df-ps-implement/SKILL.md +12 -57
  32. package/skills/df-ps-plan-feature/SKILL.md +7 -7
  33. package/skills/df-ps-project-scripts/SKILL.md +1 -1
  34. package/skills/df-ps-react/SKILL.md +82 -0
  35. package/skills/df-ps-react/references/generators.md +80 -0
  36. package/skills/df-ps-scaffold/SKILL.md +46 -28
  37. package/skills/df-ps-scaffold/references/choosing-components.md +7 -28
  38. package/skills/df-ps-scaffold/references/generators.md +6 -179
  39. package/skills/df-ps-scaffold/references/units/aggregate.md +47 -0
  40. package/skills/df-ps-scaffold/references/units/bounded-context.md +13 -0
  41. package/skills/df-ps-scaffold/references/units/command-query.md +32 -0
  42. package/skills/df-ps-scaffold/references/units/endpoint.md +28 -0
  43. package/skills/df-ps-scaffold/references/units/entity-value-object.md +27 -0
  44. package/skills/df-ps-scaffold/references/units/errors.md +26 -0
  45. package/skills/df-ps-scaffold/references/units/port.md +23 -0
  46. package/skills/df-ps-scaffold/references/units/services.md +28 -0
  47. package/skills/df-ps-scaffold/references/units/use-case.md +25 -0
  48. package/skills/df-ps-scaffold/references/units/wire-dependency.md +15 -0
  49. package/skills/df-ps-scaffold/scripts/drive.mjs +12 -4
@@ -0,0 +1,2063 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __webpack_require__ = {};
4
+ (()=>{
5
+ __webpack_require__.n = (module)=>{
6
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
7
+ __webpack_require__.d(getter, {
8
+ a: getter
9
+ });
10
+ return getter;
11
+ };
12
+ })();
13
+ (()=>{
14
+ __webpack_require__.d = (exports1, getters, values)=>{
15
+ var define = (defs, kind)=>{
16
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
17
+ enumerable: true,
18
+ [kind]: defs[key]
19
+ });
20
+ };
21
+ define(getters, "get");
22
+ define(values, "value");
23
+ };
24
+ })();
25
+ (()=>{
26
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
27
+ })();
28
+ var __webpack_exports__ = {};
29
+ const external_node_util_namespaceObject = require("node:util");
30
+ const external_node_path_namespaceObject = require("node:path");
31
+ var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_namespaceObject);
32
+ const external_zod_namespaceObject = require("zod");
33
+ var external_zod_default = /*#__PURE__*/ __webpack_require__.n(external_zod_namespaceObject);
34
+ const moduleKinds = [
35
+ 'repositories',
36
+ 'domain-services',
37
+ 'application-ports',
38
+ 'application-services',
39
+ 'use-cases',
40
+ 'commands',
41
+ 'queries',
42
+ 'infrastructure-services',
43
+ 'presentation-services'
44
+ ];
45
+ const domain = [
46
+ 'repositories',
47
+ 'domain-services'
48
+ ];
49
+ const commandsAndQueries = [
50
+ 'commands',
51
+ 'queries'
52
+ ];
53
+ const infrastructure = [
54
+ ...domain,
55
+ 'application-ports',
56
+ 'infrastructure-services'
57
+ ];
58
+ const defaultDependencies = {
59
+ 'domain-services': [
60
+ 'domain-services'
61
+ ],
62
+ repositories: [
63
+ 'domain-services',
64
+ 'application-ports',
65
+ 'infrastructure-services'
66
+ ],
67
+ 'application-ports': infrastructure,
68
+ 'application-services': [
69
+ ...domain,
70
+ 'application-ports',
71
+ ...commandsAndQueries
72
+ ],
73
+ 'use-cases': [
74
+ ...domain,
75
+ 'application-ports',
76
+ 'application-services',
77
+ ...commandsAndQueries
78
+ ],
79
+ commands: [
80
+ 'infrastructure-services'
81
+ ],
82
+ queries: [
83
+ 'infrastructure-services'
84
+ ],
85
+ 'infrastructure-services': infrastructure,
86
+ 'presentation-services': [
87
+ 'application-ports',
88
+ 'application-services',
89
+ 'use-cases',
90
+ ...commandsAndQueries,
91
+ 'presentation-services'
92
+ ]
93
+ };
94
+ const kindSchema = external_zod_default()["enum"](moduleKinds);
95
+ const dependencyRulesSchema = external_zod_default().partialRecord(kindSchema, external_zod_default().union([
96
+ external_zod_default().array(kindSchema),
97
+ external_zod_default().object({
98
+ add: external_zod_default().array(kindSchema).optional(),
99
+ remove: external_zod_default().array(kindSchema).optional()
100
+ })
101
+ ]));
102
+ const dependency_rules_resolveDependencyRules = (config = {})=>{
103
+ const entries = moduleKinds.map((kind)=>{
104
+ const override = config[kind];
105
+ if (Array.isArray(override)) return [
106
+ kind,
107
+ new Set(override)
108
+ ];
109
+ const kinds = new Set([
110
+ ...defaultDependencies[kind],
111
+ ...override?.add ?? []
112
+ ]);
113
+ for (const removed of override?.remove ?? [])kinds.delete(removed);
114
+ return [
115
+ kind,
116
+ kinds
117
+ ];
118
+ });
119
+ return Object.fromEntries(entries);
120
+ };
121
+ dependency_rules_resolveDependencyRules();
122
+ const external_node_fs_namespaceObject = require("node:fs");
123
+ var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
124
+ const pendingFiles = new Map();
125
+ const pendingFolders = new Set();
126
+ const pendingMoves = new Map();
127
+ const pendingDeletions = new Map();
128
+ const filesToOverwrite = ()=>[
129
+ ...pendingFiles
130
+ ].filter(([filePath, { replacesFile }])=>replacesFile && external_node_fs_default().existsSync(filePath)).map(([filePath])=>filePath);
131
+ const withoutOverwrites = (generate)=>{
132
+ const before = new Map(pendingFiles);
133
+ const result = generate();
134
+ for (const [filePath, change] of pendingFiles){
135
+ if (before.get(filePath) === change || !change.replacesFile || !external_node_fs_default().existsSync(filePath)) continue;
136
+ const previous = before.get(filePath);
137
+ if (previous) pendingFiles.set(filePath, previous);
138
+ else pendingFiles.delete(filePath);
139
+ }
140
+ return result;
141
+ };
142
+ const file_system_discardPendingChanges = ()=>{
143
+ pendingFolders.clear();
144
+ pendingFiles.clear();
145
+ pendingMoves.clear();
146
+ pendingDeletions.clear();
147
+ };
148
+ const removeEmptyFolders = (folderPath, stopAt)=>{
149
+ let current = folderPath;
150
+ while(current.startsWith(`${stopAt}${external_node_path_default().sep}`) && external_node_fs_default().existsSync(current) && !external_node_fs_default().readdirSync(current).length){
151
+ external_node_fs_default().rmdirSync(current);
152
+ current = external_node_path_default().dirname(current);
153
+ }
154
+ };
155
+ const writePendingChanges = ()=>{
156
+ for (const folderPath of pendingFolders)external_node_fs_default().mkdirSync(folderPath, {
157
+ recursive: true
158
+ });
159
+ for (const [filePath, { content }] of pendingFiles){
160
+ external_node_fs_default().mkdirSync(external_node_path_default().dirname(filePath), {
161
+ recursive: true
162
+ });
163
+ external_node_fs_default().writeFileSync(filePath, content, 'utf8');
164
+ }
165
+ for (const [targetPath, { sourcePath }] of pendingMoves){
166
+ external_node_fs_default().mkdirSync(external_node_path_default().dirname(targetPath), {
167
+ recursive: true
168
+ });
169
+ external_node_fs_default().renameSync(sourcePath, targetPath);
170
+ }
171
+ for (const filePath of pendingDeletions.keys())external_node_fs_default().rmSync(filePath, {
172
+ force: true
173
+ });
174
+ for (const [filePath, stopAt] of pendingDeletions)removeEmptyFolders(external_node_path_default().dirname(filePath), stopAt);
175
+ for (const { sourcePath, stopAt } of pendingMoves.values())removeEmptyFolders(external_node_path_default().dirname(sourcePath), stopAt);
176
+ file_system_discardPendingChanges();
177
+ };
178
+ class FileSystemItem {
179
+ path;
180
+ constructor(path){
181
+ this.path = path;
182
+ }
183
+ subitem = (relativePath)=>new this.constructor(external_node_path_default().resolve(this.path, ...relativePath));
184
+ get exists() {
185
+ return external_node_fs_default().existsSync(this.path);
186
+ }
187
+ }
188
+ class file_system_Folder extends FileSystemItem {
189
+ createIfNotExisted = ()=>{
190
+ pendingFolders.add(this.path);
191
+ };
192
+ get content() {
193
+ if (!this.exists) return {
194
+ subfolderNames: [],
195
+ fileNames: []
196
+ };
197
+ const content = external_node_fs_default().readdirSync(this.path, {
198
+ withFileTypes: true
199
+ });
200
+ return {
201
+ subfolderNames: content.filter((x)=>x.isDirectory()).map((x)=>x.name),
202
+ fileNames: content.filter((x)=>!x.isDirectory()).map((x)=>external_node_path_default().parse(x.name).name)
203
+ };
204
+ }
205
+ get name() {
206
+ return external_node_path_default().basename(this.path);
207
+ }
208
+ createFile = (name, content)=>{
209
+ this.createIfNotExisted();
210
+ const file = new file_system_File(this.path).subitem([
211
+ name
212
+ ]);
213
+ file.data = content;
214
+ return file;
215
+ };
216
+ file = (name)=>{
217
+ this.createIfNotExisted();
218
+ const file = new file_system_File(this.path).subitem([
219
+ name
220
+ ]);
221
+ return file;
222
+ };
223
+ }
224
+ class file_system_File extends FileSystemItem {
225
+ get exists() {
226
+ return pendingFiles.has(this.path) || pendingMoves.has(this.path) || external_node_fs_default().existsSync(this.path) && !pendingDeletions.has(this.path);
227
+ }
228
+ delete = (stopAt)=>{
229
+ pendingDeletions.set(this.path, stopAt);
230
+ };
231
+ moveTo = (targetPath, stopAt)=>{
232
+ pendingMoves.set(targetPath, {
233
+ sourcePath: this.path,
234
+ stopAt
235
+ });
236
+ };
237
+ get data() {
238
+ const pendingFile = pendingFiles.get(this.path);
239
+ if (pendingFile) return pendingFile.content;
240
+ if (!this.exists) throw new Error('File does not exist');
241
+ return external_node_fs_default().readFileSync(this.path, 'utf-8');
242
+ }
243
+ set data(content) {
244
+ pendingFiles.set(this.path, {
245
+ content,
246
+ replacesFile: true
247
+ });
248
+ }
249
+ update = (content)=>{
250
+ pendingFiles.set(this.path, {
251
+ content,
252
+ replacesFile: pendingFiles.get(this.path)?.replacesFile ?? false
253
+ });
254
+ };
255
+ addLine = (newLine, separator = '\n')=>{
256
+ const content = this.exists ? this.data : '';
257
+ pendingFiles.set(this.path, {
258
+ content: [
259
+ content.trim(),
260
+ newLine.trim()
261
+ ].filter((x)=>!!x).join(separator),
262
+ replacesFile: pendingFiles.get(this.path)?.replacesFile ?? false
263
+ });
264
+ };
265
+ addLineIfMissing = (newLine, separator = '\n')=>{
266
+ const alreadyAdded = this.exists && this.data.split('\n').some((line)=>line.trim() === newLine.trim());
267
+ if (!alreadyAdded) this.addLine(newLine, separator);
268
+ };
269
+ }
270
+ class project_root_ProjectRoot {
271
+ path;
272
+ constructor(){
273
+ let dir = process.cwd();
274
+ while(dir !== external_node_path_default().parse(dir).root){
275
+ if (external_node_fs_default().existsSync(external_node_path_default().join(dir, 'package.json'))) {
276
+ this.path = dir;
277
+ return;
278
+ }
279
+ dir = external_node_path_default().dirname(dir);
280
+ }
281
+ throw new Error('No package.json was found');
282
+ }
283
+ }
284
+ const lintChecks = [
285
+ 'context-isolation',
286
+ 'shared-kernel',
287
+ 'layers',
288
+ 'dependencies',
289
+ 'react',
290
+ 'clock'
291
+ ];
292
+ const configFileName = 'domain-first.project-structure.config.json';
293
+ const configSchema = external_zod_default().object({
294
+ rootFolder: external_zod_default().string(),
295
+ domainFirstPackages: external_zod_default().array(external_zod_default()["enum"]([
296
+ '@domain-first/types',
297
+ '@domain-first/errors',
298
+ '@domain-first/handlers',
299
+ '@domain-first/wire',
300
+ '@domain-first/handlers-rest'
301
+ ])),
302
+ defaultPersistenceLayerImplementation: external_zod_default().string(),
303
+ withInMemoryDb: external_zod_default().boolean().optional(),
304
+ useReact: external_zod_default().boolean(),
305
+ storybookFramework: external_zod_default().string().optional(),
306
+ testingLibrary: external_zod_default().string().optional(),
307
+ rules: external_zod_default().object({
308
+ dependencies: dependencyRulesSchema.optional(),
309
+ lint: external_zod_default().partialRecord(external_zod_default()["enum"](lintChecks), external_zod_default().boolean()).optional()
310
+ }).optional()
311
+ });
312
+ class config_file_ConfigFile {
313
+ data;
314
+ constructor(){
315
+ const filePath = config_file_ConfigFile.path;
316
+ const file = new file_system_File(filePath);
317
+ const configObject = JSON.parse(file.data);
318
+ this.data = configSchema.parse(configObject);
319
+ }
320
+ static get Instance() {
321
+ return new config_file_ConfigFile();
322
+ }
323
+ static get path() {
324
+ const { path: root } = new project_root_ProjectRoot();
325
+ return external_node_path_default().resolve(root, configFileName);
326
+ }
327
+ static get exists() {
328
+ return new file_system_File(config_file_ConfigFile.path).exists;
329
+ }
330
+ static write = (config)=>{
331
+ new file_system_File(config_file_ConfigFile.path).data = JSON.stringify(config, null, '\t');
332
+ };
333
+ }
334
+ const prompts_namespaceObject = require("@inquirer/prompts");
335
+ const wiring_relativeImport = (fromFile, toFile)=>{
336
+ const relativePath = external_node_path_default().relative(external_node_path_default().dirname(fromFile), toFile).replace(/\.ts$/, '').split(external_node_path_default().sep).join('/');
337
+ return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
338
+ };
339
+ const inMemoryDbService = `type Entry = {
340
+ id: unknown;
341
+ item: any;
342
+ };
343
+
344
+ declare global {
345
+ var ___SHARED_IN_MEMORY_DB___: Record<string, Array<Entry>> | undefined;
346
+ }
347
+
348
+ type Section<T, TId> = {
349
+ all: (predicate?: (x: T) => boolean) => T[];
350
+ first: (predicate: (x: T) => boolean) => T | null;
351
+ withId: (id: TId) => T | null;
352
+ lastAddedItem: () => T | null;
353
+ save: (payload: T extends { id: TId } ? T : [TId, T]) => void;
354
+ deleteById: (id: TId) => void;
355
+ delete: (predicate: (x: T) => boolean) => void;
356
+ };
357
+
358
+ type IdsAreEqual<TId> = (a: TId, b: TId) => boolean;
359
+
360
+ const comparisonMethodNames = ['equals', 'same', 'isSame', 'isEqual'] as const;
361
+
362
+ const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
363
+ if (typeof a !== 'object' || a === null) {
364
+ return Object.is(a, b);
365
+ }
366
+
367
+ for (const methodName of comparisonMethodNames) {
368
+ const method: unknown = (a as Record<string, unknown>)[methodName];
369
+ if (typeof method === 'function') {
370
+ return Boolean(method.call(a, b));
371
+ }
372
+ }
373
+
374
+ return Object.is(a, b);
375
+ };
376
+
377
+ const hasId = (x: unknown): x is { id: unknown } =>
378
+ typeof x === 'object' && x !== null && 'id' in x;
379
+
380
+ export class InMemoryDbInfrastructureService {
381
+ protected section<T extends { id: unknown }>(
382
+ key: string,
383
+ idsAreEqual?: IdsAreEqual<T['id']>
384
+ ): Section<T, T['id']>;
385
+ protected section<T, TId>(
386
+ key: string,
387
+ idsAreEqual?: IdsAreEqual<TId>
388
+ ): Section<T, TId>;
389
+ protected section<T, TId>(
390
+ key: string,
391
+ idsAreEqual: IdsAreEqual<TId> = defaultIdsAreEqual
392
+ ): Section<T, TId> {
393
+ if (!globalThis.___SHARED_IN_MEMORY_DB___) {
394
+ globalThis.___SHARED_IN_MEMORY_DB___ = {};
395
+ }
396
+
397
+ if (!globalThis.___SHARED_IN_MEMORY_DB___[key]) {
398
+ globalThis.___SHARED_IN_MEMORY_DB___[key] = [];
399
+ }
400
+
401
+ const items = (): T[] =>
402
+ globalThis.___SHARED_IN_MEMORY_DB___![key].map(
403
+ (entry) => entry.item
404
+ );
405
+
406
+ return {
407
+ all: (predicate: (x: T) => boolean = () => true): T[] =>
408
+ items().filter(predicate),
409
+ first: (predicate: (x: T) => boolean): T | null =>
410
+ items().find(predicate) ?? null,
411
+ withId: (id: TId): T | null =>
412
+ items().find(
413
+ (x: T) => hasId(x) && idsAreEqual(x.id as TId, id)
414
+ ) ?? null,
415
+ lastAddedItem: (): T | null =>
416
+ globalThis.___SHARED_IN_MEMORY_DB___![key].at(-1)?.item ?? null,
417
+ save: (payload: T extends { id: TId } ? T : [TId, T]) => {
418
+ const id = Array.isArray(payload) ? payload[0] : payload.id;
419
+ const item = Array.isArray(payload) ? payload[1] : payload;
420
+ const entries = globalThis.___SHARED_IN_MEMORY_DB___![key];
421
+ const existing = entries.find((entry) =>
422
+ idsAreEqual(entry.id as TId, id)
423
+ );
424
+ if (existing) {
425
+ existing.item = item;
426
+ return;
427
+ }
428
+ entries.push({ id, item });
429
+ },
430
+ deleteById: (id: TId) => {
431
+ globalThis.___SHARED_IN_MEMORY_DB___![key] =
432
+ globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
433
+ (entry) => !idsAreEqual(entry.id as TId, id)
434
+ );
435
+ },
436
+ delete: (predicate: (x: T) => boolean) => {
437
+ globalThis.___SHARED_IN_MEMORY_DB___![key] =
438
+ globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
439
+ (entry) => !predicate(entry.item)
440
+ );
441
+ }
442
+ };
443
+ }
444
+ }
445
+ `;
446
+ const inMemoryDbWiring = `import { wireClass } from '@domain-first/wire';
447
+ import { InMemoryDbInfrastructureService } from '../../infrastructure/services/in-memory-db-infrastructure-service';
448
+
449
+ export const wireInMemoryDbInfrastructureService = wireClass(
450
+ InMemoryDbInfrastructureService,
451
+ []
452
+ );
453
+ `;
454
+ const inMemoryDbSpec = (testingLibrary, withWiring)=>`
455
+ import { describe, test, expect, beforeEach } from '${testingLibrary}'
456
+ ${withWiring ? `import { type InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'
457
+ import { wireInMemoryDbInfrastructureService } from '../../wiring/infrastructure-services/wire-in-memory-db-infrastructure-service'` : "import { InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'"}
458
+
459
+ let inMemoryDbInfrastructureService: InMemoryDbInfrastructureService
460
+
461
+ beforeEach(() => {
462
+ inMemoryDbInfrastructureService = ${withWiring ? 'wireInMemoryDbInfrastructureService()' : 'new InMemoryDbInfrastructureService()'}
463
+ })
464
+
465
+ describe('in memory db', () => {
466
+ test('can be ${withWiring ? 'wired' : 'created'}', () => {
467
+ expect(inMemoryDbInfrastructureService).toBeDefined()
468
+ })
469
+ })
470
+ `.trim();
471
+ const in_memory_db_withWiring = ()=>config_file_ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
472
+ const in_memory_db_sharedFolder = ()=>new file_system_Folder(new project_root_ProjectRoot().path).subitem([
473
+ config_file_ConfigFile.Instance.data.rootFolder,
474
+ 'shared-kernel'
475
+ ]);
476
+ const serviceFile = ()=>new file_system_File(in_memory_db_sharedFolder().path).subitem([
477
+ 'infrastructure',
478
+ 'services',
479
+ 'in-memory-db-infrastructure-service.ts'
480
+ ]);
481
+ const in_memory_db_wireFile = ()=>new file_system_File(in_memory_db_sharedFolder().path).subitem([
482
+ 'wiring',
483
+ 'infrastructure-services',
484
+ 'wire-in-memory-db-infrastructure-service.ts'
485
+ ]);
486
+ const in_memory_db_scaffoldInMemoryDb = (shared)=>{
487
+ const { testingLibrary } = config_file_ConfigFile.Instance.data;
488
+ const servicesFolder = shared.subitem([
489
+ 'infrastructure',
490
+ 'services'
491
+ ]);
492
+ servicesFolder.createFile('in-memory-db-infrastructure-service.ts', inMemoryDbService);
493
+ if (testingLibrary) servicesFolder.createFile('in-memory-db-infrastructure-service.spec.ts', inMemoryDbSpec(testingLibrary, in_memory_db_withWiring()));
494
+ if (in_memory_db_withWiring()) shared.subitem([
495
+ 'wiring',
496
+ 'infrastructure-services'
497
+ ]).createFile('wire-in-memory-db-infrastructure-service.ts', inMemoryDbWiring);
498
+ };
499
+ const inMemoryDbScaffolded = ()=>serviceFile().exists && (!in_memory_db_withWiring() || in_memory_db_wireFile().exists);
500
+ const addInMemoryDb = ()=>{
501
+ const config = config_file_ConfigFile.Instance.data;
502
+ if (!config.withInMemoryDb) config_file_ConfigFile.write({
503
+ ...config,
504
+ withInMemoryDb: true
505
+ });
506
+ withoutOverwrites(()=>in_memory_db_scaffoldInMemoryDb(new file_system_Folder(new project_root_ProjectRoot().path).subitem([
507
+ config.rootFolder,
508
+ 'shared-kernel'
509
+ ])));
510
+ return [];
511
+ };
512
+ const inMemoryDbApplied = ()=>Boolean(config_file_ConfigFile.Instance.data.withInMemoryDb) && inMemoryDbScaffolded();
513
+ const hasDependency = (name)=>{
514
+ const manifestFile = new file_system_File(external_node_path_default().join(new project_root_ProjectRoot().path, 'package.json'));
515
+ if (!manifestFile.exists) return false;
516
+ const manifest = JSON.parse(manifestFile.data);
517
+ return [
518
+ manifest.dependencies,
519
+ manifest.devDependencies,
520
+ manifest.optionalDependencies
521
+ ].some((dependencies)=>dependencies && Object.hasOwn(dependencies, name));
522
+ };
523
+ const missingPackages = (packages)=>{
524
+ const missing = [
525
+ ...new Set(packages)
526
+ ].filter((name)=>!hasDependency(name));
527
+ return missing.length ? [
528
+ `npm i ${missing.join(' ')}`
529
+ ] : [];
530
+ };
531
+ const external_node_module_namespaceObject = require("node:module");
532
+ const tsconfig_stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
533
+ const resolveExtends = (fromFile, target)=>{
534
+ if (target.startsWith('.') || external_node_path_default().isAbsolute(target)) {
535
+ const resolved = external_node_path_default().resolve(external_node_path_default().dirname(fromFile), target);
536
+ return resolved.endsWith('.json') ? resolved : `${resolved}.json`;
537
+ }
538
+ const require1 = (0, external_node_module_namespaceObject.createRequire)(fromFile);
539
+ for (const candidate of [
540
+ target,
541
+ `${target}/tsconfig.json`
542
+ ])try {
543
+ return require1.resolve(candidate);
544
+ } catch {}
545
+ };
546
+ const compilerOption = (configFile, name, seen = new Set())=>{
547
+ if (seen.has(configFile) || !external_node_fs_default().existsSync(configFile)) return null;
548
+ seen.add(configFile);
549
+ let config;
550
+ try {
551
+ config = JSON.parse(tsconfig_stripJsonComments(external_node_fs_default().readFileSync(configFile, 'utf8')));
552
+ } catch {
553
+ return null;
554
+ }
555
+ if (config.compilerOptions && name in config.compilerOptions) return config.compilerOptions[name];
556
+ const parents = [
557
+ config.extends ?? []
558
+ ].flat().reverse();
559
+ for (const parent of parents){
560
+ const parentFile = resolveExtends(configFile, parent);
561
+ const value = parentFile ? compilerOption(parentFile, name, seen) : null;
562
+ if (void 0 !== value) return value;
563
+ }
564
+ };
565
+ const reactPageContent = (ClassName, { imports = [], body = '<></>' } = {})=>`
566
+ ${[
567
+ ...imports,
568
+ "import { type FC } from 'react'"
569
+ ].join('\n')}
570
+
571
+ export type ${ClassName}PageProps = {}
572
+
573
+ export const ${ClassName}Page: FC<${ClassName}PageProps> = (props) => {
574
+ return ${body}
575
+ }
576
+ `.trim();
577
+ const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
578
+ const rootFolderSegments = (rootFolder)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n `).join('');
579
+ const openapiExtractor = (rootFolder)=>`import path from 'node:path';
580
+ import {
581
+ type DocNode,
582
+ DocPlainText,
583
+ TSDocConfiguration,
584
+ TSDocParser,
585
+ TSDocTagDefinition,
586
+ TSDocTagSyntaxKind
587
+ } from '@microsoft/tsdoc';
588
+ import { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';
589
+
590
+ type BlockTag = \`@\${string}\`;
591
+
592
+ type OpenApiDataTags = {
593
+ /** Omit to take the summary from the comment text before the first tag. */
594
+ summary?: BlockTag;
595
+ description?: BlockTag;
596
+ };
597
+
598
+ type OpenApiData = Partial<{
599
+ summary: string;
600
+ description: string;
601
+ operationId: string;
602
+ }>;
603
+
604
+ const project = new Project({
605
+ tsConfigFilePath: 'tsconfig.json'
606
+ });
607
+
608
+ const getText = (node: DocNode): string =>
609
+ node
610
+ .getChildNodes()
611
+ .map((child) => {
612
+ if (child instanceof DocPlainText) {
613
+ return child.text;
614
+ }
615
+
616
+ return getText(child);
617
+ })
618
+ .join('');
619
+
620
+ const getRawCommentText = (comment: string): string =>
621
+ comment
622
+ .replace(/^\\/\\*\\*/, '')
623
+ .replace(/\\*\\/$/, '')
624
+ .split(/\\r?\\n/)
625
+ .map((line) => line.replace(/^\\s*\\*\\s?/, ''))
626
+ .join('\\n');
627
+
628
+ // TSDoc treats an unknown tag as summary content, so every block tag of the
629
+ // comment has to be registered for the summary section to end before it.
630
+ const parseSummary = (comment: string): string | undefined => {
631
+ const configuration = new TSDocConfiguration();
632
+ const tagNames = getRawCommentText(comment).matchAll(/(?:^|\\n)\\s*(@\\w+)/g);
633
+
634
+ for (const [, tagName] of tagNames) {
635
+ if (!configuration.tryGetTagDefinition(tagName)) {
636
+ configuration.addTagDefinition(
637
+ new TSDocTagDefinition({
638
+ tagName,
639
+ syntaxKind: TSDocTagSyntaxKind.BlockTag
640
+ })
641
+ );
642
+ }
643
+ }
644
+
645
+ const { docComment } = new TSDocParser(configuration).parseString(comment);
646
+
647
+ return getText(docComment.summarySection).trim() || undefined;
648
+ };
649
+
650
+ // Parsed by hand rather than through TSDoc, which drops the line breaks.
651
+ const getTagText = (comment: string, tag: BlockTag): string | undefined => {
652
+ const tagMatch = getRawCommentText(comment).match(
653
+ new RegExp(
654
+ \`(?:^|\\\\n)\\\\s*\${tag}(?:[ \\\\t]*\\\\n|[ \\\\t]+)([\\\\s\\\\S]*?)(?=\\\\n\\\\s*@\\\\w+|\\\\s*$)\`
655
+ )
656
+ );
657
+
658
+ return tagMatch?.[1].trim() || undefined;
659
+ };
660
+
661
+ // Endpoints pass their logic as the generator's first argument
662
+ // (\`this.endpointGenerator(this.handler.handle, ...)\`), while other injected
663
+ // queries only serve as helpers, e.g. guest checks.
664
+ const findHandlerClass = (endpointFile: SourceFile) =>
665
+ endpointFile
666
+ .getDescendantsOfKind(SyntaxKind.CallExpression)
667
+ .map((call) => call.getArguments()[0])
668
+ .filter(Node.isPropertyAccessExpression)
669
+ .find((argument) => argument.getName() === 'handle')
670
+ ?.getExpression()
671
+ .getType()
672
+ .getSymbol()
673
+ ?.getDeclarations()
674
+ .find(Node.isClassDeclaration);
675
+
676
+ // Path parameters (\`:id\`) can't be part of file and folder names
677
+ // everywhere (Windows), so endpoints name them \`_id_\` there.
678
+ const pathParameterAsName = (segment: string) =>
679
+ segment.startsWith(':') ? \`_\${segment.slice(1)}_\` : segment;
680
+
681
+ export const createOpenApiDataFromEndpointLogicExtractor = ({
682
+ summary: summaryTag,
683
+ description: descriptionTag = '@description'
684
+ }: OpenApiDataTags = {}) => {
685
+ return (routeMetadata: {
686
+ method: string;
687
+ path: readonly string[];
688
+ }): OpenApiData | undefined => {
689
+ try {
690
+ const [currentBoundedContext, controller, ...relativePath] =
691
+ routeMetadata.path;
692
+
693
+ if (!currentBoundedContext || !controller) {
694
+ return undefined;
695
+ }
696
+
697
+ const endpointFile = project.getSourceFile(
698
+ path.join(
699
+ ${rootFolderSegments(rootFolder)}'bounded-contexts',
700
+ currentBoundedContext,
701
+ 'presentation',
702
+ 'rest',
703
+ controller,
704
+ ...relativePath.map(pathParameterAsName),
705
+ \`\${routeMetadata.method.toUpperCase()}.ts\`
706
+ )
707
+ );
708
+
709
+ if (!endpointFile) {
710
+ return undefined;
711
+ }
712
+
713
+ const declaration = findHandlerClass(endpointFile);
714
+ const operationId = declaration?.getName();
715
+ const comment = declaration?.getJsDocs().at(-1)?.getText();
716
+
717
+ if (!comment) {
718
+ return { operationId };
719
+ }
720
+
721
+ return {
722
+ summary: summaryTag
723
+ ? getTagText(comment, summaryTag)
724
+ : parseSummary(comment),
725
+ description: getTagText(comment, descriptionTag),
726
+ operationId
727
+ };
728
+ } catch (e: unknown) {
729
+ console.error(e);
730
+ return undefined;
731
+ }
732
+ };
733
+ };
734
+ `;
735
+ const addPackageScripts = async (file, additions)=>{
736
+ const original = file.data;
737
+ const manifest = JSON.parse(original);
738
+ const scripts = {
739
+ ...manifest.scripts
740
+ };
741
+ const selected = {};
742
+ for (const [name, command] of Object.entries(additions)){
743
+ let target = name;
744
+ if (Object.hasOwn(scripts, name) && scripts[name] !== command) {
745
+ const action = await (0, prompts_namespaceObject.select)({
746
+ message: `Script "${name}" already exists: ${scripts[name]}`,
747
+ choices: [
748
+ 'Keep existing',
749
+ 'Replace',
750
+ 'Use another name'
751
+ ]
752
+ });
753
+ if ('Keep existing' === action) continue;
754
+ if ('Use another name' === action) target = await (0, prompts_namespaceObject.input)({
755
+ message: "New script name:",
756
+ validate: (value)=>!/^[a-zA-Z0-9:_-]+$/.test(value) || Object.hasOwn(scripts, value) || Object.hasOwn(additions, value) ? "Enter an unused script name (letters, numbers, :, _, -)." : true
757
+ });
758
+ }
759
+ scripts[target] = command;
760
+ selected[name] = target;
761
+ }
762
+ if (JSON.stringify(manifest.scripts) !== JSON.stringify(scripts)) {
763
+ manifest.scripts = scripts;
764
+ const indent = original.match(/\n([\t ]+)"/)?.[1] ?? ' ';
765
+ file.update(`${JSON.stringify(manifest, null, indent)}\n`);
766
+ }
767
+ return selected;
768
+ };
769
+ const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
770
+ const openapiScriptPath = "scripts/generate-openapi.ts";
771
+ const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
772
+ const extractorPackages = [
773
+ 'ts-morph',
774
+ '@microsoft/tsdoc'
775
+ ];
776
+ const swaggerPagePath = (rootFolder)=>external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/pages/swagger-page.tsx');
777
+ const swaggerPage = (rootFolder, outputPath)=>{
778
+ const specImport = external_node_path_default().posix.relative(external_node_path_default().posix.dirname(swaggerPagePath(rootFolder)), outputPath);
779
+ return reactPageContent('Swagger', {
780
+ imports: [
781
+ "import 'swagger-ui-react/swagger-ui.css'",
782
+ "import SwaggerUI from 'swagger-ui-react'",
783
+ `import spec from '${specImport.startsWith('.') ? specImport : `./${specImport}`}' with { type: 'json' }`
784
+ ],
785
+ body: '<SwaggerUI displayOperationId spec={spec} />'
786
+ });
787
+ };
788
+ const openapiScripts = {
789
+ openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
790
+ };
791
+ const splitPath = (value)=>value.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
792
+ const apiTitle = (packageName)=>{
793
+ const words = String(packageName ?? '').replace(/^@[^/]*\//, '').split(/[^a-zA-Z0-9]+/).filter((word)=>!!word).map((word)=>word[0].toUpperCase() + word.slice(1));
794
+ return [
795
+ ...words,
796
+ 'API'
797
+ ].join(' ');
798
+ };
799
+ const openapiGenerator = (rootFolder, title, routePrefix, outputPath, withExtractor = false)=>{
800
+ const restFolder = external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/rest');
801
+ const restImport = external_node_path_default().posix.relative(external_node_path_default().posix.dirname(openapiScriptPath), restFolder);
802
+ const prefixSegments = splitPath(routePrefix);
803
+ const apiRoutePrefix = prefixSegments.length ? `\n apiRoutePrefix: [${prefixSegments.map((segment)=>`'${segment}'`).join(', ')}],` : '';
804
+ const extractorImport = `./${external_node_path_default().posix.relative(external_node_path_default().posix.dirname(openapiScriptPath), openapiExtractorPath.replace(/\.ts$/, ''))}`;
805
+ const handlers = withExtractor ? `
806
+ const extractOpenApiDataFromEndpointLogic =
807
+ createOpenApiDataFromEndpointLogicExtractor();
808
+
809
+ const handlers = restHandlers.map((x) => ({
810
+ ...x,
811
+ metadata: {
812
+ ...x.metadata,
813
+ openApiMetadata: {
814
+ ...extractOpenApiDataFromEndpointLogic(x.metadata.route),
815
+ ...(x.metadata.openApiMetadata ?? {})
816
+ }
817
+ }
818
+ }));
819
+ ` : '';
820
+ return `import { generateOpenAPI } from '@domain-first/handlers-rest';
821
+ import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}';${withExtractor ? `\nimport { createOpenApiDataFromEndpointLogicExtractor } from '${extractorImport}';` : ''}
822
+ ${handlers}
823
+ generateOpenAPI(${withExtractor ? 'handlers' : 'restHandlers'}, {
824
+ document: { info: { title: '${title}', version: '1.0.0' } },${apiRoutePrefix}
825
+ outputFile: { path: '${outputPath}' }
826
+ });
827
+ `;
828
+ };
829
+ const addOpenapi = async ()=>{
830
+ const { rootFolder } = config_file_ConfigFile.Instance.data;
831
+ const root = new project_root_ProjectRoot().path;
832
+ const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
833
+ const manifest = JSON.parse(manifestFile.data);
834
+ const dependencies = {
835
+ ...manifest.dependencies,
836
+ ...manifest.devDependencies
837
+ };
838
+ const routePrefix = await (0, prompts_namespaceObject.input)({
839
+ message: 'Route prefix the REST handlers are served under:',
840
+ default: '/api'
841
+ });
842
+ const outputPath = await (0, prompts_namespaceObject.input)({
843
+ message: 'OpenAPI document path:',
844
+ default: defaultOpenapiPath(Boolean(dependencies.next)),
845
+ validate: (value)=>splitPath(value).length ? true : 'Path is required'
846
+ });
847
+ const withExtractor = await (0, prompts_namespaceObject.confirm)({
848
+ message: "Fill operationId, summary and description from the endpoint logic TSDoc?",
849
+ default: true
850
+ });
851
+ const withSwaggerPage = config_file_ConfigFile.Instance.data.useReact && await (0, prompts_namespaceObject.confirm)({
852
+ message: 'Add a Swagger UI page?',
853
+ default: true
854
+ });
855
+ const selected = await addPackageScripts(manifestFile, openapiScripts);
856
+ if (withExtractor) {
857
+ const extractorFile = new file_system_File(external_node_path_default().join(root, openapiExtractorPath));
858
+ const extractor = openapiExtractor(rootFolder);
859
+ if (!extractorFile.exists || extractorFile.data !== extractor) extractorFile.data = extractor;
860
+ }
861
+ const generatorFile = new file_system_File(external_node_path_default().join(root, openapiScriptPath));
862
+ const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
863
+ if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
864
+ if (withSwaggerPage) {
865
+ const pageFile = new file_system_File(external_node_path_default().join(root, swaggerPagePath(rootFolder)));
866
+ const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'));
867
+ if (!pageFile.exists || pageFile.data !== page) pageFile.data = page;
868
+ }
869
+ const resolveJsonModule = withSwaggerPage ? compilerOption(external_node_path_default().join(root, 'tsconfig.json'), 'resolveJsonModule') : true;
870
+ const hasRestHandlers = new file_system_File(external_node_path_default().join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
871
+ const missingExtractorPackages = withExtractor ? extractorPackages.filter((name)=>!dependencies[name]) : [];
872
+ return [
873
+ ...dependencies['@domain-first/handlers-rest'] ? [] : [
874
+ 'npm install @domain-first/handlers-rest'
875
+ ],
876
+ ...dependencies.tsx ? [] : [
877
+ 'npm install --save-dev tsx'
878
+ ],
879
+ ...missingExtractorPackages.length ? [
880
+ `npm install --save-dev ${missingExtractorPackages.join(' ')}`
881
+ ] : [],
882
+ ...withSwaggerPage && !dependencies['swagger-ui-react'] ? [
883
+ 'npm install swagger-ui-react'
884
+ ] : [],
885
+ ...withSwaggerPage && !dependencies['@types/swagger-ui-react'] ? [
886
+ 'npm install --save-dev @types/swagger-ui-react'
887
+ ] : [],
888
+ ...true === resolveJsonModule || null === resolveJsonModule ? [] : [
889
+ 'set "resolveJsonModule": true in compilerOptions of tsconfig.json — the Swagger UI page imports the OpenAPI document as JSON'
890
+ ],
891
+ ...describeScripts(selected, {
892
+ openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
893
+ }),
894
+ ...withSwaggerPage ? [
895
+ `SwaggerPage from ${swaggerPagePath(rootFolder)} shows ${splitPath(outputPath).join('/')} once it is generated — render it on a route of your app`
896
+ ] : [],
897
+ ...hasRestHandlers ? [] : [
898
+ `restHandlers appear in ${external_node_path_default().posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
899
+ ]
900
+ ];
901
+ };
902
+ const addGitignoreEntry = (root, entry)=>{
903
+ const gitignore = new file_system_File(external_node_path_default().join(root, '.gitignore'));
904
+ const ignored = gitignore.exists ? gitignore.data : '';
905
+ if (ignored.split(/\r?\n/).includes(entry)) return;
906
+ const newline = ignored.includes('\r\n') ? '\r\n' : '\n';
907
+ gitignore.update(`${ignored}${ignored && !ignored.endsWith('\n') ? newline : ''}${entry}${newline}`);
908
+ };
909
+ const dataLayerFolder = (rootFolder, target)=>external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'hooks' === target ? 'presentation/react/data-layer' : 'presentation/data-layer');
910
+ const orvalScripts = (rootFolder, targets)=>({
911
+ 'client:orval': targets.map((target)=>`orval --config ${JSON.stringify(`${dataLayerFolder(rootFolder, target)}/orval.config.ts`)}`).join(' && ')
912
+ });
913
+ const orvalConfig = (rootFolder, openapiPath, withNext, target = 'hooks', mutatorPath = './api-client/mutator.ts')=>{
914
+ const inputPath = external_node_path_default().posix.relative(dataLayerFolder(rootFolder, target), openapiPath);
915
+ const baseUrl = withNext ? `
916
+ baseUrl: {
917
+ runtime: 'process.env.NEXT_PUBLIC_API_BASE_URL ?? ""'
918
+ },` : '';
919
+ const client = 'hooks' === target ? `
920
+ client: 'react-query',
921
+ httpClient: 'fetch',` : `
922
+ client: 'fetch',`;
923
+ const query = 'hooks' === target ? `,
924
+ query: {
925
+ version: 5
926
+ }` : '';
927
+ return `import { defineConfig } from 'orval';
928
+
929
+ export default defineConfig({
930
+ api: {
931
+ input: '${inputPath.startsWith('.') ? inputPath : `./${inputPath}`}',
932
+ output: {
933
+ mode: 'tags-split',
934
+ target: './orval',
935
+ schemas: './orval/model',${client}${baseUrl}
936
+ clean: true,
937
+ override: {
938
+ mutator: {
939
+ path: '${mutatorPath}',
940
+ name: 'customInstance'
941
+ },
942
+ fetch: {
943
+ includeHttpResponseReturnType: false
944
+ }${query}
945
+ }
946
+ }
947
+ }
948
+ });
949
+ `;
950
+ };
951
+ const orvalMutator = `/** Error of the generated requests, with the parsed response body. */
952
+ export class ApiError<Body = unknown> extends Error {
953
+ constructor(
954
+ public readonly status: number,
955
+ public readonly body: Body
956
+ ) {
957
+ super(\`API error \${status}\`);
958
+ this.name = 'ApiError';
959
+ }
960
+ }
961
+
962
+ /** Error type of the generated requests, typed per endpoint by Orval. */
963
+ export type ErrorType<Body> = ApiError<Body>;
964
+
965
+ /** Every generated request goes through here: add auth headers, token refresh, logging. */
966
+ export const customInstance = async <T>(
967
+ url: string,
968
+ init?: RequestInit
969
+ ): Promise<T> => {
970
+ const response = await fetch(url, init);
971
+ const text = await response.text();
972
+ const body = text ? JSON.parse(text) : undefined;
973
+
974
+ if (!response.ok) {
975
+ throw new ApiError(response.status, body);
976
+ }
977
+
978
+ return body as T;
979
+ };
980
+ `;
981
+ const queryProvider = `'use client';
982
+
983
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
984
+ import { type FC, type ReactNode, useState } from 'react';
985
+
986
+ export const QueryProvider: FC<{ children: ReactNode }> = ({ children }) => {
987
+ // One client per browser session; a module-level client would be shared between requests on the server
988
+ const [queryClient] = useState(() => new QueryClient());
989
+
990
+ return (
991
+ <QueryClientProvider client={queryClient}>
992
+ {children}
993
+ </QueryClientProvider>
994
+ );
995
+ };
996
+ `;
997
+ const openapiOutputPath = (root)=>{
998
+ const generator = new file_system_File(external_node_path_default().join(root, openapiScriptPath));
999
+ if (!generator.exists) return;
1000
+ return generator.data.match(/outputFile:\s*{\s*path:\s*'([^']+)'/)?.[1];
1001
+ };
1002
+ const addOrval = async ()=>{
1003
+ const { rootFolder, useReact } = config_file_ConfigFile.Instance.data;
1004
+ const root = new project_root_ProjectRoot().path;
1005
+ const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
1006
+ const manifest = JSON.parse(manifestFile.data);
1007
+ const dependencies = {
1008
+ ...manifest.dependencies,
1009
+ ...manifest.devDependencies
1010
+ };
1011
+ const withNext = Boolean(dependencies.next);
1012
+ const generatedOpenapiPath = openapiOutputPath(root);
1013
+ const openapiPath = await (0, prompts_namespaceObject.input)({
1014
+ message: 'OpenAPI document path:',
1015
+ default: generatedOpenapiPath ?? defaultOpenapiPath(withNext),
1016
+ validate: (value)=>value.trim() ? true : 'Path is required'
1017
+ });
1018
+ const targets = useReact ? await (0, prompts_namespaceObject.checkbox)({
1019
+ message: 'Generate:',
1020
+ choices: [
1021
+ {
1022
+ name: 'React Query hooks',
1023
+ value: 'hooks',
1024
+ checked: true
1025
+ },
1026
+ {
1027
+ name: 'Typed API client',
1028
+ value: 'client'
1029
+ }
1030
+ ],
1031
+ required: true
1032
+ }) : [
1033
+ 'client'
1034
+ ];
1035
+ const selected = await addPackageScripts(manifestFile, orvalScripts(rootFolder, targets));
1036
+ const document = external_node_path_default().posix.normalize(openapiPath.trim().replaceAll('\\', '/'));
1037
+ const withClient = targets.includes('client');
1038
+ for (const target of targets){
1039
+ const dataLayer = dataLayerFolder(rootFolder, target);
1040
+ const sharedMutator = 'hooks' === target && withClient;
1041
+ const mutatorPath = sharedMutator ? `${external_node_path_default().posix.relative(dataLayer, dataLayerFolder(rootFolder, 'client'))}/api-client/mutator.ts` : void 0;
1042
+ const configFile = new file_system_File(external_node_path_default().join(root, dataLayer, 'orval.config.ts'));
1043
+ const content = orvalConfig(rootFolder, document, withNext, target, mutatorPath);
1044
+ if (!configFile.exists || configFile.data !== content) configFile.data = content;
1045
+ for (const [name, fileContent] of [
1046
+ ...sharedMutator ? [] : [
1047
+ [
1048
+ 'api-client/mutator.ts',
1049
+ orvalMutator
1050
+ ]
1051
+ ],
1052
+ ...'hooks' === target ? [
1053
+ [
1054
+ 'query-provider.tsx',
1055
+ queryProvider
1056
+ ]
1057
+ ] : []
1058
+ ]){
1059
+ const file = new file_system_File(external_node_path_default().join(root, dataLayer, name));
1060
+ if (!file.exists) file.data = fileContent;
1061
+ }
1062
+ addGitignoreEntry(root, `/${dataLayer}/orval/`);
1063
+ }
1064
+ const generated = targets.map((target)=>'hooks' === target ? `React Query hooks in ${dataLayerFolder(rootFolder, 'hooks')}/orval` : `a typed API client in ${dataLayerFolder(rootFolder, 'client')}/orval`);
1065
+ const missing = (names)=>names.filter((name)=>!dependencies[name]);
1066
+ const runtime = missing(targets.includes('hooks') ? [
1067
+ '@tanstack/react-query'
1068
+ ] : []);
1069
+ const development = missing([
1070
+ 'orval'
1071
+ ]);
1072
+ return [
1073
+ ...runtime.length ? [
1074
+ `npm install ${runtime.join(' ')}`
1075
+ ] : [],
1076
+ ...development.length ? [
1077
+ `npm install --save-dev ${development.join(' ')}`
1078
+ ] : [],
1079
+ ...describeScripts(selected, {
1080
+ 'client:orval': `generate ${generated.join(' and ')} from ${openapiPath.trim()}`
1081
+ }),
1082
+ ...targets.includes('hooks') ? [
1083
+ `Wrap your app in QueryProvider from ${dataLayerFolder(rootFolder, 'hooks')}/query-provider.tsx`
1084
+ ] : [],
1085
+ ...generatedOpenapiPath ? [] : [
1086
+ 'npx df-integration → OpenAPI generates the OpenAPI document the client is built from'
1087
+ ]
1088
+ ];
1089
+ };
1090
+ const playwrightScripts = {
1091
+ 'test:e2e': 'playwright test'
1092
+ };
1093
+ const playwrightConfig = `import { defineConfig, devices } from '@playwright/test';
1094
+
1095
+ export default defineConfig({
1096
+ testDir: './specs/e2e',
1097
+ fullyParallel: true,
1098
+ forbidOnly: !!process.env.CI,
1099
+ retries: process.env.CI ? 2 : 0,
1100
+ workers: process.env.CI ? 1 : undefined,
1101
+ reporter: 'html',
1102
+ use: {
1103
+ baseURL: 'http://localhost:3000',
1104
+ trace: 'on-first-retry',
1105
+ screenshot: 'only-on-failure',
1106
+ video: 'retain-on-failure'
1107
+ },
1108
+
1109
+ projects: [
1110
+ {
1111
+ name: 'chromium',
1112
+ use: { ...devices['Desktop Chrome'] }
1113
+ },
1114
+ {
1115
+ name: 'firefox',
1116
+ use: { ...devices['Desktop Firefox'] }
1117
+ },
1118
+ {
1119
+ name: 'webkit',
1120
+ use: { ...devices['Desktop Safari'] }
1121
+ },
1122
+ {
1123
+ name: 'Mobile Chrome',
1124
+ use: { ...devices['Pixel 5'] }
1125
+ },
1126
+ {
1127
+ name: 'Mobile Safari',
1128
+ use: { ...devices['iPhone 12'] }
1129
+ }
1130
+ ],
1131
+
1132
+ webServer: {
1133
+ // Playwright only stops the dev server on a clean shutdown. If its process dies any other
1134
+ // way (SIGHUP, SIGKILL), the dev server lives on in its own process group, so it is killed
1135
+ // as soon as Playwright is gone.
1136
+ command:
1137
+ process.platform === 'win32'
1138
+ ? 'npm run dev'
1139
+ : \`npm run dev & while kill -0 \${process.pid} 2>/dev/null && kill -0 $! 2>/dev/null; do sleep 1; done; kill 0\`,
1140
+ url: 'http://localhost:3000',
1141
+ timeout: 120000,
1142
+ reuseExistingServer: !process.env.CI
1143
+ }
1144
+ });
1145
+ `;
1146
+ const exampleSpec = `import { expect, test } from '@playwright/test';
1147
+
1148
+ test.describe('home page', () => {
1149
+ test('opens the home page', async ({ page, baseURL }) => {
1150
+ await page.goto('/');
1151
+ await expect(page).toHaveURL(\`\${baseURL}/\`);
1152
+ });
1153
+ });
1154
+ `;
1155
+ const exampleReadme = `# Home page e2e cases
1156
+
1157
+ ## User Stories
1158
+
1159
+ 1. Guest opens \`/\` and stays on the home page.
1160
+ `;
1161
+ const gitignoreEntries = [
1162
+ '/test-results/',
1163
+ '/playwright-report/',
1164
+ '/blob-report/',
1165
+ '/playwright/.cache/',
1166
+ '/playwright/.auth/'
1167
+ ];
1168
+ const addPlaywright = async ()=>{
1169
+ const root = new project_root_ProjectRoot().path;
1170
+ const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
1171
+ const manifest = JSON.parse(manifestFile.data);
1172
+ const dependencies = {
1173
+ ...manifest.dependencies,
1174
+ ...manifest.devDependencies
1175
+ };
1176
+ const selected = await addPackageScripts(manifestFile, playwrightScripts);
1177
+ const configFile = new file_system_File(external_node_path_default().join(root, 'playwright.config.ts'));
1178
+ if (!configFile.exists || configFile.data !== playwrightConfig) configFile.data = playwrightConfig;
1179
+ const exampleFolder = external_node_path_default().join(root, 'specs/e2e/home');
1180
+ for (const [name, content] of [
1181
+ [
1182
+ 'home.e2e.spec.ts',
1183
+ exampleSpec
1184
+ ],
1185
+ [
1186
+ 'README.MD',
1187
+ exampleReadme
1188
+ ]
1189
+ ]){
1190
+ const file = new file_system_File(external_node_path_default().join(exampleFolder, name));
1191
+ if (!file.exists) file.data = content;
1192
+ }
1193
+ for (const entry of gitignoreEntries)addGitignoreEntry(root, entry);
1194
+ return [
1195
+ ...dependencies['@playwright/test'] ? [] : [
1196
+ 'npm install --save-dev @playwright/test'
1197
+ ],
1198
+ 'npx playwright install --with-deps',
1199
+ ...describeScripts(selected, {
1200
+ 'test:e2e': 'start the dev server and run end-to-end specs from specs/e2e'
1201
+ })
1202
+ ];
1203
+ };
1204
+ const runtimePackages = [
1205
+ '@prisma/orm-postgres',
1206
+ 'temporal-polyfill',
1207
+ 'dotenv'
1208
+ ];
1209
+ const developmentPackages = [
1210
+ 'prisma',
1211
+ '@prisma/cli-engine'
1212
+ ];
1213
+ const prismaScripts = (rootFolder)=>{
1214
+ const config = JSON.stringify(external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'shared-kernel/infrastructure/prisma/prisma.config.ts'));
1215
+ const emit = `prisma contract emit --config ${config}`;
1216
+ return {
1217
+ 'prisma:emit': emit,
1218
+ 'prisma:migration:plan': `${emit} && prisma migration plan --config ${config}`,
1219
+ 'prisma:migration:apply': `prisma db migrate --advance-ref db --config ${config}`
1220
+ };
1221
+ };
1222
+ const prismaConfig = `import 'dotenv/config';
1223
+ import { definePrismaConfig } from '@prisma/cli-engine';
1224
+ import { defineConfig as ormConfig } from '@prisma/orm-postgres/config';
1225
+
1226
+ export default definePrismaConfig({
1227
+ orm: ormConfig({
1228
+ contract: './contract.prisma',
1229
+ migrations: { dir: './migrations' },
1230
+ db: {
1231
+ connection: process.env.DATABASE_URL
1232
+ }
1233
+ })
1234
+ });
1235
+ `;
1236
+ const prismaService = `import 'temporal-polyfill/global';
1237
+ import postgres from '@prisma/orm-postgres/runtime';
1238
+ import type {} from 'temporal-polyfill/types/global';
1239
+ import type { Contract } from '../prisma/contract.d';
1240
+ import contractJson from '../prisma/contract.json' with { type: 'json' };
1241
+
1242
+ type PrismaClient = ReturnType<typeof postgres<Contract>>;
1243
+
1244
+ const globalForPrisma = globalThis as typeof globalThis & {
1245
+ prismaClient?: PrismaClient;
1246
+ };
1247
+
1248
+ // Reuse the client across development hot reloads.
1249
+ const prismaClient = globalForPrisma.prismaClient ??
1250
+ postgres<Contract>({ contractJson, url: process.env.DATABASE_URL });
1251
+
1252
+ if (process.env.NODE_ENV !== 'production') {
1253
+ globalForPrisma.prismaClient = prismaClient;
1254
+ }
1255
+
1256
+ export class PrismaInfrastructureService {
1257
+ readonly orm = prismaClient.orm.public;
1258
+ }
1259
+ `;
1260
+ const prismaWiring = `import { wireClass } from '@domain-first/wire';
1261
+ import { PrismaInfrastructureService } from '../../infrastructure/services/prisma-infrastructure-service';
1262
+
1263
+ export const wirePrismaInfrastructureService = wireClass(
1264
+ PrismaInfrastructureService,
1265
+ []
1266
+ );
1267
+ `;
1268
+ const stageFile = (filePath, content)=>{
1269
+ const file = new file_system_File(filePath);
1270
+ if (!file.exists || file.data !== content) file.data = content;
1271
+ };
1272
+ const addPrisma = async ()=>{
1273
+ const config = config_file_ConfigFile.Instance.data;
1274
+ const root = new project_root_ProjectRoot().path;
1275
+ const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
1276
+ const manifest = JSON.parse(manifestFile.data);
1277
+ const dependencies = {
1278
+ ...manifest.dependencies,
1279
+ ...manifest.devDependencies
1280
+ };
1281
+ const shared = external_node_path_default().resolve(root, config.rootFolder, 'shared-kernel');
1282
+ const prismaFolder = external_node_path_default().join(shared, 'infrastructure/prisma');
1283
+ if (dependencies['@prisma/client'] || dependencies.prisma && !/^[~^]?8\./.test(dependencies.prisma) || dependencies['@prisma/orm-mongo'] || dependencies['@prisma/orm-sqlite'] || [
1284
+ external_node_path_default().join(root, 'prisma/schema.prisma'),
1285
+ external_node_path_default().join(prismaFolder, 'schema.prisma')
1286
+ ].some((filePath)=>new file_system_File(filePath).exists)) throw new Error('This preset adds Prisma 8 for PostgreSQL. Migrate the existing Prisma setup separately before using it.');
1287
+ const withService = await (0, prompts_namespaceObject.confirm)({
1288
+ message: 'Create the Prisma infrastructure service in the Shared Kernel?',
1289
+ default: true
1290
+ });
1291
+ const useByDefault = 'prisma' !== config.defaultPersistenceLayerImplementation && await (0, prompts_namespaceObject.confirm)({
1292
+ message: 'Use prisma as the default persistence implementation?',
1293
+ default: false
1294
+ });
1295
+ const selected = await addPackageScripts(manifestFile, prismaScripts(config.rootFolder));
1296
+ stageFile(external_node_path_default().join(prismaFolder, 'prisma.config.ts'), prismaConfig);
1297
+ const contract = new file_system_File(external_node_path_default().join(prismaFolder, 'contract.prisma'));
1298
+ if (!contract.exists) contract.data = '// use prisma-8\n\n// Add your application models here before running prisma:emit.\n';
1299
+ if (withService) {
1300
+ stageFile(external_node_path_default().join(shared, 'infrastructure/services/prisma-infrastructure-service.ts'), prismaService);
1301
+ if (config.domainFirstPackages.includes('@domain-first/wire')) stageFile(external_node_path_default().join(shared, 'wiring/infrastructure-services/wire-prisma-infrastructure-service.ts'), prismaWiring);
1302
+ }
1303
+ if (useByDefault) config_file_ConfigFile.write({
1304
+ ...config,
1305
+ defaultPersistenceLayerImplementation: 'prisma'
1306
+ });
1307
+ const install = (packages, dev)=>{
1308
+ const missing = packages.filter((name)=>!dependencies[name]);
1309
+ return missing.length ? [
1310
+ `npm install${dev ? ' --save-dev' : ''} ${missing.join(' ')}`
1311
+ ] : [];
1312
+ };
1313
+ const relativeFolder = external_node_path_default().relative(root, prismaFolder).split(external_node_path_default().sep).join('/');
1314
+ return [
1315
+ ...install(runtimePackages, false),
1316
+ ...install(developmentPackages, true),
1317
+ `Add !${relativeFolder} in your linter, to ignore prisma files.`,
1318
+ ...describeScripts(selected, {
1319
+ 'prisma:emit': 'emit contract.json and contract.d.ts from contract.prisma',
1320
+ 'prisma:migration:plan': 'emit the contract and plan a migration',
1321
+ 'prisma:migration:apply': 'apply planned migrations to the database in DATABASE_URL'
1322
+ })
1323
+ ];
1324
+ };
1325
+ class unknown_format_naming_UnknownFormatNaming {
1326
+ rawSource;
1327
+ camelCase;
1328
+ PascalCase;
1329
+ constructor(rawSource){
1330
+ this.rawSource = rawSource;
1331
+ const source = rawSource.trim();
1332
+ if (!source.includes('-')) {
1333
+ this.camelCase = source.substring(0, 1).toLowerCase() + source.substring(1);
1334
+ this.PascalCase = source.substring(0, 1).toUpperCase() + source.substring(1);
1335
+ }
1336
+ const words = source.split('-').filter((word)=>!!word);
1337
+ this.camelCase = words.map((word, index)=>0 === index ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
1338
+ this.PascalCase = words.map((word)=>word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
1339
+ }
1340
+ get fileName() {
1341
+ return this.rawSource;
1342
+ }
1343
+ get variableName() {
1344
+ return this.camelCase;
1345
+ }
1346
+ get ClassName() {
1347
+ return this.PascalCase;
1348
+ }
1349
+ get withSpaces() {
1350
+ return this.fileName.replaceAll('-', ' ');
1351
+ }
1352
+ }
1353
+ const createPresentationService = (boundedContextFolder, name, classFile)=>{
1354
+ const naming = new unknown_format_naming_UnknownFormatNaming(name);
1355
+ const className = `${naming.ClassName}PresentationService`;
1356
+ const scaffoldUnitTests = Boolean(config_file_ConfigFile.Instance.data.testingLibrary);
1357
+ const withWiring = config_file_ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
1358
+ const wiringFolder = boundedContextFolder.subitem([
1359
+ 'wiring',
1360
+ 'presentation-services'
1361
+ ]);
1362
+ const presentationServicesFolder = boundedContextFolder.subitem([
1363
+ 'presentation',
1364
+ 'services'
1365
+ ]);
1366
+ presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.ts`, classFile?.(className) ?? `
1367
+ export class ${className} {
1368
+
1369
+ }
1370
+ `.trim());
1371
+ if (scaffoldUnitTests) presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.spec.ts`, `
1372
+ import { describe, test, expect, beforeEach } from '${config_file_ConfigFile.Instance.data.testingLibrary}'
1373
+ ${withWiring ? `import { type ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'
1374
+ import { wire${naming.ClassName}PresentationService } from '../../wiring/presentation-services/wire-${naming.fileName}-presentation-service'` : `import { ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'`}
1375
+
1376
+ let ${naming.variableName}PresentationService: ${naming.ClassName}PresentationService
1377
+
1378
+ beforeEach(() => {
1379
+ ${naming.variableName}PresentationService = ${withWiring ? `wire${naming.ClassName}PresentationService()` : `new ${naming.ClassName}PresentationService()`}
1380
+ })
1381
+
1382
+ describe('${naming.withSpaces}', () => {
1383
+ test('can be ${withWiring ? 'wired' : 'created'}', () => {
1384
+ expect(${naming.variableName}PresentationService).toBeDefined()
1385
+ })
1386
+ })
1387
+ `.trim());
1388
+ if (withWiring) return wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
1389
+ import { wireClass } from '@domain-first/wire'
1390
+ import { ${naming.ClassName}PresentationService } from '../../presentation/services/${naming.fileName}-presentation-service'
1391
+
1392
+ export const wire${naming.ClassName}PresentationService = wireClass(
1393
+ ${naming.ClassName}PresentationService,
1394
+ []
1395
+ )
1396
+ `.trim());
1397
+ };
1398
+ const rest_endpoint_generator_name = 'rest-endpoint-generator';
1399
+ const scaffoldRestEndpointGenerator = (sharedFolder, { withNextAdapter = false } = {})=>createPresentationService(sharedFolder, rest_endpoint_generator_name, (className)=>{
1400
+ const adapter = withNextAdapter ? 'nextAdapter' : 'adapter';
1401
+ return `
1402
+ import {
1403
+ ${withNextAdapter ? '' : ' type Adapter,\n'} type EndpointGenerator,
1404
+ createEndpoint,
1405
+ invalidRequest
1406
+ } from '@domain-first/handlers-rest'
1407
+ ${withNextAdapter ? "import { nextAdapter } from '@domain-first/handlers-next'" : `
1408
+ /**
1409
+ * The adapter of your HTTP framework.
1410
+ */
1411
+ const adapter = undefined as unknown as Adapter<any[], any>`}
1412
+
1413
+ export class ${className} {
1414
+ get withoutGuards(): EndpointGenerator {
1415
+ return createEndpoint({
1416
+ errors: [invalidRequest()]
1417
+ })(${adapter}) as EndpointGenerator
1418
+ }
1419
+ }
1420
+ `.trim();
1421
+ });
1422
+ const rest_endpoint_generator_findRestEndpointGenerator = (sharedFolder)=>{
1423
+ const typeFile = external_node_path_default().join(sharedFolder.path, 'presentation', 'services', `${rest_endpoint_generator_name}-presentation-service.ts`);
1424
+ if (!new file_system_File(typeFile).exists) return;
1425
+ return {
1426
+ typeName: 'RestEndpointGeneratorPresentationService',
1427
+ typeFile,
1428
+ wireName: 'wireRestEndpointGeneratorPresentationService',
1429
+ wireFile: external_node_path_default().join(sharedFolder.path, 'wiring', 'presentation-services', `wire-${rest_endpoint_generator_name}-presentation-service.ts`)
1430
+ };
1431
+ };
1432
+ const nextAppFolder = (root)=>[
1433
+ 'app',
1434
+ 'src/app'
1435
+ ].find((folder)=>new file_system_Folder(external_node_path_default().join(root, folder)).exists) ?? 'app';
1436
+ const nextRoutePath = (root)=>external_node_path_default().posix.join(nextAppFolder(root), 'api/[...path]/route.ts');
1437
+ const nextRoute = (restHandlersImport)=>`
1438
+ import { nextEndpoints } from '@domain-first/handlers-next'
1439
+ ${restHandlersImport ? `import { restHandlers } from '${restHandlersImport}'
1440
+
1441
+ const handler = nextEndpoints(restHandlers)` : `
1442
+ /**
1443
+ * Pass the endpoints' handle here; their paths are relative to this route's folder.
1444
+ */
1445
+ const handler = nextEndpoints([])`}
1446
+
1447
+ export const GET = handler
1448
+ export const POST = handler
1449
+ export const PUT = handler
1450
+ export const PATCH = handler
1451
+ export const DELETE = handler
1452
+ `.trim();
1453
+ const scaffoldNextRoute = (root)=>{
1454
+ const { rootFolder, domainFirstPackages } = config_file_ConfigFile.Instance.data;
1455
+ const routePath = nextRoutePath(root);
1456
+ const routeFile = external_node_path_default().join(root, routePath);
1457
+ if (new file_system_File(routeFile).exists) return [];
1458
+ if (!domainFirstPackages.includes('@domain-first/wire')) {
1459
+ new file_system_File(routeFile).data = nextRoute(void 0);
1460
+ return [];
1461
+ }
1462
+ const restFolder = new file_system_Folder(root).subitem([
1463
+ rootFolder,
1464
+ 'presentation',
1465
+ 'rest'
1466
+ ]);
1467
+ new file_system_File(routeFile).data = nextRoute(wiring_relativeImport(routeFile, restFolder.path));
1468
+ return new file_system_File(external_node_path_default().join(restFolder.path, 'index.ts')).exists ? [] : [
1469
+ `${routePath} serves restHandlers from ${external_node_path_default().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`
1470
+ ];
1471
+ };
1472
+ const rest_endpoint_generator_askNextAdapter = async ()=>hasDependency('next') && await (0, prompts_namespaceObject.confirm)({
1473
+ message: 'Use Next adapter for REST endpoints'
1474
+ });
1475
+ const rest_endpoint_generator_scaffoldRestEndpointGeneratorFiles = ({ withNextAdapter })=>{
1476
+ const root = new project_root_ProjectRoot().path;
1477
+ const generatorExisted = restEndpointGeneratorApplied();
1478
+ const routeNotes = withoutOverwrites(()=>{
1479
+ scaffoldRestEndpointGenerator(new file_system_Folder(root).subitem([
1480
+ config_file_ConfigFile.Instance.data.rootFolder,
1481
+ 'shared-kernel'
1482
+ ]), {
1483
+ withNextAdapter
1484
+ });
1485
+ return withNextAdapter ? scaffoldNextRoute(root) : [];
1486
+ });
1487
+ if (!withNextAdapter) return [];
1488
+ return [
1489
+ ...missingPackages([
1490
+ '@domain-first/handlers-next'
1491
+ ]),
1492
+ ...routeNotes,
1493
+ ...generatorExisted ? [
1494
+ 'the existing endpoint generator was kept — pass nextAdapter from @domain-first/handlers-next to its createEndpoint calls'
1495
+ ] : []
1496
+ ];
1497
+ };
1498
+ const addRestEndpointGenerator = async ()=>rest_endpoint_generator_scaffoldRestEndpointGeneratorFiles({
1499
+ withNextAdapter: await rest_endpoint_generator_askNextAdapter()
1500
+ });
1501
+ const restEndpointGeneratorApplied = ()=>Boolean(rest_endpoint_generator_findRestEndpointGenerator(new file_system_Folder(new project_root_ProjectRoot().path).subitem([
1502
+ config_file_ConfigFile.Instance.data.rootFolder,
1503
+ 'shared-kernel'
1504
+ ])));
1505
+ const storybookFiles = (relativeProjectRoot)=>({
1506
+ 'main.ts': `import { resolve } from 'node:path';
1507
+ import react from '@vitejs/plugin-react';
1508
+ import type { StorybookConfig } from '@storybook/react-vite';
1509
+
1510
+ const projectRoot = resolve(import.meta.dirname, ${JSON.stringify(relativeProjectRoot)});
1511
+
1512
+ const config: StorybookConfig = {
1513
+ stories: ['../**/*.mdx', '../**/*.stories.@(ts|tsx)'],
1514
+ framework: {
1515
+ name: '@storybook/react-vite',
1516
+ options: {}
1517
+ },
1518
+ core: {
1519
+ disableTelemetry: true
1520
+ },
1521
+ async viteFinal(viteConfig) {
1522
+ const { mergeConfig } = await import('vite');
1523
+
1524
+ return mergeConfig(viteConfig, {
1525
+ plugins: [react()],
1526
+ resolve: {
1527
+ alias: {
1528
+ '@': projectRoot
1529
+ }
1530
+ }
1531
+ });
1532
+ }
1533
+ };
1534
+
1535
+ export default config;
1536
+ `,
1537
+ 'preview.ts': `import type { Preview } from '@storybook/react-vite';
1538
+
1539
+ const preview: Preview = {
1540
+ parameters: {
1541
+ controls: {
1542
+ matchers: {
1543
+ color: /(background|color)$/i,
1544
+ date: /Date$/i
1545
+ }
1546
+ }
1547
+ }
1548
+ };
1549
+
1550
+ export default preview;
1551
+ `
1552
+ });
1553
+ const storybookScripts = (rootFolder)=>{
1554
+ const folder = external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react');
1555
+ const quote = (value)=>JSON.stringify(value);
1556
+ return {
1557
+ storybook: `storybook dev -p 6006 -c ${quote(`${folder}/.storybook`)}`,
1558
+ 'build-storybook': `storybook build -c ${quote(`${folder}/.storybook`)} -o ${quote(`${folder}/storybook-static`)}`
1559
+ };
1560
+ };
1561
+ const addStorybook = async ()=>{
1562
+ const config = config_file_ConfigFile.Instance.data;
1563
+ if ((!config.useReact || config.storybookFramework && '@storybook/react-vite' !== config.storybookFramework) && !await (0, prompts_namespaceObject.confirm)({
1564
+ message: 'Configure React scaffolding with @storybook/react-vite?',
1565
+ default: false
1566
+ })) return [];
1567
+ const root = new project_root_ProjectRoot().path;
1568
+ const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
1569
+ const manifest = JSON.parse(manifestFile.data);
1570
+ const selected = await addPackageScripts(manifestFile, storybookScripts(config.rootFolder));
1571
+ const folder = new file_system_Folder(root).subitem([
1572
+ config.rootFolder,
1573
+ 'presentation',
1574
+ 'react',
1575
+ '.storybook'
1576
+ ]);
1577
+ for (const [name, content] of Object.entries(storybookFiles(external_node_path_default().relative(folder.path, root).split(external_node_path_default().sep).join('/')))){
1578
+ const file = new file_system_File(external_node_path_default().join(folder.path, name));
1579
+ if (!file.exists || file.data !== content) file.data = content;
1580
+ }
1581
+ if (!config.useReact || '@storybook/react-vite' !== config.storybookFramework) config_file_ConfigFile.write({
1582
+ ...config,
1583
+ useReact: true,
1584
+ storybookFramework: '@storybook/react-vite'
1585
+ });
1586
+ const buildFolder = external_node_path_default().posix.join(config.rootFolder.replaceAll('\\', '/'), 'presentation/react/storybook-static');
1587
+ addGitignoreEntry(root, `/${buildFolder}/`);
1588
+ const dependencies = {
1589
+ ...manifest.dependencies,
1590
+ ...manifest.devDependencies
1591
+ };
1592
+ const missing = [
1593
+ 'storybook',
1594
+ '@storybook/react-vite',
1595
+ 'vite',
1596
+ '@vitejs/plugin-react'
1597
+ ].filter((name)=>!dependencies[name]);
1598
+ const missingReact = [
1599
+ 'react',
1600
+ 'react-dom'
1601
+ ].filter((name)=>!dependencies[name]);
1602
+ return [
1603
+ ...missing.length ? [
1604
+ `npm install --save-dev ${missing.join(' ')}`
1605
+ ] : [],
1606
+ ...missingReact.length ? [
1607
+ `npm install ${missingReact.join(' ')}`
1608
+ ] : [],
1609
+ ...describeScripts(selected, {
1610
+ storybook: 'start Storybook on http://localhost:6006',
1611
+ 'build-storybook': `build static Storybook into ${buildFolder}`
1612
+ })
1613
+ ];
1614
+ };
1615
+ const integrationFolder = 'specs/integration';
1616
+ const testcontainersScripts = {
1617
+ 'test:integration': `vitest run --config ${integrationFolder}/vitest.config.ts --reporter=dot --silent=passed-only`
1618
+ };
1619
+ const testcontainersVitestConfig = (inlineHandlersNext)=>{
1620
+ const server = inlineHandlersNext ? `,
1621
+ server: {
1622
+ deps: {
1623
+ // Imports \`next/headers\` without an extension, which only a bundler can resolve
1624
+ inline: ['@domain-first/handlers-next']
1625
+ }
1626
+ }` : '';
1627
+ return `import { fileURLToPath } from 'node:url';
1628
+ import { defineConfig } from 'vitest/config';
1629
+
1630
+ // Runs specs from this folder against PostgreSQL in a container, see global-setup.ts.
1631
+ export default defineConfig({
1632
+ // Paths below are relative to the project root, not this folder
1633
+ root: fileURLToPath(new URL('../..', import.meta.url)),
1634
+ resolve: {
1635
+ tsconfigPaths: true
1636
+ },
1637
+ test: {
1638
+ include: ['${integrationFolder}/**/*.spec.ts'],
1639
+ // Development implementations work with the real database
1640
+ env: { NODE_ENV: 'development' },
1641
+ globalSetup: ['${integrationFolder}/global-setup.ts'],
1642
+ setupFiles: ['${integrationFolder}/setup-env.ts'],
1643
+ // Pulling the image on the first run takes a while
1644
+ hookTimeout: 120_000${server}
1645
+ }
1646
+ });
1647
+ `;
1648
+ };
1649
+ const testcontainersGlobalSetup = (migrationCommand)=>{
1650
+ const migrations = migrationCommand ? `
1651
+ // dotenv in the Prisma config does not override an already set variable
1652
+ execSync(${JSON.stringify(migrationCommand)}, {
1653
+ cwd: project.config.root,
1654
+ env: { ...process.env, DATABASE_URL: databaseUrl },
1655
+ // On failure the error carries the command's output
1656
+ stdio: 'pipe'
1657
+ });
1658
+ ` : `
1659
+ // Apply your migrations to databaseUrl here.
1660
+ `;
1661
+ return `${migrationCommand ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
1662
+ import type { TestProject } from 'vitest/node';
1663
+
1664
+ declare module 'vitest' {
1665
+ export interface ProvidedContext {
1666
+ databaseUrl: string;
1667
+ }
1668
+ }
1669
+
1670
+ const POSTGRES_IMAGE = 'postgres:15';
1671
+ const POSTGRES_PORT = 5432;
1672
+ const POSTGRES_USER = 'test';
1673
+ const POSTGRES_PASSWORD = 'test';
1674
+ const POSTGRES_DB = 'test';
1675
+
1676
+ export default async function setup(project: TestProject) {
1677
+ const container = await new GenericContainer(POSTGRES_IMAGE)
1678
+ .withEnvironment({ POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB })
1679
+ .withExposedPorts(POSTGRES_PORT)
1680
+ // During init PostgreSQL listens on a unix socket only and restarts,
1681
+ // so checking over TCP passes once the final server is up
1682
+ .withHealthCheck({
1683
+ test: [
1684
+ 'CMD-SHELL',
1685
+ \`pg_isready --host localhost --username \${POSTGRES_USER} --dbname \${POSTGRES_DB}\`
1686
+ ],
1687
+ interval: 250,
1688
+ timeout: 1000,
1689
+ retries: 1000
1690
+ })
1691
+ .withWaitStrategy(Wait.forHealthCheck())
1692
+ .withStartupTimeout(120_000)
1693
+ .start();
1694
+
1695
+ const databaseUrl = \`postgresql://\${POSTGRES_USER}:\${POSTGRES_PASSWORD}@\${container.getHost()}:\${container.getMappedPort(POSTGRES_PORT)}/\${POSTGRES_DB}\`;
1696
+ ${migrations}
1697
+ project.provide('databaseUrl', databaseUrl);
1698
+
1699
+ return async () => {
1700
+ await container.stop();
1701
+ };
1702
+ }
1703
+ `;
1704
+ };
1705
+ const testcontainersSetupEnv = `import 'dotenv/config';
1706
+ import { inject } from 'vitest';
1707
+
1708
+ // Runs before each spec's imports: development implementations get the .env
1709
+ // config, and DATABASE_URL points to the container instead of the one from .env.
1710
+ if (process.env.NODE_ENV !== 'development') {
1711
+ throw new Error(
1712
+ \`Integration specs need NODE_ENV=development to wire development implementations, got "\${process.env.NODE_ENV}"\`
1713
+ );
1714
+ }
1715
+
1716
+ process.env.DATABASE_URL = inject('databaseUrl');
1717
+ `;
1718
+ const testcontainers_exampleSpec = `import { expect, inject, test } from 'vitest';
1719
+
1720
+ test('connects to the database in the container', () => {
1721
+ expect(process.env.DATABASE_URL).toBe(inject('databaseUrl'));
1722
+ });
1723
+ `;
1724
+ const excludeFromUnitTests = (content)=>{
1725
+ const exclude = /(exclude:\s*\[\s*\.\.\.configDefaults\.exclude\b[^\]]*?)(,?)(\s*)\]/;
1726
+ if (!exclude.test(content)) return;
1727
+ const entry = `'${integrationFolder}/**'`;
1728
+ return content.replace(exclude, (_, items, comma, whitespace)=>{
1729
+ const indent = whitespace.includes('\n') ? /\n([ \t]*)[^\n]*$/.exec(items)?.[1] : void 0;
1730
+ const separator = void 0 === indent ? ', ' : `,\n${indent}`;
1731
+ return `${items}${separator}${entry}${comma}${whitespace}]`;
1732
+ }).replace('// Playwright runs end-to-end specs\n', '// Playwright runs end-to-end specs, test:integration runs integration ones\n');
1733
+ };
1734
+ const testcontainers_stageFile = (filePath, content)=>{
1735
+ const file = new file_system_File(filePath);
1736
+ if (!file.exists || file.data !== content) file.data = content;
1737
+ };
1738
+ const addTestcontainers = async ()=>{
1739
+ const config = config_file_ConfigFile.Instance.data;
1740
+ const root = new project_root_ProjectRoot().path;
1741
+ const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
1742
+ const manifest = JSON.parse(manifestFile.data);
1743
+ const dependencies = {
1744
+ ...manifest.dependencies,
1745
+ ...manifest.devDependencies
1746
+ };
1747
+ const selected = await addPackageScripts(manifestFile, testcontainersScripts);
1748
+ const withPrisma = new file_system_File(external_node_path_default().resolve(root, config.rootFolder, 'shared-kernel/infrastructure/prisma/prisma.config.ts')).exists;
1749
+ const migrationCommand = withPrisma ? `npx ${prismaScripts(config.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}` : void 0;
1750
+ const folder = external_node_path_default().join(root, integrationFolder);
1751
+ testcontainers_stageFile(external_node_path_default().join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
1752
+ testcontainers_stageFile(external_node_path_default().join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommand));
1753
+ testcontainers_stageFile(external_node_path_default().join(folder, 'setup-env.ts'), testcontainersSetupEnv);
1754
+ const example = new file_system_File(external_node_path_default().join(folder, 'database/database.spec.ts'));
1755
+ if (!example.exists) example.data = testcontainers_exampleSpec;
1756
+ const unitConfig = new file_system_File(external_node_path_default().join(root, 'vitest.config.ts'));
1757
+ let excludedFromUnitTests = !unitConfig.exists || unitConfig.data.includes(integrationFolder);
1758
+ if (!excludedFromUnitTests) {
1759
+ const excluded = excludeFromUnitTests(unitConfig.data);
1760
+ if (excluded) {
1761
+ unitConfig.update(excluded);
1762
+ excludedFromUnitTests = true;
1763
+ }
1764
+ }
1765
+ const missing = [
1766
+ 'vitest',
1767
+ 'testcontainers',
1768
+ 'dotenv'
1769
+ ].filter((name)=>!dependencies[name]);
1770
+ return [
1771
+ ...missing.length ? [
1772
+ `npm install --save-dev ${missing.join(' ')}`
1773
+ ] : [],
1774
+ `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.`,
1775
+ ...migrationCommand ? [] : [
1776
+ `Apply your migrations in ${integrationFolder}/global-setup.ts.`
1777
+ ],
1778
+ ...excludedFromUnitTests ? [] : [
1779
+ `Add '${integrationFolder}/**' to test.exclude in vitest.config.ts, so unit tests skip integration specs.`
1780
+ ],
1781
+ 'Docker must be running for integration specs.',
1782
+ ...describeScripts(selected, {
1783
+ 'test:integration': `run integration specs from ${integrationFolder} against PostgreSQL in a container`
1784
+ })
1785
+ ];
1786
+ };
1787
+ const vitestScripts = {
1788
+ test: 'vitest run --reporter=dot --silent=passed-only',
1789
+ 'test:coverage': 'vitest run --coverage --reporter=dot --silent=passed-only'
1790
+ };
1791
+ const vitestConfig = (rootFolder, inlineHandlersNext)=>{
1792
+ const folder = (subpath)=>JSON.stringify(external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), subpath));
1793
+ const server = inlineHandlersNext ? `,
1794
+ server: {
1795
+ deps: {
1796
+ // Imports \`next/headers\` without an extension, which only a bundler can resolve
1797
+ inline: ['@domain-first/handlers-next']
1798
+ }
1799
+ }` : '';
1800
+ return `import { configDefaults, defineConfig } from 'vitest/config';
1801
+
1802
+ export default defineConfig({
1803
+ resolve: {
1804
+ tsconfigPaths: true
1805
+ },
1806
+ test: {
1807
+ // Playwright runs end-to-end specs, test:integration runs integration ones
1808
+ exclude: [...configDefaults.exclude, 'specs/e2e/**', 'specs/integration/**'],
1809
+ coverage: {
1810
+ provider: 'v8',
1811
+ include: [${folder('bounded-contexts/**/*.ts')}, ${folder('shared-kernel/**/*.ts')}],
1812
+ exclude: [
1813
+ '**/*.spec.ts',
1814
+ ${folder('shared-kernel/infrastructure/**')},
1815
+ ${folder('bounded-contexts/*/infrastructure/**')},
1816
+ ${folder('bounded-contexts/*/presentation/rest/**')},
1817
+ ${folder('shared-kernel/wiring/**')},
1818
+ ${folder('bounded-contexts/*/wiring/**')}
1819
+ ],
1820
+ reporter: [['text', { skipFull: true }], 'html']
1821
+ }${server}
1822
+ }
1823
+ });
1824
+ `;
1825
+ };
1826
+ const addVitest = async ()=>{
1827
+ const config = config_file_ConfigFile.Instance.data;
1828
+ if (config.testingLibrary && 'vitest' !== config.testingLibrary && !await (0, prompts_namespaceObject.confirm)({
1829
+ message: `Replace testing library "${config.testingLibrary}" with vitest for generated tests?`,
1830
+ default: false
1831
+ })) return [];
1832
+ const root = new project_root_ProjectRoot().path;
1833
+ const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
1834
+ const manifest = JSON.parse(manifestFile.data);
1835
+ const dependencies = {
1836
+ ...manifest.dependencies,
1837
+ ...manifest.devDependencies
1838
+ };
1839
+ const selected = await addPackageScripts(manifestFile, vitestScripts);
1840
+ const configFile = new file_system_File(external_node_path_default().join(root, 'vitest.config.ts'));
1841
+ const content = vitestConfig(config.rootFolder, Boolean(dependencies['@domain-first/handlers-next']));
1842
+ if (!configFile.exists || configFile.data !== content) configFile.data = content;
1843
+ if ('vitest' !== config.testingLibrary) config_file_ConfigFile.write({
1844
+ ...config,
1845
+ testingLibrary: 'vitest'
1846
+ });
1847
+ addGitignoreEntry(root, '/coverage/');
1848
+ const missing = [
1849
+ 'vitest',
1850
+ '@vitest/coverage-v8'
1851
+ ].filter((name)=>!dependencies[name]);
1852
+ return [
1853
+ ...missing.length ? [
1854
+ `npm install --save-dev ${missing.join(' ')}`
1855
+ ] : [],
1856
+ ...describeScripts(selected, {
1857
+ test: 'run unit tests',
1858
+ 'test:coverage': 'run unit tests with a V8 coverage report in coverage/'
1859
+ })
1860
+ ];
1861
+ };
1862
+ const installCommand = /^\s*npm (?:i|install)((?:\s+(?:--save-dev|-D))?)\s+(.+)$/;
1863
+ const mergeInstallCommands = (commands)=>{
1864
+ const runtime = new Set();
1865
+ const development = new Set();
1866
+ const rest = [];
1867
+ for (const command of commands){
1868
+ const match = installCommand.exec(command);
1869
+ if (!match) {
1870
+ rest.push(command);
1871
+ continue;
1872
+ }
1873
+ for (const name of match[2].trim().split(/\s+/))(match[1] ? development : runtime).add(name);
1874
+ }
1875
+ const devOnly = [
1876
+ ...development
1877
+ ].filter((name)=>!runtime.has(name));
1878
+ return [
1879
+ ...runtime.size ? [
1880
+ `npm install ${[
1881
+ ...runtime
1882
+ ].join(' ')}`
1883
+ ] : [],
1884
+ ...devOnly.length ? [
1885
+ `npm install --save-dev ${devOnly.join(' ')}`
1886
+ ] : [],
1887
+ ...rest
1888
+ ];
1889
+ };
1890
+ const printNextSteps = (nextSteps)=>{
1891
+ const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
1892
+ const commands = mergeInstallCommands(nextSteps.filter(isCommand));
1893
+ const notes = nextSteps.filter((line)=>!isCommand(line));
1894
+ const sections = [];
1895
+ if (commands.length) sections.push([
1896
+ 'Run this command to install the required dependencies:',
1897
+ (0, external_node_util_namespaceObject.styleText)([
1898
+ 'bold',
1899
+ 'cyan'
1900
+ ], commands.join(' && '))
1901
+ ].join('\n'));
1902
+ if (notes.length) sections.push([
1903
+ 'Additional information:',
1904
+ ...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + (0, external_node_util_namespaceObject.styleText)([
1905
+ 'bold',
1906
+ 'cyan'
1907
+ ], path)))
1908
+ ].join('\n'));
1909
+ if (sections.length) console.log(sections.join('\n\n'));
1910
+ };
1911
+ const savePendingChanges = async ()=>{
1912
+ const overwrittenFiles = filesToOverwrite();
1913
+ if (overwrittenFiles.length) {
1914
+ const root = new project_root_ProjectRoot().path;
1915
+ console.log('These files already exist and will be overwritten:');
1916
+ for (const filePath of overwrittenFiles)console.log(` ${external_node_path_default().relative(root, filePath)}`);
1917
+ const overwrite = await (0, prompts_namespaceObject.confirm)({
1918
+ message: 'Overwrite them?',
1919
+ default: false
1920
+ });
1921
+ if (!overwrite) {
1922
+ file_system_discardPendingChanges();
1923
+ console.log('Cancelled: nothing was written.');
1924
+ return false;
1925
+ }
1926
+ }
1927
+ writePendingChanges();
1928
+ return true;
1929
+ };
1930
+ const withHandlersRest = ()=>config_file_ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers-rest');
1931
+ const created = (...segments)=>new file_system_File(external_node_path_default().join(new project_root_ProjectRoot().path, ...segments)).exists;
1932
+ const createdInRoot = (...segments)=>created(config_file_ConfigFile.Instance.data.rootFolder, ...segments);
1933
+ const integrations = [
1934
+ {
1935
+ name: 'Storybook (React + Vite)',
1936
+ group: 'frontend',
1937
+ run: addStorybook,
1938
+ applied: ()=>createdInRoot('presentation/react/.storybook/main.ts')
1939
+ },
1940
+ {
1941
+ name: 'REST endpoint generator',
1942
+ group: 'backend',
1943
+ run: addRestEndpointGenerator,
1944
+ available: ()=>withHandlersRest(),
1945
+ applied: restEndpointGeneratorApplied
1946
+ },
1947
+ {
1948
+ name: 'In-memory DB',
1949
+ group: 'backend',
1950
+ run: addInMemoryDb,
1951
+ applied: inMemoryDbApplied
1952
+ },
1953
+ {
1954
+ name: 'Prisma 8 (PostgreSQL, RC)',
1955
+ group: 'backend',
1956
+ run: addPrisma,
1957
+ applied: ()=>createdInRoot('shared-kernel/infrastructure/prisma/prisma.config.ts')
1958
+ },
1959
+ {
1960
+ name: 'Vitest',
1961
+ group: 'backend',
1962
+ run: addVitest,
1963
+ applied: ()=>created('vitest.config.ts')
1964
+ },
1965
+ {
1966
+ name: 'Playwright',
1967
+ group: 'frontend',
1968
+ run: addPlaywright,
1969
+ applied: ()=>created('playwright.config.ts')
1970
+ },
1971
+ {
1972
+ name: 'Integration tests (Testcontainers, PostgreSQL)',
1973
+ group: 'backend',
1974
+ run: addTestcontainers,
1975
+ applied: ()=>created('specs/integration/vitest.config.ts')
1976
+ },
1977
+ {
1978
+ name: 'OpenAPI',
1979
+ group: 'backend',
1980
+ run: addOpenapi,
1981
+ available: ()=>withHandlersRest(),
1982
+ applied: ()=>created(openapiScriptPath)
1983
+ },
1984
+ {
1985
+ name: 'Orval (API client)',
1986
+ group: 'frontend',
1987
+ run: addOrval,
1988
+ available: ()=>withHandlersRest(),
1989
+ applied: ()=>createdInRoot('presentation/react/data-layer/orval.config.ts') || createdInRoot('presentation/data-layer/orval.config.ts')
1990
+ }
1991
+ ];
1992
+ const addIntegration = async ()=>{
1993
+ const available = integrations.filter(({ available })=>available?.() ?? true).map((value)=>({
1994
+ value,
1995
+ applied: value.applied()
1996
+ }));
1997
+ const section = (title, applied)=>{
1998
+ const items = [
1999
+ 'backend',
2000
+ 'frontend'
2001
+ ].flatMap((group)=>available.filter((item)=>item.applied === applied && item.value.group === group));
2002
+ return items.length ? [
2003
+ new prompts_namespaceObject.Separator(title),
2004
+ ...items.map(({ value })=>({
2005
+ name: `${value.name} · ${value.group}`,
2006
+ value
2007
+ }))
2008
+ ] : [];
2009
+ };
2010
+ const choices = [
2011
+ ...section('New integrations', false),
2012
+ ...section('Already applied (select to reapply)', true)
2013
+ ];
2014
+ const selected = await (0, prompts_namespaceObject.checkbox)({
2015
+ message: 'Integrations:',
2016
+ choices,
2017
+ pageSize: choices.length
2018
+ });
2019
+ const nextSteps = [];
2020
+ for (const integration of integrations.filter((value)=>selected.includes(value)))nextSteps.push(...await integration.run());
2021
+ if (await savePendingChanges()) printNextSteps(nextSteps);
2022
+ };
2023
+ new Set([
2024
+ 'node_modules',
2025
+ '.git',
2026
+ '.next',
2027
+ 'dist',
2028
+ 'build',
2029
+ 'out',
2030
+ 'coverage',
2031
+ 'storybook-static'
2032
+ ]);
2033
+ const help = `Usage: df-integration
2034
+
2035
+ Adds integrations to a Domain-First project: the REST endpoint generator,
2036
+ the in-memory DB, Storybook, Prisma, Vitest, Playwright, integration tests,
2037
+ OpenAPI and Orval. Several can be selected at once. Changes project files and prints
2038
+ the install commands; nothing is installed or run.
2039
+
2040
+ Options:
2041
+ -h, --help show this help`;
2042
+ const { values } = (0, external_node_util_namespaceObject.parseArgs)({
2043
+ options: {
2044
+ help: {
2045
+ type: 'boolean',
2046
+ short: 'h',
2047
+ default: false
2048
+ }
2049
+ }
2050
+ });
2051
+ if (values.help) {
2052
+ console.log(help);
2053
+ process.exit(0);
2054
+ }
2055
+ if (!config_file_ConfigFile.exists) {
2056
+ console.log('No domain-first.project-structure.config.json found: run df-init first to initialize the project.');
2057
+ process.exit(1);
2058
+ }
2059
+ addIntegration();
2060
+ for(var __rspack_i in __webpack_exports__)exports[__rspack_i] = __webpack_exports__[__rspack_i];
2061
+ Object.defineProperty(exports, '__esModule', {
2062
+ value: true
2063
+ });