@domain-first/project-structure 3.0.0 → 3.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/dist/index.cjs CHANGED
@@ -193,6 +193,7 @@ const configSchema = external_zod_default().object({
193
193
  '@domain-first/handlers-rest'
194
194
  ])),
195
195
  defaultPersistenceLayerImplementation: external_zod_default().string(),
196
+ withInMemoryDb: external_zod_default().boolean().optional(),
196
197
  useReact: external_zod_default().boolean(),
197
198
  storybookFramework: external_zod_default().string().optional(),
198
199
  testingLibrary: external_zod_default().string().optional()
@@ -219,6 +220,28 @@ class ConfigFile {
219
220
  new File(ConfigFile.path).data = JSON.stringify(config, null, '\t');
220
221
  };
221
222
  }
223
+ const external_node_util_namespaceObject = require("node:util");
224
+ const printNextSteps = (nextSteps)=>{
225
+ const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
226
+ const commands = nextSteps.filter(isCommand);
227
+ const notes = nextSteps.filter((line)=>!isCommand(line));
228
+ const sections = [];
229
+ if (commands.length) sections.push([
230
+ 'Run these commands to install the required dependencies:',
231
+ ...commands.map((line)=>(0, external_node_util_namespaceObject.styleText)([
232
+ 'bold',
233
+ 'cyan'
234
+ ], line))
235
+ ].join('\n'));
236
+ if (notes.length) sections.push([
237
+ 'Additional information:',
238
+ ...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + (0, external_node_util_namespaceObject.styleText)([
239
+ 'bold',
240
+ 'cyan'
241
+ ], path)))
242
+ ].join('\n'));
243
+ if (sections.length) console.log(sections.join('\n\n'));
244
+ };
222
245
  const savePendingChanges = async ()=>{
223
246
  const overwrittenFiles = filesToOverwrite();
224
247
  if (overwrittenFiles.length) {
@@ -238,7 +261,6 @@ const savePendingChanges = async ()=>{
238
261
  writePendingChanges();
239
262
  return true;
240
263
  };
241
- const external_node_util_namespaceObject = require("node:util");
242
264
  const missingDomainFirstPackages = ()=>{
243
265
  const packages = ConfigFile.Instance.data.domainFirstPackages;
244
266
  const manifest = JSON.parse(new File(external_node_path_default().join(new ProjectRoot().path, 'package.json')).data);
@@ -1162,27 +1184,7 @@ const addIntegration = async ()=>{
1162
1184
  }))
1163
1185
  });
1164
1186
  const nextSteps = await integration.run();
1165
- if (await savePendingChanges()) {
1166
- const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
1167
- const commands = nextSteps.filter(isCommand);
1168
- const notes = nextSteps.filter((line)=>!isCommand(line));
1169
- const sections = [];
1170
- if (commands.length) sections.push([
1171
- 'Run these commands to install the required dependencies:',
1172
- ...commands.map((line)=>(0, external_node_util_namespaceObject.styleText)([
1173
- 'bold',
1174
- 'cyan'
1175
- ], line))
1176
- ].join('\n'));
1177
- if (notes.length) sections.push([
1178
- 'Additional information:',
1179
- ...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + (0, external_node_util_namespaceObject.styleText)([
1180
- 'bold',
1181
- 'cyan'
1182
- ], path)))
1183
- ].join('\n'));
1184
- if (sections.length) console.log(sections.join('\n\n'));
1185
- }
1187
+ if (await savePendingChanges()) printNextSteps(nextSteps);
1186
1188
  };
1187
1189
  class UnknownFormatNaming {
1188
1190
  rawSource;
@@ -1487,6 +1489,15 @@ const addConstructorParameters = (source, className, parameters)=>{
1487
1489
  ...parameters
1488
1490
  ], indent) + source.slice(closeIndex);
1489
1491
  };
