@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/dist/287.js CHANGED
@@ -3,227 +3,38 @@ import { AsyncLocalStorage } from "node:async_hooks";
3
3
  import { Separator, checkbox as prompts_checkbox, confirm as prompts_confirm, input, search, select as prompts_select } from "@inquirer/prompts";
4
4
  import node_fs from "node:fs";
5
5
  import { styleText } from "node:util";
6
- import { addImport, availableDependencies, findWiredModules, UnknownFormatNaming, readWiredModule, addClassMember, hasNeighboringBoundedContext, addBranchedImplementation, addWireDependencies, boundedContextLocation, addConstructorParameters, relativeImport, wireBranches, wireDependencies, implementationType as wiring_implementationType, crossContextImportAllowed, crossContextImplementation, isSuggestedFor } from "./947.js";
7
- import { implementationLabelSchema, withoutOverwrites, domainFirstPackages as config_file_domainFirstPackages, scaffoldBackendRules, branchNameSchema, discardPendingChanges, ConfigFile, filesToOverwrite, Folder, writePendingChanges, File, ProjectRoot, implementationKinds, compilerOption } from "./780.js";
8
- import { missingDomainFirstPackages, walk, projectImports, escapeRegExp, pathParameterAsName, hasLegacyRootEndpoints, stageModuleMove, toPosix, rootStaticSegments, openapiExtractorPath, restControllers, hasDependency, openapiExtractor, missingPackages, codeExtension, isPathParameterName } from "./526.js";
6
+ import { availableDependencies, isSuggestedFor, domainFirstPackages as config_file_domainFirstPackages, scaffoldBackendRules, discardPendingChanges, UnknownFormatNaming, findWiredModules, Folder, compilerOption, implementationKinds, writePendingChanges, readWiredModule, addBranchedImplementation, hasNeighboringBoundedContext, implementationLabelSchema, withoutOverwrites, boundedContextLocation, branchNameSchema, filesToOverwrite, ConfigFile, relativeImport, wireBranches, wireDependencies, File, ProjectRoot, crossContextImportAllowed, crossContextImplementation, implementationType as wiring_implementationType } from "./201.js";
7
+ import { codeExtension, restControllers, missingDomainFirstPackages, isPathParameterName, keepInMemoryDbSection, walk, escapeRegExp, wireInMemoryDb, projectImports, pathParameterAsName, stageModuleMove, hasLegacyRootEndpoints, inMemoryImplementationType, toPosix, rootStaticSegments, inMemoryDbScaffolded, scaffoldInMemoryDb, injectInMemoryDb, isInMemoryDb, openapiExtractorPath, inMemoryDbTypeImport, addInMemoryDbSection, openapiExtractor, plural, missingPackages, inMemoryDbSectionMembers, usesInMemoryDb, hasDependency } from "./115.js";
9
8
  const moduleId = (module)=>`${boundedContextLocation(module.typeFile)?.name ?? 'shared-kernel'}:${module.typeName}`;
10
9
  const unitId = (unit)=>`${unit.kind}:${unit.aggregate ? `${unit.aggregate}/` : ''}${unit.name}`;
