@domain-first/project-structure 8.8.0 → 8.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/287.js CHANGED
@@ -4,10 +4,373 @@ import { Separator, checkbox as prompts_checkbox, confirm as prompts_confirm, in
4
4
  import node_fs from "node:fs";
5
5
  import { styleText } from "node:util";
6
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";
7
+ import { implementationLabelSchema, withoutOverwrites, domainFirstPackages as config_file_domainFirstPackages, scaffoldBackendRules, branchNameSchema, discardPendingChanges, ConfigFile, filesToOverwrite, Folder, implementationKinds, writePendingChanges, File, ProjectRoot, compilerOption } from "./780.js";
8
8
  import { missingDomainFirstPackages, walk, projectImports, escapeRegExp, pathParameterAsName, hasLegacyRootEndpoints, stageModuleMove, toPosix, rootStaticSegments, openapiExtractorPath, restControllers, hasDependency, openapiExtractor, missingPackages, codeExtension, isPathParameterName } from "./526.js";
9
9
  const moduleId = (module)=>`${boundedContextLocation(module.typeFile)?.name ?? 'shared-kernel'}:${module.typeName}`;
10
10
  const unitId = (unit)=>`${unit.kind}:${unit.aggregate ? `${unit.aggregate}/` : ''}${unit.name}`;
11
+ const savedImplementations = (kind, purpose)=>[
12
+ ...new Set(ConfigFile.Instance.data.backend?.implementations?.[kind]?.[purpose] ?? [])
13
+ ];
14
+ const rememberImplementation = (kind, purpose, label)=>{
15
+ implementationLabelSchema.parse(label);
16
+ const backend = ConfigFile.backend;
17
+ const choices = {
18
+ ...backend.implementations
19
+ };
20
+ const group = choices[kind] ?? {
21
+ primary: [],
22
+ test: []
23
+ };
24
+ if (group[purpose].includes(label)) return;
25
+ choices[kind] = {
26
+ ...group,
27
+ [purpose]: [
28
+ ...group[purpose],
29
+ label
30
+ ]
31
+ };
32
+ ConfigFile.update({
33
+ backend: {
34
+ ...backend,
35
+ implementations: choices
36
+ }
37
+ });
38
+ };
39
+ const isSeparator = (choice)=>'function' == typeof Separator && choice instanceof Separator || 'object' == typeof choice && null !== choice && 'separator' === choice.type;
40
+ class RequestError extends Error {
41
+ code;
42
+ details;
43
+ constructor(code, message, details){
44
+ super(message), this.code = code, this.details = details;
45
+ }
46
+ }
47
+ const storage = new AsyncLocalStorage();
48
+ const isNonInteractive = ()=>Boolean(storage.getStore());
49
+ const runWithAnswers = async (answers, defaults, run)=>storage.run({
50
+ answers,
51
+ defaults,
52
+ used: new Set(),
53
+ messages: []
54
+ }, async ()=>{
55
+ const result = await run();
56
+ const state = storage.getStore();
57
+ assertAnswersConsumed();
58
+ return {
59
+ result,
60
+ messages: state.messages
61
+ };
62
+ });
63
+ const assertAnswersConsumed = ()=>{
64
+ const state = storage.getStore();
65
+ if (!state) return;
66
+ const unused = Object.keys(state.answers).filter((key)=>!state.used.has(key));
67
+ if (unused.length) throw new RequestError('UNUSED_PARAMETERS', 'Some parameters do not apply to this operation.', {
68
+ fields: unused
69
+ });
70
+ };
71
+ const answerFor = (key, fallback)=>{
72
+ const state = storage.getStore();
73
+ if (!state) return;
74
+ if (Object.hasOwn(state.answers, key)) {
75
+ state.used.add(key);
76
+ return state.answers[key];
77
+ }
78
+ return Object.hasOwn(state.defaults, key) ? state.defaults[key] : fallback;
79
+ };
80
+ const report = (...values)=>{
81
+ const state = storage.getStore();
82
+ if (state) state.messages.push(values.map(String).join(' '));
83
+ else console.log(...values);
84
+ };
85
+ const requireKey = (key)=>{
86
+ if (!key) throw new RequestError('UNSUPPORTED_PROMPT', 'This operation needs an answer that is not supported in non-interactive mode.');
87
+ return key;
88
+ };
89
+ const interaction_missing = (key)=>new RequestError('MISSING_PARAMETER', `Provide ${key}.`, {
90
+ field: key
91
+ });
92
+ const interaction_input = async (config)=>{
93
+ const { key, ...interactive } = config;
94
+ if (!isNonInteractive()) return input(interactive);
95
+ const field = requireKey(key);
96
+ const value = answerFor(field, config.default);
97
+ if ('string' != typeof value) throw interaction_missing(field);
98
+ const valid = await config.validate?.(value);
99
+ if (void 0 !== valid && true !== valid) throw new RequestError('INVALID_PARAMETER', 'string' == typeof valid ? valid : `Invalid ${field}.`, {
100
+ field
101
+ });
102
+ return value;
103
+ };
104
+ const interaction_confirm = async (config)=>{
105
+ const { key, requestRequired, ...interactive } = config;
106
+ if (!isNonInteractive()) return prompts_confirm(interactive);
107
+ const field = requireKey(key);
108
+ const value = answerFor(field, requestRequired ? void 0 : config.default ?? false);
109
+ if (void 0 === value) throw interaction_missing(field);
110
+ if ('boolean' != typeof value) throw new RequestError('INVALID_PARAMETER', `${field} must be a boolean.`, {
111
+ field
112
+ });
113
+ return value;
114
+ };
115
+ const choicesOf = (config)=>config.choices.filter((choice)=>!isSeparator(choice)).map((choice)=>'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
116
+ value: choice
117
+ });
118
+ const choiceId = (choice, id)=>id?.(choice.value) ?? choice.value;
119
+ const resolveChoice = (value, choices, key, id)=>{
120
+ const matches = choices.filter((choice)=>Object.is(choice.value, value) || choiceId(choice, id) === value);
121
+ if (1 !== matches.length || matches[0].disabled) throw new RequestError('INVALID_CHOICE', `Invalid or unavailable choice for ${key}.`, {
122
+ field: key,
123
+ value,
124
+ choices: choices.filter((choice)=>!choice.disabled).map((choice)=>choiceId(choice, id))
125
+ });
126
+ return matches[0].value;
127
+ };
128
+ const searchThreshold = 10;
129
+ const choiceLabel = (choice)=>choice.name ?? String(choice.value);
130
+ const filterChoices = (choices, term)=>{
131
+ const text = (term ?? '').trim().toLowerCase();
132
+ const words = text.split(/\s+/).filter(Boolean);
133
+ if (!words.length) return [
134
+ ...choices
135
+ ];
136
+ const groups = [
137
+ {
138
+ matches: []
139
+ }
140
+ ];
141
+ for (const choice of choices){
142
+ if (isSeparator(choice)) {
143
+ groups.push({
144
+ separator: choice,
145
+ matches: []
146
+ });
147
+ continue;
148
+ }
149
+ const normalized = 'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
150
+ value: choice
151
+ };
152
+ const label = choiceLabel(normalized).toLowerCase();
153
+ if (words.every((word)=>label.includes(word))) groups.at(-1)?.matches.push({
154
+ choice: normalized,
155
+ prefix: label.startsWith(text)
156
+ });
157
+ }
158
+ const byPrefix = (items, prefix)=>[
159
+ ...items.filter(prefix),
160
+ ...items.filter((item)=>!prefix(item))
161
+ ];
162
+ const [ungrouped, ...grouped] = groups;
163
+ return [
164
+ ungrouped,
165
+ ...byPrefix(grouped.filter(({ matches })=>matches.length), ({ matches })=>matches.some(({ prefix })=>prefix))
166
+ ].flatMap(({ separator, matches })=>[
167
+ ...separator ? [
168
+ separator
169
+ ] : [],
170
+ ...byPrefix(matches, ({ prefix })=>prefix).map(({ choice })=>choice)
171
+ ]);
172
+ };
173
+ const interaction_select = async (config)=>{
174
+ const { key, id, ...interactive } = config;
175
+ if (!isNonInteractive()) {
176
+ if (choicesOf(config).length <= searchThreshold) return prompts_select(interactive);
177
+ return search({
178
+ message: `${config.message.trimEnd()} (type to filter)`,
179
+ source: (term)=>filterChoices(config.choices, term),
180
+ pageSize: config.pageSize,
181
+ default: config.default
182
+ });
183
+ }
184
+ const field = requireKey(key);
185
+ const value = answerFor(field, config.default);
186
+ if (void 0 === value) throw interaction_missing(field);
187
+ return resolveChoice(value, choicesOf(config), field, id);
188
+ };
189
+ const interaction_checkbox = async (config)=>{
190
+ const { key, id, ...interactive } = config;
191
+ if (!isNonInteractive()) return prompts_checkbox(interactive);
192
+ const field = requireKey(key);
193
+ const choices = choicesOf(config);
194
+ const values = answerFor(field, choices.filter((choice)=>choice.checked && !choice.disabled).map((choice)=>choice.value));
195
+ if (!Array.isArray(values)) throw new RequestError('INVALID_PARAMETER', `${field} must be an array.`, {
196
+ field
197
+ });
198
+ const selected = values.map((value)=>resolveChoice(value, choices, field, id));
199
+ if (new Set(selected).size !== selected.length) throw new RequestError('INVALID_PARAMETER', `Duplicate choices for ${field}.`, {
200
+ field
201
+ });
202
+ if (config.required && !selected.length) throw interaction_missing(field);
203
+ return selected;
204
+ };
205
+ const addPackageScripts = async (file, additions)=>{
206
+ const original = file.data;
207
+ const manifest = JSON.parse(original);
208
+ const scripts = {
209
+ ...manifest.scripts
210
+ };
211
+ const selected = {};
212
+ for (const [name, command] of Object.entries(additions)){
213
+ let target = name;
214
+ if (Object.hasOwn(scripts, name) && scripts[name] !== command) {
215
+ const action = await interaction_select({
216
+ key: `scriptConflicts.${name}`,
217
+ message: `Script "${name}" already exists: ${scripts[name]}`,
218
+ choices: [
219
+ 'Keep existing',
220
+ 'Replace',
221
+ 'Use another name'
222
+ ]
223
+ });
224
+ if ('Keep existing' === action) continue;
225
+ if ('Use another name' === action) target = await interaction_input({
226
+ key: `scriptNames.${name}`,
227
+ message: "New script name:",
228
+ validate: (value)=>!/^[a-zA-Z0-9:_-]+$/.test(value) || Object.hasOwn(scripts, value) || Object.hasOwn(additions, value) ? "Enter an unused script name (letters, numbers, :, _, -)." : true
229
+ });
230
+ }
231
+ scripts[target] = command;
232
+ selected[name] = target;
233
+ }
234
+ if (JSON.stringify(manifest.scripts) !== JSON.stringify(scripts)) {
235
+ manifest.scripts = scripts;
236
+ const indent = original.match(/\n([\t ]+)"/)?.[1] ?? ' ';
237
+ file.update(`${JSON.stringify(manifest, null, indent)}\n`);
238
+ }
239
+ return selected;
240
+ };
241
+ const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
242
+ const runtimePackages = [
243
+ 'drizzle-orm',
244
+ 'pg',
245
+ 'dotenv'
246
+ ];
247
+ const developmentPackages = [
248
+ 'drizzle-kit',
249
+ '@types/pg'
250
+ ];
251
+ const drizzleFolder = (rootFolder)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'shared-kernel/infrastructure/drizzle');
252
+ const drizzleConfigPath = (rootFolder)=>node_path.posix.join(drizzleFolder(rootFolder), 'drizzle.config.ts');
253
+ const drizzleScripts = (rootFolder)=>{
254
+ const config = JSON.stringify(drizzleConfigPath(rootFolder));
255
+ return {
256
+ 'drizzle:generate': `drizzle-kit generate --config ${config}`,
257
+ 'drizzle:migrate': `drizzle-kit migrate --config ${config}`
258
+ };
259
+ };
260
+ const drizzleConfig = (rootFolder)=>{
261
+ const folder = drizzleFolder(rootFolder);
262
+ return `import 'dotenv/config';
263
+ import { defineConfig } from 'drizzle-kit';
264
+
265
+ // Paths are relative to the project root, where package scripts run.
266
+ export default defineConfig({
267
+ dialect: 'postgresql',
268
+ schema: ${JSON.stringify(node_path.posix.join(folder, 'schema.ts'))},
269
+ out: ${JSON.stringify(node_path.posix.join(folder, 'migrations'))},
270
+ dbCredentials: {
271
+ url: process.env.DATABASE_URL as string
272
+ }
273
+ });
274
+ `;
275
+ };
276
+ const drizzleSchema = `// Add your application tables here before running drizzle:generate, e.g.
277
+ //
278
+ // import { pgTable, text } from 'drizzle-orm/pg-core';
279
+ //
280
+ // export const orders = pgTable('orders', {
281
+ // id: text('id').primaryKey()
282
+ // });
283
+
284
+ export {};
285
+ `;
286
+ const drizzleService = `import { drizzle } from 'drizzle-orm/node-postgres';
287
+ import { Pool } from 'pg';
288
+
289
+ const createDatabase = () =>
290
+ drizzle({
291
+ client: new Pool({ connectionString: process.env.DATABASE_URL })
292
+ });
293
+
294
+ type DrizzleDatabase = ReturnType<typeof createDatabase>;
295
+
296
+ const globalForDrizzle = globalThis as typeof globalThis & {
297
+ drizzleDatabase?: DrizzleDatabase;
298
+ };
299
+
300
+ // Reuse the connection pool across development hot reloads.
301
+ const drizzleDatabase = globalForDrizzle.drizzleDatabase ?? createDatabase();
302
+
303
+ if (process.env.NODE_ENV !== 'production') {
304
+ globalForDrizzle.drizzleDatabase = drizzleDatabase;
305
+ }
306
+
307
+ export class DrizzleInfrastructureService {
308
+ readonly db = drizzleDatabase;
309
+ }
310
+ `;
311
+ const drizzleWiring = `import { wireClass } from '@domain-first/wire';
312
+ import { DrizzleInfrastructureService } from '../../infrastructure/services/drizzle-infrastructure-service';
313
+
314
+ export const wireDrizzleInfrastructureService = wireClass(
315
+ DrizzleInfrastructureService,
316
+ []
317
+ );
318
+ `;
319
+ const stageFile = (filePath, content)=>{
320
+ const file = new File(filePath);
321
+ if (!file.exists || file.data !== content) file.data = content;
322
+ };
323
+ const addDrizzle = async ()=>{
324
+ const config = ConfigFile.Instance.data;
325
+ const root = new ProjectRoot().path;
326
+ const manifestFile = new File(node_path.join(root, 'package.json'));
327
+ const manifest = JSON.parse(manifestFile.data);
328
+ const dependencies = {
329
+ ...manifest.dependencies,
330
+ ...manifest.devDependencies
331
+ };
332
+ const shared = node_path.resolve(root, config.project.rootFolder, 'shared-kernel');
333
+ const folder = node_path.join(shared, 'infrastructure/drizzle');
334
+ if ([
335
+ 'drizzle.config.ts',
336
+ 'drizzle.config.js',
337
+ 'drizzle.config.json'
338
+ ].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.');
339
+ const withService = await interaction_confirm({
340
+ key: 'withService',
341
+ message: 'Create the Drizzle infrastructure service in the Shared Kernel?',
342
+ default: true
343
+ });
344
+ const selected = await addPackageScripts(manifestFile, drizzleScripts(config.project.rootFolder));
345
+ stageFile(node_path.join(folder, 'drizzle.config.ts'), drizzleConfig(config.project.rootFolder));
346
+ const schema = new File(node_path.join(folder, 'schema.ts'));
347
+ if (!schema.exists) schema.data = drizzleSchema;
348
+ if (withService) {
349
+ stageFile(node_path.join(shared, 'infrastructure/services/drizzle-infrastructure-service.ts'), drizzleService);
350
+ if (ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) stageFile(node_path.join(shared, 'wiring/infrastructure-services/wire-drizzle-infrastructure-service.ts'), drizzleWiring);
351
+ }
352
+ for (const kind of [
353
+ 'repositories',
354
+ 'commands',
355
+ 'queries'
356
+ ])rememberImplementation(kind, 'primary', 'drizzle');
357
+ const install = (packages, dev)=>{
358
+ const missing = packages.filter((name)=>!dependencies[name]);
359
+ return missing.length ? [
360
+ `npm install${dev ? ' --save-dev' : ''} ${missing.join(' ')}`
361
+ ] : [];
362
+ };
363
+ const relativeFolder = node_path.relative(root, folder).split(node_path.sep).join('/');
364
+ return [
365
+ ...install(runtimePackages, false),
366
+ ...install(developmentPackages, true),
367
+ `Add !${relativeFolder}/migrations in your linter, to ignore generated migrations.`,
368
+ ...describeScripts(selected, {
369
+ 'drizzle:generate': 'generate a SQL migration from changes in schema.ts',
370
+ 'drizzle:migrate': 'apply generated migrations to the database in DATABASE_URL'
371
+ })
372
+ ];
373
+ };
11
374
  const inMemoryImplementationType = 'in-memory';
12
375
  const in_memory_db_className = 'InMemoryDbInfrastructureService';
13
376
  const in_memory_db_wireName = 'wireInMemoryDbInfrastructureService';
@@ -224,172 +587,6 @@ const addInMemoryDb = ()=>{
224
587
  return [];
225
588
  };
226
589
  const inMemoryDbApplied = ()=>Boolean(ConfigFile.Instance.data.backend?.withInMemoryDb) && inMemoryDbScaffolded();
227
- const isSeparator = (choice)=>'function' == typeof Separator && choice instanceof Separator || 'object' == typeof choice && null !== choice && 'separator' === choice.type;
228
- class RequestError extends Error {
229
- code;
230
- details;
231
- constructor(code, message, details){
232
- super(message), this.code = code, this.details = details;
233
- }
234
- }
235
- const storage = new AsyncLocalStorage();
236
- const isNonInteractive = ()=>Boolean(storage.getStore());
237
- const runWithAnswers = async (answers, defaults, run)=>storage.run({
238
- answers,
239
- defaults,
240
- used: new Set(),
241
- messages: []
242
- }, async ()=>{
243
- const result = await run();
244
- const state = storage.getStore();
245
- assertAnswersConsumed();
246
- return {
247
- result,
248
- messages: state.messages
249
- };
250
- });
251
- const assertAnswersConsumed = ()=>{
252
- const state = storage.getStore();
253
- if (!state) return;
254
- const unused = Object.keys(state.answers).filter((key)=>!state.used.has(key));
255
- if (unused.length) throw new RequestError('UNUSED_PARAMETERS', 'Some parameters do not apply to this operation.', {
256
- fields: unused
257
- });
258
- };
259
- const answerFor = (key, fallback)=>{
260
- const state = storage.getStore();
261
- if (!state) return;
262
- if (Object.hasOwn(state.answers, key)) {
263
- state.used.add(key);
264
- return state.answers[key];
265
- }
266
- return Object.hasOwn(state.defaults, key) ? state.defaults[key] : fallback;
267
- };
268
- const report = (...values)=>{
269
- const state = storage.getStore();
270
- if (state) state.messages.push(values.map(String).join(' '));
271
- else console.log(...values);
272
- };
273
- const requireKey = (key)=>{
274
- if (!key) throw new RequestError('UNSUPPORTED_PROMPT', 'This operation needs an answer that is not supported in non-interactive mode.');
275
- return key;
276
- };
277
- const interaction_missing = (key)=>new RequestError('MISSING_PARAMETER', `Provide ${key}.`, {
278
- field: key
279
- });
280
- const interaction_input = async (config)=>{
281
- const { key, ...interactive } = config;
282
- if (!isNonInteractive()) return input(interactive);
283
- const field = requireKey(key);
284
- const value = answerFor(field, config.default);
285
- if ('string' != typeof value) throw interaction_missing(field);
286
- const valid = await config.validate?.(value);
287
- if (void 0 !== valid && true !== valid) throw new RequestError('INVALID_PARAMETER', 'string' == typeof valid ? valid : `Invalid ${field}.`, {
288
- field
289
- });
290
- return value;
291
- };
292
- const interaction_confirm = async (config)=>{
293
- const { key, requestRequired, ...interactive } = config;
294
- if (!isNonInteractive()) return prompts_confirm(interactive);
295
- const field = requireKey(key);
296
- const value = answerFor(field, requestRequired ? void 0 : config.default ?? false);
297
- if (void 0 === value) throw interaction_missing(field);
298
- if ('boolean' != typeof value) throw new RequestError('INVALID_PARAMETER', `${field} must be a boolean.`, {
299
- field
300
- });
301
- return value;
302
- };
303
- const choicesOf = (config)=>config.choices.filter((choice)=>!isSeparator(choice)).map((choice)=>'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
304
- value: choice
305
- });
306
- const choiceId = (choice, id)=>id?.(choice.value) ?? choice.value;
307
- const resolveChoice = (value, choices, key, id)=>{
308
- const matches = choices.filter((choice)=>Object.is(choice.value, value) || choiceId(choice, id) === value);
309
- if (1 !== matches.length || matches[0].disabled) throw new RequestError('INVALID_CHOICE', `Invalid or unavailable choice for ${key}.`, {
310
- field: key,
311
- value,
312
- choices: choices.filter((choice)=>!choice.disabled).map((choice)=>choiceId(choice, id))
313
- });
314
- return matches[0].value;
315
- };
316
- const searchThreshold = 10;
317
- const choiceLabel = (choice)=>choice.name ?? String(choice.value);
318
- const filterChoices = (choices, term)=>{
319
- const text = (term ?? '').trim().toLowerCase();
320
- const words = text.split(/\s+/).filter(Boolean);
321
- if (!words.length) return [
322
- ...choices
323
- ];
324
- const groups = [
325
- {
326
- matches: []
327
- }
328
- ];
329
- for (const choice of choices){
330
- if (isSeparator(choice)) {
331
- groups.push({
332
- separator: choice,
333
- matches: []
334
- });
335
- continue;
336
- }
337
- const normalized = 'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
338
- value: choice
339
- };
340
- const label = choiceLabel(normalized).toLowerCase();
341
- if (words.every((word)=>label.includes(word))) groups.at(-1)?.matches.push({
342
- choice: normalized,
343
- prefix: label.startsWith(text)
344
- });
345
- }
346
- const byPrefix = (items, prefix)=>[
347
- ...items.filter(prefix),
348
- ...items.filter((item)=>!prefix(item))
349
- ];
350
- const [ungrouped, ...grouped] = groups;
351
- return [
352
- ungrouped,
353
- ...byPrefix(grouped.filter(({ matches })=>matches.length), ({ matches })=>matches.some(({ prefix })=>prefix))
354
- ].flatMap(({ separator, matches })=>[
355
- ...separator ? [
356
- separator
357
- ] : [],
358
- ...byPrefix(matches, ({ prefix })=>prefix).map(({ choice })=>choice)
359
- ]);
360
- };
361
- const interaction_select = async (config)=>{
362
- const { key, id, ...interactive } = config;
363
- if (!isNonInteractive()) {
364
- if (choicesOf(config).length <= searchThreshold) return prompts_select(interactive);
365
- return search({
366
- message: `${config.message.trimEnd()} (type to filter)`,
367
- source: (term)=>filterChoices(config.choices, term),
368
- pageSize: config.pageSize,
369
- default: config.default
370
- });
371
- }
372
- const field = requireKey(key);
373
- const value = answerFor(field, config.default);
374
- if (void 0 === value) throw interaction_missing(field);
375
- return resolveChoice(value, choicesOf(config), field, id);
376
- };
377
- const interaction_checkbox = async (config)=>{
378
- const { key, id, ...interactive } = config;
379
- if (!isNonInteractive()) return prompts_checkbox(interactive);
380
- const field = requireKey(key);
381
- const choices = choicesOf(config);
382
- const values = answerFor(field, choices.filter((choice)=>choice.checked && !choice.disabled).map((choice)=>choice.value));
383
- if (!Array.isArray(values)) throw new RequestError('INVALID_PARAMETER', `${field} must be an array.`, {
384
- field
385
- });
386
- const selected = values.map((value)=>resolveChoice(value, choices, field, id));
387
- if (new Set(selected).size !== selected.length) throw new RequestError('INVALID_PARAMETER', `Duplicate choices for ${field}.`, {
388
- field
389
- });
390
- if (config.required && !selected.length) throw interaction_missing(field);
391
- return selected;
392
- };
393
590
  const usesNext = ()=>ConfigFile.exists && ConfigFile.Instance.data.frontend?.react?.framework === 'next';
