@domain-first/project-structure 2.11.0 → 2.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -26,9 +26,9 @@ var __webpack_require__ = {};
26
26
  __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
27
27
  })();
28
28
  var __webpack_exports__ = {};
29
+ const prompts_namespaceObject = require("@inquirer/prompts");
29
30
  const external_node_path_namespaceObject = require("node:path");
30
31
  var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_namespaceObject);
31
- const prompts_namespaceObject = require("@inquirer/prompts");
32
32
  const external_zod_namespaceObject = require("zod");
33
33
  var external_zod_default = /*#__PURE__*/ __webpack_require__.n(external_zod_namespaceObject);
34
34
  const external_node_fs_namespaceObject = require("node:fs");
@@ -38,6 +38,10 @@ const pendingFolders = new Set();
38
38
  const filesToOverwrite = ()=>[
39
39
  ...pendingFiles
40
40
  ].filter(([filePath, { replacesFile }])=>replacesFile && external_node_fs_default().existsSync(filePath)).map(([filePath])=>filePath);
41
+ const discardPendingChanges = ()=>{
42
+ pendingFolders.clear();
43
+ pendingFiles.clear();
44
+ };
41
45
  const writePendingChanges = ()=>{
42
46
  for (const folderPath of pendingFolders)external_node_fs_default().mkdirSync(folderPath, {
43
47
  recursive: true
@@ -48,8 +52,7 @@ const writePendingChanges = ()=>{
48
52
  });
49
53
  external_node_fs_default().writeFileSync(filePath, content, 'utf8');
50
54
  }
51
- pendingFolders.clear();
52
- pendingFiles.clear();
55
+ discardPendingChanges();
53
56
  };
54
57
  class FileSystemItem {
55
58
  path;
@@ -113,6 +116,12 @@ class File extends FileSystemItem {
113
116
  replacesFile: true
114
117
  });
115
118
  }