11
- const inMemoryImplementationType = 'in-memory';
12
- const in_memory_db_className = 'InMemoryDbInfrastructureService';
13
- const in_memory_db_wireName = 'wireInMemoryDbInfrastructureService';
14
- const parameterName = 'inMemoryDbInfrastructureService';
15
- const inMemoryDbService = `type Entry = {
16
- id: unknown;
17
- item: any;
18
- };
19
-
20
- declare global {
21
- var ___SHARED_IN_MEMORY_DB___: Record<string, Array<Entry>> | undefined;
22
- }
23
-
24
- type Section<T, TId> = {
25
- all: (predicate?: (x: T) => boolean) => T[];
26
- first: (predicate: (x: T) => boolean) => T | null;
27
- withId: (id: TId) => T | null;
28
- lastAddedItem: () => T | null;
29
- save: (payload: T extends { id: TId } ? T : [TId, T]) => void;
30
- deleteById: (id: TId) => void;
31
- delete: (predicate: (x: T) => boolean) => void;
32
- };
33
-
34
- type IdsAreEqual<TId> = (a: TId, b: TId) => boolean;
35
-
36
- const comparisonMethodNames = ['equals', 'same', 'isSame', 'isEqual'] as const;
37
-
38
- const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
39
- if (typeof a !== 'object' || a === null) {
40
- return Object.is(a, b);
41
- }
42
-
43
- for (const methodName of comparisonMethodNames) {
44
- const method: unknown = (a as Record<string, unknown>)[methodName];
45
- if (typeof method === 'function') {
46
- return Boolean(method.call(a, b));
47
- }
48
- }
49
-
50
- return Object.is(a, b);
51
- };
52
-
53
- const hasId = (x: unknown): x is { id: unknown } =>
54
- typeof x === 'object' && x !== null && 'id' in x;
55
-
56
- export class InMemoryDbInfrastructureService {
57
- protected section<T extends { id: unknown }>(
58
- key: string,
59
- idsAreEqual?: IdsAreEqual<T['id']>
60
- ): Section<T, T['id']>;
61
- protected section<T, TId>(
62
- key: string,
63
- idsAreEqual?: IdsAreEqual<TId>
64
- ): Section<T, TId>;
65
- protected section<T, TId>(
66
- key: string,
67
- idsAreEqual: IdsAreEqual<TId> = defaultIdsAreEqual
68
- ): Section<T, TId> {
69
- if (!globalThis.___SHARED_IN_MEMORY_DB___) {
70
- globalThis.___SHARED_IN_MEMORY_DB___ = {};
71
- }
72
-
73
- if (!globalThis.___SHARED_IN_MEMORY_DB___[key]) {
74
- globalThis.___SHARED_IN_MEMORY_DB___[key] = [];
75
- }
76
-
77
- const items = (): T[] =>
78
- globalThis.___SHARED_IN_MEMORY_DB___![key].map(
79
- (entry) => entry.item
80
- );
81
-
82
- return {
83
- all: (predicate: (x: T) => boolean = () => true): T[] =>
84
- items().filter(predicate),
85
- first: (predicate: (x: T) => boolean): T | null =>
86
- items().find(predicate) ?? null,
87
- withId: (id: TId): T | null =>
88
- items().find(
89
- (x: T) => hasId(x) && idsAreEqual(x.id as TId, id)
90
- ) ?? null,
91
- 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 in_memory_db_withWiring = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
131
- const in_memory_db_sharedFolder = ()=>new Folder(new ProjectRoot().path).subitem([
132
- ConfigFile.Instance.data.project.rootFolder,
133
- 'shared-kernel'
134
- ]);
135
- const serviceFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
136
- 'infrastructure',
137
- 'services',
138
- 'in-memory-db-infrastructure-service.ts'
139
- ]);
140
- const in_memory_db_wireFile = ()=>new File(in_memory_db_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 (in_memory_db_withWiring()) shared.subitem([
152
- 'wiring',
153
- 'infrastructure-services'
154
- ]).createFile('wire-in-memory-db-infrastructure-service.ts', inMemoryDbWiring);
155
- };
156
- const inMemoryDbScaffolded = ()=>serviceFile().exists && (!in_memory_db_withWiring() || in_memory_db_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, in_memory_db_className, `${field} = this.section<${typeNaming.ClassName}>('${sectionNaming.fileName.toUpperCase()}');`));
188
- return field;
189
- };
190
- const inMemoryDbTypeImport = (fromFile)=>`import type { ${in_memory_db_className} } from '${relativeImport(fromFile, serviceFile().path)}'`;
191
- const inMemoryDbSectionMembers = (field, derived)=>`
192
- private readonly data: ${in_memory_db_className}['${field}']
193
-
194
- constructor(${parameterName}: ${in_memory_db_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 === in_memory_db_wireName;
202
- const injectInMemoryDb = (classFile, implementationName)=>{
203
- classFile.update(addConstructorParameters(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)), implementationName, [
204
- `private readonly ${parameterName}: ${in_memory_db_className}`
205
- ]));
206
- };
207
- const wireInMemoryDb = (consumerWireFile, implementationName)=>{
208
- consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${in_memory_db_wireName} } from '${relativeImport(consumerWireFile.path, in_memory_db_wireFile().path)}'`), implementationName, [
209
- in_memory_db_wireName
210
- ]));
211
- };
212
- const addInMemoryDb = ()=>{
213
- const config = ConfigFile.Instance.data;
214
- if (!ConfigFile.backend.withInMemoryDb) ConfigFile.update({
10
+ const savedImplementations = (kind, purpose)=>[
11
+ ...new Set(ConfigFile.Instance.data.backend?.implementations?.[kind]?.[purpose] ?? [])
12
+ ];
13
+ const rememberImplementation = (kind, purpose, label)=>{
14
+ implementationLabelSchema.parse(label);
15
+ const backend = ConfigFile.backend;
16
+ const choices = {
17
+ ...backend.implementations
18
+ };
19
+ const group = choices[kind] ?? {
20
+ primary: [],
21
+ test: []
22
+ };
23
+ if (group[purpose].includes(label)) return;
24
+ choices[kind] = {
25
+ ...group,
26
+ [purpose]: [
27
+ ...group[purpose],
28
+ label
29
+ ]
30
+ };
31
+ ConfigFile.update({
215
32
  backend: {
216
- ...ConfigFile.backend,
217
- withInMemoryDb: true
33
+ ...backend,
34
+ implementations: choices
218
35
  }
219
36
  });
220
- withoutOverwrites(()=>scaffoldInMemoryDb(new Folder(new ProjectRoot().path).subitem([
221
- config.project.rootFolder,
222
- 'shared-kernel'
223
- ])));
224
- return [];
225
37
  };
226
- const inMemoryDbApplied = ()=>Boolean(ConfigFile.Instance.data.backend?.withInMemoryDb) && inMemoryDbScaffolded();
227
38
  const isSeparator = (choice)=>'function' == typeof Separator && choice instanceof Separator || 'object' == typeof choice && null !== choice && 'separator' === choice.type;
228
39
  class RequestError extends Error {
229
40
  code;
@@ -390,6 +201,190 @@ const interaction_checkbox = async (config)=>{
390
201
  if (config.required && !selected.length) throw interaction_missing(field);
391
202
  return selected;
392
203
  };
204
+ const addPackageScripts = async (file, additions)=>{
205
+ const original = file.data;
206
+ const manifest = JSON.parse(original);
207
+ const scripts = {
208
+ ...manifest.scripts
209
+ };
210
+ const selected = {};
211
+ for (const [name, command] of Object.entries(additions)){
212
+ let target = name;
213
+ if (Object.hasOwn(scripts, name) && scripts[name] !== command) {
214
+ const action = await interaction_select({
215
+ key: `scriptConflicts.${name}`,
216
+ message: `Script "${name}" already exists: ${scripts[name]}`,
217
+ choices: [
218
+ 'Keep existing',
219
+ 'Replace',
220
+ 'Use another name'
221
+ ]
222
+ });
223
+ if ('Keep existing' === action) continue;
224
+ if ('Use another name' === action) target = await interaction_input({
225
+ key: `scriptNames.${name}`,
226
+ message: "New script name:",
227
+ validate: (value)=>!/^[a-zA-Z0-9:_-]+$/.test(value) || Object.hasOwn(scripts, value) || Object.hasOwn(additions, value) ? "Enter an unused script name (letters, numbers, :, _, -)." : true
228
+ });
229
+ }
230
+ scripts[target] = command;
231
+ selected[name] = target;
232
+ }
233
+ if (JSON.stringify(manifest.scripts) !== JSON.stringify(scripts)) {
234
+ manifest.scripts = scripts;
235
+ const indent = original.match(/\n([\t ]+)"/)?.[1] ?? ' ';
236
+ file.update(`${JSON.stringify(manifest, null, indent)}\n`);
237
+ }
238
+ return selected;
239
+ };
240
+ const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
241
+ const runtimePackages = [
242
+ 'drizzle-orm',
243
+ 'pg',
244
+ 'dotenv'
245
+ ];
246
+ const developmentPackages = [
247
+ 'drizzle-kit',
248
+ '@types/pg'
249
+ ];
250
+ const drizzleFolder = (rootFolder)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'shared-kernel/infrastructure/drizzle');
251
+ const drizzleConfigPath = (rootFolder)=>node_path.posix.join(drizzleFolder(rootFolder), 'drizzle.config.ts');
252
+ const drizzleScripts = (rootFolder)=>{
253
+ const config = JSON.stringify(drizzleConfigPath(rootFolder));
254
+ return {
255
+ 'drizzle:generate': `drizzle-kit generate --config ${config}`,
256
+ 'drizzle:migrate': `drizzle-kit migrate --config ${config}`
257
+ };
258
+ };
259
+ const drizzleConfig = (rootFolder)=>{
260
+ const folder = drizzleFolder(rootFolder);
261
+ return `import 'dotenv/config';
262
+ import { defineConfig } from 'drizzle-kit';
263
+
264
+ // Paths are relative to the project root, where package scripts run.
265
+ export default defineConfig({
266
+ dialect: 'postgresql',
267
+ schema: ${JSON.stringify(node_path.posix.join(folder, 'schema.ts'))},
268
+ out: ${JSON.stringify(node_path.posix.join(folder, 'migrations'))},
269
+ dbCredentials: {
270
+ url: process.env.DATABASE_URL as string
271
+ }
272
+ });
273
+ `;
274
+ };
275
+ const drizzleSchema = `// Add your application tables here before running drizzle:generate, e.g.
276
+ //
277
+ // import { pgTable, text } from 'drizzle-orm/pg-core';
278
+ //
279
+ // export const orders = pgTable('orders', {
280
+ // id: text('id').primaryKey()
281
+ // });
282
+
283
+ export {};
284
+ `;
285
+ const drizzleService = `import { drizzle } from 'drizzle-orm/node-postgres';
286
+ import { Pool } from 'pg';
287
+
288
+ const createDatabase = () =>
289
+ drizzle({
290
+ client: new Pool({ connectionString: process.env.DATABASE_URL })
291
+ });
292
+
293
+ type DrizzleDatabase = ReturnType<typeof createDatabase>;
294
+
295
+ const globalForDrizzle = globalThis as typeof globalThis & {
296
+ drizzleDatabase?: DrizzleDatabase;
297
+ };
298
+
299
+ // Reuse the connection pool across development hot reloads.
300
+ const drizzleDatabase = globalForDrizzle.drizzleDatabase ?? createDatabase();
301
+
302
+ if (process.env.NODE_ENV !== 'production') {
303
+ globalForDrizzle.drizzleDatabase = drizzleDatabase;
304
+ }
305
+
306
+ export class DrizzleInfrastructureService {
307
+ readonly db = drizzleDatabase;
308
+ }
309
+ `;
310
+ const drizzleWiring = `import { wireClass } from '@domain-first/wire';
311
+ import { DrizzleInfrastructureService } from '../../infrastructure/services/drizzle-infrastructure-service';
312
+
313
+ export const wireDrizzleInfrastructureService = wireClass(
314
+ DrizzleInfrastructureService,
315
+ []
316
+ );
317
+ `;
318
+ const stageFile = (filePath, content)=>{
319
+ const file = new File(filePath);
320
+ if (!file.exists || file.data !== content) file.data = content;
321
+ };
322
+ const addDrizzle = async ()=>{
323
+ const config = ConfigFile.Instance.data;
324
+ const root = new ProjectRoot().path;
325
+ const manifestFile = new File(node_path.join(root, 'package.json'));
326
+ const manifest = JSON.parse(manifestFile.data);
327
+ const dependencies = {
328
+ ...manifest.dependencies,
329
+ ...manifest.devDependencies
330
+ };
331
+ const shared = node_path.resolve(root, config.project.rootFolder, 'shared-kernel');
332
+ const folder = node_path.join(shared, 'infrastructure/drizzle');
333
+ if ([
334
+ 'drizzle.config.ts',
335
+ 'drizzle.config.js',
336
+ 'drizzle.config.json'
337
+ ].some((name)=>new File(node_path.join(root, name)).exists)) throw new Error('This preset adds Drizzle for PostgreSQL in the Shared Kernel. Move the existing Drizzle setup separately before using it.');
338
+ const withService = await interaction_confirm({
339
+ key: 'withService',
340
+ message: 'Create the Drizzle infrastructure service in the Shared Kernel?',
341
+ default: true
342
+ });
343
+ const selected = await addPackageScripts(manifestFile, drizzleScripts(config.project.rootFolder));
344
+ stageFile(node_path.join(folder, 'drizzle.config.ts'), drizzleConfig(config.project.rootFolder));
345
+ const schema = new File(node_path.join(folder, 'schema.ts'));
346
+ if (!schema.exists) schema.data = drizzleSchema;
347
+ if (withService) {
348
+ stageFile(node_path.join(shared, 'infrastructure/services/drizzle-infrastructure-service.ts'), drizzleService);
349
+ if (ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) stageFile(node_path.join(shared, 'wiring/infrastructure-services/wire-drizzle-infrastructure-service.ts'), drizzleWiring);
350
+ }
351
+ for (const kind of [
352
+ 'repositories',
353
+ 'commands',
354
+ 'queries'
355
+ ])rememberImplementation(kind, 'primary', 'drizzle');
356
+ const install = (packages, dev)=>{
357
+ const missing = packages.filter((name)=>!dependencies[name]);
358
+ return missing.length ? [
359
+ `npm install${dev ? ' --save-dev' : ''} ${missing.join(' ')}`
360
+ ] : [];
361
+ };
362
+ const relativeFolder = node_path.relative(root, folder).split(node_path.sep).join('/');
363
+ return [
364
+ ...install(runtimePackages, false),
365
+ ...install(developmentPackages, true),
366
+ `Add !${relativeFolder}/migrations in your linter, to ignore generated migrations.`,
367
+ ...describeScripts(selected, {
368
+ 'drizzle:generate': 'generate a SQL migration from changes in schema.ts',
369
+ 'drizzle:migrate': 'apply generated migrations to the database in DATABASE_URL'
370
+ })
371
+ ];
372
+ };
373
+ const addInMemoryDb = ()=>{
374
+ const config = ConfigFile.Instance.data;
375
+ if (!ConfigFile.backend.withInMemoryDb) ConfigFile.update({
376
+ backend: {
377
+ ...ConfigFile.backend,
378
+ withInMemoryDb: true
379
+ }
380
+ });
381
+ withoutOverwrites(()=>scaffoldInMemoryDb(new Folder(new ProjectRoot().path).subitem([
382
+ config.project.rootFolder,
383
+ 'shared-kernel'
384
+ ])));
385
+ return [];
386
+ };
387
+ const inMemoryDbApplied = ()=>Boolean(ConfigFile.Instance.data.backend?.withInMemoryDb) && inMemoryDbScaffolded();
393
388
  const usesNext = ()=>ConfigFile.exists && ConfigFile.Instance.data.frontend?.react?.framework === 'next';
394
389
  const nextAppFolder = (root)=>[
395
390
  'app',
@@ -458,43 +453,6 @@ const scaffoldReactPage = async (presentationReactFolder)=>{
458
453
  ]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
459
454
  if (usesNext()) scaffoldNextRoute(nestedName, pageFile);
460
455
  };
461
- const addPackageScripts = async (file, additions)=>{
462
- const original = file.data;
463
- const manifest = JSON.parse(original);
464
- const scripts = {
465
- ...manifest.scripts
466
- };
467
- const selected = {};
468
- for (const [name, command] of Object.entries(additions)){
469
- let target = name;
470
- if (Object.hasOwn(scripts, name) && scripts[name] !== command) {
471
- const action = await interaction_select({
472
- key: `scriptConflicts.${name}`,
473
- message: `Script "${name}" already exists: ${scripts[name]}`,
474
- choices: [
475
- 'Keep existing',
476
- 'Replace',
477
- 'Use another name'
478
- ]
479
- });
480
- if ('Keep existing' === action) continue;
481
- if ('Use another name' === action) target = await interaction_input({
482
- key: `scriptNames.${name}`,
483
- message: "New script name:",
484
- validate: (value)=>!/^[a-zA-Z0-9:_-]+$/.test(value) || Object.hasOwn(scripts, value) || Object.hasOwn(additions, value) ? "Enter an unused script name (letters, numbers, :, _, -)." : true
485
- });
486
- }
487
- scripts[target] = command;
488
- selected[name] = target;
489
- }
490
- if (JSON.stringify(manifest.scripts) !== JSON.stringify(scripts)) {
491
- manifest.scripts = scripts;
492
- const indent = original.match(/\n([\t ]+)"/)?.[1] ?? ' ';
493
- file.update(`${JSON.stringify(manifest, null, indent)}\n`);
494
- }
495
- return selected;
496
- };
497
- const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
498
456
  const openapiScriptPath = "scripts/generate-openapi.ts";
499
457
  const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
500
458
  const extractorPackages = [
@@ -936,40 +894,12 @@ const addPlaywright = async ()=>{
936
894
  })
937
895
  ];
938
896
  };
939
- const savedImplementations = (kind, purpose)=>[
940
- ...new Set(ConfigFile.Instance.data.backend?.implementations?.[kind]?.[purpose] ?? [])
941
- ];
942
- const rememberImplementation = (kind, purpose, label)=>{
943
- implementationLabelSchema.parse(label);
944
- const backend = ConfigFile.backend;
945
- const choices = {
946
- ...backend.implementations
947
- };
948
- const group = choices[kind] ?? {
949
- primary: [],
950
- test: []
951
- };
952
- if (group[purpose].includes(label)) return;
953
- choices[kind] = {
954
- ...group,
955
- [purpose]: [
956
- ...group[purpose],
957
- label
958
- ]
959
- };
960
- ConfigFile.update({
961
- backend: {
962
- ...backend,
963
- implementations: choices
964
- }
965
- });
966
- };
967
- const runtimePackages = [
897
+ const prisma_runtimePackages = [
968
898
  '@prisma/orm-postgres',
969
899
  'temporal-polyfill',
970
900
  'dotenv'
971
901
  ];
972
- const developmentPackages = [
902
+ const prisma_developmentPackages = [
973
903
  'prisma',
974
904
  '@prisma/cli-engine'
975
905
  ];
@@ -1028,7 +958,7 @@ export const wirePrismaInfrastructureService = wireClass(
1028
958
  []
1029
959
  );
1030
960
  `;
