@domain-first/project-structure 3.1.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/README.md CHANGED
@@ -28,7 +28,7 @@ The full technical specification lives in [API.md](./API.md).
28
28
 
29
29
  ### How to initialize a project
30
30
 
31
- Run `df-ps` in a project with a `package.json`. The first run asks for the source folder, the `@domain-first` packages you use, the default persistence implementation, React, Storybook and the testing library, then writes `domain-first.project-structure.config.json` and exits. With `@domain-first/handlers-rest`, it also scaffolds the [endpoint generator](#how-to-add-a-rest-endpoint); if `next` is among your dependencies, it offers to connect `nextAdapter` from `@domain-first/handlers-next` right away and prints the install command for it when it's missing.
31
+ Run `df-ps` in a project with a `package.json`. The first run asks for the source folder, the `@domain-first` packages you use, the default persistence implementation, whether to scaffold a shared in-memory DB for test implementations, React, Storybook and the testing library, then writes `domain-first.project-structure.config.json` and exits. With `@domain-first/handlers-rest`, it also scaffolds the [endpoint generator](#how-to-add-a-rest-endpoint); if `next` is among your dependencies, it offers to connect `nextAdapter` from `@domain-first/handlers-next` right away and prints the install command for it when it's missing.
32
32
 
33
33
  ```
34
34
  npx df-ps
@@ -44,6 +44,7 @@ npx df-ps
44
44
  "@domain-first/wire"
45
45
  ],
46
46
  "defaultPersistenceLayerImplementation": "prisma",
47
+ "withInMemoryDb": true,
47
48
  "useReact": false,
48
49
  "testingLibrary": "vitest"
49
50
  }
@@ -9,6 +9,7 @@ declare const configSchema: z.ZodObject<{
9
9
  "@domain-first/handlers-rest": "@domain-first/handlers-rest";
10
10
  }>>;
11
11
  defaultPersistenceLayerImplementation: z.ZodString;
12
+ withInMemoryDb: z.ZodOptional<z.ZodBoolean>;
12
13
  useReact: z.ZodBoolean;
13
14
  storybookFramework: z.ZodOptional<z.ZodString>;
14
15
  testingLibrary: z.ZodOptional<z.ZodString>;
@@ -0,0 +1,38 @@
1
+ import { File, Folder } from './file-system';
2
+ import { UnknownFormatNaming } from './unknown-format-naming';
3
+ /**
4
+ * The shared in-memory DB with its spec and wire, as the config says.
5
+ */
6
+ export declare const scaffoldInMemoryDb: (shared: Folder) => void;
7
+ /**
8
+ * Whether implementations of this type get the in-memory DB: it is
9
+ * enabled in the config and its files are there.
10
+ */
11
+ export declare const usesInMemoryDb: (implementationType: string) => boolean;
12
+ /**
13
+ * Adds a section of the type to the in-memory DB, unless it is there,
14
+ * and returns the section's field name.
15
+ */
16
+ export declare const addInMemoryDbSection: (typeNaming: UnknownFormatNaming, typeImportTarget: string) => string;
17
+ /**
18
+ * Import of the in-memory DB type for a file.
19
+ */
20
+ export declare const inMemoryDbTypeImport: (fromFile: string) => string;
21
+ /**
22
+ * Constructor of an implementation that keeps one section of the
23
+ * in-memory DB as `data`.
24
+ */
25
+ export declare const inMemoryDbSectionMembers: (field: string, derived: boolean) => string;
26
+ /**
27
+ * Injects the whole in-memory DB into the implementation's constructor.
28
+ */
29
+ export declare const injectInMemoryDb: (classFile: File, implementationName: string) => void;
30
+ /**
31
+ * Passes the in-memory DB wire to the implementation's `wireClass`.
32
+ */
33
+ export declare const wireInMemoryDb: (consumerWireFile: File, implementationName: string) => void;
34
+ /**
35
+ * A spec without wiring builds the implementation itself, so it has to
36
+ * pass the in-memory DB.
37
+ */
38
+ export declare const passInMemoryDb: (specFile: File, implementationName: string) => void;
@@ -0,0 +1 @@
1
+ export {};
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()
@@ -1488,6 +1489,15 @@ const addConstructorParameters = (source, className, parameters)=>{
1488
1489
  ...parameters
1489
1490
  ], indent) + source.slice(closeIndex);
1490
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
+ };
1491
1501
  const wireListRange = (source, className)=>{
1492
1502
  const match = new RegExp(`wireClass\\(\\s*${className}\\s*,\\s*\\[`).exec(codeOnly(source));
1493
1503
  if (!match) throw new Error(`wireClass(${className}, [...]) not found`);
@@ -1516,6 +1526,206 @@ const wireDependencies = (consumer, implementation, dependencies)=>{
1516
1526
  for (const dependency of dependencies)classSource = addImport(classSource, `import type { ${dependency.typeName} } from '${relativeImport(implementation.file, dependency.typeFile)}'`);
1517
1527
  classFile.update(addConstructorParameters(classSource, implementation.className, dependencies.map((x)=>`private readonly ${parameterName(x.typeName)}: ${x.typeName}`)));
1518
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
+ };
1519
1729
  const kindTitles = {
1520
1730
  repositories: 'Repositories',
1521
1731
  'domain-services': 'Domain services',
@@ -1766,6 +1976,9 @@ const initializeUseCase = async ()=>{
1766
1976
  const defaultPersistenceLayerImplementation = await (0, prompts_namespaceObject.input)({
1767
1977
  message: 'Default persistence layer implementation:'
1768
1978
  });
1979
+ const withInMemoryDb = await (0, prompts_namespaceObject.confirm)({
1980
+ message: 'Scaffold in-memory DB for test implementations'
1981
+ });
1769
1982
  const useReact = await (0, prompts_namespaceObject.confirm)({
1770
1983
  message: 'Use React'
1771
1984
  });
@@ -1789,6 +2002,7 @@ const initializeUseCase = async ()=>{
1789
2002
  rootFolder: rootFolderName,
1790
2003
  domainFirstPackages,
1791
2004
  defaultPersistenceLayerImplementation,
2005
+ withInMemoryDb,
1792
2006
  useReact,
1793
2007
  storybookFramework,
1794
2008
  testingLibrary
@@ -1806,6 +2020,10 @@ export const envBranchedWire = branchedWire(() => {
1806
2020
  return process.env.NODE_ENV ?? 'development' as 'test' | 'development' | 'production'
1807
2021
  });
1808
2022
  `.trim());
2023
+ if (withInMemoryDb) scaffoldInMemoryDb(rootFolder.subitem([
2024
+ rootFolderName,
2025
+ 'shared'
2026
+ ]));
1809
2027
  if (domainFirstPackages.includes('@domain-first/errors')) rootFolder.subitem([
1810
2028
  rootFolderName,
1811
2029
  'shared'
@@ -2154,9 +2372,25 @@ describe('${aggregateNaming.withSpaces}', () => {
2154
2372
  ].filter((x)=>!!x);
2155
2373
  for (const implementation of implementationTypes){
2156
2374
  const naming = new UnknownFormatNaming(implementation);
2157
- infrastructureRepositoriesFolder.subitem([
2375
+ const repositoryFolder = infrastructureRepositoriesFolder.subitem([
2158
2376
  naming.fileName
2159
- ]).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, `
2160
2394
  import { ${aggregateNaming.ClassName}Repository } from '../../../domain/aggregates/${aggregateName}'
2161
2395
 
2162
2396
  export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implements ${aggregateNaming.ClassName}Repository {
@@ -2167,7 +2401,7 @@ export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implement
2167
2401
  }
2168
2402
  if (scaffoldUnitTests) {
2169
2403
  const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
2170
- aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.spec.ts`, `
2404
+ const specFile = aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.spec.ts`, `
2171
2405
  import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
2172
2406
  ${ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? `import { wire${aggregateNaming.ClassName}Repository } from '../../../wiring/repositories/wire-${aggregateNaming.fileName}-repository'
2173
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'
@@ -2186,6 +2420,7 @@ describe('${aggregateNaming.withSpaces} repository', () => {
2186
2420
  })
2187
2421
  })
2188
2422
  `.trim());
2423
+ if (!ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') && usesInMemoryDb(infrastructureImplementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository`);
2189
2424
  }
2190
2425
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2191
2426
  const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
@@ -2206,6 +2441,7 @@ export const wire${aggregateNaming.ClassName}Repository = envBranchedWire({
2206
2441
  production: wire${implementationNaming.ClassName}Implementation
2207
2442
  })
2208
2443
  `.trim());
2444
+ for (const implementation of implementationTypes.filter(usesInMemoryDb))wireInMemoryDb(wireFile, `${new UnknownFormatNaming(implementation).ClassName}${aggregateNaming.ClassName}Repository`);
2209
2445
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
2210
2446
  }
2211
2447
  }
@@ -2422,7 +2658,7 @@ const scaffoldNewCommand = async (boundedContextFolder)=>{
2422
2658
  ].filter((x)=>!!x);
2423
2659
  for (const implementation of implementationTypes){
2424
2660
  const formatNaming = new UnknownFormatNaming(implementation);
2425
- infrastructureFolder.subitem([
2661
+ const implementationFile = infrastructureFolder.subitem([
2426
2662
  formatNaming.fileName
2427
2663
  ]).createFile(`${formatNaming.fileName}-${naming.fileName}-command.ts`, ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
2428
2664
  import { defineHandler } from '@domain-first/handlers'
@@ -2450,6 +2686,7 @@ export class ${formatNaming.ClassName}${naming.ClassName}Command extends ${namin
2450
2686
  }
2451
2687
  }
2452
2688
  `.trim());
2689
+ if (usesInMemoryDb(implementation)) injectInMemoryDb(implementationFile, `${formatNaming.ClassName}${naming.ClassName}Command`);
2453
2690
  }
2454
2691
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers')) commandsFolder.subitem([
2455
2692
  'execution'
@@ -2471,7 +2708,7 @@ export abstract class ${naming.ClassName}Command {
2471
2708
  }`.trim());
2472
2709
  if (scaffoldUnitTests) {
2473
2710
  const implementationNaming = new UnknownFormatNaming(implementationType);
2474
- commandsFolder.subitem([
2711
+ const specFile = commandsFolder.subitem([
2475
2712
  'execution'
2476
2713
  ]).createFile(`${naming.fileName}-command.spec.ts`, `
2477
2714
  import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
@@ -2492,6 +2729,7 @@ describe('${naming.withSpaces} command', () => {
2492
2729
  })
2493
2730
  })
2494
2731
  `.trim());
2732
+ if (!withWiring && usesInMemoryDb(implementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${naming.ClassName}Command`);
2495
2733
  }