119
+ update = (content)=>{
120
+ pendingFiles.set(this.path, {
121
+ content,
122
+ replacesFile: pendingFiles.get(this.path)?.replacesFile ?? false
123
+ });
124
+ };
116
125
  addLine = (newLine, separator = '\n')=>{
117
126
  const content = this.exists ? this.data : '';
118
127
  pendingFiles.set(this.path, {
@@ -179,6 +188,348 @@ class ConfigFile {
179
188
  new File(ConfigFile.path).data = JSON.stringify(config, null, '\t');
180
189
  };
181
190
  }
191
+ const savePendingChanges = async ()=>{
192
+ const overwrittenFiles = filesToOverwrite();
193
+ if (overwrittenFiles.length) {
194
+ const root = new ProjectRoot().path;
195
+ console.log('These files already exist and will be overwritten:');
196
+ for (const filePath of overwrittenFiles)console.log(` ${external_node_path_default().relative(root, filePath)}`);
197
+ const overwrite = await (0, prompts_namespaceObject.confirm)({
198
+ message: 'Overwrite them?',
199
+ default: false
200
+ });
201
+ if (!overwrite) {
202
+ discardPendingChanges();
203
+ console.log('Cancelled: nothing was written.');
204
+ return false;
205
+ }
206
+ }
207
+ writePendingChanges();
208
+ return true;
209
+ };
210
+ const external_node_util_namespaceObject = require("node:util");
211
+ const missingDomainFirstPackages = ()=>{
212
+ const packages = ConfigFile.Instance.data.domainFirstPackages;
213
+ const manifest = JSON.parse(new File(external_node_path_default().join(new ProjectRoot().path, 'package.json')).data);
214
+ const dependencies = {
215
+ ...manifest.dependencies,
216
+ ...manifest.devDependencies,
217
+ ...manifest.optionalDependencies
218
+ };
219
+ const missing = [
220
+ ...new Set(packages)
221
+ ].filter((name)=>!Object.hasOwn(dependencies, name));
222
+ return missing.length ? [
223
+ 'Install missing domain-first packages (run from the project package directory):',
224
+ ` npm i ${missing.join(' ')}`
225
+ ] : [
226
+ 'All configured domain-first packages are already declared in package.json.'
227
+ ];
228
+ };
229
+ const addPackageScripts = async (file, additions)=>{
230
+ const original = file.data;
231
+ const manifest = JSON.parse(original);
232
+ const scripts = {
233
+ ...manifest.scripts
234
+ };
235
+ const selected = {};
236
+ for (const [name, command] of Object.entries(additions)){
237
+ let target = name;
238
+ if (Object.hasOwn(scripts, name) && scripts[name] !== command) {
239
+ const action = await (0, prompts_namespaceObject.select)({
240
+ message: `Script "${name}" already exists: ${scripts[name]}`,
241
+ choices: [
242
+ 'Keep existing',
243
+ 'Replace',
244
+ 'Use another name'
245
+ ]
246
+ });
247
+ if ('Keep existing' === action) continue;
248
+ if ('Use another name' === action) target = await (0, prompts_namespaceObject.input)({
249
+ message: "New script name:",
250
+ validate: (value)=>!/^[a-zA-Z0-9:_-]+$/.test(value) || Object.hasOwn(scripts, value) || Object.hasOwn(additions, value) ? "Enter an unused script name (letters, numbers, :, _, -)." : true
251
+ });
252
+ }
253
+ scripts[target] = command;
254
+ selected[name] = target;
255
+ }
256
+ if (JSON.stringify(manifest.scripts) !== JSON.stringify(scripts)) {
257
+ manifest.scripts = scripts;
258
+ const indent = original.match(/\n([\t ]+)"/)?.[1] ?? ' ';
259
+ file.update(`${JSON.stringify(manifest, null, indent)}\n`);
260
+ }
261
+ return selected;
262
+ };
263
+ const runtimePackages = [
264
+ '@prisma/orm-postgres',
265
+ 'temporal-polyfill',
266
+ 'dotenv'
267
+ ];
268
+ const developmentPackages = [
269
+ 'prisma',
270
+ '@prisma/cli-engine'
271
+ ];
272
+ const prismaScripts = (rootFolder)=>{
273
+ const config = JSON.stringify(external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'shared/infrastructure/prisma/prisma.config.ts'));
274
+ const emit = `prisma contract emit --config ${config}`;
275
+ return {
276
+ 'prisma:emit': emit,
277
+ 'prisma:migration:plan': `${emit} && prisma migration plan --config ${config}`,
278
+ 'prisma:migration:apply': `prisma db migrate --advance-ref db --config ${config}`
279
+ };
280
+ };
281
+ const prismaConfig = `import 'dotenv/config';
282
+ import { definePrismaConfig } from '@prisma/cli-engine';
283
+ import { defineConfig as ormConfig } from '@prisma/orm-postgres/config';
284
+
285
+ export default definePrismaConfig({
286
+ orm: ormConfig({
287
+ contract: './contract.prisma',
288
+ migrations: { dir: './migrations' },
289
+ db: {
290
+ connection: process.env.DATABASE_URL
291
+ }
292
+ })
293
+ });
294
+ `;
295
+ const prismaService = `import 'temporal-polyfill/global';
296
+ import postgres from '@prisma/orm-postgres/runtime';
297
+ import type {} from 'temporal-polyfill/types/global';
298
+ import type { Contract } from '../prisma/contract.d';
299
+ import contractJson from '../prisma/contract.json' with { type: 'json' };
300
+
301
+ type PrismaClient = ReturnType<typeof postgres<Contract>>;
302
+
303
+ const globalForPrisma = globalThis as typeof globalThis & {
304
+ prismaClient?: PrismaClient;
305
+ };
306
+
307
+ // Reuse the client across development hot reloads.
308
+ const prismaClient = globalForPrisma.prismaClient ??
309
+ postgres<Contract>({ contractJson, url: process.env.DATABASE_URL });
310
+
311
+ if (process.env.NODE_ENV !== 'production') {
312
+ globalForPrisma.prismaClient = prismaClient;
313
+ }
314
+
315
+ export class PrismaInfrastructureService {
316
+ readonly orm = prismaClient.orm.public;
317
+ }
318
+ `;
319
+ const prismaWiring = `import { wireClass } from '@domain-first/wire';
320
+ import { PrismaInfrastructureService } from '../../infrastructure/services/prisma-infrastructure-service';
321
+
322
+ export const wirePrismaInfrastructureService = wireClass(
323
+ PrismaInfrastructureService,
324
+ []
325
+ );
326
+ `;
327
+ const stageFile = (filePath, content)=>{
328
+ const file = new File(filePath);
329
+ if (!file.exists || file.data !== content) file.data = content;
330
+ };
331
+ const addPrisma = async ()=>{
332
+ const config = ConfigFile.Instance.data;
333
+ const root = new ProjectRoot().path;
334
+ const manifestFile = new File(external_node_path_default().join(root, 'package.json'));
335
+ const manifest = JSON.parse(manifestFile.data);
336
+ const dependencies = {
337
+ ...manifest.dependencies,
338
+ ...manifest.devDependencies
339
+ };
340
+ const shared = external_node_path_default().resolve(root, config.rootFolder, 'shared');
341
+ const prismaFolder = external_node_path_default().join(shared, 'infrastructure/prisma');
342
+ if (dependencies['@prisma/client'] || dependencies.prisma && !/^[~^]?8\./.test(dependencies.prisma) || dependencies['@prisma/orm-mongo'] || dependencies['@prisma/orm-sqlite'] || [
343
+ external_node_path_default().join(root, 'prisma/schema.prisma'),
344
+ external_node_path_default().join(prismaFolder, 'schema.prisma')
345
+ ].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.');
346
+ const withService = await (0, prompts_namespaceObject.confirm)({
347
+ message: 'Create shared Prisma infrastructure service?',
348
+ default: true
349
+ });
350
+ const useByDefault = 'prisma' !== config.defaultPersistenceLayerImplementation && await (0, prompts_namespaceObject.confirm)({
351
+ message: 'Use prisma as the default persistence implementation?',
352
+ default: false
353
+ });
354
+ const selected = await addPackageScripts(manifestFile, prismaScripts(config.rootFolder));
355
+ stageFile(external_node_path_default().join(prismaFolder, 'prisma.config.ts'), prismaConfig);
356
+ const contract = new File(external_node_path_default().join(prismaFolder, 'contract.prisma'));
357
+ if (!contract.exists) contract.data = '// use prisma-8\n\n// Add your application models here before running prisma:emit.\n';
358
+ if (withService) {
359
+ stageFile(external_node_path_default().join(shared, 'infrastructure/services/prisma-infrastructure-service.ts'), prismaService);
360
+ if (config.domainFirstPackages.includes('@domain-first/wire')) stageFile(external_node_path_default().join(shared, 'wiring/infrastructure-services/wire-prisma-infrastructure-service.ts'), prismaWiring);
361
+ }
362
+ if (useByDefault) ConfigFile.write({
363
+ ...config,
364
+ defaultPersistenceLayerImplementation: 'prisma'
365
+ });
366
+ const install = (packages, dev)=>{
367
+ const missing = packages.filter((name)=>!dependencies[name]);
368
+ return missing.length ? [
369
+ ` npm install${dev ? ' --save-dev' : ''} ${missing.join(' ')}`
370
+ ] : [];
371
+ };
372
+ const scriptCommand = (name)=>selected[name] ? `npm run ${selected[name]}` : prismaScripts(config.rootFolder)[name];
373
+ const relativeFolder = external_node_path_default().relative(root, prismaFolder).split(external_node_path_default().sep).join('/');
374
+ return [
375
+ 'Prisma 8 configuration saved (PostgreSQL, RC preset).',
376
+ 'Next steps (run from the project package directory):',
377
+ ...install(runtimePackages, false),
378
+ ...install(developmentPackages, true),
379
+ ' Existing dependency versions were kept.',
380
+ ' Use Node.js 22.18+ and TypeScript 5.9+ with ESM and JSON import support.',
381
+ ' Set DATABASE_URL in your project environment (.env for the CLI); load it in the application runtime too.',
382
+ ` Add your models to ${relativeFolder}/contract.prisma.`,
383
+ ` Emit the contract before compiling or importing the service: ${scriptCommand('prisma:emit')}`,
384
+ ` Plan migrations: ${scriptCommand('prisma:migration:plan')}`,
385
+ ` Review the generated migrations, then apply: ${scriptCommand('prisma:migration:apply')}`
386
+ ];
387
+ };
388
+ const storybookFiles = (relativeProjectRoot)=>({
389
+ 'main.ts': `import { resolve } from 'node:path';
390
+ import react from '@vitejs/plugin-react';
391
+ import type { StorybookConfig } from '@storybook/react-vite';
392
+
393
+ const projectRoot = resolve(import.meta.dirname, ${JSON.stringify(relativeProjectRoot)});
394
+
395
+ const config: StorybookConfig = {
396
+ stories: ['../**/*.mdx', '../**/*.stories.@(ts|tsx)'],
397
+ framework: {
398
+ name: '@storybook/react-vite',
399
+ options: {}
400
+ },
401
+ core: {
402
+ disableTelemetry: true
403
+ },
404
+ async viteFinal(viteConfig) {
405
+ const { mergeConfig } = await import('vite');
406
+
407
+ return mergeConfig(viteConfig, {
408
+ plugins: [react()],
409
+ resolve: {
410
+ alias: {
411
+ '@': projectRoot
412
+ }
413
+ }
414
+ });
415
+ }
416
+ };
417
+
418
+ export default config;
419
+ `,
420
+ 'preview.ts': `import type { Preview } from '@storybook/react-vite';
421
+
422
+ const preview: Preview = {
423
+ parameters: {
424
+ controls: {
425
+ matchers: {
426
+ color: /(background|color)$/i,
427
+ date: /Date$/i
428
+ }
429
+ }
430
+ }
431
+ };
432
+
433
+ export default preview;
434
+ `
435
+ });
436
+ const storybookScripts = (rootFolder)=>{
437
+ const folder = external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react');
438
+ const quote = (value)=>JSON.stringify(value);
439
+ return {
440
+ storybook: `storybook dev -p 6006 -c ${quote(`${folder}/.storybook`)}`,
441
+ 'build-storybook': `storybook build -c ${quote(`${folder}/.storybook`)} -o ${quote(`${folder}/storybook-static`)}`
442
+ };
443
+ };
444
+ const addStorybook = async ()=>{
445
+ const config = ConfigFile.Instance.data;
446
+ if ((!config.useReact || config.storybookFramework && '@storybook/react-vite' !== config.storybookFramework) && !await (0, prompts_namespaceObject.confirm)({
447
+ message: 'Configure React scaffolding with @storybook/react-vite?',
448
+ default: false
449
+ })) return [];
450
+ const root = new ProjectRoot().path;
451
+ const manifestFile = new File(external_node_path_default().join(root, 'package.json'));
452
+ const manifest = JSON.parse(manifestFile.data);
453
+ const selected = await addPackageScripts(manifestFile, storybookScripts(config.rootFolder));
454
+ const folder = new Folder(root).subitem([
455
+ config.rootFolder,
456
+ 'presentation',
457
+ 'react',
458
+ '.storybook'
459
+ ]);
460
+ for (const [name, content] of Object.entries(storybookFiles(external_node_path_default().relative(folder.path, root).split(external_node_path_default().sep).join('/')))){
461
+ const file = new File(external_node_path_default().join(folder.path, name));
462
+ if (!file.exists || file.data !== content) file.data = content;
463
+ }
464
+ if (!config.useReact || '@storybook/react-vite' !== config.storybookFramework) ConfigFile.write({
465
+ ...config,
466
+ useReact: true,
467
+ storybookFramework: '@storybook/react-vite'
468
+ });
469
+ const dependencies = {
470
+ ...manifest.dependencies,
471
+ ...manifest.devDependencies
472
+ };
473
+ const missing = [
474
+ 'storybook',
475
+ '@storybook/react-vite',
476
+ 'vite',
477
+ '@vitejs/plugin-react'
478
+ ].filter((name)=>!dependencies[name]);
479
+ const missingReact = [
480
+ 'react',
481
+ 'react-dom'
482
+ ].filter((name)=>!dependencies[name]);
483
+ return [
484
+ 'Storybook configuration saved (React + Vite).',
485
+ 'Next steps (run from the project package directory):',
486
+ ...missing.length ? [
487
+ ` npm install --save-dev ${missing.join(' ')}`
488
+ ] : [],
489
+ ...missingReact.length ? [
490
+ ` npm install ${missingReact.join(' ')}`
491
+ ] : [],
492
+ ' Existing dependency versions were kept; ensure Storybook packages are compatible.',
493
+ ' Add your CSS imports to .storybook/preview.ts using relative paths or the @/ alias (project root).',
494
+ ' Generate a UI-kit component or widget UI to create a story.',
495
+ ...selected.storybook ? [
496
+ ` npm run ${selected.storybook}`
497
+ ] : [],
498
+ ...selected['build-storybook'] ? [
499
+ ` npm run ${selected['build-storybook']}`
500
+ ] : []
501
+ ];
502
+ };
503
+ const integrations = [
504
+ {
505
+ name: 'Storybook (React + Vite)',
506
+ run: addStorybook
507
+ },
508
+ {
509
+ name: 'Prisma 8 (PostgreSQL, RC)',
510
+ run: addPrisma
511
+ },
512
+ {
513
+ name: 'Missing domain-first packages',
514
+ run: missingDomainFirstPackages
515
+ }
516
+ ];
517
+ const addIntegration = async ()=>{
518
+ const index = await (0, prompts_namespaceObject.select)({
519
+ message: 'Integration:',
520
+ choices: integrations.map((integration, value)=>({
521
+ name: integration.name,
522
+ value
523
+ }))
524
+ });
525
+ const nextSteps = await integrations[index].run();
526
+ if (await savePendingChanges()) {
527
+ if (nextSteps.length) console.log(nextSteps.map((line)=>/^\s*npm (?:i|install)\b/.test(line) ? (0, external_node_util_namespaceObject.styleText)([
528
+ 'bold',
529
+ 'cyan'
530
+ ], line) : line).join('\n'));
531
+ }
532
+ };
182
533
  const initializeUseCase = async ()=>{
183
534
  const rootFolderName = await (0, prompts_namespaceObject.input)({
184
535
  message: 'Root folder (use "/" for inner folders):',
@@ -277,6 +628,439 @@ class UnknownFormatNaming {
277
628
  return this.fileName.replaceAll('-', ' ');
278
629
  }
279
630
  }
631
+ const wiring_layers = [
632
+ 'domain',
633
+ 'application',
634
+ 'infrastructure',
635
+ 'presentation'
636
+ ];
637
+ const visibleLayers = {
638
+ domain: [
639
+ 'domain'
640
+ ],
641
+ application: [
642
+ 'domain',
643
+ 'application'
644
+ ],
645
+ infrastructure: [
646
+ 'domain',
647
+ 'infrastructure'
648
+ ],
649
+ presentation: [
650
+ 'application',
651
+ 'presentation'
652
+ ]
653
+ };
654
+ const branchedTypeFiles = {
655
+ repositories: (fileBase)=>[
656
+ 'domain',
657
+ 'aggregates',
658
+ fileBase.replace(/-repository$/, ''),
659
+ `${fileBase}.ts`
660
+ ],
661
+ commands: (fileBase)=>[
662
+ 'application',
663
+ 'commands',
664
+ 'execution',
665
+ `${fileBase}.ts`
666
+ ],
667
+ queries: (fileBase)=>[
668
+ 'application',
669
+ 'queries',
670
+ 'execution',
671
+ `${fileBase}.ts`
672
+ ],
673
+ 'application-ports': (fileBase)=>[
674
+ 'application',
675
+ 'ports',
676
+ `${fileBase}.ts`
677
+ ]
678
+ };
679
+ const layerOf = (file, contextPath)=>{
680
+ const [firstSegment] = external_node_path_default().relative(contextPath, file).split(external_node_path_default().sep);
681
+ return wiring_layers.find((layer)=>layer === firstSegment);
682
+ };
683
+ const namedImports = (source, fromFile)=>{
684
+ const result = new Map();
685
+ for (const [, names, importPath] of source.matchAll(/import\s*(?:type\s*)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g))for (const name of names.split(',')){
686
+ const cleanName = name.replace(/^\s*type\s+/, '').trim();
687
+ if (cleanName) result.set(cleanName, `${external_node_path_default().resolve(external_node_path_default().dirname(fromFile), importPath)}.ts`);
688
+ }
689
+ return result;
690
+ };
691
+ const isEndpointWire = (wiringRelativePath)=>wiringRelativePath.startsWith([
692
+ 'presentation',
693
+ 'rest'
694
+ ].join(external_node_path_default().sep));
695
+ const wireClassDefinitions = (source)=>[
696
+ ...codeOnly(source).matchAll(/(?:export\s+)?const\s+(\w+)\s*=\s*(?:\w+\(\s*)*wireClass\(\s*(\w+)\s*,/g)
697
+ ].map(([, wireName, className])=>({
698
+ wireName,
699
+ className
700
+ }));
701
+ const wiredClassNames = (source, wireName, initializerStart, branched)=>{
702
+ const definitions = wireClassDefinitions(source);
703
+ if (!branched) return definitions.filter((x)=>x.wireName === wireName).map((x)=>x.className);
704
+ const openIndex = source.indexOf('(', initializerStart);
705
+ const branches = codeOnly(source).slice(openIndex, closingIndex(source, openIndex));
706
+ const referenced = new Set(branches.match(/\w+/g));
707
+ return definitions.filter((x)=>referenced.has(x.wireName)).map((x)=>x.className);
708
+ };
709
+ const readWiredModule = (wireFile, contextPath)=>{
710
+ const wiringRelativePath = external_node_path_default().relative(external_node_path_default().join(contextPath, 'wiring'), wireFile);
711
+ if (isEndpointWire(wiringRelativePath)) return;
712
+ const source = new File(wireFile).data;
713
+ const wireName = `wire${new UnknownFormatNaming(external_node_path_default().basename(wireFile, '.ts').replace(/^wire-/, '')).ClassName}`;
714
+ const exportMatch = new RegExp(`export\\s+const\\s+${wireName}\\s*=\\s*`).exec(source);
715
+ if (!exportMatch) return;
716
+ const branched = source.slice(exportMatch.index + exportMatch[0].length).startsWith('envBranchedWire(');
717
+ const imports = namedImports(source, wireFile);
718
+ const implementations = wiredClassNames(source, wireName, exportMatch.index + exportMatch[0].length, branched).flatMap((className)=>{
719
+ const file = imports.get(className);
720
+ return file ? [
721
+ {
722
+ className,
723
+ file
724
+ }
725
+ ] : [];
726
+ });
727
+ if (!implementations.length) return;
728
+ const typeName = wireName.slice(4);
729
+ const [wiringFolder] = wiringRelativePath.split(external_node_path_default().sep);
730
+ const typeFileSegments = branchedTypeFiles[wiringFolder]?.(external_node_path_default().basename(wireFile, '.ts').replace(/^wire-/, ''));
731
+ const typeFile = branched ? typeFileSegments && external_node_path_default().join(contextPath, ...typeFileSegments) : implementations[0].file;
732
+ const layer = typeFile && layerOf(typeFile, contextPath);
733
+ const implementationsLayer = layerOf(implementations[0].file, contextPath);
734
+ if (!typeFile || !layer || !implementationsLayer) return;
735
+ return {
736
+ wireName,
737
+ typeName,
738
+ wireFile,
739
+ typeFile,
740
+ layer,
741
+ implementations,
742
+ branched,
743
+ implementationsLayer,
744
+ kind: wiringFolder
745
+ };
746
+ };
747
+ const findWiredModules = (contextPath)=>{
748
+ const result = [];
749
+ const walk = (folderPath)=>{
750
+ if (!external_node_fs_default().existsSync(folderPath)) return;
751
+ for (const entry of external_node_fs_default().readdirSync(folderPath, {
752
+ withFileTypes: true
753
+ })){
754
+ const entryPath = external_node_path_default().join(folderPath, entry.name);
755
+ if (entry.isDirectory()) walk(entryPath);
756
+ else if (/^wire-.*(?<!\.spec)\.ts$/.test(entry.name)) {
757
+ const wiredModule = readWiredModule(entryPath, contextPath);
758
+ if (wiredModule) result.push(wiredModule);
759
+ }
760
+ }
761
+ };
762
+ walk(external_node_path_default().join(contextPath, 'wiring'));
763
+ return result.sort((a, b)=>a.typeName.localeCompare(b.typeName));
764
+ };
765
+ const isCommandOrQuery = (module)=>'commands' === module.kind || 'queries' === module.kind;
766
+ const isExecution = (module)=>isCommandOrQuery(module) && 'execution' === external_node_path_default().basename(external_node_path_default().dirname(module.typeFile));
767
+ const commandOrQueryRule = (candidate, consumer)=>isExecution(consumer) ? !isCommandOrQuery(candidate) : 'application' !== candidate.layer || isExecution(candidate);
768
+ const kindRules = {
769
+ 'application-services': (candidate)=>'application' !== candidate.layer || 'application-ports' === candidate.kind,
770
+ 'use-cases': (candidate)=>'use-cases' !== candidate.kind,
771
+ repositories: (candidate)=>'repositories' !== candidate.kind,
772
+ commands: commandOrQueryRule,
773
+ queries: commandOrQueryRule
774
+ };
775
+ const wiring_implementationType = (consumer, implementation)=>consumer.branched ? external_node_path_default().basename(external_node_path_default().dirname(implementation.file)) : void 0;
776
+ const isSuggestedFor = (candidate, implementation)=>'infrastructure' === candidate.layer && `-${external_node_path_default().basename(candidate.typeFile, '.ts')}-`.includes(`-${implementation}-`);
777
+ const isSuggestedEndpointGenerator = (candidate)=>candidate.typeName.toLowerCase().includes('endpoint');
778
+ const canDependOn = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && (kindRules[consumer.kind]?.(candidate, consumer) ?? true);
779
+ const availableDependencies = (consumer, implementation, candidates)=>{
780
+ const wired = wiredDependencyNames(new File(consumer.wireFile).data, implementation.className);
781
+ return candidates.filter((candidate)=>candidate.wireFile !== consumer.wireFile && canDependOn(consumer, candidate) && !wired.includes(candidate.wireName));
782
+ };
783
+ const relativeImport = (fromFile, toFile)=>{
784
+ const relativePath = external_node_path_default().relative(external_node_path_default().dirname(fromFile), toFile).replace(/\.ts$/, '').split(external_node_path_default().sep).join('/');
785
+ return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
786
+ };
787
+ const codeOnly = (source)=>{
788
+ let result = '';
789
+ let index = 0;
790
+ const blank = (text)=>text.replace(/[^\n]/g, ' ');
791
+ while(index < source.length){
792
+ const pair = source.slice(index, index + 2);
793
+ const char = source[index];
794
+ let end = index + 1;
795
+ if ('//' === pair) {
796
+ const lineEnd = source.indexOf('\n', index);
797
+ end = -1 === lineEnd ? source.length : lineEnd;
798
+ result += blank(source.slice(index, end));
799
+ } else if ('/*' === pair) {
800
+ const commentEnd = source.indexOf('*/', index + 2);
801
+ end = -1 === commentEnd ? source.length : commentEnd + 2;
802
+ result += blank(source.slice(index, end));
803
+ } else if ('=>' === pair) {
804
+ end = index + 2;
805
+ result += ' ';
806
+ } else if ("'" === char || '"' === char || '`' === char) {
807
+ while(end < source.length && source[end] !== char)end += '\\' === source[end] ? 2 : 1;
808
+ end = Math.min(end + 1, source.length);
809
+ result += char + blank(source.slice(index + 1, end - 1));
810
+ result += end - 1 > index ? source[end - 1] : '';
811
+ } else result += char;
812
+ index = end;
813
+ }
814
+ return result;
815
+ };
816
+ const addImport = (source, importLine)=>{
817
+ if (source.split('\n').some((line)=>line.trim() === importLine)) return source;
818
+ const lastImport = [
819
+ ...codeOnly(source).matchAll(/^import\s(?:[^'"]*?from\s*)?['"][^'"]*['"]/gm)
820
+ ].at(-1);
821
+ if (!lastImport) return `${importLine}\n\n${source}`;
822
+ const importEnd = lastImport.index + lastImport[0].length;
823
+ const lineEnd = source.indexOf('\n', importEnd);
824
+ const insertAt = -1 === lineEnd ? source.length : lineEnd;
825
+ return `${source.slice(0, insertAt)}\n${importLine}${source.slice(insertAt)}`;
826
+ };
827
+ const brackets = {
828
+ '(': ')',
829
+ '[': ']',
830
+ '{': '}',
831
+ '<': '>'
832
+ };
833
+ const closingIndex = (source, openIndex)=>{
834
+ const code = codeOnly(source);
835
+ let depth = 0;
836
+ for(let index = openIndex; index < code.length; index++){
837
+ const char = code[index];
838
+ if (char === code[openIndex]) depth++;
839
+ else if (char === brackets[code[openIndex]]) {
840
+ depth--;
841
+ if (0 === depth) return index;
842
+ }
843
+ }
844
+ return -1;
845
+ };
846
+ const splitTopLevel = (content)=>{
847
+ const code = codeOnly(content);
848
+ const items = [];
849
+ let depth = 0;
850
+ let itemStart = 0;
851
+ for(let index = 0; index <= code.length; index++){
852
+ const char = code[index];
853
+ if (void 0 !== char && char in brackets) depth++;
854
+ else if (Object.values(brackets).includes(char)) depth--;
855
+ if (index === code.length || ',' === char && 0 === depth) {
856
+ const item = content.slice(itemStart, index);
857
+ const itemCode = code.slice(itemStart, index);
858
+ const first = itemCode.search(/\S/);
859
+ const last = itemCode.search(/\S\s*$/);
860
+ if (-1 !== first) items.push(item.slice(first, last + 1));
861
+ itemStart = index + 1;
862
+ }
863
+ }
864
+ return items;
865
+ };
866
+ const appendItems = (content, items)=>{
867
+ const code = codeOnly(content);
868
+ const lastCode = code.search(/\S\s*$/);
869
+ if (-1 === lastCode) return items.join(', ');
870
+ const trailingComma = ',' === code[lastCode];
871
+ if (!content.includes('\n')) {
872
+ const added = trailingComma ? ` ${items.join(', ')},` : `, ${items.join(', ')}`;
873
+ return content.slice(0, lastCode + 1) + added + content.slice(lastCode + 1);
874
+ }
875
+ const indent = content.match(/\n([ \t]*)\S/)?.[1] ?? '';
876
+ const withComma = trailingComma ? content : `${content.slice(0, lastCode + 1)},${content.slice(lastCode + 1)}`;
877
+ const lineEndIndex = withComma.indexOf('\n', lastCode + 1);
878
+ const lineEnd = -1 === lineEndIndex ? withComma.length : lineEndIndex;
879
+ const added = trailingComma ? items.map((x)=>`\n${indent}${x},`).join('') : items.map((x)=>`\n${indent}${x}`).join(',');
880
+ return withComma.slice(0, lineEnd) + added + withComma.slice(lineEnd);
881
+ };
882
+ const addConstructorParameters = (source, className, parameters)=>{
883
+ const classMatch = new RegExp(`class\\s+${className}\\b[^{]*\\{`).exec(codeOnly(source));
884
+ if (!classMatch) throw new Error(`Class ${className} not found`);
885
+ const bodyStart = classMatch.index + classMatch[0].length;
886
+ const bodyEnd = closingIndex(source, bodyStart - 1);
887
+ const body = source.slice(bodyStart, bodyEnd);
888
+ const constructorIndex = codeOnly(body).search(/\bconstructor\s*\(/);
889
+ const renderParameters = (allParameters, indent)=>1 === allParameters.length ? allParameters[0] : `\n${allParameters.map((x)=>`${indent} ${x}`).join(',\n')}\n${indent}`;
890
+ if (-1 === constructorIndex) {
891
+ const constructorBody = /\bextends\b/.test(classMatch[0]) ? '{\n super()\n }' : '{}';
892
+ const constructorLine = ` constructor(${renderParameters(parameters, ' ')}) ${constructorBody}`;
893
+ const newBody = body.trim() ? `\n${constructorLine}\n${body.replace(/^\s*\n/, '\n')}` : `\n${constructorLine}\n`;
894
+ return source.slice(0, bodyStart) + newBody + source.slice(bodyEnd);
895
+ }
896
+ const openIndex = bodyStart + body.indexOf('(', constructorIndex);
897
+ const closeIndex = closingIndex(source, openIndex);
898
+ const content = source.slice(openIndex + 1, closeIndex);
899
+ if (content.includes('\n')) return source.slice(0, openIndex + 1) + appendItems(content, parameters) + source.slice(closeIndex);
900
+ const lineStart = source.lastIndexOf('\n', openIndex) + 1;
901
+ const indent = source.slice(lineStart).match(/^\s*/)?.[0] ?? '';
902
+ return source.slice(0, openIndex + 1) + renderParameters([
903
+ ...splitTopLevel(content),
904
+ ...parameters
905
+ ], indent) + source.slice(closeIndex);
906
+ };
907
+ const wireListRange = (source, className)=>{
908
+ const match = new RegExp(`wireClass\\(\\s*${className}\\s*,\\s*\\[`).exec(codeOnly(source));
909
+ if (!match) throw new Error(`wireClass(${className}, [...]) not found`);
910
+ const openIndex = match.index + match[0].length - 1;
911
+ return {
912
+ openIndex,
913
+ closeIndex: closingIndex(source, openIndex)
914
+ };
915
+ };
916
+ const wiredDependencyNames = (source, className)=>{
917
+ const { openIndex, closeIndex } = wireListRange(source, className);
918
+ return splitTopLevel(source.slice(openIndex + 1, closeIndex));
919
+ };
920
+ const addWireDependencies = (source, className, wireNames)=>{
921
+ const { openIndex, closeIndex } = wireListRange(source, className);
922
+ return source.slice(0, openIndex + 1) + appendItems(source.slice(openIndex + 1, closeIndex), wireNames) + source.slice(closeIndex);
923
+ };
924
+ const parameterName = (typeName)=>typeName.substring(0, 1).toLowerCase() + typeName.substring(1);
925
+ const wireDependencies = (consumer, implementation, dependencies)=>{
926
+ const wireFile = new File(consumer.wireFile);
927
+ let wireSource = wireFile.data;
928
+ for (const dependency of dependencies)wireSource = addImport(wireSource, `import { ${dependency.wireName} } from '${relativeImport(consumer.wireFile, dependency.wireFile)}'`);
929
+ wireFile.update(addWireDependencies(wireSource, implementation.className, dependencies.map((x)=>x.wireName)));
930
+ const classFile = new File(implementation.file);
931
+ let classSource = classFile.data;
932
+ for (const dependency of dependencies)classSource = addImport(classSource, `import type { ${dependency.typeName} } from '${relativeImport(implementation.file, dependency.typeFile)}'`);
933
+ classFile.update(addConstructorParameters(classSource, implementation.className, dependencies.map((x)=>`private readonly ${parameterName(x.typeName)}: ${x.typeName}`)));
934
+ };
935
+ const kindTitles = {
936
+ repositories: 'Repositories',
937
+ 'domain-services': 'Domain services',
938
+ 'application-ports': 'Ports',
939
+ 'application-services': 'Application services',
940
+ queries: 'Queries',
941
+ commands: 'Commands',
942
+ 'use-cases': 'Use cases',
943
+ 'infrastructure-services': 'Infrastructure services',
944
+ 'presentation-services': 'Presentation services'
945
+ };
946
+ const groupedChoices = (items, suggested = [])=>{
947
+ const suggestedChoices = suggested.length ? [
948
+ new prompts_namespaceObject.Separator('── Suggested'),
949
+ ...suggested.map((x)=>({
950
+ name: x.label,
951
+ value: x
952
+ }))
953
+ ] : [];
954
+ const kinds = [
955
+ ...new Set([
956
+ ...Object.keys(kindTitles),
957
+ ...items.map((x)=>x.module.kind)
958
+ ])
959
+ ];
960
+ return [
961
+ ...suggestedChoices,
962
+ ...kinds.flatMap((kind)=>{
963
+ const group = items.filter((x)=>x.module.kind === kind && !suggested.includes(x));
964
+ return group.length ? [
965
+ new prompts_namespaceObject.Separator(`── ${kindTitles[kind] ?? kind}`),
966
+ ...group.map((x)=>({
967
+ name: x.label,
968
+ value: x
969
+ }))
970
+ ] : [];
971
+ })
972
+ ];
973
+ };
974
+ const groupedPageSize = 20;
975
+ const contextAndSharedModules = (boundedContextFolder)=>{
976
+ const sharedFolder = new Folder(new ProjectRoot().path).subitem([
977
+ ConfigFile.Instance.data.rootFolder,
978
+ 'shared'
979
+ ]);
980
+ const isShared = sharedFolder.path === boundedContextFolder.path;
981
+ return [
982
+ ...findWiredModules(boundedContextFolder.path).map((x)=>({
983
+ module: x,
984
+ label: x.typeName
985
+ })),
986
+ ...isShared ? [] : findWiredModules(sharedFolder.path).map((x)=>({
987
+ module: x,
988
+ label: `${x.typeName} (shared)`
989
+ }))
990
+ ];
991
+ };
992
+ const promptDependencies = async (boundedContextFolder, consumer, implementations = consumer.implementations)=>{
993
+ const options = contextAndSharedModules(boundedContextFolder);
994
+ let asked = false;
995
+ for (const implementation of implementations){
996
+ const available = availableDependencies(consumer, implementation, options.map((x)=>x.module));
997
+ const candidates = options.filter((x)=>available.includes(x.module));
998
+ if (!candidates.length) continue;
999
+ asked = true;
1000
+ const type = wiring_implementationType(consumer, implementation);
1001
+ const suggested = type ? candidates.filter((x)=>isSuggestedFor(x.module, type)) : [];
1002
+ const dependencies = await (0, prompts_namespaceObject.checkbox)({
1003
+ message: consumer.branched ? `Dependencies for ${implementation.className}:` : 'Dependencies:',
1004
+ choices: groupedChoices(candidates, suggested),
1005
+ pageSize: groupedPageSize,
1006
+ loop: false
1007
+ });
1008
+ if (dependencies.length) wireDependencies(consumer, implementation, dependencies.map((x)=>x.module));
1009
+ }
1010
+ return asked;
1011
+ };
1012
+ const wireNewModuleDependencies = async (boundedContextFolder, wireFile)=>{
1013
+ const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
1014
+ if (consumer) await promptDependencies(boundedContextFolder, consumer);
1015
+ };
1016
+ const wireDependency = async (boundedContextFolder)=>{
1017
+ const modules = findWiredModules(boundedContextFolder.path);
1018
+ if (!modules.length) return void console.log('No wired modules here yet.');
1019
+ const { module: consumer, implementation } = await (0, prompts_namespaceObject.select)({
1020
+ message: 'Module:',
1021
+ choices: groupedChoices(modules.flatMap((x)=>x.implementations.map((implementation)=>{
1022
+ const type = wiring_implementationType(x, implementation);
1023
+ return {
1024
+ module: x,
1025
+ label: type ? `${x.typeName} (${type})` : x.typeName,
1026
+ implementation
1027
+ };
1028
+ }))),
1029
+ pageSize: groupedPageSize,
1030
+ loop: false
1031
+ });
1032
+ if (!await promptDependencies(boundedContextFolder, consumer, [
1033
+ implementation
1034
+ ])) console.log('No dependencies available for this module.');
1035
+ };
1036
+ const promptEndpointDependencies = async (boundedContextFolder)=>{
1037
+ const options = contextAndSharedModules(boundedContextFolder);
1038
+ const generators = options.filter((x)=>'presentation-services' === x.module.kind);
1039
+ const handlers = findWiredModules(boundedContextFolder.path).filter((x)=>[
1040
+ 'queries',
1041
+ 'commands',
1042
+ 'use-cases'
1043
+ ].includes(x.kind)).map((x)=>({
1044
+ module: x,
1045
+ label: x.typeName
1046
+ }));
1047
+ const endpointGenerator = generators.length ? (await (0, prompts_namespaceObject.select)({
1048
+ message: 'Endpoint generator:',
1049
+ choices: groupedChoices(generators, generators.filter((x)=>isSuggestedEndpointGenerator(x.module))),
1050
+ pageSize: groupedPageSize,
1051
+ loop: false
1052
+ })).module : void 0;
1053
+ const handler = handlers.length ? (await (0, prompts_namespaceObject.select)({
1054
+ message: 'Handler:',
1055
+ choices: groupedChoices(handlers),
1056
+ pageSize: groupedPageSize,
1057
+ loop: false
1058
+ })).module : void 0;
1059
+ return {
1060
+ endpointGenerator,
1061
+ handler
1062
+ };
1063
+ };
280
1064
  const scaffoldNewAggregateUseCase = async (boundedContextFolder)=>{
281
1065
  const aggregateName = await (0, prompts_namespaceObject.input)({
282
1066
  message: 'Aggregate name:'
@@ -376,7 +1160,7 @@ describe('${aggregateNaming.withSpaces} repository', () => {
376
1160
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
377
1161
  const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
378
1162
  const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
379
- boundedContextFolder.subitem([
1163
+ const wireFile = boundedContextFolder.subitem([
380
1164
  'wiring',
381
1165
  'repositories'
382
1166
  ]).createFile(`wire-${aggregateNaming.fileName}-repository.ts`, `
@@ -392,6 +1176,7 @@ export const wire${aggregateNaming.ClassName}Repository = envBranchedWire({
392
1176
  production: wire${implementationNaming.ClassName}Implementation
393
1177
  })
394
1178
  `.trim());
1179
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
395
1180
  }
396
1181
  }
397
1182
  };
@@ -468,18 +1253,19 @@ describe('${naming.withSpaces}', () => {
468
1253
  })
469
1254
  `.trim());
470
1255
  }
471
- if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) wiringFolder.createFile(`wire-${naming.fileName}.ts`, `
1256
+ if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
1257
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}.ts`, `
472
1258
  import { wireClass } from '@domain-first/wire'
473
1259
  import { envBranchedWire } from '../../../${'shared' === boundedContextFolder.name ? '' : '../'}shared/wiring/env-branched-wire'
474
1260
  ${implementationTypes.map((x)=>({
475
- naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
476
- implementation: x
477
- })).map(({ naming: { ClassName, fileName }, implementation })=>`import { ${ClassName} } from '../../infrastructure/application-adapters/${implementation}/${fileName}'`).join('\n')}
1261
+ naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
1262
+ implementation: x
1263
+ })).map(({ naming: { ClassName, fileName }, implementation })=>`import { ${ClassName} } from '../../infrastructure/application-adapters/${implementation}/${fileName}'`).join('\n')}
478
1264
 
479
1265
  ${implementationTypes.map((x)=>({
480
- naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
481
- implementation: x
482
- })).map(({ naming: { ClassName }, implementation })=>`const wire${new UnknownFormatNaming(implementation).ClassName}Implementation = wireClass(${ClassName}, [])`).join('\n\n')}
1266
+ naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
1267
+ implementation: x
1268
+ })).map(({ naming: { ClassName }, implementation })=>`const wire${new UnknownFormatNaming(implementation).ClassName}Implementation = wireClass(${ClassName}, [])`).join('\n\n')}
483
1269
 
484
1270
  export const wire${naming.ClassName} = envBranchedWire({
485
1271
  test: wire${new UnknownFormatNaming(`${implementationTypes.at(-1)}-implementation`).ClassName},
@@ -488,6 +1274,8 @@ export const wire${naming.ClassName} = envBranchedWire({
488
1274
  })
489
1275
 
490
1276
  `.trim());
1277
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1278
+ }
491
1279
  };
492
1280
  const scaffoldNewApplicationService = async (boundedContextFolder)=>{
493
1281
  const name = await (0, prompts_namespaceObject.input)({
@@ -526,7 +1314,8 @@ describe('${naming.withSpaces}', () => {
526
1314
  })
527
1315
  })
528
1316
  `.trim());
529
- if (withWiring) wiringFolder.createFile(`wire-${naming.fileName}-application-service.ts`, `
1317
+ if (withWiring) {
1318
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-application-service.ts`, `
530
1319
  import { wireClass } from '@domain-first/wire'
531
1320
  import { ${naming.ClassName}ApplicationService } from '../../application/services/${naming.fileName}-application-service'
532
1321
 
@@ -535,6 +1324,8 @@ export const wire${naming.ClassName}ApplicationService = wireClass(
535
1324
  []
536
1325
  )
537
1326
  `.trim());
1327
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1328
+ }
538
1329
  };
539
1330
  const scaffoldNewBoundedContextUseCase = async ()=>{
540
1331
  const name = await (0, prompts_namespaceObject.input)({
@@ -675,7 +1466,7 @@ describe('${naming.withSpaces} command', () => {
675
1466
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
676
1467
  const implementationNaming = new UnknownFormatNaming(implementationType);
677
1468
  const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
678
- boundedContextFolder.subitem([
1469
+ const wireFile = boundedContextFolder.subitem([
679
1470
  'wiring',
680
1471
  'commands'
681
1472
  ]).createFile(`wire-${naming.fileName}-command.ts`, `
@@ -691,6 +1482,7 @@ export const wire${naming.ClassName}Command = envBranchedWire({
691
1482
  production: wire${implementationNaming.ClassName}Implementation
692
1483
  })
693
1484
  `.trim());
1485
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
694
1486
  }
695
1487
  return;
696
1488
  }
@@ -748,6 +1540,10 @@ test('can be ${withWiring ? 'wired' : 'created via constructor'}', () => {
748
1540
  })
749
1541
  })
750
1542
  `.trim());
1543
+ if (withWiring) await wireNewModuleDependencies(boundedContextFolder, boundedContextFolder.subitem([
1544
+ 'wiring',
1545
+ 'commands'
1546
+ ]).file(`wire-${naming.fileName}-command.ts`));
751
1547
  };
752
1548
  const noAggregate = 'No aggregate';
753
1549
  const scaffoldNewDomainObject = async (boundedContextFolder, kind)=>{
@@ -836,10 +1632,11 @@ describe('${naming.withSpaces}', () => {
836
1632
  })
837
1633
  })
838
1634
  `.trim());
839
- if (withWiring) boundedContextFolder.subitem([
840
- 'wiring',
841
- 'domain-services'
842
- ]).createFile(`wire-${naming.fileName}-domain-service.ts`, `
1635
+ if (withWiring) {
1636
+ const wireFile = boundedContextFolder.subitem([
1637
+ 'wiring',
1638
+ 'domain-services'
1639
+ ]).createFile(`wire-${naming.fileName}-domain-service.ts`, `
843
1640
  import { wireClass } from '@domain-first/wire'
844
1641
  import { ${naming.ClassName}DomainService } from '../../domain/services/${naming.fileName}-domain-service'
845
1642
 
@@ -848,6 +1645,8 @@ export const wire${naming.ClassName}DomainService = wireClass(
848
1645
  []
849
1646
  )
850
1647
  `.trim());
1648
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1649
+ }
851
1650
  };
852
1651
  const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
853
1652
  const currentErrorFolder = boundedContextFolder.subitem([
@@ -942,33 +1741,40 @@ export const restHandlers = restWires.map(x => x().handle)
942
1741
  'put'
943
1742
  ]
944
1743
  });
945
- const path = (await (0, prompts_namespaceObject.input)({
1744
+ const routeSegments = (await (0, prompts_namespaceObject.input)({
946
1745
  message: 'Relative path (split by "/"):'
947
1746
  })).split('/').filter((x)=>!!x);
948
1747
  const controllerFolder = restPresentationFolder.subitem([
949
1748
  controller
950
1749
  ]);
951
- const endpointFolder = controllerFolder.subitem(path);
952
- const nameBase = `${controller}-${path.length ? `${path.join('-')}-` : ''}${method}-endpoint`;
1750
+ const endpointFolder = controllerFolder.subitem(routeSegments);
1751
+ const nameBase = `${controller}-${routeSegments.length ? `${routeSegments.join('-')}-` : ''}${method}-endpoint`;
953
1752
  const endpointNaming = new UnknownFormatNaming(nameBase);
1753
+ const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
1754
+ const { endpointGenerator, handler } = withWiring ? await promptEndpointDependencies(boundedContextFolder) : {
1755
+ endpointGenerator: void 0,
1756
+ handler: void 0
1757
+ };
1758
+ const endpointFile = external_node_path_default().join(endpointFolder.path, `${method.toUpperCase()}.ts`);
954
1759
  endpointFolder.createFile(`${method.toUpperCase()}.ts`, `
955
- import { EndpointGenerator } from '@domain-first/handlers-rest'
1760
+ ${endpointGenerator ? `import type { ${endpointGenerator.typeName} } from '${relativeImport(endpointFile, endpointGenerator.typeFile)}'` : "import { EndpointGenerator } from '@domain-first/handlers-rest'"}${handler ? `
1761
+ import type { ${handler.typeName} } from '${relativeImport(endpointFile, handler.typeFile)}'` : ''}
956
1762
 
957
1763
  export class ${endpointNaming.ClassName} {
958
1764
  constructor(
959
- private readonly endpointGenerator: EndpointGenerator,
960
- private readonly handler: never
1765
+ private readonly endpointGenerator: ${endpointGenerator?.typeName ?? 'EndpointGenerator'},
1766
+ private readonly handler: ${handler?.typeName ?? 'never'}
961
1767
  ) {}
962
1768
 
963
1769
  get handle() {
964
1770
  return this.endpointGenerator(this.handler.handle, {
965
- route: { method: '${method}', path: ['${boundedContextFolder.name}', '${controller}'${path.length ? `, ${path.map((x)=>`'${x}'`).join(', ')}` : ''}] },
1771
+ route: { method: '${method}', path: ['${boundedContextFolder.name}', '${controller}'${routeSegments.length ? `, ${routeSegments.map((x)=>`'${x}'`).join(', ')}` : ''}] },
966
1772
  tags: ['${boundedContextFolder.name}: ${controller}'],
967
1773
  })
968
1774
  }
969
1775
  }
970
1776
  `.trim());
971
- if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
1777
+ if (withWiring) {
972
1778
  const wiringFolder = boundedContextFolder.subitem([
973
1779
  'wiring',
974
1780
  'presentation',
@@ -977,13 +1783,19 @@ export class ${endpointNaming.ClassName} {
977
1783
  ]);
978
1784
  const wireNameBase = `wire-${nameBase}`;
979
1785
  const wireNaming = new UnknownFormatNaming(wireNameBase);
1786
+ const wireFile = external_node_path_default().join(wiringFolder.path, `${wireNaming.fileName}.ts`);
1787
+ const dependencies = endpointGenerator ? [
1788
+ endpointGenerator,
1789
+ handler
1790
+ ].filter((x)=>!!x) : [];
980
1791
  wiringFolder.createFile(`${wireNaming.fileName}.ts`, `
981
1792
  import { wireClass } from '@domain-first/wire'
982
- import { ${endpointNaming.ClassName} } from '../../../../presentation/rest/${controller}/${path.length ? `${path.join('/')}/` : ''}${method.toUpperCase()}'
1793
+ import { ${endpointNaming.ClassName} } from '${relativeImport(wireFile, endpointFile)}'
1794
+ ${dependencies.map((x)=>`import { ${x.wireName} } from '${relativeImport(wireFile, x.wireFile)}'`).join('\n')}
983
1795
 
984
1796
  export const wire${endpointNaming.ClassName} = wireClass(
985
1797
  ${endpointNaming.ClassName},
986
- []
1798
+ [${dependencies.map((x)=>x.wireName).join(', ')}]
987
1799
  )
988
1800
  `.trim());
989
1801
  wiringFolder.file('index.ts').addLine(`export * from './${wireNaming.fileName}'`);
@@ -1026,7 +1838,8 @@ describe('${naming.withSpaces}', () => {
1026
1838
  })
1027
1839
  })
1028
1840
  `.trim());
1029
- if (withWiring) wiringFolder.createFile(`wire-${naming.fileName}-infrastructure-service.ts`, `
1841
+ if (withWiring) {
1842
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-infrastructure-service.ts`, `
1030
1843
  import { wireClass } from '@domain-first/wire'
1031
1844
  import { ${naming.ClassName}InfrastructureService } from '../../infrastructure/services/${naming.fileName}-infrastructure-service'
1032
1845
 
@@ -1035,6 +1848,8 @@ export const wire${naming.ClassName}InfrastructureService = wireClass(
1035
1848
  []
1036
1849
  )
1037
1850
  `.trim());
1851
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1852
+ }
1038
1853
  };
1039
1854
  const scaffoldNewPresentationService = async (boundedContextFolder)=>{
1040
1855
  const name = await (0, prompts_namespaceObject.input)({
@@ -1073,7 +1888,8 @@ describe('${naming.withSpaces}', () => {
1073
1888
  })
1074
1889
  })
1075
1890
  `.trim());
1076
- if (withWiring) wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
1891
+ if (withWiring) {
1892
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
1077
1893
  import { wireClass } from '@domain-first/wire'
1078
1894
  import { ${naming.ClassName}PresentationService } from '../../presentation/services/${naming.fileName}-presentation-service'
1079
1895
 
@@ -1082,6 +1898,8 @@ export const wire${naming.ClassName}PresentationService = wireClass(
1082
1898
  []
1083
1899
  )
1084
1900
  `.trim());
1901
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1902
+ }
1085
1903
  };
1086
1904
  const scaffoldNewQuery = async (boundedContextFolder)=>{
1087
1905
  const queriesFolder = boundedContextFolder.subitem([
@@ -1200,7 +2018,7 @@ describe('${naming.withSpaces} query', () => {
1200
2018
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
1201
2019
  const implementationNaming = new UnknownFormatNaming(implementationType);
1202
2020
  const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
1203
- boundedContextFolder.subitem([
2021
+ const wireFile = boundedContextFolder.subitem([
1204
2022
  'wiring',
1205
2023
  'queries'
1206
2024
  ]).createFile(`wire-${naming.fileName}-query.ts`, `
@@ -1216,6 +2034,7 @@ export const wire${naming.ClassName}Query = envBranchedWire({
1216
2034
  production: wire${implementationNaming.ClassName}Implementation
1217
2035
  })
1218
2036
  `.trim());
2037
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1219
2038
  }
1220
2039
  return;
1221
2040
  }
@@ -1273,6 +2092,10 @@ test('can be ${withWiring ? 'wired' : 'created via constructor'}', () => {
1273
2092
  })
1274
2093
  })
1275
2094
  `.trim());
2095
+ if (withWiring) await wireNewModuleDependencies(boundedContextFolder, boundedContextFolder.subitem([
2096
+ 'wiring',
2097
+ 'queries'
2098
+ ]).file(`wire-${naming.fileName}-query.ts`));
1276
2099
  };
1277
2100
  const scaffoldNewUseCase = async (boundedContextFolder)=>{
1278
2101
  const useCasesFolder = boundedContextFolder.subitem([
@@ -1324,10 +2147,11 @@ describe('${naming.withSpaces} use case', () => {
1324
2147
  })
1325
2148
  })
1326
2149
  `.trim());
1327
- if (withWiring) boundedContextFolder.subitem([
1328
- 'wiring',
1329
- 'use-cases'
1330
- ]).createFile(`wire-${naming.fileName}-use-case.ts`, `
2150
+ if (withWiring) {
2151
+ const wireFile = boundedContextFolder.subitem([
2152
+ 'wiring',
2153
+ 'use-cases'
2154
+ ]).createFile(`wire-${naming.fileName}-use-case.ts`, `
1331
2155
  import { wireClass } from '@domain-first/wire'
1332
2156
  import { ${naming.ClassName}UseCase } from '../../application/use-cases/${naming.fileName}-use-case'
1333
2157
 
@@ -1337,6 +2161,8 @@ export const wire${naming.ClassName}UseCase = wireClass(
1337
2161
  )
1338
2162
 
1339
2163
  `.trim());
2164
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
2165
+ }
1340
2166
  };
1341
2167
  const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
1342
2168
  class NestedName {
@@ -1587,7 +2413,11 @@ const main = async ()=>{
1587
2413
  name: 'Shared Layer',
1588
2414
  action: 'Scaffold in bounded context'
1589
2415
  },
1590
- scaffoldNewBoundedContext
2416
+ scaffoldNewBoundedContext,
2417
+ {
2418
+ name: 'Add integration',
2419
+ action: 'Add integration'
2420
+ }
1591
2421
  ].filter((x)=>!!x);
1592
2422
  const result = await (0, prompts_namespaceObject.select)({
1593
2423
  message: '@domain-first/project-structure',
@@ -1595,6 +2425,8 @@ const main = async ()=>{
1595
2425
  });
1596
2426
  const { action, name } = options.find((x)=>x.name === result);
1597
2427
  switch(action){
2428
+ case 'Add integration':
2429
+ return void await addIntegration();
1598
2430
  case 'Scaffold React module':
1599
2431
  {
1600
2432
  const reactFolder = new Folder(rootPath).subitem([
@@ -1643,9 +2475,11 @@ const main = async ()=>{
1643
2475
  'Domain',
1644
2476
  'Application',
1645
2477
  'Infrastructure',
1646
- 'Presentation'
1647
- ]
2478
+ 'Presentation',
2479
+ ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? 'Wire dependency' : void 0
2480
+ ].filter((x)=>!!x)
1648
2481
  });
2482
+ if ('Wire dependency' === layer) return void await wireDependency(boundedContextFolder);
1649
2483
  if ('Domain' === layer) {
1650
2484
  const operation = await (0, prompts_namespaceObject.select)({
1651
2485
  message: 'Domain layer operation:',
@@ -1739,18 +2573,7 @@ const main = async ()=>{
1739
2573
  };
1740
2574
  const run = async ()=>{
1741
2575
  await main();
1742
- const overwrittenFiles = filesToOverwrite();
1743
- if (overwrittenFiles.length) {
1744
- const root = new ProjectRoot().path;
1745
- console.log('These files already exist and will be overwritten:');
1746
- for (const filePath of overwrittenFiles)console.log(` ${external_node_path_default().relative(root, filePath)}`);
1747
- const overwrite = await (0, prompts_namespaceObject.confirm)({
1748
- message: 'Overwrite them?',
1749
- default: false
1750
- });
1751
- if (!overwrite) return void console.log('Cancelled: nothing was written.');
1752
- }
1753
- writePendingChanges();
2576
+ await savePendingChanges();
1754
2577
  };
1755
2578
  run();
1756
2579
  for(var __rspack_i in __webpack_exports__)exports[__rspack_i] = __webpack_exports__[__rspack_i];