1031
- const stageFile = (filePath, content)=>{
961
+ const prisma_stageFile = (filePath, content)=>{
1032
962
  const file = new File(filePath);
1033
963
  if (!file.exists || file.data !== content) file.data = content;
1034
964
  };
@@ -1053,12 +983,12 @@ const addPrisma = async ()=>{
1053
983
  default: true
1054
984
  });
1055
985
  const selected = await addPackageScripts(manifestFile, prismaScripts(config.project.rootFolder));
1056
- stageFile(node_path.join(prismaFolder, 'prisma.config.ts'), prismaConfig);
986
+ prisma_stageFile(node_path.join(prismaFolder, 'prisma.config.ts'), prismaConfig);
1057
987
  const contract = new File(node_path.join(prismaFolder, 'contract.prisma'));
1058
988
  if (!contract.exists) contract.data = '// use prisma-8\n\n// Add your application models here before running prisma:emit.\n';
1059
989
  if (withService) {
1060
- stageFile(node_path.join(shared, 'infrastructure/services/prisma-infrastructure-service.ts'), prismaService);
1061
- if (ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) stageFile(node_path.join(shared, 'wiring/infrastructure-services/wire-prisma-infrastructure-service.ts'), prismaWiring);
990
+ prisma_stageFile(node_path.join(shared, 'infrastructure/services/prisma-infrastructure-service.ts'), prismaService);
991
+ if (ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) prisma_stageFile(node_path.join(shared, 'wiring/infrastructure-services/wire-prisma-infrastructure-service.ts'), prismaWiring);
1062
992
  }