2496
2734
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2497
2735
  const implementationNaming = new UnknownFormatNaming(implementationType);
@@ -2512,6 +2750,7 @@ export const wire${naming.ClassName}Command = envBranchedWire({
2512
2750
  production: wire${implementationNaming.ClassName}Implementation
2513
2751
  })
2514
2752
  `.trim());
2753
+ for (const implementation of implementationTypes.filter(usesInMemoryDb))wireInMemoryDb(wireFile, `${new UnknownFormatNaming(implementation).ClassName}${naming.ClassName}Command`);
2515
2754
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
2516
2755
  }
2517
2756
  return;
@@ -2932,7 +3171,7 @@ const scaffoldNewQuery = async (boundedContextFolder)=>{
2932
3171
  ].filter((x)=>!!x);
2933
3172
  for (const implementation of implementationTypes){
2934
3173
  const formatNaming = new UnknownFormatNaming(implementation);
2935
- infrastructureFolder.subitem([
3174
+ const implementationFile = infrastructureFolder.subitem([
2936
3175
  formatNaming.fileName
2937
3176
  ]).createFile(`${formatNaming.fileName}-${naming.fileName}-query.ts`, ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
2938
3177
  import { defineHandler } from '@domain-first/handlers'
@@ -2960,6 +3199,7 @@ export class ${formatNaming.ClassName}${naming.ClassName}Query extends ${naming.
2960
3199
  }
2961
3200
  }
2962
3201
  `.trim());