1492
+ const addClassMember = (source, className, member)=>{
1493
+ const classMatch = new RegExp(`class\\s+${className}\\b[^{]*\\{`).exec(codeOnly(source));
1494
+ if (!classMatch) throw new Error(`Class ${className} not found`);
1495
+ const bodyStart = classMatch.index + classMatch[0].length;
1496
+ const bodyEnd = closingIndex(source, bodyStart - 1);
1497
+ const body = source.slice(bodyStart, bodyEnd).trimEnd();
1498
+ const separator = body.trim() ? '\n\n' : '\n';
1499
+ return `${source.slice(0, bodyStart)}${body}${separator} ${member}\n${source.slice(bodyEnd)}`;
1500
+ };
1490
1501
  const wireListRange = (source, className)=>{
1491
1502
  const match = new RegExp(`wireClass\\(\\s*${className}\\s*,\\s*\\[`).exec(codeOnly(source));
1492
1503
  if (!match) throw new Error(`wireClass(${className}, [...]) not found`);
@@ -1515,6 +1526,206 @@ const wireDependencies = (consumer, implementation, dependencies)=>{
1515
1526
  for (const dependency of dependencies)classSource = addImport(classSource, `import type { ${dependency.typeName} } from '${relativeImport(implementation.file, dependency.typeFile)}'`);
1516
1527
  classFile.update(addConstructorParameters(classSource, implementation.className, dependencies.map((x)=>`private readonly ${parameterName(x.typeName)}: ${x.typeName}`)));
1517
1528
  };
1529
+ const inMemoryImplementationType = 'in-memory';
1530
+ const in_memory_db_className = 'InMemoryDbInfrastructureService';
1531
+ const in_memory_db_wireName = 'wireInMemoryDbInfrastructureService';
1532
+ const in_memory_db_parameterName = 'inMemoryDbInfrastructureService';
1533
+ const inMemoryDbService = `type Entry = {
1534
+ id: unknown;
1535
+ item: any;
1536
+ };
1537
+
1538
+ declare global {
1539
+ var ___SHARED_IN_MEMORY_DB___: Record<string, Array<Entry>> | undefined;
1540
+ }
1541
+
1542
+ type Section<T, TId> = {
1543
+ all: (predicate?: (x: T) => boolean) => T[];
1544
+ first: (predicate: (x: T) => boolean) => T | null;
1545
+ withId: (id: TId) => T | null;
1546
+ lastAddedItem: () => T | null;
1547
+ save: (payload: T extends { id: TId } ? T : [TId, T]) => void;
1548
+ deleteById: (id: TId) => void;
1549
+ delete: (predicate: (x: T) => boolean) => void;
1550
+ };
1551
+
1552
+ type IdsAreEqual<TId> = (a: TId, b: TId) => boolean;
1553
+
1554
+ const comparisonMethodNames = ['equals', 'same', 'isSame', 'isEqual'] as const;
1555
+
1556
+ const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
1557
+ if (typeof a !== 'object' || a === null) {
1558
+ return Object.is(a, b);
1559
+ }
1560
+
1561
+ for (const methodName of comparisonMethodNames) {
1562
+ const method: unknown = (a as Record<string, unknown>)[methodName];
1563
+ if (typeof method === 'function') {
1564
+ return Boolean(method.call(a, b));
1565
+ }
1566
+ }
1567
+
1568
+ return Object.is(a, b);
1569
+ };
1570
+
1571
+ const hasId = (x: unknown): x is { id: unknown } =>
1572
+ typeof x === 'object' && x !== null && 'id' in x;
1573
+
1574
+ export class InMemoryDbInfrastructureService {
1575
+ protected section<T extends { id: unknown }>(
1576
+ key: string,
1577
+ idsAreEqual?: IdsAreEqual<T['id']>
1578
+ ): Section<T, T['id']>;
1579
+ protected section<T, TId>(
1580
+ key: string,
1581
+ idsAreEqual?: IdsAreEqual<TId>
1582
+ ): Section<T, TId>;
1583
+ protected section<T, TId>(
1584
+ key: string,
1585
+ idsAreEqual: IdsAreEqual<TId> = defaultIdsAreEqual
1586
+ ): Section<T, TId> {
1587
+ if (!globalThis.___SHARED_IN_MEMORY_DB___) {
1588
+ globalThis.___SHARED_IN_MEMORY_DB___ = {};
1589
+ }
1590
+
1591
+ if (!globalThis.___SHARED_IN_MEMORY_DB___[key]) {
1592
+ globalThis.___SHARED_IN_MEMORY_DB___[key] = [];
1593
+ }
1594
+
1595
+ const items = (): T[] =>
1596
+ globalThis.___SHARED_IN_MEMORY_DB___![key].map(
1597
+ (entry) => entry.item
1598
+ );
1599
+
1600
+ return {
1601
+ all: (predicate: (x: T) => boolean = () => true): T[] =>
1602
+ items().filter(predicate),
1603
+ first: (predicate: (x: T) => boolean): T | null =>
1604
+ items().find(predicate) ?? null,
1605
+ withId: (id: TId): T | null =>
1606
+ items().find(
1607
+ (x: T) => hasId(x) && idsAreEqual(x.id as TId, id)
1608
+ ) ?? null,
1609
+ lastAddedItem: (): T | null =>
1610
+ globalThis.___SHARED_IN_MEMORY_DB___![key].at(-1)?.item ?? null,
1611
+ save: (payload: T extends { id: TId } ? T : [TId, T]) => {
1612
+ const id = Array.isArray(payload) ? payload[0] : payload.id;
1613
+ const item = Array.isArray(payload) ? payload[1] : payload;
1614
+ const entries = globalThis.___SHARED_IN_MEMORY_DB___![key];
1615
+ const existing = entries.find((entry) =>
1616
+ idsAreEqual(entry.id as TId, id)
1617
+ );
1618
+ if (existing) {
1619
+ existing.item = item;
1620
+ return;
1621
+ }
1622
+ entries.push({ id, item });
1623
+ },
1624
+ deleteById: (id: TId) => {
1625
+ globalThis.___SHARED_IN_MEMORY_DB___![key] =
1626
+ globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
1627
+ (entry) => !idsAreEqual(entry.id as TId, id)
1628
+ );
1629
+ },
1630
+ delete: (predicate: (x: T) => boolean) => {
1631
+ globalThis.___SHARED_IN_MEMORY_DB___![key] =
1632
+ globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
1633
+ (entry) => !predicate(entry.item)
1634
+ );
1635
+ }
1636
+ };
1637
+ }
1638
+ }
1639
+ `;
1640
+ const inMemoryDbWiring = `import { wireClass } from '@domain-first/wire';
1641
+ import { InMemoryDbInfrastructureService } from '../../infrastructure/services/in-memory-db-infrastructure-service';
1642
+
1643
+ export const wireInMemoryDbInfrastructureService = wireClass(
1644
+ InMemoryDbInfrastructureService,
1645
+ []
1646
+ );
1647
+ `;
1648
+ const inMemoryDbSpec = (testingLibrary, withWiring)=>`
1649
+ import { describe, test, expect, beforeEach } from '${testingLibrary}'
1650
+ ${withWiring ? `import { type InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'
1651
+ import { wireInMemoryDbInfrastructureService } from '../../wiring/infrastructure-services/wire-in-memory-db-infrastructure-service'` : "import { InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'"}
1652
+
1653
+ let inMemoryDbInfrastructureService: InMemoryDbInfrastructureService
1654
+
1655
+ beforeEach(() => {
1656
+ inMemoryDbInfrastructureService = ${withWiring ? 'wireInMemoryDbInfrastructureService()' : 'new InMemoryDbInfrastructureService()'}
1657
+ })
1658
+
1659
+ describe('in memory db', () => {
1660
+ test('can be ${withWiring ? 'wired' : 'created'}', () => {
1661
+ expect(inMemoryDbInfrastructureService).toBeDefined()
1662
+ })
1663
+ })
1664
+ `.trim();
1665
+ const in_memory_db_withWiring = ()=>ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
1666
+ const in_memory_db_sharedFolder = ()=>new Folder(new ProjectRoot().path).subitem([
1667
+ ConfigFile.Instance.data.rootFolder,
1668
+ 'shared'
1669
+ ]);
1670
+ const serviceFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
1671
+ 'infrastructure',
1672
+ 'services',
1673
+ 'in-memory-db-infrastructure-service.ts'
1674
+ ]);
1675
+ const in_memory_db_wireFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
1676
+ 'wiring',
1677
+ 'infrastructure-services',
1678
+ 'wire-in-memory-db-infrastructure-service.ts'
1679
+ ]);
1680
+ const scaffoldInMemoryDb = (shared)=>{
1681
+ const { testingLibrary } = ConfigFile.Instance.data;
1682
+ const servicesFolder = shared.subitem([
1683
+ 'infrastructure',
1684
+ 'services'
1685
+ ]);
1686
+ servicesFolder.createFile('in-memory-db-infrastructure-service.ts', inMemoryDbService);
1687
+ if (testingLibrary) servicesFolder.createFile('in-memory-db-infrastructure-service.spec.ts', inMemoryDbSpec(testingLibrary, in_memory_db_withWiring()));
1688
+ if (in_memory_db_withWiring()) shared.subitem([
1689
+ 'wiring',
1690
+ 'infrastructure-services'
1691
+ ]).createFile('wire-in-memory-db-infrastructure-service.ts', inMemoryDbWiring);
1692
+ };
1693
+ const usesInMemoryDb = (implementationType)=>Boolean(ConfigFile.Instance.data.withInMemoryDb) && new UnknownFormatNaming(implementationType).fileName === inMemoryImplementationType && serviceFile().exists && (!in_memory_db_withWiring() || in_memory_db_wireFile().exists);
1694
+ const plural = (word)=>{
1695
+ if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
1696
+ if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
1697
+ return `${word}s`;
1698
+ };
1699
+ const addInMemoryDbSection = (typeNaming, typeImportTarget)=>{
1700
+ const file = serviceFile();
1701
+ const sectionNaming = new UnknownFormatNaming(plural(typeNaming.fileName));
1702
+ const field = sectionNaming.variableName;
1703
+ if (new RegExp(`\\b${field}\\s*=\\s*this\\.section\\b`).test(file.data)) return field;
1704
+ const withImport = addImport(file.data, `import type { ${typeNaming.ClassName} } from '${relativeImport(file.path, typeImportTarget)}';`);
1705
+ file.update(addClassMember(withImport, in_memory_db_className, `${field} = this.section<${typeNaming.ClassName}>('${sectionNaming.fileName.toUpperCase()}');`));
1706
+ return field;
1707
+ };
1708
+ const inMemoryDbTypeImport = (fromFile)=>`import type { ${in_memory_db_className} } from '${relativeImport(fromFile, serviceFile().path)}'`;
1709
+ const inMemoryDbSectionMembers = (field, derived)=>`
1710
+ private readonly data: ${in_memory_db_className}['${field}']
1711
+
1712
+ constructor(${in_memory_db_parameterName}: ${in_memory_db_className}) {
1713
+ ${derived ? 'super()\n ' : ''}this.data = ${in_memory_db_parameterName}.${field}
1714
+ }
1715
+ `.trim();
1716
+ const injectInMemoryDb = (classFile, implementationName)=>{
1717
+ classFile.update(addConstructorParameters(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)), implementationName, [
1718
+ `private readonly ${in_memory_db_parameterName}: ${in_memory_db_className}`
1719
+ ]));
1720
+ };
1721
+ const wireInMemoryDb = (consumerWireFile, implementationName)=>{
1722
+ consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${in_memory_db_wireName} } from '${relativeImport(consumerWireFile.path, in_memory_db_wireFile().path)}'`), implementationName, [
1723
+ in_memory_db_wireName
1724
+ ]));
1725
+ };
1726
+ const passInMemoryDb = (specFile, implementationName)=>{
1727
+ specFile.update(addImport(specFile.data, `import { ${in_memory_db_className} } from '${relativeImport(specFile.path, serviceFile().path)}'`).replace(`new ${implementationName}()`, `new ${implementationName}(new ${in_memory_db_className}())`));
1728
+ };
1518
1729
  const kindTitles = {
1519
1730
  repositories: 'Repositories',
1520
1731
  'domain-services': 'Domain services',
@@ -1685,44 +1896,44 @@ const scaffoldNewPresentationService = async (boundedContextFolder)=>{
1685
1896
  if (wireFile) await wireNewModuleDependencies(boundedContextFolder, wireFile);
1686
1897
  };
1687
1898
  const rest_endpoint_generator_name = 'rest-endpoint-generator';
1688
- const scaffoldRestEndpointGenerator = (sharedFolder)=>createPresentationService(sharedFolder, rest_endpoint_generator_name, (className)=>`
1899
+ const scaffoldRestEndpointGenerator = (sharedFolder, { withNextAdapter = false } = {})=>createPresentationService(sharedFolder, rest_endpoint_generator_name, (className)=>{
1900
+ const adapter = withNextAdapter ? 'nextAdapter' : 'adapter';
1901
+ return `
1689
1902
  import {
1690
- type Adapter,
1691
- type EndpointGenerator,
1903
+ ${withNextAdapter ? '' : ' type Adapter,\n'} type EndpointGenerator,
1692
1904
  type ErrorStatuses,
1693
1905
  createEndpoint,
1694
1906
  InputMappingError,
1695
1907
  RequestParsingError
1696
1908
  } from '@domain-first/handlers-rest'
1909
+ ${withNextAdapter ? "import { nextAdapter } from '@domain-first/handlers-next'" : `
1910
+ /**
1911
+ * The adapter of your HTTP framework.
1912
+ */
1913
+ const adapter = undefined as unknown as Adapter<any[], any>`}
1697
1914
 
1698
1915
  export class ${className} {
1916
+ /**
1917
+ * Default errors of a client request, to spread into a generator's
1918
+ * own checks.
1919
+ */
1920
+ private get defaultClientRequestErrors(): ErrorStatuses[number]['checks'] {
1921
+ return [RequestParsingError.is, InputMappingError.is]
1922
+ }
1923
+
1699
1924
  get withoutGuards(): EndpointGenerator {
1700
1925
  return createEndpoint({
1701
1926
  errorStatuses: {
1702
1927
  400: {
1703
- checks: this.invalidRequestChecks,
1928
+ checks: this.defaultClientRequestErrors,
1704
1929
  description: 'Invalid request'
1705
1930
  }
1706
1931
  }
1707
- })(this.adapter) as EndpointGenerator
1708
- }
1709
-
1710
- /**
1711
- * Default checks of an invalid request, to spread into a generator's
1712
- * own checks.
1713
- */
1714
- private get invalidRequestChecks(): ErrorStatuses[number]['checks'] {
1715
- return [RequestParsingError.is, InputMappingError.is]
1716
- }
1717
-
1718
- /**
1719
- * The adapter of your HTTP framework.
1720
- */
1721
- private get adapter(): Adapter<any[], any> {
1722
- throw new Error('REST adapter is not set')
1932
+ })(${adapter}) as EndpointGenerator
1723
1933
  }
1724
1934
  }
1725
- `.trim());
1935
+ `.trim();
1936
+ });
1726
1937
  const findRestEndpointGenerator = (sharedFolder)=>{
1727
1938
  const typeFile = external_node_path_default().join(sharedFolder.path, 'presentation', 'services', `${rest_endpoint_generator_name}-presentation-service.ts`);
1728
1939
  if (!new File(typeFile).exists) return;
@@ -1733,7 +1944,18 @@ const findRestEndpointGenerator = (sharedFolder)=>{
1733
1944
  wireFile: external_node_path_default().join(sharedFolder.path, 'wiring', 'presentation-services', `wire-${rest_endpoint_generator_name}-presentation-service.ts`)
1734
1945
  };
1735
1946
  };
1947
+ const hasDependency = (root, name)=>{
1948
+ const manifestFile = new File(external_node_path_default().join(root, 'package.json'));
1949
+ if (!manifestFile.exists) return false;
1950
+ const manifest = JSON.parse(manifestFile.data);
1951
+ return [
1952
+ manifest.dependencies,
1953
+ manifest.devDependencies,
1954
+ manifest.optionalDependencies
1955
+ ].some((dependencies)=>dependencies && Object.hasOwn(dependencies, name));
1956
+ };
1736
1957
  const initializeUseCase = async ()=>{
1958
+ const nextSteps = [];
1737
1959
  const rootFolderName = await (0, prompts_namespaceObject.input)({
1738
1960
  message: 'Root folder (use "/" for inner folders):',
1739
1961
  default: 'src'
@@ -1748,9 +1970,15 @@ const initializeUseCase = async ()=>{
1748
1970
  '@domain-first/handlers-rest'
1749
1971
  ]
1750
1972
  });
1973
+ const withNextAdapter = domainFirstPackages.includes('@domain-first/handlers-rest') && hasDependency(new ProjectRoot().path, 'next') && await (0, prompts_namespaceObject.confirm)({
1974
+ message: 'Use Next adapter for REST endpoints'
1975
+ });
1751
1976
  const defaultPersistenceLayerImplementation = await (0, prompts_namespaceObject.input)({
1752
1977
  message: 'Default persistence layer implementation:'
1753
1978
  });
1979
+ const withInMemoryDb = await (0, prompts_namespaceObject.confirm)({
1980
+ message: 'Scaffold in-memory DB for test implementations'
1981
+ });
1754
1982
  const useReact = await (0, prompts_namespaceObject.confirm)({
1755
1983
  message: 'Use React'
1756
1984
  });
@@ -1774,6 +2002,7 @@ const initializeUseCase = async ()=>{
1774
2002
  rootFolder: rootFolderName,
1775
2003
  domainFirstPackages,
1776
2004
  defaultPersistenceLayerImplementation,
2005
+ withInMemoryDb,
1777
2006
  useReact,
1778
2007
  storybookFramework,
1779
2008
  testingLibrary
@@ -1791,6 +2020,10 @@ export const envBranchedWire = branchedWire(() => {
1791
2020
  return process.env.NODE_ENV ?? 'development' as 'test' | 'development' | 'production'
1792
2021
  });
1793
2022
  `.trim());
