@domain-first/project-structure 7.1.1 → 7.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -130,6 +130,10 @@ export const wirePlaceOrderUseCase = wireClass(PlaceOrderUseCase, [
130
130
 
131
131
  Only the dependencies that respect the layers are offered: a use case can't take another use case, the domain can't take the application. To add a dependency later, choose **Wire dependency** in the context menu.
132
132
 
133
+ ### How to add an implementation
134
+
135
+ Choose **Infrastructure → New Implementation** to give an existing repository, command, query or port one more implementation, say a `local` adapter of a `FileStorage` port next to `s3` and `in-memory`. With `wire`, pick the environments that use it: `test` stays on `in-memory`, `development` moves to `local`, `production` stays on `s3`.
136
+
133
137
  ### How to move or rename a module
134
138
 
135
139
  Choose **Move or rename** in the context menu: rename an aggregate, entity, value object, service, port, query, command or use case, move it to another bounded context or to the Shared Kernel, or move an entity in or out of an aggregate. Its files, implementations, wire, specs and every import and derived name in the project follow it: `OrderRepository`, `PrismaOrderRepository`, `wireOrderRepository`, the `orderRepository` parameter of a use case, the in-memory DB section. A move that would make one context import another is refused, with the list of imports that would cross the boundary.
package/dist/201.js CHANGED
@@ -564,9 +564,9 @@ const closingIndex = (source, openIndex)=>{
564
564
  }
565
565
  return -1;
566
566
  };
567
- const splitTopLevel = (content)=>{
567
+ const topLevelItemRanges = (content)=>{
568
568
  const code = codeOnly(content);
569
- const items = [];
569
+ const ranges = [];
570
570
  let depth = 0;
571
571
  let itemStart = 0;
572
572
  for(let index = 0; index <= code.length; index++){
@@ -574,16 +574,19 @@ const splitTopLevel = (content)=>{
574
574
  if (void 0 !== char && char in brackets) depth++;
575
575
  else if (Object.values(brackets).includes(char)) depth--;
576
576
  if (index === code.length || ',' === char && 0 === depth) {
577
- const item = content.slice(itemStart, index);
578
577
  const itemCode = code.slice(itemStart, index);
579
578
  const first = itemCode.search(/\S/);
580
579
  const last = itemCode.search(/\S\s*$/);
581
- if (-1 !== first) items.push(item.slice(first, last + 1));
580
+ if (-1 !== first) ranges.push({
581
+ start: itemStart + first,
582
+ end: itemStart + last + 1
583
+ });
582
584
  itemStart = index + 1;
583
585
  }
584
586
  }
585
- return items;
587
+ return ranges;
586
588
  };
589
+ const splitTopLevel = (content)=>topLevelItemRanges(content).map(({ start, end })=>content.slice(start, end));
587
590
  const appendItems = (content, items)=>{
588
591
  const code = codeOnly(content);
589
592
  const lastCode = code.search(/\S\s*$/);
@@ -662,6 +665,58 @@ const wireDependencies = (consumer, implementation, dependencies)=>{
662
665
  for (const dependency of dependencies)classSource = addImport(classSource, `import type { ${dependency.typeName} } from '${relativeImport(implementation.file, dependency.typeFile)}'`);
663
666
  classFile.update(addConstructorParameters(classSource, implementation.className, dependencies.map((x)=>`private readonly ${parameterName(x.typeName)}: ${x.typeName}`)));
664
667
  };
668
+ const branchesRange = (source, wireName)=>{
669
+ const match = new RegExp(`export\\s+const\\s+${wireName}\\s*=\\s*envBranchedWire\\(\\s*\\{`).exec(codeOnly(source));
670
+ if (!match) throw new Error(`${wireName} = envBranchedWire({...}) not found`);
671
+ const openIndex = match.index + match[0].length - 1;
672
+ return {
673
+ declarationIndex: match.index,
674
+ openIndex,
675
+ closeIndex: closingIndex(source, openIndex)
676
+ };
677
+ };
678
+ const branchItems = (content)=>topLevelItemRanges(content).map(({ start, end })=>{
679
+ const item = content.slice(start, end);
680
+ const colon = codeOnly(item).indexOf(':');
681
+ if (-1 === colon) return {
682
+ key: item,
683
+ valueStart: start,
684
+ end,
685
+ shorthand: true
686
+ };
687
+ const valueStart = start + colon + 1 + item.slice(colon + 1).search(/\S/);
688
+ return {
689
+ key: item.slice(0, colon).trim(),
690
+ valueStart,
691
+ end,
692
+ shorthand: false
693
+ };
694
+ });
695
+ const wireBranches = (source, wireName)=>{
696
+ const { openIndex, closeIndex } = branchesRange(source, wireName);
697
+ const content = source.slice(openIndex + 1, closeIndex);
698
+ return new Map(branchItems(content).map(({ key, valueStart, end })=>[
699
+ key,
700
+ content.slice(valueStart, end)
701
+ ]));
702
+ };
703
+ const setWireBranches = (source, wireName, environments, branchWire)=>{
704
+ const { openIndex, closeIndex } = branchesRange(source, wireName);
705
+ let content = source.slice(openIndex + 1, closeIndex);
706
+ const items = branchItems(content);
707
+ for (const { key, valueStart, end, shorthand } of [
708
+ ...items
709
+ ].reverse())if (environments.includes(key)) content = content.slice(0, valueStart) + (shorthand ? `${key}: ${branchWire}` : branchWire) + content.slice(end);
710
+ const missing = environments.filter((environment)=>!items.some((x)=>x.key === environment));
711
+ if (missing.length) content = appendItems(content, missing.map((environment)=>`${environment}: ${branchWire}`));
712
+ return source.slice(0, openIndex + 1) + content + source.slice(closeIndex);
713
+ };
714
+ const addBranchedImplementation = (source, wireName, implementation)=>{
715
+ const withImport = addImport(source, implementation.importLine);
716
+ const { declarationIndex } = branchesRange(withImport, wireName);
717
+ const withWireClass = `${withImport.slice(0, declarationIndex)}const ${implementation.wireName} = wireClass(${implementation.className}, [])\n\n${withImport.slice(declarationIndex)}`;
718
+ return setWireBranches(withWireClass, wireName, implementation.environments, implementation.wireName);
719
+ };
665
720
  const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
666
721
  const resolveExtends = (fromFile, target)=>{
667
722
  if (target.startsWith('.') || node_path.isAbsolute(target)) {
@@ -695,4 +750,4 @@ const compilerOption = (configFile, name, seen = new Set())=>{
695
750
  if (void 0 !== value) return value;
696
751
  }
697
752
  };
698
- export { ConfigFile, File, Folder, ProjectRoot, UnknownFormatNaming, addClassMember, addConstructorParameters, addImport, addWireDependencies, availableDependencies, canDependOn, compilerOption, configuredDependencyRules, defaultDependencyRules, discardPendingChanges, fileModuleKind, filesToOverwrite, findWiredModules, implementationType, isSuggestedFor, moduleKindOf, readWiredModule, relativeImport, stripJsonComments, wireDependencies, wiredDependencyNames, withoutOverwrites, writePendingChanges };
753
+ export { ConfigFile, File, Folder, ProjectRoot, UnknownFormatNaming, addBranchedImplementation, addClassMember, addConstructorParameters, addImport, addWireDependencies, availableDependencies, canDependOn, compilerOption, configuredDependencyRules, defaultDependencyRules, discardPendingChanges, fileModuleKind, filesToOverwrite, findWiredModules, implementationType, isSuggestedFor, moduleKindOf, readWiredModule, relativeImport, stripJsonComments, wireBranches, wireDependencies, wiredDependencyNames, withoutOverwrites, writePendingChanges };
package/dist/287.js CHANGED
@@ -2,7 +2,7 @@ import node_path from "node:path";
2
2
  import { Separator, checkbox as prompts_checkbox, confirm as prompts_confirm, input, select as prompts_select } from "@inquirer/prompts";
3
3
  import { styleText } from "node:util";
4
4
  import node_fs from "node:fs";
5
- import { addImport, availableDependencies, discardPendingChanges, findWiredModules, UnknownFormatNaming, Folder, writePendingChanges, readWiredModule, stripJsonComments, addClassMember, withoutOverwrites, addWireDependencies, addConstructorParameters, filesToOverwrite, ConfigFile, relativeImport, wireDependencies, File, ProjectRoot, implementationType as wiring_implementationType, isSuggestedFor, compilerOption } from "./201.js";
5
+ import { addImport, availableDependencies, discardPendingChanges, findWiredModules, UnknownFormatNaming, Folder, writePendingChanges, readWiredModule, stripJsonComments, addClassMember, addBranchedImplementation, withoutOverwrites, addWireDependencies, addConstructorParameters, filesToOverwrite, ConfigFile, relativeImport, wireBranches, wireDependencies, File, ProjectRoot, implementationType as wiring_implementationType, isSuggestedFor, compilerOption } from "./201.js";
6
6
  const savePendingChanges = async ()=>{
7
7
  const overwrittenFiles = filesToOverwrite();
8
8
  if (overwrittenFiles.length) {
@@ -24,7 +24,7 @@ const savePendingChanges = async ()=>{
24
24
  };
25
25
  const inMemoryImplementationType = 'in-memory';
26
26
  const in_memory_db_className = 'InMemoryDbInfrastructureService';
27
- const wireName = 'wireInMemoryDbInfrastructureService';
27
+ const in_memory_db_wireName = 'wireInMemoryDbInfrastructureService';
28
28
  const parameterName = 'inMemoryDbInfrastructureService';
29
29
  const inMemoryDbService = `type Entry = {
30
30
  id: unknown;
@@ -231,15 +231,15 @@ const inMemoryDbSectionMembers = (field, derived)=>`
231
231
  const keepInMemoryDbSection = (classFile, field)=>{
232
232
  classFile.update(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)).replace('constructor() {}', inMemoryDbSectionMembers(field, false)));
233
233
  };
234
- const isInMemoryDb = (module)=>module.wireName === wireName;
234
+ const isInMemoryDb = (module)=>module.wireName === in_memory_db_wireName;
235
235
  const injectInMemoryDb = (classFile, implementationName)=>{
236
236
  classFile.update(addConstructorParameters(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)), implementationName, [
237
237
  `private readonly ${parameterName}: ${in_memory_db_className}`
238
238
  ]));
239
239
  };
240
240
  const wireInMemoryDb = (consumerWireFile, implementationName)=>{
241
- consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${wireName} } from '${relativeImport(consumerWireFile.path, in_memory_db_wireFile().path)}'`), implementationName, [
242
- wireName
241
+ consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${in_memory_db_wireName} } from '${relativeImport(consumerWireFile.path, in_memory_db_wireFile().path)}'`), implementationName, [
242
+ in_memory_db_wireName
243
243
  ]));