3202
+ if (usesInMemoryDb(implementation)) injectInMemoryDb(implementationFile, `${formatNaming.ClassName}${naming.ClassName}Query`);
2963
3203
  }
2964
3204
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers')) queriesFolder.subitem([
2965
3205
  'execution'
@@ -2981,7 +3221,7 @@ export abstract class ${naming.ClassName}Query {
2981
3221
  }`.trim());
2982
3222
  if (scaffoldUnitTests) {
2983
3223
  const implementationNaming = new UnknownFormatNaming(implementationType);
2984
- queriesFolder.subitem([
3224
+ const specFile = queriesFolder.subitem([
2985
3225
  'execution'
2986
3226
  ]).createFile(`${naming.fileName}-query.spec.ts`, `
2987
3227
  import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
@@ -3002,6 +3242,7 @@ describe('${naming.withSpaces} query', () => {
3002
3242
  })
3003
3243
  })
3004
3244
  `.trim());
3245
+ if (!withWiring && usesInMemoryDb(implementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${naming.ClassName}Query`);
3005
3246
  }
3006
3247
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
3007
3248
  const implementationNaming = new UnknownFormatNaming(implementationType);
@@ -3022,6 +3263,7 @@ export const wire${naming.ClassName}Query = envBranchedWire({
3022
3263
  production: wire${implementationNaming.ClassName}Implementation
3023
3264
  })
