@domain-first/project-structure 8.8.0 → 8.9.1

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
@@ -116,7 +116,7 @@ System implementations are marked explicitly:
116
116
 
117
117
  The first available saved type is selected by default, then an available system type; otherwise the save-entry action is selected and its name input is empty. Adding an implementation to an existing contract shows both primary and test choices. With the save action, ordinary types are remembered according to their selected environments; the run-only action never registers them.
118
118
 
119
- Updates to `backend.implementations` preserve all other config sections and are saved together with generated files; cancellation discards both. Prisma integration adds `prisma` to repository, command and query choices. There is no global persistence-default setting.
119
+ Updates to `backend.implementations` preserve all other config sections and are saved together with generated files; cancellation discards both. The Prisma and Drizzle integrations add `prisma` and `drizzle` to repository, command and query choices. There is no global persistence-default setting.
120
120
 
121
121
  ### How to create a bounded context
122
122
 
@@ -276,11 +276,11 @@ With Next.js, a new page also gets its App Router route, `app/admin/panel/users/
276
276
 
277
277
  ### How to add tooling
278
278
 
279
- Run `npx df-integration` to configure one or several of the REST endpoint generator, the shared in-memory DB, Storybook, Prisma 8, Vitest, Playwright, integration tests on PostgreSQL in Testcontainers, OpenAPI generation or an Orval API client (typed client and React Query hooks). Integrations add config files, package scripts and `.gitignore` entries, then print one install command to copy. Nothing is installed or run for you.
279
+ Run `npx df-integration` to configure one or several of the REST endpoint generator, the shared in-memory DB, Storybook, Prisma 8, Drizzle, Vitest, Playwright, integration tests on PostgreSQL in Testcontainers, OpenAPI generation or an Orval API client (typed client and React Query hooks). Integrations add config files, package scripts and `.gitignore` entries, then print one install command to copy. Nothing is installed or run for you.
280
280
 
281
281
  The endpoint generator and the in-memory DB are what `df-init` scaffolds; as integrations they add them later or restore missing files, and never overwrite existing ones.
282
282
 
283
- With Testcontainers, the CLI asks which implementation types get integration tests (`prisma` yes, `stripe` probably not). From then on, each new implementation of such a type, like `PrismaOrdersQuery`, gets a spec in `specs/integration/` that builds it through its wire and runs against PostgreSQL in a container; an infrastructure service gets one when you ask. Unit specs stay with the domain model, services and use cases.
283
+ With Testcontainers, the CLI asks which implementation types get integration tests (`prisma` or `drizzle` yes, `stripe` probably not). From then on, each new implementation of such a type, like `PrismaOrdersQuery`, gets a spec in `specs/integration/` that builds it through its wire and runs against PostgreSQL in a container; an infrastructure service gets one when you ask. Unit specs stay with the domain model, services and use cases.
284
284
 
285
285
  ### How to check the rules
286
286
 
@@ -1,6 +1,214 @@
1
1
  import node_path from "node:path";
2
2
  import node_fs from "node:fs";
3
- import { ProjectRoot, File, stripJsonComments, ConfigFile } from "./780.js";
3
+ import { addImport, addWireDependencies, addConstructorParameters, UnknownFormatNaming, ConfigFile, Folder, relativeImport, File, ProjectRoot, addClassMember, stripJsonComments } from "./201.js";
4
+ const inMemoryImplementationType = 'in-memory';
5
+ const className = 'InMemoryDbInfrastructureService';
6
+ const wireName = 'wireInMemoryDbInfrastructureService';
7
+ const parameterName = 'inMemoryDbInfrastructureService';
8
+ const legacyWithIdLookup = ` withId: (id: TId): T | null =>
9
+ items().find(
10
+ (x: T) => hasId(x) && idsAreEqual(x.id as TId, id)
11
+ ) ?? null,
12
+ `;
13
+ const legacyHasId = `const hasId = (x: unknown): x is { id: unknown } =>
14
+ typeof x === 'object' && x !== null && 'id' in x;
15
+
16
+ `;
17
+ const withIdLookup = ` withId: (id: TId): T | null =>
18
+ globalThis.___SHARED_IN_MEMORY_DB___![key].find((entry) =>
19
+ idsAreEqual(entry.id as TId, id)
20
+ )?.item ?? null,
21
+ `;
22
+ const inMemoryDbService = `type Entry = {
23
+ id: unknown;
24
+ item: any;
25
+ };
26
+
27
+ declare global {
28
+ var ___SHARED_IN_MEMORY_DB___: Record<string, Array<Entry>> | undefined;
29
+ }
30
+
31
+ type Section<T, TId> = {
32
+ all: (predicate?: (x: T) => boolean) => T[];
33
+ first: (predicate: (x: T) => boolean) => T | null;
34
+ withId: (id: TId) => T | null;
35
+ lastAddedItem: () => T | null;
36
+ save: (payload: T extends { id: TId } ? T : [TId, T]) => void;
37
+ deleteById: (id: TId) => void;
38
+ delete: (predicate: (x: T) => boolean) => void;
39
+ };
40
+
41
+ type IdsAreEqual<TId> = (a: TId, b: TId) => boolean;
42
+
43
+ const comparisonMethodNames = ['equals', 'same', 'isSame', 'isEqual'] as const;
44
+
45
+ const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
46
+ if (typeof a !== 'object' || a === null) {
47
+ return Object.is(a, b);
48
+ }
49
+
50
+ for (const methodName of comparisonMethodNames) {
51
+ const method: unknown = (a as Record<string, unknown>)[methodName];
52
+ if (typeof method === 'function') {
53
+ return Boolean(method.call(a, b));
54
+ }
55
+ }
56
+
57
+ return Object.is(a, b);
58
+ };
59
+
60
+ export class InMemoryDbInfrastructureService {
61
+ protected section<T extends { id: unknown }>(
62
+ key: string,
63
+ idsAreEqual?: IdsAreEqual<T['id']>
64
+ ): Section<T, T['id']>;
65
+ protected section<T, TId>(
66
+ key: string,
67
+ idsAreEqual?: IdsAreEqual<TId>
68
+ ): Section<T, TId>;
69
+ protected section<T, TId>(
70
+ key: string,
71
+ idsAreEqual: IdsAreEqual<TId> = defaultIdsAreEqual
72
+ ): Section<T, TId> {
73
+ if (!globalThis.___SHARED_IN_MEMORY_DB___) {
74
+ globalThis.___SHARED_IN_MEMORY_DB___ = {};
75
+ }
76
+
77
+ if (!globalThis.___SHARED_IN_MEMORY_DB___[key]) {
78
+ globalThis.___SHARED_IN_MEMORY_DB___[key] = [];
79
+ }
80
+
81
+ const items = (): T[] =>
82
+ globalThis.___SHARED_IN_MEMORY_DB___![key].map(
83
+ (entry) => entry.item
84
+ );
85
+
86
+ return {
87
+ all: (predicate: (x: T) => boolean = () => true): T[] =>
88
+ items().filter(predicate),
89
+ first: (predicate: (x: T) => boolean): T | null =>
90
+ items().find(predicate) ?? null,
91
+ ${withIdLookup} lastAddedItem: (): T | null =>
92
+ globalThis.___SHARED_IN_MEMORY_DB___![key].at(-1)?.item ?? null,
93
+ save: (payload: T extends { id: TId } ? T : [TId, T]) => {
94
+ const id = Array.isArray(payload) ? payload[0] : payload.id;
95
+ const item = Array.isArray(payload) ? payload[1] : payload;
96
+ const entries = globalThis.___SHARED_IN_MEMORY_DB___![key];
97
+ const existing = entries.find((entry) =>
98
+ idsAreEqual(entry.id as TId, id)
99
+ );
100
+ if (existing) {
101
+ existing.item = item;
102
+ return;
103
+ }
104
+ entries.push({ id, item });
105
+ },
106
+ deleteById: (id: TId) => {
107
+ globalThis.___SHARED_IN_MEMORY_DB___![key] =
108
+ globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
109
+ (entry) => !idsAreEqual(entry.id as TId, id)
110
+ );
111
+ },
112
+ delete: (predicate: (x: T) => boolean) => {
113
+ globalThis.___SHARED_IN_MEMORY_DB___![key] =
114
+ globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
115
+ (entry) => !predicate(entry.item)
116
+ );
117
+ }
118
+ };
119
+ }
120
+ }
121
+ `;
122
+ const inMemoryDbWiring = `import { wireClass } from '@domain-first/wire';
123
+ import { InMemoryDbInfrastructureService } from '../../infrastructure/services/in-memory-db-infrastructure-service';
124
+
125
+ export const wireInMemoryDbInfrastructureService = wireClass(
126
+ InMemoryDbInfrastructureService,
127
+ []
128
+ );
129
+ `;
130
+ const withWiring = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
131
+ const sharedFolder = ()=>new Folder(new ProjectRoot().path).subitem([
132
+ ConfigFile.Instance.data.project.rootFolder,
133
+ 'shared-kernel'
134
+ ]);
135
+ const serviceFile = ()=>new File(sharedFolder().path).subitem([
136
+ 'infrastructure',
137
+ 'services',
138
+ 'in-memory-db-infrastructure-service.ts'
139
+ ]);
140
+ const wireFile = ()=>new File(sharedFolder().path).subitem([
141
+ 'wiring',
142
+ 'infrastructure-services',
143
+ 'wire-in-memory-db-infrastructure-service.ts'
144
+ ]);
145
+ const scaffoldInMemoryDb = (shared)=>{
146
+ const servicesFolder = shared.subitem([
147
+ 'infrastructure',
148
+ 'services'
149
+ ]);
150
+ servicesFolder.createFile('in-memory-db-infrastructure-service.ts', inMemoryDbService);
151
+ if (withWiring()) shared.subitem([
152
+ 'wiring',
153
+ 'infrastructure-services'
154
+ ]).createFile('wire-in-memory-db-infrastructure-service.ts', inMemoryDbWiring);
155
+ };
156
+ const inMemoryDbScaffolded = ()=>serviceFile().exists && (!withWiring() || wireFile().exists);
157
+ const usesInMemoryDb = (implementationType)=>Boolean(ConfigFile.Instance.data.backend?.withInMemoryDb) && new UnknownFormatNaming(implementationType).fileName === inMemoryImplementationType && inMemoryDbScaffolded();
158
+ const uncountableEndings = [
159
+ 'data',
160
+ 'info',
161
+ 'usage',
162
+ 'feedback',
163
+ 'media',
164
+ 'ware',
165
+ 'equipment',
166
+ 'information',
167
+ 'knowledge',
168
+ 'traffic',
169
+ 'telemetry',
170
+ 'analytics',
171
+ 'series'
172
+ ];
173
+ const uncountable = new RegExp(`(${uncountableEndings.join('|')})$`, 'i');
174
+ const plural = (word)=>{
175
+ if (uncountable.test(word)) return word;
176
+ if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
177
+ if (/(^|[^aeiou]|qu)[aeiou]z$/i.test(word)) return `${word}zes`;
178
+ if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
179
+ return `${word}s`;
180
+ };
181
+ const addInMemoryDbSection = (typeNaming, typeImportTarget)=>{
182
+ const file = serviceFile();
183
+ const sectionNaming = new UnknownFormatNaming(plural(typeNaming.fileName));
184
+ const field = sectionNaming.variableName;
185
+ if (new RegExp(`\\b${field}\\s*=\\s*this\\.section\\b`).test(file.data)) return field;
186
+ const withImport = addImport(file.data, `import type { ${typeNaming.ClassName} } from '${relativeImport(file.path, typeImportTarget)}';`);
187
+ file.update(addClassMember(withImport, className, `${field} = this.section<${typeNaming.ClassName}>('${sectionNaming.fileName.toUpperCase()}');`));
188
+ return field;
189
+ };
190
+ const inMemoryDbTypeImport = (fromFile)=>`import type { ${className} } from '${relativeImport(fromFile, serviceFile().path)}'`;
191
+ const inMemoryDbSectionMembers = (field, derived)=>`
192
+ private readonly data: ${className}['${field}']
193
+
194
+ constructor(${parameterName}: ${className}) {
195
+ ${derived ? 'super()\n ' : ''}this.data = ${parameterName}.${field}
196
+ }
197
+ `.trim();
198
+ const keepInMemoryDbSection = (classFile, field)=>{
199
+ classFile.update(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)).replace('constructor() {}', inMemoryDbSectionMembers(field, false)));
200
+ };
201
+ const isInMemoryDb = (module)=>module.wireName === wireName;
202
+ const injectInMemoryDb = (classFile, implementationName)=>{
203
+ classFile.update(addConstructorParameters(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)), implementationName, [
204
+ `private readonly ${parameterName}: ${className}`
205
+ ]));
206
+ };
207
+ const wireInMemoryDb = (consumerWireFile, implementationName)=>{
208
+ consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${wireName} } from '${relativeImport(consumerWireFile.path, wireFile().path)}'`), implementationName, [
209
+ wireName
210
+ ]));
211
+ };
4
212
  const hasDependency = (name)=>{
5
213
  const manifestFile = new File(node_path.join(new ProjectRoot().path, 'package.json'));
6
214
  if (!manifestFile.exists) return false;
@@ -373,4 +581,4 @@ const legacyRootEndpoints = (boundedContextFolder)=>{
373
581
  };
374
582
  };