2023
+ if (withInMemoryDb) scaffoldInMemoryDb(rootFolder.subitem([
2024
+ rootFolderName,
2025
+ 'shared'
2026
+ ]));
1794
2027
  if (domainFirstPackages.includes('@domain-first/errors')) rootFolder.subitem([
1795
2028
  rootFolderName,
1796
2029
  'shared'
@@ -1802,10 +2035,16 @@ import { errorNamespace } from '@domain-first/errors'
1802
2035
 
1803
2036
  export const SharedErrors = errorNamespace('shared')
1804
2037
  `.trim());
1805
- if (domainFirstPackages.includes('@domain-first/handlers-rest')) scaffoldRestEndpointGenerator(rootFolder.subitem([
1806
- rootFolderName,
1807
- 'shared'
1808
- ]));
2038
+ if (domainFirstPackages.includes('@domain-first/handlers-rest')) {
2039
+ scaffoldRestEndpointGenerator(rootFolder.subitem([
2040
+ rootFolderName,
2041
+ 'shared'
2042
+ ]), {
2043
+ withNextAdapter
2044
+ });
2045
+ if (withNextAdapter && !hasDependency(path, '@domain-first/handlers-next')) nextSteps.push('npm i @domain-first/handlers-next');
2046
+ }
2047
+ return nextSteps;
1809
2048
  };
1810
2049
  const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
1811
2050
  class NestedName {
@@ -2133,9 +2372,25 @@ describe('${aggregateNaming.withSpaces}', () => {
2133
2372
  ].filter((x)=>!!x);
2134
2373
  for (const implementation of implementationTypes){
2135
2374
  const naming = new UnknownFormatNaming(implementation);
2136
- infrastructureRepositoriesFolder.subitem([
2375
+ const repositoryFolder = infrastructureRepositoriesFolder.subitem([
2137
2376
  naming.fileName
2138
- ]).createFile(`${naming.fileName}-${aggregateName}-repository.ts`, `
2377
+ ]);
2378
+ const repositoryFileName = `${naming.fileName}-${aggregateName}-repository.ts`;
2379
+ if (usesInMemoryDb(implementation)) {
2380
+ const section = addInMemoryDbSection(aggregateNaming, aggregatesFolder.path);
2381
+ repositoryFolder.createFile(repositoryFileName, `
2382
+ ${inMemoryDbTypeImport(repositoryFolder.subitem([
2383
+ repositoryFileName
2384
+ ]).path)}
2385
+ import { ${aggregateNaming.ClassName}Repository } from '../../../domain/aggregates/${aggregateName}'
2386
+
2387
+ export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implements ${aggregateNaming.ClassName}Repository {
2388
+ ${inMemoryDbSectionMembers(section, false)}
2389
+ }
2390
+ `.trim());
2391
+ continue;
2392
+ }
2393
+ repositoryFolder.createFile(repositoryFileName, `
2139
2394
  import { ${aggregateNaming.ClassName}Repository } from '../../../domain/aggregates/${aggregateName}'
2140
2395
 
2141
2396
  export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implements ${aggregateNaming.ClassName}Repository {
@@ -2146,7 +2401,7 @@ export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implement
2146
2401
  }
2147
2402
  if (scaffoldUnitTests) {
2148
2403
  const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
2149
- aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.spec.ts`, `
2404
+ const specFile = aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.spec.ts`, `
2150
2405
  import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
2151
2406
  ${ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? `import { wire${aggregateNaming.ClassName}Repository } from '../../../wiring/repositories/wire-${aggregateNaming.fileName}-repository'
2152
2407
  import type { ${aggregateNaming.ClassName}Repository } from './${aggregateNaming.fileName}-repository'` : `import { ${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository } from '../../../infrastructure/repositories/${implementationNaming.fileName}/${implementationNaming.fileName}-${aggregateNaming.fileName}-repository'
@@ -2165,6 +2420,7 @@ describe('${aggregateNaming.withSpaces} repository', () => {
2165
2420
  })
2166
2421
  })