3024
3265
  `.trim());
3266
+ for (const implementation of implementationTypes.filter(usesInMemoryDb))wireInMemoryDb(wireFile, `${new UnknownFormatNaming(implementation).ClassName}${naming.ClassName}Query`);
3025
3267
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
3026
3268
  }
3027
3269
  return;
package/dist/index.js CHANGED
@@ -164,6 +164,7 @@ const configSchema = zod.object({
164
164
  '@domain-first/handlers-rest'
165
165
  ])),
166
166
  defaultPersistenceLayerImplementation: zod.string(),
167
+ withInMemoryDb: zod.boolean().optional(),
167
168
  useReact: zod.boolean(),
168
169
  storybookFramework: zod.string().optional(),
169
170
  testingLibrary: zod.string().optional()
@@ -1458,6 +1459,15 @@ const addConstructorParameters = (source, className, parameters)=>{
1458
1459
  ...parameters
1459
1460
  ], indent) + source.slice(closeIndex);
1460
1461
  };
1462
+ const addClassMember = (source, className, member)=>{
1463
+ const classMatch = new RegExp(`class\\s+${className}\\b[^{]*\\{`).exec(codeOnly(source));
1464
+ if (!classMatch) throw new Error(`Class ${className} not found`);
1465
+ const bodyStart = classMatch.index + classMatch[0].length;
1466
+ const bodyEnd = closingIndex(source, bodyStart - 1);
1467
+ const body = source.slice(bodyStart, bodyEnd).trimEnd();
1468
+ const separator = body.trim() ? '\n\n' : '\n';
1469
+ return `${source.slice(0, bodyStart)}${body}${separator} ${member}\n${source.slice(bodyEnd)}`;
1470
+ };
1461
1471
  const wireListRange = (source, className)=>{
1462
1472
  const match = new RegExp(`wireClass\\(\\s*${className}\\s*,\\s*\\[`).exec(codeOnly(source));
1463
1473
  if (!match) throw new Error(`wireClass(${className}, [...]) not found`);
@@ -1486,6 +1496,206 @@ const wireDependencies = (consumer, implementation, dependencies)=>{
1486
1496
  for (const dependency of dependencies)classSource = addImport(classSource, `import type { ${dependency.typeName} } from '${relativeImport(implementation.file, dependency.typeFile)}'`);
1487
1497
  classFile.update(addConstructorParameters(classSource, implementation.className, dependencies.map((x)=>`private readonly ${parameterName(x.typeName)}: ${x.typeName}`)));
1488
1498
  };
1499
+ const inMemoryImplementationType = 'in-memory';
1500
+ const in_memory_db_className = 'InMemoryDbInfrastructureService';
1501
+ const in_memory_db_wireName = 'wireInMemoryDbInfrastructureService';
1502
+ const in_memory_db_parameterName = 'inMemoryDbInfrastructureService';
1503
+ const inMemoryDbService = `type Entry = {
1504
+ id: unknown;
1505
+ item: any;
1506
+ };
1507
+
1508
+ declare global {
1509
+ var ___SHARED_IN_MEMORY_DB___: Record<string, Array<Entry>> | undefined;
1510
+ }
1511
+
1512
+ type Section<T, TId> = {
1513
+ all: (predicate?: (x: T) => boolean) => T[];
1514
+ first: (predicate: (x: T) => boolean) => T | null;
1515
+ withId: (id: TId) => T | null;
1516
+ lastAddedItem: () => T | null;
1517
+ save: (payload: T extends { id: TId } ? T : [TId, T]) => void;
1518
+ deleteById: (id: TId) => void;
1519
+ delete: (predicate: (x: T) => boolean) => void;
1520
+ };
1521
+
1522
+ type IdsAreEqual<TId> = (a: TId, b: TId) => boolean;
1523
+
1524
+ const comparisonMethodNames = ['equals', 'same', 'isSame', 'isEqual'] as const;
1525
+
1526
+ const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
1527
+ if (typeof a !== 'object' || a === null) {
1528
+ return Object.is(a, b);
1529
+ }
1530
+
1531
+ for (const methodName of comparisonMethodNames) {
1532
+ const method: unknown = (a as Record<string, unknown>)[methodName];
1533
+ if (typeof method === 'function') {
1534
+ return Boolean(method.call(a, b));
1535
+ }
1536
+ }
1537
+
1538
+ return Object.is(a, b);
1539
+ };
1540
+
1541
+ const hasId = (x: unknown): x is { id: unknown } =>
1542
+ typeof x === 'object' && x !== null && 'id' in x;
1543
+
1544
+ export class InMemoryDbInfrastructureService {
1545
+ protected section<T extends { id: unknown }>(
1546
+ key: string,
1547
+ idsAreEqual?: IdsAreEqual<T['id']>
1548
+ ): Section<T, T['id']>;
1549
+ protected section<T, TId>(
1550
+ key: string,
1551
+ idsAreEqual?: IdsAreEqual<TId>
1552
+ ): Section<T, TId>;
1553
+ protected section<T, TId>(
1554
+ key: string,
1555
+ idsAreEqual: IdsAreEqual<TId> = defaultIdsAreEqual
1556
+ ): Section<T, TId> {
1557
+ if (!globalThis.___SHARED_IN_MEMORY_DB___) {
1558
+ globalThis.___SHARED_IN_MEMORY_DB___ = {};
1559
+ }
1560
+
1561
+ if (!globalThis.___SHARED_IN_MEMORY_DB___[key]) {
1562
+ globalThis.___SHARED_IN_MEMORY_DB___[key] = [];
1563
+ }
1564
+
1565
+ const items = (): T[] =>
1566
+ globalThis.___SHARED_IN_MEMORY_DB___![key].map(
1567
+ (entry) => entry.item
1568
+ );
1569
+
1570
+ return {
1571
+ all: (predicate: (x: T) => boolean = () => true): T[] =>
1572
+ items().filter(predicate),
1573
+ first: (predicate: (x: T) => boolean): T | null =>
1574
+ items().find(predicate) ?? null,
1575
+ withId: (id: TId): T | null =>
1576
+ items().find(
1577
+ (x: T) => hasId(x) && idsAreEqual(x.id as TId, id)
1578
+ ) ?? null,
1579
+ lastAddedItem: (): T | null =>
1580
+ globalThis.___SHARED_IN_MEMORY_DB___![key].at(-1)?.item ?? null,
1581
+ save: (payload: T extends { id: TId } ? T : [TId, T]) => {
1582
+ const id = Array.isArray(payload) ? payload[0] : payload.id;
1583
+ const item = Array.isArray(payload) ? payload[1] : payload;
1584
+ const entries = globalThis.___SHARED_IN_MEMORY_DB___![key];
1585
+ const existing = entries.find((entry) =>
1586
+ idsAreEqual(entry.id as TId, id)
1587
+ );
1588
+ if (existing) {
1589
+ existing.item = item;
1590
+ return;
1591
+ }
1592
+ entries.push({ id, item });
1593
+ },
1594
+ deleteById: (id: TId) => {
1595
+ globalThis.___SHARED_IN_MEMORY_DB___![key] =
1596
+ globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
1597
+ (entry) => !idsAreEqual(entry.id as TId, id)
1598
+ );
1599
+ },
1600
+ delete: (predicate: (x: T) => boolean) => {
1601
+ globalThis.___SHARED_IN_MEMORY_DB___![key] =
1602
+ globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
1603
+ (entry) => !predicate(entry.item)
1604
+ );
1605
+ }
1606
+ };
1607
+ }
1608
+ }
1609
+ `;
1610
+ const inMemoryDbWiring = `import { wireClass } from '@domain-first/wire';
1611
+ import { InMemoryDbInfrastructureService } from '../../infrastructure/services/in-memory-db-infrastructure-service';
1612
+
1613
+ export const wireInMemoryDbInfrastructureService = wireClass(
1614
+ InMemoryDbInfrastructureService,
1615
+ []
1616
+ );
1617
+ `;
1618
+ const inMemoryDbSpec = (testingLibrary, withWiring)=>`
1619
+ import { describe, test, expect, beforeEach } from '${testingLibrary}'
1620
+ ${withWiring ? `import { type InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'
1621
+ import { wireInMemoryDbInfrastructureService } from '../../wiring/infrastructure-services/wire-in-memory-db-infrastructure-service'` : "import { InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'"}
1622
+
1623
+ let inMemoryDbInfrastructureService: InMemoryDbInfrastructureService
1624
+
1625
+ beforeEach(() => {
1626
+ inMemoryDbInfrastructureService = ${withWiring ? 'wireInMemoryDbInfrastructureService()' : 'new InMemoryDbInfrastructureService()'}
1627
+ })
1628
+
1629
+ describe('in memory db', () => {
1630
+ test('can be ${withWiring ? 'wired' : 'created'}', () => {
1631
+ expect(inMemoryDbInfrastructureService).toBeDefined()
1632
+ })
1633
+ })
1634
+ `.trim();
1635
+ const in_memory_db_withWiring = ()=>ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
1636
+ const in_memory_db_sharedFolder = ()=>new Folder(new ProjectRoot().path).subitem([
1637
+ ConfigFile.Instance.data.rootFolder,
1638
+ 'shared'
1639
+ ]);
1640
+ const serviceFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
1641
+ 'infrastructure',
1642
+ 'services',
1643
+ 'in-memory-db-infrastructure-service.ts'
1644
+ ]);
1645
+ const in_memory_db_wireFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
1646
+ 'wiring',
1647
+ 'infrastructure-services',
1648
+ 'wire-in-memory-db-infrastructure-service.ts'
1649
+ ]);
1650
+ const scaffoldInMemoryDb = (shared)=>{
1651
+ const { testingLibrary } = ConfigFile.Instance.data;
1652
+ const servicesFolder = shared.subitem([
1653
+ 'infrastructure',
1654
+ 'services'
1655
+ ]);
1656
+ servicesFolder.createFile('in-memory-db-infrastructure-service.ts', inMemoryDbService);
1657
+ if (testingLibrary) servicesFolder.createFile('in-memory-db-infrastructure-service.spec.ts', inMemoryDbSpec(testingLibrary, in_memory_db_withWiring()));
1658
+ if (in_memory_db_withWiring()) shared.subitem([
1659
+ 'wiring',
1660
+ 'infrastructure-services'
1661
+ ]).createFile('wire-in-memory-db-infrastructure-service.ts', inMemoryDbWiring);
1662
+ };
1663
+ const usesInMemoryDb = (implementationType)=>Boolean(ConfigFile.Instance.data.withInMemoryDb) && new UnknownFormatNaming(implementationType).fileName === inMemoryImplementationType && serviceFile().exists && (!in_memory_db_withWiring() || in_memory_db_wireFile().exists);
1664
+ const plural = (word)=>{
1665
+ if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
1666
+ if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
1667
+ return `${word}s`;
1668
+ };
1669
+ const addInMemoryDbSection = (typeNaming, typeImportTarget)=>{
1670
+ const file = serviceFile();
1671
+ const sectionNaming = new UnknownFormatNaming(plural(typeNaming.fileName));
1672
+ const field = sectionNaming.variableName;
1673
+ if (new RegExp(`\\b${field}\\s*=\\s*this\\.section\\b`).test(file.data)) return field;
1674
+ const withImport = addImport(file.data, `import type { ${typeNaming.ClassName} } from '${relativeImport(file.path, typeImportTarget)}';`);
1675
+ file.update(addClassMember(withImport, in_memory_db_className, `${field} = this.section<${typeNaming.ClassName}>('${sectionNaming.fileName.toUpperCase()}');`));
1676
+ return field;
1677
+ };
1678
+ const inMemoryDbTypeImport = (fromFile)=>`import type { ${in_memory_db_className} } from '${relativeImport(fromFile, serviceFile().path)}'`;
1679
+ const inMemoryDbSectionMembers = (field, derived)=>`
1680
+ private readonly data: ${in_memory_db_className}['${field}']
1681
+
1682
+ constructor(${in_memory_db_parameterName}: ${in_memory_db_className}) {
1683
+ ${derived ? 'super()\n ' : ''}this.data = ${in_memory_db_parameterName}.${field}
1684
+ }
1685
+ `.trim();
1686
+ const injectInMemoryDb = (classFile, implementationName)=>{
1687
+ classFile.update(addConstructorParameters(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)), implementationName, [
1688
+ `private readonly ${in_memory_db_parameterName}: ${in_memory_db_className}`
1689
+ ]));
1690
+ };
1691
+ const wireInMemoryDb = (consumerWireFile, implementationName)=>{
1692
+ consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${in_memory_db_wireName} } from '${relativeImport(consumerWireFile.path, in_memory_db_wireFile().path)}'`), implementationName, [
1693
+ in_memory_db_wireName
1694
+ ]));
1695
+ };
1696
+ const passInMemoryDb = (specFile, implementationName)=>{
1697
+ 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}())`));
1698
+ };
1489
1699
  const kindTitles = {
1490
1700
  repositories: 'Repositories',
1491
1701
  'domain-services': 'Domain services',
@@ -1736,6 +1946,9 @@ const initializeUseCase = async ()=>{
1736
1946
  const defaultPersistenceLayerImplementation = await input({
1737
1947
  message: 'Default persistence layer implementation:'
1738
1948
  });
1949
+ const withInMemoryDb = await prompts_confirm({
1950
+ message: 'Scaffold in-memory DB for test implementations'
1951
+ });
1739
1952
  const useReact = await prompts_confirm({
1740
1953
  message: 'Use React'
1741
1954
  });
@@ -1759,6 +1972,7 @@ const initializeUseCase = async ()=>{
1759
1972
  rootFolder: rootFolderName,
1760
1973
  domainFirstPackages,
1761
1974
  defaultPersistenceLayerImplementation,
1975
+ withInMemoryDb,
1762
1976
  useReact,
1763
1977
  storybookFramework,
1764
1978
  testingLibrary
@@ -1776,6 +1990,10 @@ export const envBranchedWire = branchedWire(() => {
1776
1990
  return process.env.NODE_ENV ?? 'development' as 'test' | 'development' | 'production'
1777
1991
  });
1778
1992
  `.trim());
