@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.
@@ -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;
@@ -16,7 +16,8 @@ export declare const inMemoryDbScaffolded: () => boolean;
16
16
  */
17
17
  export declare const usesInMemoryDb: (implementationType: string) => boolean;
18
18
  /**
19
- * `user` → `users`, `category` → `categories`, `box` → `boxes`.
19
+ * `user` → `users`, `category` → `categories`, `box` → `boxes`,
20
+ * `quiz` → `quizzes`, `user-data` → `user-data`.
20
21
  */
21
22
  export declare const plural: (word: string) => string;
22
23
  /**
package/dist/index.cjs CHANGED
@@ -579,9 +579,9 @@ const closingIndex = (source, openIndex)=>{
579
579
  }
580
580
  return -1;
581
581
  };
582
- const splitTopLevel = (content)=>{
582
+ const topLevelItemRanges = (content)=>{
583
583
  const code = codeOnly(content);
584
- const items = [];
584
+ const ranges = [];
585
585
  let depth = 0;
586
586
  let itemStart = 0;
587
587
  for(let index = 0; index <= code.length; index++){
@@ -589,16 +589,19 @@ const splitTopLevel = (content)=>{
589
589
  if (void 0 !== char && char in brackets) depth++;
590
590
  else if (Object.values(brackets).includes(char)) depth--;
591
591
  if (index === code.length || ',' === char && 0 === depth) {
592
- const item = content.slice(itemStart, index);
593
592
  const itemCode = code.slice(itemStart, index);
594
593
  const first = itemCode.search(/\S/);
595
594
  const last = itemCode.search(/\S\s*$/);
596
- if (-1 !== first) items.push(item.slice(first, last + 1));
595
+ if (-1 !== first) ranges.push({
596
+ start: itemStart + first,
597
+ end: itemStart + last + 1
598
+ });
597
599
  itemStart = index + 1;
598
600
  }
599
601
  }
600
- return items;
602
+ return ranges;
601
603
  };
604
+ const splitTopLevel = (content)=>topLevelItemRanges(content).map(({ start, end })=>content.slice(start, end));
602
605
  const appendItems = (content, items)=>{
603
606
  const code = codeOnly(content);
604
607
  const lastCode = code.search(/\S\s*$/);
@@ -677,6 +680,58 @@ const wireDependencies = (consumer, implementation, dependencies)=>{
677
680
  for (const dependency of dependencies)classSource = addImport(classSource, `import type { ${dependency.typeName} } from '${wiring_relativeImport(implementation.file, dependency.typeFile)}'`);
678
681
  classFile.update(addConstructorParameters(classSource, implementation.className, dependencies.map((x)=>`private readonly ${parameterName(x.typeName)}: ${x.typeName}`)));
679
682
  };
683
+ const branchesRange = (source, wireName)=>{
684
+ const match = new RegExp(`export\\s+const\\s+${wireName}\\s*=\\s*envBranchedWire\\(\\s*\\{`).exec(codeOnly(source));
685
+ if (!match) throw new Error(`${wireName} = envBranchedWire({...}) not found`);
686
+ const openIndex = match.index + match[0].length - 1;
687
+ return {
688
+ declarationIndex: match.index,
689
+ openIndex,
690
+ closeIndex: closingIndex(source, openIndex)
691
+ };
692
+ };
693
+ const branchItems = (content)=>topLevelItemRanges(content).map(({ start, end })=>{
694
+ const item = content.slice(start, end);
695
+ const colon = codeOnly(item).indexOf(':');
696
+ if (-1 === colon) return {
697
+ key: item,
698
+ valueStart: start,
699
+ end,
700
+ shorthand: true
701
+ };
702
+ const valueStart = start + colon + 1 + item.slice(colon + 1).search(/\S/);
703
+ return {
704
+ key: item.slice(0, colon).trim(),
705
+ valueStart,
706
+ end,
707
+ shorthand: false
708
+ };
709
+ });
710
+ const wireBranches = (source, wireName)=>{
711
+ const { openIndex, closeIndex } = branchesRange(source, wireName);
712
+ const content = source.slice(openIndex + 1, closeIndex);
713
+ return new Map(branchItems(content).map(({ key, valueStart, end })=>[
714
+ key,
715
+ content.slice(valueStart, end)
716
+ ]));
717
+ };
718
+ const setWireBranches = (source, wireName, environments, branchWire)=>{
719
+ const { openIndex, closeIndex } = branchesRange(source, wireName);
720
+ let content = source.slice(openIndex + 1, closeIndex);
721
+ const items = branchItems(content);
722
+ for (const { key, valueStart, end, shorthand } of [
723
+ ...items
724
+ ].reverse())if (environments.includes(key)) content = content.slice(0, valueStart) + (shorthand ? `${key}: ${branchWire}` : branchWire) + content.slice(end);
725
+ const missing = environments.filter((environment)=>!items.some((x)=>x.key === environment));
726
+ if (missing.length) content = appendItems(content, missing.map((environment)=>`${environment}: ${branchWire}`));
727
+ return source.slice(0, openIndex + 1) + content + source.slice(closeIndex);
728
+ };
729
+ const addBranchedImplementation = (source, wireName, implementation)=>{
730
+ const withImport = addImport(source, implementation.importLine);
731
+ const { declarationIndex } = branchesRange(withImport, wireName);
732
+ const withWireClass = `${withImport.slice(0, declarationIndex)}const ${implementation.wireName} = wireClass(${implementation.className}, [])\n\n${withImport.slice(declarationIndex)}`;
733
+ return setWireBranches(withWireClass, wireName, implementation.environments, implementation.wireName);
734
+ };
680
735
  const inMemoryImplementationType = 'in-memory';
681
736
  const in_memory_db_className = 'InMemoryDbInfrastructureService';
682
737
  const in_memory_db_wireName = 'wireInMemoryDbInfrastructureService';
@@ -698,8 +753,26 @@ const in_memory_db_wireFile = ()=>new file_system_File(in_memory_db_sharedFolder
698
753
  ]);
699
754
  const in_memory_db_inMemoryDbScaffolded = ()=>serviceFile().exists && (!in_memory_db_withWiring() || in_memory_db_wireFile().exists);
700
755
  const usesInMemoryDb = (implementationType)=>Boolean(config_file_ConfigFile.Instance.data.withInMemoryDb) && new unknown_format_naming_UnknownFormatNaming(implementationType).fileName === inMemoryImplementationType && in_memory_db_inMemoryDbScaffolded();
756
+ const uncountableEndings = [
757
+ 'data',
758
+ 'info',
759
+ 'usage',
760
+ 'feedback',
761
+ 'media',
762
+ 'ware',
763
+ 'equipment',
764
+ 'information',
765
+ 'knowledge',
766
+ 'traffic',
767
+ 'telemetry',
768
+ 'analytics',
769
+ 'series'
770
+ ];
771
+ const uncountable = new RegExp(`(${uncountableEndings.join('|')})$`, 'i');
701
772
  const plural = (word)=>{
773
+ if (uncountable.test(word)) return word;
702
774
  if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
775
+ if (/(^|[^aeiou]|qu)[aeiou]z$/i.test(word)) return `${word}zes`;
703
776
  if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
704
777
  return `${word}s`;
705
778
  };
@@ -822,6 +895,13 @@ const wireNewModuleDependencies = async (boundedContextFolder, wireFile, customW
822
895
  const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
823
896
  if (consumer) await promptDependencies(boundedContextFolder, consumer, consumer.implementations, customWiring);
824
897
  };
898
+ const wireNewImplementationDependencies = async (boundedContextFolder, wireFile, className, customWiring)=>{
899
+ const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
900
+ const implementation = consumer?.implementations.find((x)=>x.className === className);
901
+ if (consumer && implementation) await promptDependencies(boundedContextFolder, consumer, [
902
+ implementation
903
+ ], customWiring);
904
+ };
825
905
  const wireDependency = async (boundedContextFolder)=>{
826
906
  const modules = findWiredModules(boundedContextFolder.path);
827
907
  if (!modules.length) return void console.log('No wired modules here yet.');
@@ -1475,6 +1555,139 @@ const moveBackendUnitUseCase = async (ownerFolder)=>{
1475
1555
  console.log('Cancelled: nothing was written.');
1476
1556
  }
1477
1557
  };
1558
+ const contractKinds = [
1559
+ 'aggregate',
1560
+ 'command',
1561
+ 'query',
1562
+ 'port'
1563
+ ];
1564
+ const implementations_withWiring = ()=>config_file_ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
1565
+ const withHandlers = ()=>config_file_ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers');
1566
+ const contractFile = (unit)=>'aggregate' === unit.kind ? `domain/aggregates/${unit.name}/${unit.name}-repository.ts` : kindLayouts[unit.kind].files(unit, [])[0];
1567
+ const findContracts = (ownerPath)=>findBackendUnits(ownerPath).filter((unit)=>contractKinds.includes(unit.kind) && external_node_fs_default().existsSync(external_node_path_default().join(ownerPath, contractFile(unit))));
1568
+ const implementationWireName = (label)=>`wire${new unknown_format_naming_UnknownFormatNaming(label).ClassName}Implementation`;
1569
+ const contractClassName = (unit)=>kindLayouts[unit.kind].core(new unknown_format_naming_UnknownFormatNaming(unit.name).ClassName);
1570
+ const implementationClassName = (unit, label)=>`${new unknown_format_naming_UnknownFormatNaming(label).ClassName}${contractClassName(unit)}`;
1571
+ const implementationFile = (unit, label)=>{
1572
+ const { implementations } = kindLayouts[unit.kind];
1573
+ return kindLayouts[unit.kind].files(unit, [
1574
+ label
1575
+ ]).find((file)=>file.startsWith(`${implementations}/`));
1576
+ };
1577
+ const contractWireFile = (unit)=>kindLayouts[unit.kind].files(unit, []).find((file)=>file.startsWith('wiring/'));
1578
+ const handlerImplementation = (ContractName, ClassName, contractImport)=>withHandlers() ? `
1579
+ import { defineHandler } from '@domain-first/handlers'
1580
+ import { ${ContractName} } from '${contractImport}'
1581
+
1582
+ export class ${ClassName} extends ${ContractName} {
1583
+ constructor() {
1584
+ super()
1585
+ }
1586
+
1587
+ handle = defineHandler({
1588
+ inputSchema: ${ContractName}.inputSchema,
1589
+ outputSchema: ${ContractName}.outputSchema,
1590
+ handler: async (input) => {
1591
+ return {}
1592
+ }
1593
+ })
1594
+ }
1595
+ `.trim() : `
1596
+ import { ${ContractName} } from '${contractImport}'
1597
+
1598
+ export class ${ClassName} extends ${ContractName} {
1599
+ constructor() {
1600
+ super()
1601
+ }
1602
+ }
1603
+ `.trim();
1604
+ const createImplementation = (ownerFolder, unit, label)=>{
1605
+ const naming = new unknown_format_naming_UnknownFormatNaming(unit.name);
1606
+ const ContractName = contractClassName(unit);
1607
+ const className = implementationClassName(unit, label);
1608
+ const [folder, fileName] = [
1609
+ external_node_path_default().dirname(implementationFile(unit, label)),
1610
+ external_node_path_default().basename(implementationFile(unit, label))
1611
+ ];
1612
+ const implementationFolder = ownerFolder.subitem(folder.split('/'));
1613
+ const inMemoryDb = !implementations_withWiring() && usesInMemoryDb(label);
1614
+ switch(unit.kind){
1615
+ case 'aggregate':
1616
+ {
1617
+ const contractImport = `../../../domain/aggregates/${unit.name}`;
1618
+ if (inMemoryDb) {
1619
+ const section = addInMemoryDbSection(naming, ownerFolder.subitem([
1620
+ 'domain',
1621
+ 'aggregates',
1622
+ unit.name
1623
+ ]).path);
1624
+ const file = implementationFolder.createFile(fileName, `
1625
+ ${inMemoryDbTypeImport(implementationFolder.subitem([
1626
+ fileName
1627
+ ]).path)}
1628
+ import { ${ContractName} } from '${contractImport}'
1629
+
1630
+ export class ${className} implements ${ContractName} {
1631
+ ${inMemoryDbSectionMembers(section, false)}
1632
+ }
1633
+ `.trim());
1634
+ return {
1635
+ file,
1636
+ className
1637
+ };
1638
+ }
1639
+ const file = implementationFolder.createFile(fileName, `
1640
+ import { ${ContractName} } from '${contractImport}'
1641
+
1642
+ export class ${className} implements ${ContractName} {
1643
+ constructor() {}
1644
+ }
1645
+
1646
+ `.trim());
1647
+ return {
1648
+ file,
1649
+ className
1650
+ };
1651
+ }
1652
+ case 'command':
1653
+ case 'query':
1654
+ {
1655
+ const folderName = 'command' === unit.kind ? 'commands' : 'queries';
1656
+ const file = implementationFolder.createFile(fileName, handlerImplementation(ContractName, className, `../../../application/${folderName}/${naming.fileName}-${unit.kind}`));
1657
+ if (inMemoryDb) injectInMemoryDb(file, className);
1658
+ return {
1659
+ file,
1660
+ className
1661
+ };
1662
+ }
1663
+ case 'port':
1664
+ {
1665
+ const file = implementationFolder.createFile(fileName, `
1666
+ import { ${ContractName} } from '../../../application/ports/${naming.fileName}'
1667
+
1668
+ export class ${className} extends ${ContractName} {
1669
+
1670
+ }
1671
+ `.trim());
1672
+ return {
1673
+ file,
1674
+ className
1675
+ };
1676
+ }
1677
+ default:
1678
+ throw new Error(`${unit.kind} has no implementations`);
1679
+ }
1680
+ };
1681
+ const inMemoryRepositoryWiring = (ownerFolder, unit, wireFile)=>(implementation, dependency)=>{
1682
+ if ('aggregate' !== unit.kind || !isInMemoryDb(dependency)) return false;
1683
+ keepInMemoryDbSection(new file_system_File(implementation.file), addInMemoryDbSection(new unknown_format_naming_UnknownFormatNaming(unit.name), ownerFolder.subitem([
1684
+ 'domain',
1685
+ 'aggregates',
1686
+ unit.name
1687
+ ]).path));
1688
+ wireInMemoryDb(wireFile, implementation.className);
1689
+ return true;
1690
+ };
1478
1691
  const scaffoldNewAggregateUseCase = async (boundedContextFolder)=>{
1479
1692
  const aggregateName = await (0, prompts_namespaceObject.input)({
1480
1693
  message: 'Aggregate name:'
@@ -1529,43 +1742,17 @@ describe('${aggregateNaming.withSpaces}', () => {
1529
1742
  message: 'Test Repository infrastructure implementation type:',
1530
1743
  default: 'in-memory'
1531
1744
  });
1532
- const infrastructureRepositoriesFolder = boundedContextFolder.subitem([
1533
- 'infrastructure',
1534
- 'repositories'
1535
- ]);
1536
1745
  const implementationTypes = [
1537
1746
  infrastructureImplementationType,
1538
1747
  testImplementationType
1539
1748
  ].filter((x)=>!!x);
1540
- for (const implementation of implementationTypes){
1541
- const naming = new unknown_format_naming_UnknownFormatNaming(implementation);
1542
- const repositoryFolder = infrastructureRepositoriesFolder.subitem([
1543
- naming.fileName
1544
- ]);
1545
- const repositoryFileName = `${naming.fileName}-${aggregateName}-repository.ts`;
1546
- if (usesInMemoryDb(implementation) && !config_file_ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
1547
- const section = addInMemoryDbSection(aggregateNaming, aggregatesFolder.path);
1548
- repositoryFolder.createFile(repositoryFileName, `
1549
- ${inMemoryDbTypeImport(repositoryFolder.subitem([
1550
- repositoryFileName
1551
- ]).path)}
1552
- import { ${aggregateNaming.ClassName}Repository } from '../../../domain/aggregates/${aggregateName}'
1553
-
1554
- export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implements ${aggregateNaming.ClassName}Repository {
1555
- ${inMemoryDbSectionMembers(section, false)}
1556
- }
1557
- `.trim());
1558
- continue;
1559
- }
1560
- repositoryFolder.createFile(repositoryFileName, `
1561
- import { ${aggregateNaming.ClassName}Repository } from '../../../domain/aggregates/${aggregateName}'
1562
-
1563
- export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implements ${aggregateNaming.ClassName}Repository {
1564
- constructor() {}
1565
- }
1566
-
1567
- `.trim());
1568
- }
1749
+ const repository = {
1750
+ kind: 'aggregate',
1751
+ name: aggregateName,
1752
+ ownerPath: boundedContextFolder.path,
1753
+ labels: []
1754
+ };
1755
+ for (const implementation of implementationTypes)createImplementation(boundedContextFolder, repository, new unknown_format_naming_UnknownFormatNaming(implementation).fileName);
1569
1756
  if (scaffoldUnitTests) {
1570
1757
  const implementationNaming = new unknown_format_naming_UnknownFormatNaming(infrastructureImplementationType);
1571
1758
  const specFile = aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.spec.ts`, `
@@ -1608,12 +1795,7 @@ export const wire${aggregateNaming.ClassName}Repository = envBranchedWire({
1608
1795
  production: wire${implementationNaming.ClassName}Implementation
1609
1796
  })
1610
1797
  `.trim());
1611
- await wireNewModuleDependencies(boundedContextFolder, wireFile, (implementation, dependency)=>{
1612
- if (!isInMemoryDb(dependency)) return false;
1613
- keepInMemoryDbSection(new file_system_File(implementation.file), addInMemoryDbSection(aggregateNaming, aggregatesFolder.path));
1614
- wireInMemoryDb(wireFile, implementation.className);
1615
- return true;
1616
- });
1798
+ await wireNewModuleDependencies(boundedContextFolder, wireFile, inMemoryRepositoryWiring(boundedContextFolder, repository, wireFile));
1617
1799
  }
1618
1800
  }
1619
1801
  };
@@ -1648,26 +1830,16 @@ export abstract class ${naming.ClassName} {
1648
1830
  message: 'Test adapter implementation type:',
1649
1831
  default: 'mock'
1650
1832
  });
1651
- const infrastructureFolder = boundedContextFolder.subitem([
1652
- 'infrastructure',
1653
- 'application-adapters'
1654
- ]);
1655
1833
  const implementationTypes = [
1656
1834
  implementationType,
1657
1835
  testImplementationType
1658
- ].filter((x)=>!!x);
1659
- for (const implementation of implementationTypes){
1660
- const currentNaming = new unknown_format_naming_UnknownFormatNaming(`${implementation}-${naming.fileName}`);
1661
- infrastructureFolder.subitem([
1662
- implementation
1663
- ]).createFile(`${currentNaming.fileName}.ts`, `
1664
- import { ${naming.ClassName} } from '../../../application/ports/${naming.fileName}'
1665
-
1666
- export class ${currentNaming.ClassName} extends ${naming.ClassName} {
1667
-
1668
- }
1669
- `.trim());
1670
- }
1836
+ ].filter((x)=>!!x).map((x)=>new unknown_format_naming_UnknownFormatNaming(x).fileName);
1837
+ for (const implementation of implementationTypes)createImplementation(boundedContextFolder, {
1838
+ kind: 'port',
1839
+ name: naming.fileName,
1840
+ ownerPath: boundedContextFolder.path,
1841
+ labels: []
1842
+ }, implementation);
1671
1843
  if (scaffoldUnitTests) {
1672
1844
  const implementationNaming = new unknown_format_naming_UnknownFormatNaming(implementationType);
1673
1845
  applicationPortsFolder.createFile(`${naming.fileName}.spec.ts`, `
@@ -1783,10 +1955,6 @@ const scaffoldNewCommand = async (boundedContextFolder)=>{
1783
1955
  'application',
1784
1956
  'commands'
1785
1957
  ]);
1786
- const infrastructureFolder = boundedContextFolder.subitem([
1787
- 'infrastructure',
1788
- 'commands'
1789
- ]);
1790
1958
  const commandName = await (0, prompts_namespaceObject.input)({
1791
1959
  message: 'Name: '
1792
1960
  });
@@ -1810,38 +1978,12 @@ const scaffoldNewCommand = async (boundedContextFolder)=>{
1810
1978
  implementationType,
1811
1979
  testImplementationType
1812
1980
  ].filter((x)=>!!x);
1813
- for (const implementation of implementationTypes){
1814
- const formatNaming = new unknown_format_naming_UnknownFormatNaming(implementation);
1815
- const implementationFile = infrastructureFolder.subitem([
1816
- formatNaming.fileName
1817
- ]).createFile(`${formatNaming.fileName}-${naming.fileName}-command.ts`, config_file_ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
1818
- import { defineHandler } from '@domain-first/handlers'
1819
- import { ${naming.ClassName}Command } from '../../../application/commands/${naming.fileName}-command'
1820
-
1821
- export class ${formatNaming.ClassName}${naming.ClassName}Command extends ${naming.ClassName}Command {
1822
- constructor() {
1823
- super()
1824
- }
1825
-
1826
- handle = defineHandler({
1827
- inputSchema: ${naming.ClassName}Command.inputSchema,
1828
- outputSchema: ${naming.ClassName}Command.outputSchema,
1829
- handler: async (input) => {
1830
- return {}
1831
- }
1832
- })
1833
- }
1834
- `.trim() : `
1835
- import { ${naming.ClassName}Command } from '../../../application/commands/${naming.fileName}-command'
1836
-
1837
- export class ${formatNaming.ClassName}${naming.ClassName}Command extends ${naming.ClassName}Command {
1838
- constructor() {
1839
- super()
1840
- }
1841
- }
1842
- `.trim());
1843
- if (!withWiring && usesInMemoryDb(implementation)) injectInMemoryDb(implementationFile, `${formatNaming.ClassName}${naming.ClassName}Command`);
1844
- }
1981
+ for (const implementation of implementationTypes)createImplementation(boundedContextFolder, {
1982
+ kind: 'command',
1983
+ name: naming.fileName,
1984
+ ownerPath: boundedContextFolder.path,
1985
+ labels: []
1986
+ }, new unknown_format_naming_UnknownFormatNaming(implementation).fileName);
1845
1987
  if (config_file_ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers')) commandsFolder.createFile(`${naming.fileName}-command.ts`, `
1846
1988
  import type { Handler } from '@domain-first/handlers'
1847
1989
 
@@ -2194,6 +2336,88 @@ export const wire${endpointClassName} = wireClass(
2194
2336
  wiringFolder.file('index.ts').addLine(`export * from './${wireNaming.fileName}'`);
2195
2337
  }
2196
2338
  };
2339
+ const scaffold_new_implementation_kindTitles = {
2340
+ aggregate: 'Repositories',
2341
+ command: 'Commands',
2342
+ query: 'Queries',
2343
+ port: 'Ports'
2344
+ };
2345
+ const scaffold_new_implementation_environments = [
2346
+ 'test',
2347
+ 'development',
2348
+ 'production'
2349
+ ];
2350
+ const branchesOf = (wireFile, wireName)=>{
2351
+ if (!wireFile.exists) return;
2352
+ try {
2353
+ return wireBranches(wireFile.data, wireName);
2354
+ } catch {
2355
+ return;
2356
+ }
2357
+ };
2358
+ const scaffoldNewImplementation = async (ownerFolder)=>{
2359
+ const contracts = findContracts(ownerFolder.path);
2360
+ if (!contracts.length) return void console.log('No repositories, commands, queries or ports here yet.');
2361
+ const unit = await (0, prompts_namespaceObject.select)({
2362
+ message: 'Contract:',
2363
+ choices: contractKinds.flatMap((kind)=>{
2364
+ const group = contracts.filter((x)=>x.kind === kind);
2365
+ return group.length ? [
2366
+ new prompts_namespaceObject.Separator(`── ${scaffold_new_implementation_kindTitles[kind]}`),
2367
+ ...group.map((value)=>({
2368
+ name: value.labels.length ? `${value.name} (${value.labels.join(', ')})` : value.name,
2369
+ value
2370
+ }))
2371
+ ] : [];
2372
+ }),
2373
+ pageSize: 20
2374
+ });
2375
+ const label = (await (0, prompts_namespaceObject.input)({
2376
+ message: 'Implementation type:',
2377
+ validate: (value)=>{
2378
+ const type = value.trim();
2379
+ if (!kebabName.test(type)) return 'Use lowercase kebab-case, e.g. api or in-memory.';
2380
+ return unit.labels.includes(type) ? `${unit.name} already has the ${type} implementation.` : true;
2381
+ }
2382
+ })).trim();
2383
+ const { file, className } = createImplementation(ownerFolder, unit, label);
2384
+ if (!config_file_ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) return;
2385
+ const wireFile = new file_system_File(ownerFolder.path).subitem(contractWireFile(unit).split('/'));
2386
+ const wireName = `wire${contractClassName(unit)}`;
2387
+ const branches = branchesOf(wireFile, wireName);
2388
+ if (!branches) return void console.log(`${wireFile.path} has no ${wireName} = envBranchedWire({...}): wire ${className} there yourself.`);
2389
+ const labelOfWire = new Map(unit.labels.map((x)=>[
2390
+ implementationWireName(x),
2391
+ x
2392
+ ]));
2393
+ const chosenEnvironments = await (0, prompts_namespaceObject.checkbox)({
2394
+ message: 'Environments:',
2395
+ choices: [
2396
+ ...new Set([
2397
+ ...scaffold_new_implementation_environments,
2398
+ ...branches.keys()
2399
+ ])
2400
+ ].map((environment)=>{
2401
+ const current = branches.get(environment);
2402
+ return {
2403
+ name: current ? `${environment} (now: ${labelOfWire.get(current) ?? current})` : environment,
2404
+ value: environment
2405
+ };
2406
+ }),
2407
+ required: true
2408
+ });
2409
+ const before = readWiredModule(wireFile.path, ownerFolder.path);
2410
+ wireFile.update(addBranchedImplementation(wireFile.data, wireName, {
2411
+ importLine: `import { ${className} } from '${wiring_relativeImport(wireFile.path, file.path)}'`,
2412
+ className,
2413
+ wireName: implementationWireName(label),
2414
+ environments: chosenEnvironments
2415
+ }));
2416
+ const after = readWiredModule(wireFile.path, ownerFolder.path);
2417
+ const unused = (before?.implementations ?? []).filter((x)=>!after?.implementations.some((y)=>y.className === x.className));
2418
+ for (const implementation of unused)console.log(`${implementation.className} is no longer used in any environment.`);
2419
+ await wireNewImplementationDependencies(ownerFolder, wireFile, className, inMemoryRepositoryWiring(ownerFolder, unit, wireFile));
2420
+ };
2197
2421
  const scaffoldNewInfrastructureService = async (boundedContextFolder)=>{
2198
2422
  const name = await (0, prompts_namespaceObject.input)({
2199
2423
  message: 'Name: '
@@ -2249,10 +2473,6 @@ const scaffoldNewQuery = async (boundedContextFolder)=>{
2249
2473
  'application',
2250
2474
  'queries'
2251
2475
  ]);
2252
- const infrastructureFolder = boundedContextFolder.subitem([
2253
- 'infrastructure',
2254
- 'queries'
2255
- ]);
2256
2476
  const queryName = await (0, prompts_namespaceObject.input)({
2257
2477
  message: 'Name: '
2258
2478
  });
@@ -2276,38 +2496,12 @@ const scaffoldNewQuery = async (boundedContextFolder)=>{
2276
2496
  implementationType,
2277
2497
  testImplementationType
2278
2498
  ].filter((x)=>!!x);
2279
- for (const implementation of implementationTypes){
2280
- const formatNaming = new unknown_format_naming_UnknownFormatNaming(implementation);
2281
- const implementationFile = infrastructureFolder.subitem([
2282
- formatNaming.fileName
2283
- ]).createFile(`${formatNaming.fileName}-${naming.fileName}-query.ts`, config_file_ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
2284
- import { defineHandler } from '@domain-first/handlers'
2285
- import { ${naming.ClassName}Query } from '../../../application/queries/${naming.fileName}-query'
2286
-
2287
- export class ${formatNaming.ClassName}${naming.ClassName}Query extends ${naming.ClassName}Query {
2288
- constructor() {
2289
- super()
2290
- }
2291
-
2292
- handle = defineHandler({
2293
- inputSchema: ${naming.ClassName}Query.inputSchema,
2294
- outputSchema: ${naming.ClassName}Query.outputSchema,
2295
- handler: async (input) => {
2296
- return {}
2297
- }
2298
- })
2299
- }
2300
- `.trim() : `
2301
- import { ${naming.ClassName}Query } from '../../../application/queries/${naming.fileName}-query'
2302
-
2303
- export class ${formatNaming.ClassName}${naming.ClassName}Query extends ${naming.ClassName}Query {
2304
- constructor() {
2305
- super()
2306
- }
2307
- }
2308
- `.trim());
2309
- if (!withWiring && usesInMemoryDb(implementation)) injectInMemoryDb(implementationFile, `${formatNaming.ClassName}${naming.ClassName}Query`);
2310
- }
2499
+ for (const implementation of implementationTypes)createImplementation(boundedContextFolder, {
2500
+ kind: 'query',
2501
+ name: naming.fileName,
2502
+ ownerPath: boundedContextFolder.path,
2503
+ labels: []
2504
+ }, new unknown_format_naming_UnknownFormatNaming(implementation).fileName);
2311
2505
  if (config_file_ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers')) queriesFolder.createFile(`${naming.fileName}-query.ts`, `
2312
2506
  import type { Handler } from '@domain-first/handlers'
2313
2507
 
@@ -2551,10 +2745,13 @@ const main = async ()=>{
2551
2745
  const operation = await (0, prompts_namespaceObject.select)({
2552
2746
  message: 'Infrastructure layer operation:',
2553
2747
  choices: [
2554
- 'New Service'
2748
+ 'New Service',
2749
+ 'New Implementation'
2555
2750
  ]
2556
2751
  });
2557
2752
  switch(operation){
2753
+ case 'New Implementation':
2754
+ return void await scaffoldNewImplementation(boundedContextFolder);
2558
2755
  case 'New Service':
2559
2756
  return void await scaffoldNewInfrastructureService(boundedContextFolder);
2560
2757
  }
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { select as prompts_select } from "@inquirer/prompts";
3
3
  import { ProjectRoot, ConfigFile, Folder } from "./201.js";
4
- import { scaffoldNewDomainService, scaffoldNewErrorUseCase, scaffoldNewAggregateUseCase, scaffoldNewQuery, scaffoldNewInfrastructureService, scaffoldNewHandlersRestEndpoint, savePendingChanges, moveBackendUnitUseCase, scaffoldNewCommand, scaffoldNewPresentationService, scaffoldNewApplicationService, scaffoldNewUseCase, wireDependency, scaffoldNewBoundedContextUseCase, scaffoldNewDomainObject, scaffoldNewApplicationPort } from "./287.js";
4
+ import { scaffoldNewDomainService, scaffoldNewErrorUseCase, scaffoldNewAggregateUseCase, scaffoldNewQuery, scaffoldNewInfrastructureService, scaffoldNewHandlersRestEndpoint, savePendingChanges, moveBackendUnitUseCase, scaffoldNewCommand, scaffoldNewPresentationService, scaffoldNewApplicationService, scaffoldNewUseCase, scaffoldNewImplementation, wireDependency, scaffoldNewBoundedContextUseCase, scaffoldNewDomainObject, scaffoldNewApplicationPort } from "./287.js";
5
5
  const main = async ()=>{
6
6
  if (!ConfigFile.exists) {
7
7
  console.log('No domain-first.project-structure.config.json found: run df-init first to initialize the project.');
@@ -119,10 +119,13 @@ const main = async ()=>{
119
119
  const operation = await prompts_select({
120
120
  message: 'Infrastructure layer operation:',
121
121
  choices: [
122
- 'New Service'
122
+ 'New Service',
123
+ 'New Implementation'
123
124
  ]
124
125
  });
125
126
  switch(operation){
127
+ case 'New Implementation':
128
+ return void await scaffoldNewImplementation(boundedContextFolder);
126
129
  case 'New Service':
127
130
  return void await scaffoldNewInfrastructureService(boundedContextFolder);
128
131
  }