375
583
  const hasLegacyRootEndpoints = (boundedContextFolder)=>Object.values(legacyRootEndpoints(boundedContextFolder)).some((paths)=>paths.length > 0);
376
- export { codeExtension, endpointFileLookup, escapeRegExp, hasDependency, hasLegacyRootEndpoints, isPathParameterName, legacyEndpointFileLookup, legacyRootEndpoints, missingDomainFirstPackages, missingPackages, openapiExtractor, openapiExtractorPath, pathParameterAsName, projectImports, restControllers, restFolders, rootStaticSegments, stageModuleMove, toPosix, walk };
584
+ export { addInMemoryDbSection, codeExtension, endpointFileLookup, escapeRegExp, hasDependency, hasLegacyRootEndpoints, inMemoryDbScaffolded, inMemoryDbSectionMembers, inMemoryDbTypeImport, inMemoryImplementationType, injectInMemoryDb, isInMemoryDb, isPathParameterName, keepInMemoryDbSection, legacyEndpointFileLookup, legacyHasId, legacyRootEndpoints, legacyWithIdLookup, missingDomainFirstPackages, missingPackages, openapiExtractor, openapiExtractorPath, pathParameterAsName, plural, projectImports, restControllers, restFolders, rootStaticSegments, scaffoldInMemoryDb, stageModuleMove, toPosix, usesInMemoryDb, walk, wireInMemoryDb, withIdLookup };