1993
+ if (withInMemoryDb) scaffoldInMemoryDb(rootFolder.subitem([
1994
+ rootFolderName,
1995
+ 'shared'
1996
+ ]));
1779
1997
  if (domainFirstPackages.includes('@domain-first/errors')) rootFolder.subitem([
1780
1998
  rootFolderName,
1781
1999
  'shared'
@@ -2124,9 +2342,25 @@ describe('${aggregateNaming.withSpaces}', () => {
2124
2342
  ].filter((x)=>!!x);
2125
2343
  for (const implementation of implementationTypes){
2126
2344
  const naming = new UnknownFormatNaming(implementation);
2127
- infrastructureRepositoriesFolder.subitem([
2345
+ const repositoryFolder = infrastructureRepositoriesFolder.subitem([
2128
2346
  naming.fileName
2129
- ]).createFile(`${naming.fileName}-${aggregateName}-repository.ts`, `
2347
+ ]);
2348
+ const repositoryFileName = `${naming.fileName}-${aggregateName}-repository.ts`;
2349
+ if (usesInMemoryDb(implementation)) {
2350
+ const section = addInMemoryDbSection(aggregateNaming, aggregatesFolder.path);
2351
+ repositoryFolder.createFile(repositoryFileName, `
2352
+ ${inMemoryDbTypeImport(repositoryFolder.subitem([
2353
+ repositoryFileName
2354
+ ]).path)}
2355
+ import { ${aggregateNaming.ClassName}Repository } from '../../../domain/aggregates/${aggregateName}'
2356
+
2357
+ export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implements ${aggregateNaming.ClassName}Repository {
2358
+ ${inMemoryDbSectionMembers(section, false)}
2359
+ }
2360
+ `.trim());
2361
+ continue;
2362
+ }
2363
+ repositoryFolder.createFile(repositoryFileName, `
2130
2364
  import { ${aggregateNaming.ClassName}Repository } from '../../../domain/aggregates/${aggregateName}'
2131
2365
 
2132
2366
  export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implements ${aggregateNaming.ClassName}Repository {
@@ -2137,7 +2371,7 @@ export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implement
2137
2371
  }
2138
2372
  if (scaffoldUnitTests) {
2139
2373
  const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
2140
- aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.spec.ts`, `
2374
+ const specFile = aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.spec.ts`, `
2141
2375
  import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
2142
2376
  ${ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? `import { wire${aggregateNaming.ClassName}Repository } from '../../../wiring/repositories/wire-${aggregateNaming.fileName}-repository'
2143
2377
  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'
@@ -2156,6 +2390,7 @@ describe('${aggregateNaming.withSpaces} repository', () => {
2156
2390
  })
2157
2391
  })
2158
2392
  `.trim());
2393
+ if (!ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') && usesInMemoryDb(infrastructureImplementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository`);
2159
2394
  }
2160
2395
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2161
2396
  const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
@@ -2176,6 +2411,7 @@ export const wire${aggregateNaming.ClassName}Repository = envBranchedWire({
2176
2411
  production: wire${implementationNaming.ClassName}Implementation
2177
2412
  })
2178
2413
  `.trim());
2414
+ for (const implementation of implementationTypes.filter(usesInMemoryDb))wireInMemoryDb(wireFile, `${new UnknownFormatNaming(implementation).ClassName}${aggregateNaming.ClassName}Repository`);
2179
2415
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
2180
2416
  }
2181
2417
  }
@@ -2392,7 +2628,7 @@ const scaffoldNewCommand = async (boundedContextFolder)=>{
2392
2628
  ].filter((x)=>!!x);
2393
2629
  for (const implementation of implementationTypes){
2394
2630
  const formatNaming = new UnknownFormatNaming(implementation);
2395
- infrastructureFolder.subitem([
2631
+ const implementationFile = infrastructureFolder.subitem([
2396
2632
  formatNaming.fileName
2397
2633
  ]).createFile(`${formatNaming.fileName}-${naming.fileName}-command.ts`, ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
2398
2634
  import { defineHandler } from '@domain-first/handlers'
@@ -2420,6 +2656,7 @@ export class ${formatNaming.ClassName}${naming.ClassName}Command extends ${namin
2420
2656
  }
2421
2657
  }
2422
2658
  `.trim());
2659
+ if (usesInMemoryDb(implementation)) injectInMemoryDb(implementationFile, `${formatNaming.ClassName}${naming.ClassName}Command`);
2423
2660
  }
2424
2661
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers')) commandsFolder.subitem([
2425
2662
  'execution'
@@ -2441,7 +2678,7 @@ export abstract class ${naming.ClassName}Command {
2441
2678
  }`.trim());
2442
2679
  if (scaffoldUnitTests) {
2443
2680
  const implementationNaming = new UnknownFormatNaming(implementationType);
2444
- commandsFolder.subitem([
2681
+ const specFile = commandsFolder.subitem([
2445
2682
  'execution'
2446
2683
  ]).createFile(`${naming.fileName}-command.spec.ts`, `
2447
2684
  import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
@@ -2462,6 +2699,7 @@ describe('${naming.withSpaces} command', () => {
2462
2699
  })
2463
2700
  })
2464
2701
  `.trim());
2702
+ if (!withWiring && usesInMemoryDb(implementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${naming.ClassName}Command`);
2465
2703
  }
2466
2704
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2467
2705
  const implementationNaming = new UnknownFormatNaming(implementationType);
@@ -2482,6 +2720,7 @@ export const wire${naming.ClassName}Command = envBranchedWire({
2482
2720
  production: wire${implementationNaming.ClassName}Implementation
2483
2721
  })
2484
2722
  `.trim());
2723
+ for (const implementation of implementationTypes.filter(usesInMemoryDb))wireInMemoryDb(wireFile, `${new UnknownFormatNaming(implementation).ClassName}${naming.ClassName}Command`);
2485
2724
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
2486
2725
  }
2487
2726
  return;
@@ -2902,7 +3141,7 @@ const scaffoldNewQuery = async (boundedContextFolder)=>{
2902
3141
  ].filter((x)=>!!x);
2903
3142
  for (const implementation of implementationTypes){
2904
3143
  const formatNaming = new UnknownFormatNaming(implementation);
2905
- infrastructureFolder.subitem([
3144
+ const implementationFile = infrastructureFolder.subitem([
2906
3145
  formatNaming.fileName
2907
3146
  ]).createFile(`${formatNaming.fileName}-${naming.fileName}-query.ts`, ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
2908
3147
  import { defineHandler } from '@domain-first/handlers'
@@ -2930,6 +3169,7 @@ export class ${formatNaming.ClassName}${naming.ClassName}Query extends ${naming.
2930
3169
  }
2931
3170
  }
2932
3171
  `.trim());
3172
+ if (usesInMemoryDb(implementation)) injectInMemoryDb(implementationFile, `${formatNaming.ClassName}${naming.ClassName}Query`);
2933
3173
  }