244
244
  };
245
245
  const passInMemoryDb = (specFile, implementationName)=>{
@@ -1153,6 +1153,13 @@ const wireNewModuleDependencies = async (boundedContextFolder, wireFile, customW
1153
1153
  const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
1154
1154
  if (consumer) await promptDependencies(boundedContextFolder, consumer, consumer.implementations, customWiring);
1155
1155
  };
1156
+ const wireNewImplementationDependencies = async (boundedContextFolder, wireFile, className, customWiring)=>{
1157
+ const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
1158
+ const implementation = consumer?.implementations.find((x)=>x.className === className);
1159
+ if (consumer && implementation) await promptDependencies(boundedContextFolder, consumer, [
1160
+ implementation
1161
+ ], customWiring);
1162
+ };
1156
1163
  const wireDependency = async (boundedContextFolder)=>{
1157
1164
  const modules = findWiredModules(boundedContextFolder.path);
1158
1165
  if (!modules.length) return void console.log('No wired modules here yet.');
@@ -2599,6 +2606,139 @@ const moveReactModuleUseCase = async (presentationReactFolder, kind)=>{
2599
2606
  console.log('Cancelled: nothing was written.');
2600
2607
  }
2601
2608
  };
2609
+ const contractKinds = [
2610
+ 'aggregate',
2611
+ 'command',
2612
+ 'query',
2613
+ 'port'
2614
+ ];
2615
+ const implementations_withWiring = ()=>ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
2616
+ const withHandlers = ()=>ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers');
2617
+ const contractFile = (unit)=>'aggregate' === unit.kind ? `domain/aggregates/${unit.name}/${unit.name}-repository.ts` : kindLayouts[unit.kind].files(unit, [])[0];
2618
+ const findContracts = (ownerPath)=>findBackendUnits(ownerPath).filter((unit)=>contractKinds.includes(unit.kind) && node_fs.existsSync(node_path.join(ownerPath, contractFile(unit))));
2619
+ const implementationWireName = (label)=>`wire${new UnknownFormatNaming(label).ClassName}Implementation`;
2620
+ const contractClassName = (unit)=>kindLayouts[unit.kind].core(new UnknownFormatNaming(unit.name).ClassName);
2621
+ const implementationClassName = (unit, label)=>`${new UnknownFormatNaming(label).ClassName}${contractClassName(unit)}`;
2622
+ const implementationFile = (unit, label)=>{
2623
+ const { implementations } = kindLayouts[unit.kind];
2624
+ return kindLayouts[unit.kind].files(unit, [
2625
+ label
2626
+ ]).find((file)=>file.startsWith(`${implementations}/`));
2627
+ };
2628
+ const contractWireFile = (unit)=>kindLayouts[unit.kind].files(unit, []).find((file)=>file.startsWith('wiring/'));
2629
+ const handlerImplementation = (ContractName, ClassName, contractImport)=>withHandlers() ? `
2630
+ import { defineHandler } from '@domain-first/handlers'
2631
+ import { ${ContractName} } from '${contractImport}'
2632
+
2633
+ export class ${ClassName} extends ${ContractName} {
2634
+ constructor() {
2635
+ super()
2636
+ }
2637
+
2638
+ handle = defineHandler({
2639
+ inputSchema: ${ContractName}.inputSchema,
2640
+ outputSchema: ${ContractName}.outputSchema,
2641
+ handler: async (input) => {
2642
+ return {}
2643
+ }
2644
+ })
2645
+ }
2646
+ `.trim() : `
2647
+ import { ${ContractName} } from '${contractImport}'
2648
+
2649
+ export class ${ClassName} extends ${ContractName} {
2650
+ constructor() {
2651
+ super()
2652
+ }
2653
+ }
2654
+ `.trim();
2655
+ const createImplementation = (ownerFolder, unit, label)=>{
2656
+ const naming = new UnknownFormatNaming(unit.name);
2657
+ const ContractName = contractClassName(unit);
2658
+ const className = implementationClassName(unit, label);
2659
+ const [folder, fileName] = [
2660
+ node_path.dirname(implementationFile(unit, label)),
2661
+ node_path.basename(implementationFile(unit, label))
2662
+ ];
2663
+ const implementationFolder = ownerFolder.subitem(folder.split('/'));
2664
+ const inMemoryDb = !implementations_withWiring() && usesInMemoryDb(label);
2665
+ switch(unit.kind){
2666
+ case 'aggregate':
2667
+ {
2668
+ const contractImport = `../../../domain/aggregates/${unit.name}`;
2669
+ if (inMemoryDb) {
2670
+ const section = addInMemoryDbSection(naming, ownerFolder.subitem([
2671
+ 'domain',
2672
+ 'aggregates',
2673
+ unit.name
2674
+ ]).path);
2675
+ const file = implementationFolder.createFile(fileName, `
2676
+ ${inMemoryDbTypeImport(implementationFolder.subitem([
2677
+ fileName
2678
+ ]).path)}
2679
+ import { ${ContractName} } from '${contractImport}'
2680
+
2681
+ export class ${className} implements ${ContractName} {
2682
+ ${inMemoryDbSectionMembers(section, false)}
2683
+ }
2684
+ `.trim());
2685
+ return {
2686
+ file,
2687
+ className
2688
+ };
2689
+ }
2690
+ const file = implementationFolder.createFile(fileName, `
2691
+ import { ${ContractName} } from '${contractImport}'
2692
+
2693
+ export class ${className} implements ${ContractName} {
2694
+ constructor() {}
2695
+ }
2696
+
2697
+ `.trim());
2698
+ return {
2699
+ file,
2700
+ className
2701
+ };
2702
+ }
2703
+ case 'command':
2704
+ case 'query':
2705
+ {
2706
+ const folderName = 'command' === unit.kind ? 'commands' : 'queries';
2707
+ const file = implementationFolder.createFile(fileName, handlerImplementation(ContractName, className, `../../../application/${folderName}/${naming.fileName}-${unit.kind}`));
2708
+ if (inMemoryDb) injectInMemoryDb(file, className);
2709
+ return {
2710
+ file,
2711
+ className
2712
+ };
2713
+ }
2714
+ case 'port':
2715
+ {
2716
+ const file = implementationFolder.createFile(fileName, `
2717
+ import { ${ContractName} } from '../../../application/ports/${naming.fileName}'
2718
+
2719
+ export class ${className} extends ${ContractName} {
2720
+
2721
+ }
2722
+ `.trim());
2723
+ return {
2724
+ file,
2725
+ className
2726
+ };
2727
+ }
2728
+ default:
2729
+ throw new Error(`${unit.kind} has no implementations`);
2730
+ }
2731
+ };
2732
+ const inMemoryRepositoryWiring = (ownerFolder, unit, wireFile)=>(implementation, dependency)=>{
2733
+ if ('aggregate' !== unit.kind || !isInMemoryDb(dependency)) return false;
2734
+ keepInMemoryDbSection(new File(implementation.file), addInMemoryDbSection(new UnknownFormatNaming(unit.name), ownerFolder.subitem([
2735
+ 'domain',
2736
+ 'aggregates',
2737
+ unit.name
2738
+ ]).path));
2739
+ wireInMemoryDb(wireFile, implementation.className);
2740
+ return true;
2741
+ };
2602
2742
  const scaffoldNewAggregateUseCase = async (boundedContextFolder)=>{
2603
2743
  const aggregateName = await input({
2604
2744
  message: 'Aggregate name:'
@@ -2653,43 +2793,17 @@ describe('${aggregateNaming.withSpaces}', () => {
2653
2793
  message: 'Test Repository infrastructure implementation type:',
2654
2794
  default: 'in-memory'
2655
2795
  });
2656
- const infrastructureRepositoriesFolder = boundedContextFolder.subitem([
2657
- 'infrastructure',
2658
- 'repositories'
2659
- ]);
2660
2796
  const implementationTypes = [
2661
2797
  infrastructureImplementationType,
2662
2798
  testImplementationType
2663
2799
  ].filter((x)=>!!x);
2664
- for (const implementation of implementationTypes){
2665
- const naming = new UnknownFormatNaming(implementation);
2666
- const repositoryFolder = infrastructureRepositoriesFolder.subitem([
2667
- naming.fileName
2668
- ]);
2669
- const repositoryFileName = `${naming.fileName}-${aggregateName}-repository.ts`;
2670
- if (usesInMemoryDb(implementation) && !ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2671
- const section = addInMemoryDbSection(aggregateNaming, aggregatesFolder.path);
2672
- repositoryFolder.createFile(repositoryFileName, `
2673
- ${inMemoryDbTypeImport(repositoryFolder.subitem([
2674
- repositoryFileName
2675
- ]).path)}
2676
- import { ${aggregateNaming.ClassName}Repository } from '../../../domain/aggregates/${aggregateName}'
2677
-
2678
- export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implements ${aggregateNaming.ClassName}Repository {
2679
- ${inMemoryDbSectionMembers(section, false)}
2680
- }
2681
- `.trim());
2682
- continue;
2683
- }
2684
- repositoryFolder.createFile(repositoryFileName, `
2685
- import { ${aggregateNaming.ClassName}Repository } from '../../../domain/aggregates/${aggregateName}'
2686
-
2687
- export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implements ${aggregateNaming.ClassName}Repository {
2688
- constructor() {}
2689
- }
2690
-
2691
- `.trim());
2692
- }
2800
+ const repository = {
2801
+ kind: 'aggregate',
2802
+ name: aggregateName,
2803
+ ownerPath: boundedContextFolder.path,
2804
+ labels: []
2805
+ };
2806
+ for (const implementation of implementationTypes)createImplementation(boundedContextFolder, repository, new UnknownFormatNaming(implementation).fileName);
2693
2807
  if (scaffoldUnitTests) {
2694
2808
  const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
2695
2809
  const specFile = aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.spec.ts`, `
@@ -2732,12 +2846,7 @@ export const wire${aggregateNaming.ClassName}Repository = envBranchedWire({
2732
2846
  production: wire${implementationNaming.ClassName}Implementation
2733
2847
  })
2734
2848
  `.trim());
2735
- await wireNewModuleDependencies(boundedContextFolder, wireFile, (implementation, dependency)=>{
2736
- if (!isInMemoryDb(dependency)) return false;
2737
- keepInMemoryDbSection(new File(implementation.file), addInMemoryDbSection(aggregateNaming, aggregatesFolder.path));
2738
- wireInMemoryDb(wireFile, implementation.className);
2739
- return true;
2740
- });
2849
+ await wireNewModuleDependencies(boundedContextFolder, wireFile, inMemoryRepositoryWiring(boundedContextFolder, repository, wireFile));
2741
2850
  }
2742
2851
  }
2743
2852
  };
@@ -2772,26 +2881,16 @@ export abstract class ${naming.ClassName} {
2772
2881
  message: 'Test adapter implementation type:',
2773
2882
  default: 'mock'
2774
2883
  });
2775
- const infrastructureFolder = boundedContextFolder.subitem([
2776
- 'infrastructure',
2777
- 'application-adapters'
2778
- ]);
2779
2884
  const implementationTypes = [
2780
2885
  implementationType,
2781
2886
  testImplementationType
2782
- ].filter((x)=>!!x);
2783
- for (const implementation of implementationTypes){
2784
- const currentNaming = new UnknownFormatNaming(`${implementation}-${naming.fileName}`);
2785
- infrastructureFolder.subitem([
2786
- implementation
2787
- ]).createFile(`${currentNaming.fileName}.ts`, `
2788
- import { ${naming.ClassName} } from '../../../application/ports/${naming.fileName}'
2789
-
2790
- export class ${currentNaming.ClassName} extends ${naming.ClassName} {
2791
-
2792
- }
2793
- `.trim());
2794
- }
2887
+ ].filter((x)=>!!x).map((x)=>new UnknownFormatNaming(x).fileName);
2888
+ for (const implementation of implementationTypes)createImplementation(boundedContextFolder, {
2889
+ kind: 'port',
2890
+ name: naming.fileName,
2891
+ ownerPath: boundedContextFolder.path,
2892
+ labels: []
2893
+ }, implementation);
2795
2894
  if (scaffoldUnitTests) {
2796
2895
  const implementationNaming = new UnknownFormatNaming(implementationType);
2797
2896
  applicationPortsFolder.createFile(`${naming.fileName}.spec.ts`, `
@@ -2907,10 +3006,6 @@ const scaffoldNewCommand = async (boundedContextFolder)=>{
2907
3006
  'application',
2908
3007
  'commands'
2909
3008
  ]);
2910
- const infrastructureFolder = boundedContextFolder.subitem([
2911
- 'infrastructure',
2912
- 'commands'
2913
- ]);
2914
3009
  const commandName = await input({
2915
3010
  message: 'Name: '
2916
3011
  });
@@ -2934,38 +3029,12 @@ const scaffoldNewCommand = async (boundedContextFolder)=>{
2934
3029
  implementationType,
2935
3030
  testImplementationType
2936
3031
  ].filter((x)=>!!x);
2937
- for (const implementation of implementationTypes){
2938
- const formatNaming = new UnknownFormatNaming(implementation);
2939
- const implementationFile = infrastructureFolder.subitem([
2940
- formatNaming.fileName
2941
- ]).createFile(`${formatNaming.fileName}-${naming.fileName}-command.ts`, ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
2942
- import { defineHandler } from '@domain-first/handlers'
2943
- import { ${naming.ClassName}Command } from '../../../application/commands/${naming.fileName}-command'
2944
-
2945
- export class ${formatNaming.ClassName}${naming.ClassName}Command extends ${naming.ClassName}Command {
2946
- constructor() {
2947
- super()
2948
- }
2949
-
2950
- handle = defineHandler({
2951
- inputSchema: ${naming.ClassName}Command.inputSchema,
2952
- outputSchema: ${naming.ClassName}Command.outputSchema,
2953
- handler: async (input) => {
2954
- return {}
2955
- }
2956
- })
2957
- }
2958
- `.trim() : `
2959
- import { ${naming.ClassName}Command } from '../../../application/commands/${naming.fileName}-command'
2960
-
2961
- export class ${formatNaming.ClassName}${naming.ClassName}Command extends ${naming.ClassName}Command {
2962
- constructor() {
2963
- super()
2964
- }
2965
- }
2966
- `.trim());
2967
- if (!withWiring && usesInMemoryDb(implementation)) injectInMemoryDb(implementationFile, `${formatNaming.ClassName}${naming.ClassName}Command`);
2968
- }
3032
+ for (const implementation of implementationTypes)createImplementation(boundedContextFolder, {
3033
+ kind: 'command',
3034
+ name: naming.fileName,
3035
+ ownerPath: boundedContextFolder.path,
3036
+ labels: []
3037
+ }, new UnknownFormatNaming(implementation).fileName);
2969
3038
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers')) commandsFolder.createFile(`${naming.fileName}-command.ts`, `
2970
3039
  import type { Handler } from '@domain-first/handlers'
2971
3040
 
@@ -3318,6 +3387,88 @@ export const wire${endpointClassName} = wireClass(
3318
3387
  wiringFolder.file('index.ts').addLine(`export * from './${wireNaming.fileName}'`);
3319
3388
  }
3320
3389
  };
3390
+ const scaffold_new_implementation_kindTitles = {
3391
+ aggregate: 'Repositories',
3392
+ command: 'Commands',
3393
+ query: 'Queries',
3394
+ port: 'Ports'
3395
+ };
3396
+ const environments = [
3397
+ 'test',
3398
+ 'development',
3399
+ 'production'
3400
+ ];
3401
+ const branchesOf = (wireFile, wireName)=>{
3402
+ if (!wireFile.exists) return;
3403
+ try {
3404
+ return wireBranches(wireFile.data, wireName);
3405
+ } catch {
3406
+ return;
3407
+ }
3408
+ };
3409
+ const scaffoldNewImplementation = async (ownerFolder)=>{
3410
+ const contracts = findContracts(ownerFolder.path);
3411
+ if (!contracts.length) return void console.log('No repositories, commands, queries or ports here yet.');
3412
+ const unit = await prompts_select({
3413
+ message: 'Contract:',
3414
+ choices: contractKinds.flatMap((kind)=>{
3415
+ const group = contracts.filter((x)=>x.kind === kind);
3416
+ return group.length ? [
3417
+ new Separator(`── ${scaffold_new_implementation_kindTitles[kind]}`),
3418
+ ...group.map((value)=>({
3419
+ name: value.labels.length ? `${value.name} (${value.labels.join(', ')})` : value.name,
3420
+ value
3421
+ }))
3422
+ ] : [];
3423
+ }),
3424
+ pageSize: 20
3425
+ });
3426
+ const label = (await input({
3427
+ message: 'Implementation type:',
3428
+ validate: (value)=>{
3429
+ const type = value.trim();
3430
+ if (!kebabName.test(type)) return 'Use lowercase kebab-case, e.g. api or in-memory.';
3431
+ return unit.labels.includes(type) ? `${unit.name} already has the ${type} implementation.` : true;
3432
+ }
3433
+ })).trim();
3434
+ const { file, className } = createImplementation(ownerFolder, unit, label);
3435
+ if (!ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) return;
3436
+ const wireFile = new File(ownerFolder.path).subitem(contractWireFile(unit).split('/'));
3437
+ const wireName = `wire${contractClassName(unit)}`;
3438
+ const branches = branchesOf(wireFile, wireName);
3439
+ if (!branches) return void console.log(`${wireFile.path} has no ${wireName} = envBranchedWire({...}): wire ${className} there yourself.`);
3440
+ const labelOfWire = new Map(unit.labels.map((x)=>[
3441
+ implementationWireName(x),
3442
+ x
3443
+ ]));
3444
+ const chosenEnvironments = await prompts_checkbox({
3445
+ message: 'Environments:',
3446
+ choices: [
3447
+ ...new Set([
3448
+ ...environments,
3449
+ ...branches.keys()
3450
+ ])
3451
+ ].map((environment)=>{
3452
+ const current = branches.get(environment);
3453
+ return {
3454
+ name: current ? `${environment} (now: ${labelOfWire.get(current) ?? current})` : environment,
3455
+ value: environment
3456
+ };
3457
+ }),
3458
+ required: true
3459
+ });
3460
+ const before = readWiredModule(wireFile.path, ownerFolder.path);
3461
+ wireFile.update(addBranchedImplementation(wireFile.data, wireName, {
3462
+ importLine: `import { ${className} } from '${relativeImport(wireFile.path, file.path)}'`,
3463
+ className,
3464
+ wireName: implementationWireName(label),
3465
+ environments: chosenEnvironments
3466
+ }));
3467
+ const after = readWiredModule(wireFile.path, ownerFolder.path);
3468
+ const unused = (before?.implementations ?? []).filter((x)=>!after?.implementations.some((y)=>y.className === x.className));
3469
+ for (const implementation of unused)console.log(`${implementation.className} is no longer used in any environment.`);
3470
+ await wireNewImplementationDependencies(ownerFolder, wireFile, className, inMemoryRepositoryWiring(ownerFolder, unit, wireFile));
3471
+ };
3321
3472
  const scaffoldNewInfrastructureService = async (boundedContextFolder)=>{
3322
3473
  const name = await input({
3323
3474
  message: 'Name: '
@@ -3373,10 +3524,6 @@ const scaffoldNewQuery = async (boundedContextFolder)=>{
3373
3524
  'application',
3374
3525
  'queries'
3375
3526
  ]);
3376
- const infrastructureFolder = boundedContextFolder.subitem([
3377
- 'infrastructure',
3378
- 'queries'
3379
- ]);
3380
3527
  const queryName = await input({
3381
3528
  message: 'Name: '
3382
3529
  });
@@ -3400,38 +3547,12 @@ const scaffoldNewQuery = async (boundedContextFolder)=>{
3400
3547
  implementationType,
3401
3548
  testImplementationType
3402
3549
  ].filter((x)=>!!x);
3403
- for (const implementation of implementationTypes){
3404
- const formatNaming = new UnknownFormatNaming(implementation);
3405
- const implementationFile = infrastructureFolder.subitem([
3406
- formatNaming.fileName
3407
- ]).createFile(`${formatNaming.fileName}-${naming.fileName}-query.ts`, ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
3408
- import { defineHandler } from '@domain-first/handlers'
3409
- import { ${naming.ClassName}Query } from '../../../application/queries/${naming.fileName}-query'
3410
-
3411
- export class ${formatNaming.ClassName}${naming.ClassName}Query extends ${naming.ClassName}Query {
3412
- constructor() {
3413
- super()
3414
- }
3415
-
3416
- handle = defineHandler({
3417
- inputSchema: ${naming.ClassName}Query.inputSchema,
3418
- outputSchema: ${naming.ClassName}Query.outputSchema,
3419
- handler: async (input) => {
3420
- return {}
3421
- }
3422
- })
3423
- }
3424
- `.trim() : `
3425
- import { ${naming.ClassName}Query } from '../../../application/queries/${naming.fileName}-query'
3426
-
3427
- export class ${formatNaming.ClassName}${naming.ClassName}Query extends ${naming.ClassName}Query {
3428
- constructor() {
3429
- super()
3430
- }
3431
- }
3432
- `.trim());
3433
- if (!withWiring && usesInMemoryDb(implementation)) injectInMemoryDb(implementationFile, `${formatNaming.ClassName}${naming.ClassName}Query`);
3434
- }
3550
+ for (const implementation of implementationTypes)createImplementation(boundedContextFolder, {
3551
+ kind: 'query',
3552
+ name: naming.fileName,
3553
+ ownerPath: boundedContextFolder.path,
3554
+ labels: []
3555
+ }, new UnknownFormatNaming(implementation).fileName);
3435
3556
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers')) queriesFolder.createFile(`${naming.fileName}-query.ts`, `
3436
3557
  import type { Handler } from '@domain-first/handlers'
3437
3558
 
@@ -3744,4 +3865,4 @@ export const use${ClassName}UIModel = (widgetProps: Omit<${ClassName}WidgetProps
3744
3865
  break;
3745
3866
  }
3746
3867
  };
3747
- export { addIntegration, initializeUseCase, moveBackendUnitUseCase, moveReactModuleUseCase, printNextSteps, savePendingChanges, scaffoldNewAggregateUseCase, scaffoldNewApplicationPort, scaffoldNewApplicationService, scaffoldNewBoundedContextUseCase, scaffoldNewCommand, scaffoldNewDomainObject, scaffoldNewDomainService, scaffoldNewErrorUseCase, scaffoldNewHandlersRestEndpoint, scaffoldNewInfrastructureService, scaffoldNewPresentationService, scaffoldNewQuery, scaffoldNewUseCase, scaffoldReactPage, scaffoldReactSharedHook, scaffoldReactUIKitComponent, scaffoldReactWidget, wireDependency };
3868
+ export { addIntegration, initializeUseCase, moveBackendUnitUseCase, moveReactModuleUseCase, printNextSteps, savePendingChanges, scaffoldNewAggregateUseCase, scaffoldNewApplicationPort, scaffoldNewApplicationService, scaffoldNewBoundedContextUseCase, scaffoldNewCommand, scaffoldNewDomainObject, scaffoldNewDomainService, scaffoldNewErrorUseCase, scaffoldNewHandlersRestEndpoint, scaffoldNewImplementation, scaffoldNewInfrastructureService, scaffoldNewPresentationService, scaffoldNewQuery, scaffoldNewUseCase, scaffoldReactPage, scaffoldReactSharedHook, scaffoldReactUIKitComponent, scaffoldReactWidget, wireDependency };
@@ -33,6 +33,7 @@ export declare const aggregatesOf: (ownerPath: string) => string[];
33
33
  * their file layout, so projects without wiring are covered too.
34
34
  */
35
35
  export declare const findBackendUnits: (ownerPath: string) => BackendUnit[];
36
+ export declare const kebabName: RegExp;
36
37
  /**
37
38
  * Checks a move before anything is staged; true or the reason it can't
38
39
  * be done.
@@ -0,0 +1,48 @@
1
+ import { type BackendUnit } from './backend-module-move';
2
+ import { File, type Folder } from './file-system';
3
+ import type { CustomWiring } from './use-cases/wire-dependency';
4
+ /**
5
+ * Kinds of units whose contract has implementations: a repository (of
6
+ * an aggregate), a command, a query, a port.
7
+ */
8
+ export type ContractKind = 'aggregate' | 'command' | 'query' | 'port';
9
+ export declare const contractKinds: ContractKind[];
10
+ /**
11
+ * Units of the folder that have a contract to implement: aggregates
12
+ * only with their repository.
13
+ */
14
+ export declare const findContracts: (ownerPath: string) => BackendUnit[];
15
+ /**
16
+ * `in-memory` → `wireInMemoryImplementation`.
17
+ */
18
+ export declare const implementationWireName: (label: string) => string;
19
+ /**
20
+ * `OrderRepository`, `PlaceOrderCommand`, `PaymentGateway`.
21
+ */
22
+ export declare const contractClassName: (unit: BackendUnit) => string;
23
+ /**
24
+ * `in-memory` → `InMemoryOrderRepository`.
25
+ */
26
+ export declare const implementationClassName: (unit: BackendUnit, label: string) => string;
27
+ /**
28
+ * The implementation's file, relative to the unit's owner.
29
+ */
30
+ export declare const implementationFile: (unit: BackendUnit, label: string) => string;
31
+ /**
32
+ * The unit's wire, relative to its owner.
33
+ */
34
+ export declare const contractWireFile: (unit: BackendUnit) => string;
35
+ /**
36
+ * Creates the class of one implementation of the contract. Without
37
+ * wiring, an `in-memory` one gets the in-memory DB in its constructor;
38
+ * with wiring, it is a suggested dependency instead.
39
+ */
40
+ export declare const createImplementation: (ownerFolder: Folder, unit: BackendUnit, label: string) => {
41
+ file: File;
42
+ className: string;
43
+ };
44
+ /**
45
+ * With wiring, an in-memory repository keeps only its aggregate's
46
+ * section of the in-memory DB.
47
+ */
48
+ export declare const inMemoryRepositoryWiring: (ownerFolder: Folder, unit: BackendUnit, wireFile: File) => CustomWiring;