2167
2422
  `.trim());
2423
+ if (!ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') && usesInMemoryDb(infrastructureImplementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository`);
2168
2424
  }
2169
2425
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2170
2426
  const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
@@ -2185,6 +2441,7 @@ export const wire${aggregateNaming.ClassName}Repository = envBranchedWire({
2185
2441
  production: wire${implementationNaming.ClassName}Implementation
2186
2442
  })
2187
2443
  `.trim());
2444
+ for (const implementation of implementationTypes.filter(usesInMemoryDb))wireInMemoryDb(wireFile, `${new UnknownFormatNaming(implementation).ClassName}${aggregateNaming.ClassName}Repository`);
2188
2445
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
2189
2446
  }
2190
2447
  }
@@ -2401,7 +2658,7 @@ const scaffoldNewCommand = async (boundedContextFolder)=>{
2401
2658
  ].filter((x)=>!!x);
2402
2659
  for (const implementation of implementationTypes){
2403
2660
  const formatNaming = new UnknownFormatNaming(implementation);
2404
- infrastructureFolder.subitem([
2661
+ const implementationFile = infrastructureFolder.subitem([
2405
2662
  formatNaming.fileName
2406
2663
  ]).createFile(`${formatNaming.fileName}-${naming.fileName}-command.ts`, ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
2407
2664
  import { defineHandler } from '@domain-first/handlers'
@@ -2429,6 +2686,7 @@ export class ${formatNaming.ClassName}${naming.ClassName}Command extends ${namin
2429
2686
  }
2430
2687
  }
2431
2688
  `.trim());