2934
3174
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers')) queriesFolder.subitem([
2935
3175
  'execution'
@@ -2951,7 +3191,7 @@ export abstract class ${naming.ClassName}Query {
2951
3191
  }`.trim());
2952
3192
  if (scaffoldUnitTests) {
2953
3193
  const implementationNaming = new UnknownFormatNaming(implementationType);
2954
- queriesFolder.subitem([
3194
+ const specFile = queriesFolder.subitem([
2955
3195
  'execution'
2956
3196
  ]).createFile(`${naming.fileName}-query.spec.ts`, `
2957
3197
  import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
@@ -2972,6 +3212,7 @@ describe('${naming.withSpaces} query', () => {
2972
3212
  })
2973
3213
  })
2974
3214
  `.trim());
3215
+ if (!withWiring && usesInMemoryDb(implementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${naming.ClassName}Query`);
2975
3216
  }
2976
3217
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2977
3218
  const implementationNaming = new UnknownFormatNaming(implementationType);
@@ -2992,6 +3233,7 @@ export const wire${naming.ClassName}Query = envBranchedWire({
2992
3233
  production: wire${implementationNaming.ClassName}Implementation
2993
3234
  })
2994
3235
  `.trim());
3236
+ for (const implementation of implementationTypes.filter(usesInMemoryDb))wireInMemoryDb(wireFile, `${new UnknownFormatNaming(implementation).ClassName}${naming.ClassName}Query`);
2995
3237
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
2996
3238
  }
2997
3239
  return;
package/dist/wiring.d.ts CHANGED
@@ -73,6 +73,10 @@ export declare const addImport: (source: string, importLine: string) => string;
73
73
  * Appends parameters to the class constructor, adding one if missing.
74
74
  */
75
75
  export declare const addConstructorParameters: (source: string, className: string, parameters: string[]) => string;
76
+ /**
77
+ * Appends a member at the end of the class body.
78
+ */
79
+ export declare const addClassMember: (source: string, className: string, member: string) => string;
76
80
  export declare const wiredDependencyNames: (source: string, className: string) => string[];
77
81
  /**
78
82
  * Appends wires to the dependency list of `wireClass(className, [...])`,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@domain-first/project-structure",
3
3
  "description": "Build and manage your Domain-First project structure with CLI",
4
- "version": "3.1.0",
4
+ "version": "3.2.0",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -21,6 +21,7 @@ Prompts: name → `With Repository` → if yes: implementation (default = config
21
21
  - `<C>/domain/aggregates/n/`: `n.aggregate-root.ts` (`class N extends domainType()` {types}), `index.ts`, spec; with repository: `n-repository.ts` (`abstract class NRepository`), spec
22
22
  - `<C>/infrastructure/repositories/I/I-n-repository.ts` per implementation (`class INRepository implements NRepository`)
23
23
  - {wire} `<C>/wiring/repositories/wire-n-repository.ts` (env-branched)
24
+ - With `withInMemoryDb` in the config, the `in-memory` implementation is not empty: `private readonly data: InMemoryDbInfrastructureService['ns']`, set in the constructor from its `inMemoryDbInfrastructureService` parameter; `ns = this.section<N>('NS');` is added to `<rootFolder>/shared/infrastructure/services/in-memory-db-infrastructure-service.ts` if missing (`N` needs an `id`), and {wire} its `wireClass` already has `wireInMemoryDbInfrastructureService`, so `Dependencies for InMemoryNRepository:` doesn't list it.
24
25
 
25
26
  ## Domain → New Entity / New Value Object (context and Shared Layer)
26
27
 
@@ -77,6 +78,7 @@ Execution:
77
78
  - `<C>/application/commands/execution/n-command.ts`: abstract `NCommand` ({handlers} schemas + abstract `handle: Handler<…>`), spec
78
79
  - `<C>/infrastructure/commands/I/I-n-command.ts` per implementation (`extends NCommand`, implements `handle`)
79
80
  - {wire} `<C>/wiring/commands/wire-n-command.ts` (env-branched)
81
+ - With `withInMemoryDb` in the config, the `in-memory` implementation gets the whole DB: `constructor(private readonly inMemoryDbInfrastructureService: InMemoryDbInfrastructureService)`, {wire} already in its `wireClass`. No section is added.
80
82
 
81
83
  Orchestrator: `<C>/application/commands/orchestration/n-command.ts` (concrete class), spec, {wire} `wire-n-command.ts`.
82
84