@domain-first/project-structure 7.1.0 → 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;
@@ -188,8 +188,26 @@ const scaffoldInMemoryDb = (shared)=>{
188
188
  };
189
189
  const inMemoryDbScaffolded = ()=>serviceFile().exists && (!in_memory_db_withWiring() || in_memory_db_wireFile().exists);
190
190
  const usesInMemoryDb = (implementationType)=>Boolean(ConfigFile.Instance.data.withInMemoryDb) && new UnknownFormatNaming(implementationType).fileName === inMemoryImplementationType && inMemoryDbScaffolded();
191
+ const uncountableEndings = [
192
+ 'data',
193
+ 'info',
194
+ 'usage',
195
+ 'feedback',
196
+ 'media',
197
+ 'ware',
198
+ 'equipment',
199
+ 'information',
200
+ 'knowledge',
201
+ 'traffic',
202
+ 'telemetry',
203
+ 'analytics',
204
+ 'series'
205
+ ];
206
+ const uncountable = new RegExp(`(${uncountableEndings.join('|')})$`, 'i');
191
207
  const plural = (word)=>{
208
+ if (uncountable.test(word)) return word;
192
209
  if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
210
+ if (/(^|[^aeiou]|qu)[aeiou]z$/i.test(word)) return `${word}zes`;
193
211
  if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
194
212
  return `${word}s`;
195
213
  };
@@ -213,15 +231,15 @@ const inMemoryDbSectionMembers = (field, derived)=>`
213
231
  const keepInMemoryDbSection = (classFile, field)=>{
214
232
  classFile.update(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)).replace('constructor() {}', inMemoryDbSectionMembers(field, false)));
215
233
  };
216
- const isInMemoryDb = (module)=>module.wireName === wireName;
234
+ const isInMemoryDb = (module)=>module.wireName === in_memory_db_wireName;
217
235
  const injectInMemoryDb = (classFile, implementationName)=>{
218
236
  classFile.update(addConstructorParameters(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)), implementationName, [
219
237
  `private readonly ${parameterName}: ${in_memory_db_className}`
220
238
  ]));
221
239
  };
222
240
  const wireInMemoryDb = (consumerWireFile, implementationName)=>{
223
- consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${wireName} } from '${relativeImport(consumerWireFile.path, in_memory_db_wireFile().path)}'`), implementationName, [
224
- wireName
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
225
243
  ]));
226
244
  };