2689
+ if (usesInMemoryDb(implementation)) injectInMemoryDb(implementationFile, `${formatNaming.ClassName}${naming.ClassName}Command`);
2432
2690
  }
2433
2691
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers')) commandsFolder.subitem([
2434
2692
  'execution'
@@ -2450,7 +2708,7 @@ export abstract class ${naming.ClassName}Command {
2450
2708
  }`.trim());
2451
2709
  if (scaffoldUnitTests) {
2452
2710
  const implementationNaming = new UnknownFormatNaming(implementationType);
2453
- commandsFolder.subitem([
2711
+ const specFile = commandsFolder.subitem([
2454
2712
  'execution'
2455
2713
  ]).createFile(`${naming.fileName}-command.spec.ts`, `
2456
2714
  import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
@@ -2471,6 +2729,7 @@ describe('${naming.withSpaces} command', () => {
2471
2729
  })
2472
2730
  })
2473
2731
  `.trim());
2732
+ if (!withWiring && usesInMemoryDb(implementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${naming.ClassName}Command`);
2474
2733
  }
2475
2734
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2476
2735
  const implementationNaming = new UnknownFormatNaming(implementationType);
@@ -2491,6 +2750,7 @@ export const wire${naming.ClassName}Command = envBranchedWire({
2491
2750
  production: wire${implementationNaming.ClassName}Implementation
2492
2751
  })