1063
993
  for (const kind of [
1064
994
  'repositories',
@@ -1073,8 +1003,8 @@ const addPrisma = async ()=>{
1073
1003
  };
1074
1004
  const relativeFolder = node_path.relative(root, prismaFolder).split(node_path.sep).join('/');
1075
1005
  return [
1076
- ...install(runtimePackages, false),
1077
- ...install(developmentPackages, true),
1006
+ ...install(prisma_runtimePackages, false),
1007
+ ...install(prisma_developmentPackages, true),
1078
1008
  `Add !${relativeFolder} in your linter, to ignore prisma files.`,
1079
1009
  ...describeScripts(selected, {
1080
1010
  'prisma:emit': 'emit contract.json and contract.d.ts from contract.prisma',
@@ -2277,19 +2207,19 @@ export default defineConfig({
2277
2207
  });
2278
2208
  `;
2279
2209
  };
2280
- const testcontainersGlobalSetup = (migrationCommand)=>{
2281
- const migrations = migrationCommand ? `
2282
- // dotenv in the Prisma config does not override an already set variable
2283
- execSync(${JSON.stringify(migrationCommand)}, {
2210
+ const testcontainersGlobalSetup = (migrationCommands = [])=>{
2211
+ const migrations = migrationCommands.length ? `
2212
+ // dotenv in the ORM config does not override an already set variable
2213
+ ${migrationCommands.map((command)=>` execSync(${JSON.stringify(command)}, {
2284
2214
  cwd: project.config.root,
2285
2215
  env: { ...process.env, DATABASE_URL: databaseUrl },
2286
2216
  // On failure the error carries the command's output
2287
2217
  stdio: 'pipe'
2288
2218
  });
2289
- ` : `
2219
+ `).join('')}` : `
2290
2220
  // Apply your migrations to databaseUrl here.
2291
2221
  `;
2292
- return `${migrationCommand ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
2222
+ return `${migrationCommands.length ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
2293
2223
  import type { TestProject } from 'vitest/node';
2294
2224
 
2295
2225
  declare module 'vitest' {
@@ -2435,11 +2365,18 @@ const addTestcontainers = async ()=>{
2435
2365
  ...manifest.devDependencies
2436
2366
  };
2437
2367
  const selected = await addPackageScripts(manifestFile, testcontainersScripts);
2438
- const withPrisma = new File(node_path.resolve(root, config.project.rootFolder, 'shared-kernel/infrastructure/prisma/prisma.config.ts')).exists;
2439
- const migrationCommand = withPrisma ? `npx ${prismaScripts(config.project.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}` : void 0;
2368
+ const presetExists = (relativePath)=>new File(node_path.resolve(root, relativePath)).exists;
2369
+ const migrationCommands = [
2370
+ ...presetExists(node_path.join(config.project.rootFolder, 'shared-kernel/infrastructure/prisma/prisma.config.ts')) ? [
2371
+ `npx ${prismaScripts(config.project.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}`
2372
+ ] : [],
2373
+ ...presetExists(drizzleConfigPath(config.project.rootFolder)) ? [
2374
+ `npx ${drizzleScripts(config.project.rootFolder)['drizzle:migrate']}`
2375
+ ] : []
2376
+ ];
2440
2377
  const folder = node_path.join(root, integrationFolder);
2441
2378
  testcontainers_stageFile(node_path.join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
2442
- testcontainers_stageFile(node_path.join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommand));
2379
+ testcontainers_stageFile(node_path.join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommands));
2443
2380
  testcontainers_stageFile(node_path.join(folder, 'setup-env.ts'), testcontainersSetupEnv);
2444
2381
  const example = new File(node_path.join(folder, 'database/database.spec.ts'));
2445
2382
  if (!example.exists) example.data = testcontainers_exampleSpec;
@@ -2463,7 +2400,7 @@ const addTestcontainers = async ()=>{
2463
2400
  `npm install --save-dev ${missing.join(' ')}`
2464
2401
  ] : [],
2465
2402
  `Integration specs run against postgres:15 and get its address in DATABASE_URL. Change the image, credentials and connection string in ${integrationFolder}/global-setup.ts, and the variable name in ${integrationFolder}/setup-env.ts.`,
2466
- ...migrationCommand ? [] : [
2403
+ ...migrationCommands.length ? [] : [
2467
2404
  `Apply your migrations in ${integrationFolder}/global-setup.ts.`
2468
2405
  ],
2469
2406
  ...excludedFromUnitTests ? [] : [
@@ -2640,6 +2577,7 @@ const integrationIds = [
2640
2577
  'rest-endpoint-generator',
2641
2578
  'in-memory-db',
2642
2579
  'prisma',
2580
+ 'drizzle',
2643
2581
  'vitest',
2644
2582
  'playwright',
2645
2583
  'testcontainers',
@@ -2676,6 +2614,13 @@ const integrations = [
2676
2614
  run: addPrisma,
2677
2615
  applied: ()=>createdInRoot('shared-kernel/infrastructure/prisma/prisma.config.ts')
2678
2616
  },
2617
+ {
2618
+ id: 'drizzle',
2619
+ name: 'Drizzle (PostgreSQL)',
2620
+ group: 'backend',
2621
+ run: addDrizzle,
2622
+ applied: ()=>created(drizzleConfigPath(ConfigFile.Instance.data.project.rootFolder))
2623
+ },
2679
2624
  {
2680
2625
  id: 'vitest',
2681
2626
  name: 'Vitest',
package/dist/38.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import node_fs from "node:fs";
2
2
  import node_path from "node:path";
3
- import { namedImportFiles, canDependOn, isCrossContextImplementation, findWiredModules, moduleKindOf, readWiredModule, crossContextImportAllowed, wiredDependencyNames } from "./947.js";
4
- import { defaultDependencyRules, fileModuleKind, compilerOption } from "./780.js";
3
+ import { defaultDependencyRules, fileModuleKind, namedImportFiles, canDependOn, isCrossContextImplementation, findWiredModules, moduleKindOf, readWiredModule, crossContextImportAllowed, compilerOption, wiredDependencyNames } from "./201.js";
5
4
  const readAliases = (projectRoot)=>{
6
5
  const tsconfig = node_path.join(projectRoot, 'tsconfig.json');
7
6
  const paths = compilerOption(tsconfig, 'paths');
package/dist/561.js CHANGED
@@ -2,10 +2,9 @@ import node_fs from "node:fs";
2
2
  import node_path from "node:path";
3
3
  import { parseArgs } from "node:util";
4
4
  import zod from "zod";
5
- import { implementationLabelSchema, discardPendingChanges, filesToOverwrite, ConfigFile, Folder, implementationKinds, ProjectRoot, pendingChanges } from "./780.js";
5
+ import { implementationLabelSchema, availableDependencies, discardPendingChanges, findWiredModules, filesToOverwrite, ConfigFile, Folder, implementationKinds, ProjectRoot, pendingChanges, hasNeighboringBoundedContext } from "./201.js";
6
6
  import { scaffoldNewHandlersRestEndpoint, addIntegration, findContracts, helperImplementationTypes, scaffoldNewAggregateUseCase, scaffoldNewInfrastructureService, runWithAnswers, scaffoldNewCommand, scaffoldNewQuery, findReactModules, moveBackendUnitUseCase, scaffoldReactUIKitComponent, scaffoldReactSharedHook, moveReactModuleUseCase, reactKindTitles, deleteBackendUnitUseCase, integrationIds, scaffoldNewApplicationService, scaffoldNewImplementation, savedImplementations, RequestError, deleteReactModuleUseCase, rootControllerChoice, moduleId, assertAnswersConsumed, scaffoldNewDomainService, findRestEndpointGenerator, scaffoldNewErrorUseCase, scaffoldReactWidget, savePendingChanges, unitId, systemImplementationChoices, scaffoldReactPage, scaffoldNewPresentationService, scaffoldNewInfrastructureHelper, integrationSpecsAvailable, integrationSpecFile, findBackendUnits, scaffoldNewUseCase, integrationDescriptions, wireDependency, scaffoldNewDomainObject, scaffoldNewBoundedContextUseCase, scaffoldNewApplicationPort } from "./287.js";
7
- import { findWiredModules, availableDependencies, hasNeighboringBoundedContext } from "./947.js";
8
- import { restControllers } from "./526.js";
7
+ import { restControllers } from "./115.js";
9
8
  const agent_requests_name = implementationLabelSchema;
10
9
  const nestedName = zod.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*(?:\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*)*$/);
11
10
  const id = zod.string().min(1);