394
591
  const nextAppFolder = (root)=>[
395
592
  'app',
@@ -458,43 +655,6 @@ const scaffoldReactPage = async (presentationReactFolder)=>{
458
655
  ]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
459
656
  if (usesNext()) scaffoldNextRoute(nestedName, pageFile);
460
657
  };
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
658
  const openapiScriptPath = "scripts/generate-openapi.ts";
499
659
  const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
500
660
  const extractorPackages = [
@@ -936,40 +1096,12 @@ const addPlaywright = async ()=>{
936
1096
  })
937
1097
  ];
938
1098
  };
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 = [
1099
+ const prisma_runtimePackages = [
968
1100
  '@prisma/orm-postgres',
969
1101
  'temporal-polyfill',
970
1102
  'dotenv'
971
1103
  ];
972
- const developmentPackages = [
1104
+ const prisma_developmentPackages = [
973
1105
  'prisma',
974
1106
  '@prisma/cli-engine'
975
1107
  ];
@@ -1028,7 +1160,7 @@ export const wirePrismaInfrastructureService = wireClass(
1028
1160
  []
1029
1161
  );
1030
1162
  `;
1031
- const stageFile = (filePath, content)=>{
1163
+ const prisma_stageFile = (filePath, content)=>{
1032
1164
  const file = new File(filePath);
1033
1165
  if (!file.exists || file.data !== content) file.data = content;
1034
1166
  };
@@ -1053,12 +1185,12 @@ const addPrisma = async ()=>{
1053
1185
  default: true
1054
1186
  });
1055
1187
  const selected = await addPackageScripts(manifestFile, prismaScripts(config.project.rootFolder));
1056
- stageFile(node_path.join(prismaFolder, 'prisma.config.ts'), prismaConfig);
1188
+ prisma_stageFile(node_path.join(prismaFolder, 'prisma.config.ts'), prismaConfig);
1057
1189
  const contract = new File(node_path.join(prismaFolder, 'contract.prisma'));
1058
1190
  if (!contract.exists) contract.data = '// use prisma-8\n\n// Add your application models here before running prisma:emit.\n';
1059
1191
  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);
1192
+ prisma_stageFile(node_path.join(shared, 'infrastructure/services/prisma-infrastructure-service.ts'), prismaService);
1193
+ if (ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) prisma_stageFile(node_path.join(shared, 'wiring/infrastructure-services/wire-prisma-infrastructure-service.ts'), prismaWiring);
1062
1194
  }
1063
1195
  for (const kind of [
1064
1196
  'repositories',
@@ -1073,8 +1205,8 @@ const addPrisma = async ()=>{
1073
1205
  };
1074
1206
  const relativeFolder = node_path.relative(root, prismaFolder).split(node_path.sep).join('/');
1075
1207
  return [
1076
- ...install(runtimePackages, false),
1077
- ...install(developmentPackages, true),
1208
+ ...install(prisma_runtimePackages, false),
1209
+ ...install(prisma_developmentPackages, true),
1078
1210
  `Add !${relativeFolder} in your linter, to ignore prisma files.`,
1079
1211
  ...describeScripts(selected, {
1080
1212
  'prisma:emit': 'emit contract.json and contract.d.ts from contract.prisma',
@@ -2277,19 +2409,19 @@ export default defineConfig({
2277
2409
  });
2278
2410
  `;
2279
2411
  };
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)}, {
2412
+ const testcontainersGlobalSetup = (migrationCommands = [])=>{
2413
+ const migrations = migrationCommands.length ? `
2414
+ // dotenv in the ORM config does not override an already set variable
2415
+ ${migrationCommands.map((command)=>` execSync(${JSON.stringify(command)}, {
2284
2416
  cwd: project.config.root,
2285
2417
  env: { ...process.env, DATABASE_URL: databaseUrl },
2286
2418
  // On failure the error carries the command's output
2287
2419
  stdio: 'pipe'
2288
2420
  });
2289
- ` : `
2421
+ `).join('')}` : `
2290
2422
  // Apply your migrations to databaseUrl here.
2291
2423
  `;
2292
- return `${migrationCommand ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
2424
+ return `${migrationCommands.length ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
2293
2425
  import type { TestProject } from 'vitest/node';
2294
2426
 
2295
2427
  declare module 'vitest' {
@@ -2435,11 +2567,18 @@ const addTestcontainers = async ()=>{
2435
2567
  ...manifest.devDependencies
2436
2568
  };
2437
2569
  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;
2570
+ const presetExists = (relativePath)=>new File(node_path.resolve(root, relativePath)).exists;
2571
+ const migrationCommands = [
2572
+ ...presetExists(node_path.join(config.project.rootFolder, 'shared-kernel/infrastructure/prisma/prisma.config.ts')) ? [
2573
+ `npx ${prismaScripts(config.project.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}`
2574
+ ] : [],
2575
+ ...presetExists(drizzleConfigPath(config.project.rootFolder)) ? [
2576
+ `npx ${drizzleScripts(config.project.rootFolder)['drizzle:migrate']}`
2577
+ ] : []
2578
+ ];
2440
2579
  const folder = node_path.join(root, integrationFolder);
2441
2580
  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));
2581
+ testcontainers_stageFile(node_path.join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommands));
2443
2582
  testcontainers_stageFile(node_path.join(folder, 'setup-env.ts'), testcontainersSetupEnv);
2444
2583
  const example = new File(node_path.join(folder, 'database/database.spec.ts'));
2445
2584
  if (!example.exists) example.data = testcontainers_exampleSpec;
@@ -2463,7 +2602,7 @@ const addTestcontainers = async ()=>{
2463
2602
  `npm install --save-dev ${missing.join(' ')}`
2464
2603
  ] : [],
2465
2604
  `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 ? [] : [
2605
+ ...migrationCommands.length ? [] : [
2467
2606
  `Apply your migrations in ${integrationFolder}/global-setup.ts.`
2468
2607
  ],
2469
2608
  ...excludedFromUnitTests ? [] : [
@@ -2640,6 +2779,7 @@ const integrationIds = [
2640
2779
  'rest-endpoint-generator',
2641
2780
  'in-memory-db',
2642
2781
  'prisma',
2782
+ 'drizzle',
2643
2783
  'vitest',
2644
2784
  'playwright',
2645
2785
  'testcontainers',
@@ -2676,6 +2816,13 @@ const integrations = [
2676
2816
  run: addPrisma,
2677
2817
  applied: ()=>createdInRoot('shared-kernel/infrastructure/prisma/prisma.config.ts')
2678
2818
  },
2819
+ {
2820
+ id: 'drizzle',
2821
+ name: 'Drizzle (PostgreSQL)',
2822
+ group: 'backend',
2823
+ run: addDrizzle,
2824
+ applied: ()=>created(drizzleConfigPath(ConfigFile.Instance.data.project.rootFolder))
2825
+ },
2679
2826
  {
2680
2827
  id: 'vitest',
2681
2828
  name: 'Vitest',