2493
2752
  `.trim());
2753
+ for (const implementation of implementationTypes.filter(usesInMemoryDb))wireInMemoryDb(wireFile, `${new UnknownFormatNaming(implementation).ClassName}${naming.ClassName}Command`);
2494
2754
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
2495
2755
  }
2496
2756
  return;
@@ -2911,7 +3171,7 @@ const scaffoldNewQuery = async (boundedContextFolder)=>{
2911
3171
  ].filter((x)=>!!x);
2912
3172
  for (const implementation of implementationTypes){
2913
3173
  const formatNaming = new UnknownFormatNaming(implementation);
2914
- infrastructureFolder.subitem([
3174
+ const implementationFile = infrastructureFolder.subitem([
2915
3175
  formatNaming.fileName
2916
3176
  ]).createFile(`${formatNaming.fileName}-${naming.fileName}-query.ts`, ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
2917
3177
  import { defineHandler } from '@domain-first/handlers'
@@ -2939,6 +3199,7 @@ export class ${formatNaming.ClassName}${naming.ClassName}Query extends ${naming.
2939
3199
  }
2940
3200
  }
2941
3201
  `.trim());
3202
+ if (usesInMemoryDb(implementation)) injectInMemoryDb(implementationFile, `${formatNaming.ClassName}${naming.ClassName}Query`);
2942
3203
  }