227
245
  const passInMemoryDb = (specFile, implementationName)=>{
@@ -1135,6 +1153,13 @@ const wireNewModuleDependencies = async (boundedContextFolder, wireFile, customW
1135
1153
  const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
1136
1154
  if (consumer) await promptDependencies(boundedContextFolder, consumer, consumer.implementations, customWiring);
1137
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
+ };
1138
1163
  const wireDependency = async (boundedContextFolder)=>{
1139
1164
  const modules = findWiredModules(boundedContextFolder.path);
1140
1165
  if (!modules.length) return void console.log('No wired modules here yet.');
@@ -2581,6 +2606,139 @@ const moveReactModuleUseCase = async (presentationReactFolder, kind)=>{
2581
2606
  console.log('Cancelled: nothing was written.');
2582
2607
  }
2583
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
+ };
2584
2742
  const scaffoldNewAggregateUseCase = async (boundedContextFolder)=>{
2585
2743
  const aggregateName = await input({
2586
2744
  message: 'Aggregate name:'
@@ -2635,43 +2793,17 @@ describe('${aggregateNaming.withSpaces}', () => {
2635
2793
  message: 'Test Repository infrastructure implementation type:',
2636
2794
  default: 'in-memory'
2637
2795
  });
2638
- const infrastructureRepositoriesFolder = boundedContextFolder.subitem([
2639
- 'infrastructure',
2640
- 'repositories'
2641
- ]);
2642
2796
  const implementationTypes = [
2643
2797
  infrastructureImplementationType,
2644
2798
  testImplementationType
2645
2799
  ].filter((x)=>!!x);
2646
- for (const implementation of implementationTypes){
2647
- const naming = new UnknownFormatNaming(implementation);
2648
- const repositoryFolder = infrastructureRepositoriesFolder.subitem([
2649
- naming.fileName
2650
- ]);
2651
- const repositoryFileName = `${naming.fileName}-${aggregateName}-repository.ts`;
2652
- if (usesInMemoryDb(implementation) && !ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2653
- const section = addInMemoryDbSection(aggregateNaming, aggregatesFolder.path);
2654
- repositoryFolder.createFile(repositoryFileName, `
2655
- ${inMemoryDbTypeImport(repositoryFolder.subitem([
2656
- repositoryFileName
2657
- ]).path)}
2658
- import { ${aggregateNaming.ClassName}Repository } from '../../../domain/aggregates/${aggregateName}'
2659
-
2660
- export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implements ${aggregateNaming.ClassName}Repository {
2661
- ${inMemoryDbSectionMembers(section, false)}
2662
- }
2663
- `.trim());
2664
- continue;
2665
- }
2666
- repositoryFolder.createFile(repositoryFileName, `
2667
- import { ${aggregateNaming.ClassName}Repository } from '../../../domain/aggregates/${aggregateName}'
2668
-
2669
- export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implements ${aggregateNaming.ClassName}Repository {
2670
- constructor() {}
2671
- }
2672
-
2673
- `.trim());
2674
- }
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);
2675
2807
  if (scaffoldUnitTests) {
2676
2808
  const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
2677
2809
  const specFile = aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.spec.ts`, `
@@ -2714,12 +2846,7 @@ export const wire${aggregateNaming.ClassName}Repository = envBranchedWire({
2714
2846
  production: wire${implementationNaming.ClassName}Implementation
2715
2847
  })
2716
2848
  `.trim());
2717
- await wireNewModuleDependencies(boundedContextFolder, wireFile, (implementation, dependency)=>{
2718
- if (!isInMemoryDb(dependency)) return false;
2719
- keepInMemoryDbSection(new File(implementation.file), addInMemoryDbSection(aggregateNaming, aggregatesFolder.path));
2720
- wireInMemoryDb(wireFile, implementation.className);
2721
- return true;
2722
- });
2849
+ await wireNewModuleDependencies(boundedContextFolder, wireFile, inMemoryRepositoryWiring(boundedContextFolder, repository, wireFile));
2723
2850
  }
2724
2851
  }
2725
2852
  };
@@ -2754,26 +2881,16 @@ export abstract class ${naming.ClassName} {
2754
2881
  message: 'Test adapter implementation type:',
2755
2882
  default: 'mock'
2756
2883
  });
2757
- const infrastructureFolder = boundedContextFolder.subitem([
2758
- 'infrastructure',
2759
- 'application-adapters'
2760
- ]);
2761
2884
  const implementationTypes = [
2762
2885
  implementationType,
2763
2886
  testImplementationType
2764
- ].filter((x)=>!!x);
2765
- for (const implementation of implementationTypes){
2766
- const currentNaming = new UnknownFormatNaming(`${implementation}-${naming.fileName}`);
2767
- infrastructureFolder.subitem([
2768
- implementation
2769
- ]).createFile(`${currentNaming.fileName}.ts`, `
2770
- import { ${naming.ClassName} } from '../../../application/ports/${naming.fileName}'
2771
-
2772
- export class ${currentNaming.ClassName} extends ${naming.ClassName} {
2773
-
2774
- }
2775
- `.trim());
2776
- }
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);
2777
2894
  if (scaffoldUnitTests) {
2778
2895
  const implementationNaming = new UnknownFormatNaming(implementationType);
2779
2896
  applicationPortsFolder.createFile(`${naming.fileName}.spec.ts`, `
@@ -2889,10 +3006,6 @@ const scaffoldNewCommand = async (boundedContextFolder)=>{
2889
3006
  'application',
2890
3007
  'commands'
2891
3008
  ]);
2892
- const infrastructureFolder = boundedContextFolder.subitem([
2893
- 'infrastructure',
2894
- 'commands'
2895
- ]);
2896
3009
  const commandName = await input({
2897
3010
  message: 'Name: '
2898
3011
  });
@@ -2916,38 +3029,12 @@ const scaffoldNewCommand = async (boundedContextFolder)=>{
2916
3029
  implementationType,
2917
3030
  testImplementationType
2918
3031
  ].filter((x)=>!!x);
2919
- for (const implementation of implementationTypes){
2920
- const formatNaming = new UnknownFormatNaming(implementation);
2921
- const implementationFile = infrastructureFolder.subitem([
2922
- formatNaming.fileName
2923
- ]).createFile(`${formatNaming.fileName}-${naming.fileName}-command.ts`, ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
2924
- import { defineHandler } from '@domain-first/handlers'
2925
- import { ${naming.ClassName}Command } from '../../../application/commands/${naming.fileName}-command'
2926
-
2927
- export class ${formatNaming.ClassName}${naming.ClassName}Command extends ${naming.ClassName}Command {
2928
- constructor() {
2929
- super()
2930
- }
2931
-
2932
- handle = defineHandler({
2933
- inputSchema: ${naming.ClassName}Command.inputSchema,
2934
- outputSchema: ${naming.ClassName}Command.outputSchema,
2935
- handler: async (input) => {
2936
- return {}
2937
- }
2938
- })
2939
- }
2940
- `.trim() : `
2941
- import { ${naming.ClassName}Command } from '../../../application/commands/${naming.fileName}-command'
2942
-
2943
- export class ${formatNaming.ClassName}${naming.ClassName}Command extends ${naming.ClassName}Command {
2944
- constructor() {
2945
- super()
2946
- }
2947
- }
2948
- `.trim());
2949
- if (!withWiring && usesInMemoryDb(implementation)) injectInMemoryDb(implementationFile, `${formatNaming.ClassName}${naming.ClassName}Command`);
2950
- }
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);
2951
3038
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers')) commandsFolder.createFile(`${naming.fileName}-command.ts`, `
2952
3039
  import type { Handler } from '@domain-first/handlers'
2953
3040
 
@@ -3300,6 +3387,88 @@ export const wire${endpointClassName} = wireClass(
3300
3387
  wiringFolder.file('index.ts').addLine(`export * from './${wireNaming.fileName}'`);
3301
3388
  }
3302
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
+ };
3303
3472
  const scaffoldNewInfrastructureService = async (boundedContextFolder)=>{
3304
3473
  const name = await input({
3305
3474
  message: 'Name: '
@@ -3355,10 +3524,6 @@ const scaffoldNewQuery = async (boundedContextFolder)=>{
3355
3524
  'application',
3356
3525
  'queries'
3357
3526
  ]);
3358
- const infrastructureFolder = boundedContextFolder.subitem([
3359
- 'infrastructure',
3360
- 'queries'
3361
- ]);
3362
3527
  const queryName = await input({
3363
3528
  message: 'Name: '
3364
3529
  });
@@ -3382,38 +3547,12 @@ const scaffoldNewQuery = async (boundedContextFolder)=>{
3382
3547
  implementationType,
3383
3548
  testImplementationType
3384
3549
  ].filter((x)=>!!x);
3385
- for (const implementation of implementationTypes){
3386
- const formatNaming = new UnknownFormatNaming(implementation);
3387
- const implementationFile = infrastructureFolder.subitem([
3388
- formatNaming.fileName
3389
- ]).createFile(`${formatNaming.fileName}-${naming.fileName}-query.ts`, ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
3390
- import { defineHandler } from '@domain-first/handlers'
3391
- import { ${naming.ClassName}Query } from '../../../application/queries/${naming.fileName}-query'
3392
-
3393
- export class ${formatNaming.ClassName}${naming.ClassName}Query extends ${naming.ClassName}Query {
3394
- constructor() {
3395
- super()
3396
- }
3397
-
3398
- handle = defineHandler({
3399
- inputSchema: ${naming.ClassName}Query.inputSchema,
3400
- outputSchema: ${naming.ClassName}Query.outputSchema,
3401
- handler: async (input) => {
3402
- return {}
3403
- }
3404
- })
3405
- }
3406
- `.trim() : `
3407
- import { ${naming.ClassName}Query } from '../../../application/queries/${naming.fileName}-query'
3408
-
3409
- export class ${formatNaming.ClassName}${naming.ClassName}Query extends ${naming.ClassName}Query {
3410
- constructor() {
3411
- super()
3412
- }
3413
- }
3414
- `.trim());
3415
- if (!withWiring && usesInMemoryDb(implementation)) injectInMemoryDb(implementationFile, `${formatNaming.ClassName}${naming.ClassName}Query`);
3416
- }
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);
3417
3556
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers')) queriesFolder.createFile(`${naming.fileName}-query.ts`, `
3418
3557
  import type { Handler } from '@domain-first/handlers'
3419
3558
 
@@ -3726,4 +3865,4 @@ export const use${ClassName}UIModel = (widgetProps: Omit<${ClassName}WidgetProps
3726
3865
  break;
3727
3866
  }
3728
3867
  };
3729
- 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.