2943
3204
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers')) queriesFolder.subitem([
2944
3205
  'execution'
@@ -2960,7 +3221,7 @@ export abstract class ${naming.ClassName}Query {
2960
3221
  }`.trim());
2961
3222
  if (scaffoldUnitTests) {
2962
3223
  const implementationNaming = new UnknownFormatNaming(implementationType);
2963
- queriesFolder.subitem([
3224
+ const specFile = queriesFolder.subitem([
2964
3225
  'execution'
2965
3226
  ]).createFile(`${naming.fileName}-query.spec.ts`, `
2966
3227
  import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
@@ -2981,6 +3242,7 @@ describe('${naming.withSpaces} query', () => {
2981
3242
  })
2982
3243
  })
2983
3244
  `.trim());
3245
+ if (!withWiring && usesInMemoryDb(implementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${naming.ClassName}Query`);
2984
3246
  }
2985
3247
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2986
3248
  const implementationNaming = new UnknownFormatNaming(implementationType);
@@ -3001,6 +3263,7 @@ export const wire${naming.ClassName}Query = envBranchedWire({
3001
3263
  production: wire${implementationNaming.ClassName}Implementation
3002
3264
  })
3003
3265
  `.trim());
3266
+ for (const implementation of implementationTypes.filter(usesInMemoryDb))wireInMemoryDb(wireFile, `${new UnknownFormatNaming(implementation).ClassName}${naming.ClassName}Query`);
3004
3267
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
3005
3268
  }
3006
3269
  return;
@@ -3337,7 +3600,11 @@ export const use${ClassName}UIModel = (widgetProps: Omit<${ClassName}WidgetProps
3337
3600
  }
3338
3601
  };
3339
3602
  const main = async ()=>{
3340
- if (!ConfigFile.exists) return void await initializeUseCase();
3603
+ if (!ConfigFile.exists) {
3604
+ const nextSteps = await initializeUseCase();
3605
+ if (await savePendingChanges()) printNextSteps(nextSteps);
3606
+ return;
3607
+ }
3341
3608
  const rootPath = new ProjectRoot().path;
3342
3609
  const currentBoundedContextOptions = new Folder(rootPath).subitem([
3343
3610
  ConfigFile.Instance.data.rootFolder,