@domain-first/project-structure 2.12.0 → 2.13.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
@@ -203,6 +203,84 @@ Enable `useReact` and choose **Scaffold React module** from the main menu. Modul
203
203
 
204
204
  Page and widget names can include folders split by `/`. For example, a page named `admin/panel/users` is created at `pages/admin/panel/users-page.tsx` as `AdminPanelUsersPage`, and a widget with the same name at `widgets/admin/panel/users/` as `AdminPanelUsersWidget` with the story title `Widgets/Admin/Panel/Users`. File names use only the last segment; code names use the whole path.
205
205
 
206
+ ### Project integrations
207
+
208
+ Choose **Add integration → Storybook (React + Vite)** to configure Storybook.
209
+ The integration creates `main.ts` and `preview.ts` under
210
+ `<rootFolder>/presentation/react/.storybook`, enables React scaffolding and sets
211
+ `storybookFramework` to `@storybook/react-vite` for future generated stories.
212
+ It uses relative story paths and configures the Vite alias `@` to the absolute
213
+ project root (the directory containing `package.json`), computed at runtime
214
+ from the config location. Add project CSS to `preview.ts` with relative imports
215
+ or `@/` imports. The setup includes `@vitejs/plugin-react`.
216
+
217
+ It adds these package scripts, with paths adjusted to your `rootFolder`:
218
+
219
+ ```json
220
+ {
221
+ "storybook": "storybook dev -p 6006 -c \"src/presentation/react/.storybook\"",
222
+ "build-storybook": "storybook build -c \"src/presentation/react/.storybook\" -o \"src/presentation/react/storybook-static\""
223
+ }
224
+ ```
225
+
226
+ Existing unrelated scripts and package fields are preserved. If a script name
227
+ already has a different command, choose to keep it, replace it, or use another
228
+ name. Identical generated configs and scripts are skipped on subsequent runs;
229
+ changed config files use the usual overwrite confirmation. Cancelling before
230
+ writing leaves all files unchanged.
231
+
232
+ After writing, the CLI prints npm commands for missing dependencies and the
233
+ selected scripts. It does not install packages or execute scripts. Install commands omit version constraints for Storybook, its React + Vite
234
+ framework, Vite and the React plugin; existing dependency versions are preserved
235
+ and must be compatible with those packages. Generate a
236
+ UI-kit component or a widget with separated UI to add your first story. The
237
+ static build goes to `<rootFolder>/presentation/react/storybook-static`; the
238
+ integration adds this directory to the project `.gitignore` without duplicating
239
+ the entry on subsequent runs.
240
+
241
+ ### Missing domain-first packages
242
+
243
+ Choose **Add integration → Missing domain-first packages** to compare
244
+ `domainFirstPackages` in the configuration with `dependencies`, `devDependencies`
245
+ and `optionalDependencies` in the project's `package.json`. The CLI prints one
246
+ `npm i` command for missing packages, without version constraints. If none are
247
+ missing, it reports that all configured packages are already declared. This
248
+ checks declared dependencies, not the contents of `node_modules`, and does not
249
+ modify files or install packages.
250
+
251
+ ### Prisma 8 (PostgreSQL)
252
+
253
+ Choose **Add integration → Prisma 8 (PostgreSQL, RC)**. The preset creates
254
+ `<rootFolder>/shared/infrastructure/prisma/prisma.config.ts` and a starter
255
+ `contract.prisma`. Existing contracts are preserved, including your models.
256
+
257
+ You can optionally create `PrismaInfrastructureService` in
258
+ `shared/infrastructure/services`; it exposes `orm`, uses the Temporal polyfill,
259
+ and reuses the client across development hot reloads. When `@domain-first/wire`
260
+ is enabled, the integration also creates its wiring factory. A separate prompt
261
+ lets you make `prisma` the default persistence implementation.
262
+
263
+ The integration adds three scripts, all pointing to the generated config:
264
+
265
+ - `prisma:emit`: emit `contract.json` and `contract.d.ts`.
266
+ - `prisma:migration:plan`: emit the contract, then plan a migration.
267
+ - `prisma:migration:apply`: apply migrations and advance the `db` ref.
268
+
269
+ Script conflicts use the same keep/replace/rename flow as Storybook. File changes
270
+ are staged until overwrite confirmation; no packages are installed and no
271
+ commands connect to the database during scaffolding.
272
+
273
+ The printed install commands omit version constraints for `prisma`,
274
+ `@prisma/cli-engine`, `@prisma/orm-postgres`, `temporal-polyfill`, and `dotenv`. Already declared dependencies are kept. This is a PostgreSQL
275
+ preset for Prisma 8 RC, not a Prisma 7 migration tool.
276
+
277
+ After installing dependencies, configure `DATABASE_URL` (the CLI loads `.env`;
278
+ your application must load its runtime environment), add your models to the
279
+ contract and run the emit script before compiling or importing the service.
280
+ Use Node.js 22.18+, TypeScript 5.9+, ESM and JSON import support. Review planned
281
+ migrations before running the apply script. Generated contract files and
282
+ migration history are managed by Prisma, not by this scaffolder.
283
+
206
284
  ## Configuration
207
285
 
208
286
  The project configuration is stored in `domain-first.project-structure.config.json`. Commit it to share generation settings with your team. For example:
@@ -2,6 +2,7 @@
2
2
  * Existing files a full rewrite would replace, whatever their content.
3
3
  */
4
4
  export declare const filesToOverwrite: () => string[];
5
+ export declare const discardPendingChanges: () => void;
5
6
  export declare const writePendingChanges: () => void;
6
7
  declare class FileSystemItem {
7
8
  readonly path: string;
package/dist/index.cjs CHANGED
@@ -26,9 +26,9 @@ var __webpack_require__ = {};
26
26
  __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
27
27
  })();
28
28
  var __webpack_exports__ = {};
29
+ const prompts_namespaceObject = require("@inquirer/prompts");
29
30
  const external_node_path_namespaceObject = require("node:path");
30
31
  var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_namespaceObject);
31
- const prompts_namespaceObject = require("@inquirer/prompts");
32
32
  const external_zod_namespaceObject = require("zod");
33
33
  var external_zod_default = /*#__PURE__*/ __webpack_require__.n(external_zod_namespaceObject);
34
34
  const external_node_fs_namespaceObject = require("node:fs");
@@ -38,6 +38,10 @@ const pendingFolders = new Set();
38
38
  const filesToOverwrite = ()=>[
39
39
  ...pendingFiles
40
40
  ].filter(([filePath, { replacesFile }])=>replacesFile && external_node_fs_default().existsSync(filePath)).map(([filePath])=>filePath);
41
+ const discardPendingChanges = ()=>{
42
+ pendingFolders.clear();
43
+ pendingFiles.clear();
44
+ };
41
45
  const writePendingChanges = ()=>{
42
46
  for (const folderPath of pendingFolders)external_node_fs_default().mkdirSync(folderPath, {
43
47
  recursive: true
@@ -48,8 +52,7 @@ const writePendingChanges = ()=>{
48
52
  });
49
53
  external_node_fs_default().writeFileSync(filePath, content, 'utf8');
50
54
  }
51
- pendingFolders.clear();
52
- pendingFiles.clear();
55
+ discardPendingChanges();
53
56
  };
54
57
  class FileSystemItem {
55
58
  path;
@@ -185,6 +188,360 @@ class ConfigFile {
185
188
  new File(ConfigFile.path).data = JSON.stringify(config, null, '\t');
186
189
  };
187
190
  }
191
+ const savePendingChanges = async ()=>{
192
+ const overwrittenFiles = filesToOverwrite();
193
+ if (overwrittenFiles.length) {
194
+ const root = new ProjectRoot().path;
195
+ console.log('These files already exist and will be overwritten:');
196
+ for (const filePath of overwrittenFiles)console.log(` ${external_node_path_default().relative(root, filePath)}`);
197
+ const overwrite = await (0, prompts_namespaceObject.confirm)({
198
+ message: 'Overwrite them?',
199
+ default: false
200
+ });
201
+ if (!overwrite) {
202
+ discardPendingChanges();
203
+ console.log('Cancelled: nothing was written.');
204
+ return false;
205
+ }
206
+ }
207
+ writePendingChanges();
208
+ return true;
209
+ };
210
+ const external_node_util_namespaceObject = require("node:util");
211
+ const missingDomainFirstPackages = ()=>{
212
+ const packages = ConfigFile.Instance.data.domainFirstPackages;
213
+ const manifest = JSON.parse(new File(external_node_path_default().join(new ProjectRoot().path, 'package.json')).data);
214
+ const dependencies = {
215
+ ...manifest.dependencies,
216
+ ...manifest.devDependencies,
217
+ ...manifest.optionalDependencies
218
+ };
219
+ const missing = [
220
+ ...new Set(packages)
221
+ ].filter((name)=>!Object.hasOwn(dependencies, name));
222
+ return missing.length ? [
223
+ 'Install missing domain-first packages (run from the project package directory):',
224
+ ` npm i ${missing.join(' ')}`
225
+ ] : [
226
+ 'All configured domain-first packages are already declared in package.json.'
227
+ ];
228
+ };
229
+ const addPackageScripts = async (file, additions)=>{
230
+ const original = file.data;
231
+ const manifest = JSON.parse(original);
232
+ const scripts = {
233
+ ...manifest.scripts
234
+ };
235
+ const selected = {};
236
+ for (const [name, command] of Object.entries(additions)){
237
+ let target = name;
238
+ if (Object.hasOwn(scripts, name) && scripts[name] !== command) {
239
+ const action = await (0, prompts_namespaceObject.select)({
240
+ message: `Script "${name}" already exists: ${scripts[name]}`,
241
+ choices: [
242
+ 'Keep existing',
243
+ 'Replace',
244
+ 'Use another name'
245
+ ]
246
+ });
247
+ if ('Keep existing' === action) continue;
248
+ if ('Use another name' === action) target = await (0, prompts_namespaceObject.input)({
249
+ message: "New script name:",
250
+ validate: (value)=>!/^[a-zA-Z0-9:_-]+$/.test(value) || Object.hasOwn(scripts, value) || Object.hasOwn(additions, value) ? "Enter an unused script name (letters, numbers, :, _, -)." : true
251
+ });
252
+ }
253
+ scripts[target] = command;
254
+ selected[name] = target;
255
+ }
256
+ if (JSON.stringify(manifest.scripts) !== JSON.stringify(scripts)) {
257
+ manifest.scripts = scripts;
258
+ const indent = original.match(/\n([\t ]+)"/)?.[1] ?? ' ';
259
+ file.update(`${JSON.stringify(manifest, null, indent)}\n`);
260
+ }
261
+ return selected;
262
+ };
263
+ const runtimePackages = [
264
+ '@prisma/orm-postgres',
265
+ 'temporal-polyfill',
266
+ 'dotenv'
267
+ ];
268
+ const developmentPackages = [
269
+ 'prisma',
270
+ '@prisma/cli-engine'
271
+ ];
272
+ const prismaScripts = (rootFolder)=>{
273
+ const config = JSON.stringify(external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'shared/infrastructure/prisma/prisma.config.ts'));
274
+ const emit = `prisma contract emit --config ${config}`;
275
+ return {
276
+ 'prisma:emit': emit,
277
+ 'prisma:migration:plan': `${emit} && prisma migration plan --config ${config}`,
278
+ 'prisma:migration:apply': `prisma db migrate --advance-ref db --config ${config}`
279
+ };
280
+ };
281
+ const prismaConfig = `import 'dotenv/config';
282
+ import { definePrismaConfig } from '@prisma/cli-engine';
283
+ import { defineConfig as ormConfig } from '@prisma/orm-postgres/config';
284
+
285
+ export default definePrismaConfig({
286
+ orm: ormConfig({
287
+ contract: './contract.prisma',
288
+ migrations: { dir: './migrations' },
289
+ db: {
290
+ connection: process.env.DATABASE_URL
291
+ }
292
+ })
293
+ });
294
+ `;
295
+ const prismaService = `import 'temporal-polyfill/global';
296
+ import postgres from '@prisma/orm-postgres/runtime';
297
+ import type {} from 'temporal-polyfill/types/global';
298
+ import type { Contract } from '../prisma/contract.d';
299
+ import contractJson from '../prisma/contract.json' with { type: 'json' };
300
+
301
+ type PrismaClient = ReturnType<typeof postgres<Contract>>;
302
+
303
+ const globalForPrisma = globalThis as typeof globalThis & {
304
+ prismaClient?: PrismaClient;
305
+ };
306
+
307
+ // Reuse the client across development hot reloads.
308
+ const prismaClient = globalForPrisma.prismaClient ??
309
+ postgres<Contract>({ contractJson, url: process.env.DATABASE_URL });
310
+
311
+ if (process.env.NODE_ENV !== 'production') {
312
+ globalForPrisma.prismaClient = prismaClient;
313
+ }
314
+
315
+ export class PrismaInfrastructureService {
316
+ readonly orm = prismaClient.orm.public;
317
+ }
318
+ `;
319
+ const prismaWiring = `import { wireClass } from '@domain-first/wire';
320
+ import { PrismaInfrastructureService } from '../../infrastructure/services/prisma-infrastructure-service';
321
+
322
+ export const wirePrismaInfrastructureService = wireClass(
323
+ PrismaInfrastructureService,
324
+ []
325
+ );
326
+ `;
327
+ const stageFile = (filePath, content)=>{
328
+ const file = new File(filePath);
329
+ if (!file.exists || file.data !== content) file.data = content;
330
+ };
331
+ const addPrisma = async ()=>{
332
+ const config = ConfigFile.Instance.data;
333
+ const root = new ProjectRoot().path;
334
+ const manifestFile = new File(external_node_path_default().join(root, 'package.json'));
335
+ const manifest = JSON.parse(manifestFile.data);
336
+ const dependencies = {
337
+ ...manifest.dependencies,
338
+ ...manifest.devDependencies
339
+ };
340
+ const shared = external_node_path_default().resolve(root, config.rootFolder, 'shared');
341
+ const prismaFolder = external_node_path_default().join(shared, 'infrastructure/prisma');
342
+ if (dependencies['@prisma/client'] || dependencies.prisma && !/^[~^]?8\./.test(dependencies.prisma) || dependencies['@prisma/orm-mongo'] || dependencies['@prisma/orm-sqlite'] || [
343
+ external_node_path_default().join(root, 'prisma/schema.prisma'),
344
+ external_node_path_default().join(prismaFolder, 'schema.prisma')
345
+ ].some((filePath)=>new File(filePath).exists)) throw new Error('This preset adds Prisma 8 for PostgreSQL. Migrate the existing Prisma setup separately before using it.');
346
+ const withService = await (0, prompts_namespaceObject.confirm)({
347
+ message: 'Create shared Prisma infrastructure service?',
348
+ default: true
349
+ });
350
+ const useByDefault = 'prisma' !== config.defaultPersistenceLayerImplementation && await (0, prompts_namespaceObject.confirm)({
351
+ message: 'Use prisma as the default persistence implementation?',
352
+ default: false
353
+ });
354
+ const selected = await addPackageScripts(manifestFile, prismaScripts(config.rootFolder));
355
+ stageFile(external_node_path_default().join(prismaFolder, 'prisma.config.ts'), prismaConfig);
356
+ const contract = new File(external_node_path_default().join(prismaFolder, 'contract.prisma'));
357
+ if (!contract.exists) contract.data = '// use prisma-8\n\n// Add your application models here before running prisma:emit.\n';
358
+ if (withService) {
359
+ stageFile(external_node_path_default().join(shared, 'infrastructure/services/prisma-infrastructure-service.ts'), prismaService);
360
+ if (config.domainFirstPackages.includes('@domain-first/wire')) stageFile(external_node_path_default().join(shared, 'wiring/infrastructure-services/wire-prisma-infrastructure-service.ts'), prismaWiring);
361
+ }
362
+ if (useByDefault) ConfigFile.write({
363
+ ...config,
364
+ defaultPersistenceLayerImplementation: 'prisma'
365
+ });
366
+ const install = (packages, dev)=>{
367
+ const missing = packages.filter((name)=>!dependencies[name]);
368
+ return missing.length ? [
369
+ ` npm install${dev ? ' --save-dev' : ''} ${missing.join(' ')}`
370
+ ] : [];
371
+ };
372
+ const scriptCommand = (name)=>selected[name] ? `npm run ${selected[name]}` : prismaScripts(config.rootFolder)[name];
373
+ const relativeFolder = external_node_path_default().relative(root, prismaFolder).split(external_node_path_default().sep).join('/');
374
+ return [
375
+ 'Prisma 8 configuration saved (PostgreSQL, RC preset).',
376
+ 'Next steps (run from the project package directory):',
377
+ ...install(runtimePackages, false),
378
+ ...install(developmentPackages, true),
379
+ ` Add !${relativeFolder} in your linter, to ignore prisma files.`,
380
+ ' Existing dependency versions were kept.',
381
+ ' Use Node.js 22.18+ and TypeScript 5.9+ with ESM and JSON import support.',
382
+ ' Set DATABASE_URL in your project environment (.env for the CLI); load it in the application runtime too.',
383
+ ` Add your models to ${relativeFolder}/contract.prisma.`,
384
+ ` Emit the contract before compiling or importing the service: ${scriptCommand('prisma:emit')}`,
385
+ ` Plan migrations: ${scriptCommand('prisma:migration:plan')}`,
386
+ ` Review the generated migrations, then apply: ${scriptCommand('prisma:migration:apply')}`
387
+ ];
388
+ };
389
+ const storybookFiles = (relativeProjectRoot)=>({
390
+ 'main.ts': `import { resolve } from 'node:path';
391
+ import react from '@vitejs/plugin-react';
392
+ import type { StorybookConfig } from '@storybook/react-vite';
393
+
394
+ const projectRoot = resolve(import.meta.dirname, ${JSON.stringify(relativeProjectRoot)});
395
+
396
+ const config: StorybookConfig = {
397
+ stories: ['../**/*.mdx', '../**/*.stories.@(ts|tsx)'],
398
+ framework: {
399
+ name: '@storybook/react-vite',
400
+ options: {}
401
+ },
402
+ core: {
403
+ disableTelemetry: true
404
+ },
405
+ async viteFinal(viteConfig) {
406
+ const { mergeConfig } = await import('vite');
407
+
408
+ return mergeConfig(viteConfig, {
409
+ plugins: [react()],
410
+ resolve: {
411
+ alias: {
412
+ '@': projectRoot
413
+ }
414
+ }
415
+ });
416
+ }
417
+ };
418
+
419
+ export default config;
420
+ `,
421
+ 'preview.ts': `import type { Preview } from '@storybook/react-vite';
422
+
423
+ const preview: Preview = {
424
+ parameters: {
425
+ controls: {
426
+ matchers: {
427
+ color: /(background|color)$/i,
428
+ date: /Date$/i
429
+ }
430
+ }
431
+ }
432
+ };
433
+
434
+ export default preview;
435
+ `
436
+ });
437
+ const storybookScripts = (rootFolder)=>{
438
+ const folder = external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react');
439
+ const quote = (value)=>JSON.stringify(value);
440
+ return {
441
+ storybook: `storybook dev -p 6006 -c ${quote(`${folder}/.storybook`)}`,
442
+ 'build-storybook': `storybook build -c ${quote(`${folder}/.storybook`)} -o ${quote(`${folder}/storybook-static`)}`
443
+ };
444
+ };
445
+ const addStorybook = async ()=>{
446
+ const config = ConfigFile.Instance.data;
447
+ if ((!config.useReact || config.storybookFramework && '@storybook/react-vite' !== config.storybookFramework) && !await (0, prompts_namespaceObject.confirm)({
448
+ message: 'Configure React scaffolding with @storybook/react-vite?',
449
+ default: false
450
+ })) return [];
451
+ const root = new ProjectRoot().path;
452
+ const manifestFile = new File(external_node_path_default().join(root, 'package.json'));
453
+ const manifest = JSON.parse(manifestFile.data);
454
+ const selected = await addPackageScripts(manifestFile, storybookScripts(config.rootFolder));
455
+ const folder = new Folder(root).subitem([
456
+ config.rootFolder,
457
+ 'presentation',
458
+ 'react',
459
+ '.storybook'
460
+ ]);
461
+ for (const [name, content] of Object.entries(storybookFiles(external_node_path_default().relative(folder.path, root).split(external_node_path_default().sep).join('/')))){
462
+ const file = new File(external_node_path_default().join(folder.path, name));
463
+ if (!file.exists || file.data !== content) file.data = content;
464
+ }
465
+ if (!config.useReact || '@storybook/react-vite' !== config.storybookFramework) ConfigFile.write({
466
+ ...config,
467
+ useReact: true,
468
+ storybookFramework: '@storybook/react-vite'
469
+ });
470
+ const buildFolder = external_node_path_default().posix.join(config.rootFolder.replaceAll('\\', '/'), 'presentation/react/storybook-static');
471
+ const ignoreEntry = `/${buildFolder}/`;
472
+ const gitignore = new File(external_node_path_default().join(root, '.gitignore'));
473
+ const ignored = gitignore.exists ? gitignore.data : '';
474
+ if (!ignored.split(/\r?\n/).includes(ignoreEntry)) {
475
+ const newline = ignored.includes('\r\n') ? '\r\n' : '\n';
476
+ gitignore.update(`${ignored}${ignored && !ignored.endsWith('\n') ? newline : ''}${ignoreEntry}${newline}`);
477
+ }
478
+ const dependencies = {
479
+ ...manifest.dependencies,
480
+ ...manifest.devDependencies
481
+ };
482
+ const missing = [
483
+ 'storybook',
484
+ '@storybook/react-vite',
485
+ 'vite',
486
+ '@vitejs/plugin-react'
487
+ ].filter((name)=>!dependencies[name]);
488
+ const missingReact = [
489
+ 'react',
490
+ 'react-dom'
491
+ ].filter((name)=>!dependencies[name]);
492
+ return [
493
+ 'Storybook configuration saved (React + Vite).',
494
+ 'Next steps (run from the project package directory):',
495
+ ...missing.length ? [
496
+ ` npm install --save-dev ${missing.join(' ')}`
497
+ ] : [],
498
+ ...missingReact.length ? [
499
+ ` npm install ${missingReact.join(' ')}`
500
+ ] : [],
501
+ ' Existing dependency versions were kept; ensure Storybook packages are compatible.',
502
+ ' Add your CSS imports to .storybook/preview.ts using relative paths or the @/ alias (project root).',
503
+ ' Generate a UI-kit component or widget UI to create a story.',
504
+ ...selected.storybook ? [
505
+ ` npm run ${selected.storybook}`
506
+ ] : [],
507
+ ...selected['build-storybook'] ? [
508
+ ` npm run ${selected['build-storybook']}`
509
+ ] : []
510
+ ];
511
+ };
512
+ const integrations = [
513
+ {
514
+ name: 'Storybook (React + Vite)',
515
+ run: addStorybook
516
+ },
517
+ {
518
+ name: 'Prisma 8 (PostgreSQL, RC)',
519
+ run: addPrisma
520
+ },
521
+ {
522
+ name: 'Missing domain-first packages',
523
+ run: missingDomainFirstPackages
524
+ }
525
+ ];
526
+ const addIntegration = async ()=>{
527
+ const index = await (0, prompts_namespaceObject.select)({
528
+ message: 'Integration:',
529
+ choices: integrations.map((integration, value)=>({
530
+ name: integration.name,
531
+ value
532
+ }))
533
+ });
534
+ const nextSteps = await integrations[index].run();
535
+ if (await savePendingChanges()) {
536
+ if (nextSteps.length) console.log(nextSteps.map((line)=>/^\s*npm (?:i|install)\b/.test(line) ? (0, external_node_util_namespaceObject.styleText)([
537
+ 'bold',
538
+ 'cyan'
539
+ ], line) : line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + (0, external_node_util_namespaceObject.styleText)([
540
+ 'bold',
541
+ 'cyan'
542
+ ], path))).join('\n'));
543
+ }
544
+ };
188
545
  const initializeUseCase = async ()=>{
189
546
  const rootFolderName = await (0, prompts_namespaceObject.input)({
190
547
  message: 'Root folder (use "/" for inner folders):',
@@ -2068,7 +2425,11 @@ const main = async ()=>{
2068
2425
  name: 'Shared Layer',
2069
2426
  action: 'Scaffold in bounded context'
2070
2427
  },
2071
- scaffoldNewBoundedContext
2428
+ scaffoldNewBoundedContext,
2429
+ {
2430
+ name: 'Add integration',
2431
+ action: 'Add integration'
2432
+ }
2072
2433
  ].filter((x)=>!!x);
2073
2434
  const result = await (0, prompts_namespaceObject.select)({
2074
2435
  message: '@domain-first/project-structure',
@@ -2076,6 +2437,8 @@ const main = async ()=>{
2076
2437
  });
2077
2438
  const { action, name } = options.find((x)=>x.name === result);
2078
2439
  switch(action){
2440
+ case 'Add integration':
2441
+ return void await addIntegration();
2079
2442
  case 'Scaffold React module':
2080
2443
  {
2081
2444
  const reactFolder = new Folder(rootPath).subitem([
@@ -2222,18 +2585,7 @@ const main = async ()=>{
2222
2585
  };
2223
2586
  const run = async ()=>{
2224
2587
  await main();
2225
- const overwrittenFiles = filesToOverwrite();
2226
- if (overwrittenFiles.length) {
2227
- const root = new ProjectRoot().path;
2228
- console.log('These files already exist and will be overwritten:');
2229
- for (const filePath of overwrittenFiles)console.log(` ${external_node_path_default().relative(root, filePath)}`);
2230
- const overwrite = await (0, prompts_namespaceObject.confirm)({
2231
- message: 'Overwrite them?',
2232
- default: false
2233
- });
2234
- if (!overwrite) return void console.log('Cancelled: nothing was written.');
2235
- }
2236
- writePendingChanges();
2588
+ await savePendingChanges();
2237
2589
  };
2238
2590
  run();
2239
2591
  for(var __rspack_i in __webpack_exports__)exports[__rspack_i] = __webpack_exports__[__rspack_i];
package/dist/index.js CHANGED
@@ -1,13 +1,18 @@
1
1
  #!/usr/bin/env node
2
- import node_path from "node:path";
3
2
  import { Separator, checkbox as prompts_checkbox, confirm as prompts_confirm, input, select as prompts_select } from "@inquirer/prompts";
3
+ import node_path from "node:path";
4
4
  import zod from "zod";
5
5
  import node_fs from "node:fs";
6
+ import { styleText } from "node:util";
6
7
  const pendingFiles = new Map();
7
8
  const pendingFolders = new Set();
8
9
  const filesToOverwrite = ()=>[
9
10
  ...pendingFiles
10
11
  ].filter(([filePath, { replacesFile }])=>replacesFile && node_fs.existsSync(filePath)).map(([filePath])=>filePath);
12
+ const discardPendingChanges = ()=>{
13
+ pendingFolders.clear();
14
+ pendingFiles.clear();
15
+ };
11
16
  const writePendingChanges = ()=>{
12
17
  for (const folderPath of pendingFolders)node_fs.mkdirSync(folderPath, {
13
18
  recursive: true
@@ -18,8 +23,7 @@ const writePendingChanges = ()=>{
18
23
  });
19
24
  node_fs.writeFileSync(filePath, content, 'utf8');
20
25
  }
21
- pendingFolders.clear();
22
- pendingFiles.clear();
26
+ discardPendingChanges();
23
27
  };
24
28
  class FileSystemItem {
25
29
  path;
@@ -155,6 +159,359 @@ class ConfigFile {
155
159
  new File(ConfigFile.path).data = JSON.stringify(config, null, '\t');
156
160
  };
157
161
  }
162
+ const savePendingChanges = async ()=>{
163
+ const overwrittenFiles = filesToOverwrite();
164
+ if (overwrittenFiles.length) {
165
+ const root = new ProjectRoot().path;
166
+ console.log('These files already exist and will be overwritten:');
167
+ for (const filePath of overwrittenFiles)console.log(` ${node_path.relative(root, filePath)}`);
168
+ const overwrite = await prompts_confirm({
169
+ message: 'Overwrite them?',
170
+ default: false
171
+ });
172
+ if (!overwrite) {
173
+ discardPendingChanges();
174
+ console.log('Cancelled: nothing was written.');
175
+ return false;
176
+ }
177
+ }
178
+ writePendingChanges();
179
+ return true;
180
+ };
181
+ const missingDomainFirstPackages = ()=>{
182
+ const packages = ConfigFile.Instance.data.domainFirstPackages;
183
+ const manifest = JSON.parse(new File(node_path.join(new ProjectRoot().path, 'package.json')).data);
184
+ const dependencies = {
185
+ ...manifest.dependencies,
186
+ ...manifest.devDependencies,
187
+ ...manifest.optionalDependencies
188
+ };
189
+ const missing = [
190
+ ...new Set(packages)
191
+ ].filter((name)=>!Object.hasOwn(dependencies, name));
192
+ return missing.length ? [
193
+ 'Install missing domain-first packages (run from the project package directory):',
194
+ ` npm i ${missing.join(' ')}`
195
+ ] : [
196
+ 'All configured domain-first packages are already declared in package.json.'
197
+ ];
198
+ };
199
+ const addPackageScripts = async (file, additions)=>{
200
+ const original = file.data;
201
+ const manifest = JSON.parse(original);
202
+ const scripts = {
203
+ ...manifest.scripts
204
+ };
205
+ const selected = {};
206
+ for (const [name, command] of Object.entries(additions)){
207
+ let target = name;
208
+ if (Object.hasOwn(scripts, name) && scripts[name] !== command) {
209
+ const action = await prompts_select({
210
+ message: `Script "${name}" already exists: ${scripts[name]}`,
211
+ choices: [
212
+ 'Keep existing',
213
+ 'Replace',
214
+ 'Use another name'
215
+ ]
216
+ });
217
+ if ('Keep existing' === action) continue;
218
+ if ('Use another name' === action) target = await input({
219
+ message: "New script name:",
220
+ validate: (value)=>!/^[a-zA-Z0-9:_-]+$/.test(value) || Object.hasOwn(scripts, value) || Object.hasOwn(additions, value) ? "Enter an unused script name (letters, numbers, :, _, -)." : true
221
+ });
222
+ }
223
+ scripts[target] = command;
224
+ selected[name] = target;
225
+ }
226
+ if (JSON.stringify(manifest.scripts) !== JSON.stringify(scripts)) {
227
+ manifest.scripts = scripts;
228
+ const indent = original.match(/\n([\t ]+)"/)?.[1] ?? ' ';
229
+ file.update(`${JSON.stringify(manifest, null, indent)}\n`);
230
+ }
231
+ return selected;
232
+ };
233
+ const runtimePackages = [
234
+ '@prisma/orm-postgres',
235
+ 'temporal-polyfill',
236
+ 'dotenv'
237
+ ];
238
+ const developmentPackages = [
239
+ 'prisma',
240
+ '@prisma/cli-engine'
241
+ ];
242
+ const prismaScripts = (rootFolder)=>{
243
+ const config = JSON.stringify(node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'shared/infrastructure/prisma/prisma.config.ts'));
244
+ const emit = `prisma contract emit --config ${config}`;
245
+ return {
246
+ 'prisma:emit': emit,
247
+ 'prisma:migration:plan': `${emit} && prisma migration plan --config ${config}`,
248
+ 'prisma:migration:apply': `prisma db migrate --advance-ref db --config ${config}`
249
+ };
250
+ };
251
+ const prismaConfig = `import 'dotenv/config';
252
+ import { definePrismaConfig } from '@prisma/cli-engine';
253
+ import { defineConfig as ormConfig } from '@prisma/orm-postgres/config';
254
+
255
+ export default definePrismaConfig({
256
+ orm: ormConfig({
257
+ contract: './contract.prisma',
258
+ migrations: { dir: './migrations' },
259
+ db: {
260
+ connection: process.env.DATABASE_URL
261
+ }
262
+ })
263
+ });
264
+ `;
265
+ const prismaService = `import 'temporal-polyfill/global';
266
+ import postgres from '@prisma/orm-postgres/runtime';
267
+ import type {} from 'temporal-polyfill/types/global';
268
+ import type { Contract } from '../prisma/contract.d';
269
+ import contractJson from '../prisma/contract.json' with { type: 'json' };
270
+
271
+ type PrismaClient = ReturnType<typeof postgres<Contract>>;
272
+
273
+ const globalForPrisma = globalThis as typeof globalThis & {
274
+ prismaClient?: PrismaClient;
275
+ };
276
+
277
+ // Reuse the client across development hot reloads.
278
+ const prismaClient = globalForPrisma.prismaClient ??
279
+ postgres<Contract>({ contractJson, url: process.env.DATABASE_URL });
280
+
281
+ if (process.env.NODE_ENV !== 'production') {
282
+ globalForPrisma.prismaClient = prismaClient;
283
+ }
284
+
285
+ export class PrismaInfrastructureService {
286
+ readonly orm = prismaClient.orm.public;
287
+ }
288
+ `;
289
+ const prismaWiring = `import { wireClass } from '@domain-first/wire';
290
+ import { PrismaInfrastructureService } from '../../infrastructure/services/prisma-infrastructure-service';
291
+
292
+ export const wirePrismaInfrastructureService = wireClass(
293
+ PrismaInfrastructureService,
294
+ []
295
+ );
296
+ `;
297
+ const stageFile = (filePath, content)=>{
298
+ const file = new File(filePath);
299
+ if (!file.exists || file.data !== content) file.data = content;
300
+ };
301
+ const addPrisma = async ()=>{
302
+ const config = ConfigFile.Instance.data;
303
+ const root = new ProjectRoot().path;
304
+ const manifestFile = new File(node_path.join(root, 'package.json'));
305
+ const manifest = JSON.parse(manifestFile.data);
306
+ const dependencies = {
307
+ ...manifest.dependencies,
308
+ ...manifest.devDependencies
309
+ };
310
+ const shared = node_path.resolve(root, config.rootFolder, 'shared');
311
+ const prismaFolder = node_path.join(shared, 'infrastructure/prisma');
312
+ if (dependencies['@prisma/client'] || dependencies.prisma && !/^[~^]?8\./.test(dependencies.prisma) || dependencies['@prisma/orm-mongo'] || dependencies['@prisma/orm-sqlite'] || [
313
+ node_path.join(root, 'prisma/schema.prisma'),
314
+ node_path.join(prismaFolder, 'schema.prisma')
315
+ ].some((filePath)=>new File(filePath).exists)) throw new Error('This preset adds Prisma 8 for PostgreSQL. Migrate the existing Prisma setup separately before using it.');
316
+ const withService = await prompts_confirm({
317
+ message: 'Create shared Prisma infrastructure service?',
318
+ default: true
319
+ });
320
+ const useByDefault = 'prisma' !== config.defaultPersistenceLayerImplementation && await prompts_confirm({
321
+ message: 'Use prisma as the default persistence implementation?',
322
+ default: false
323
+ });
324
+ const selected = await addPackageScripts(manifestFile, prismaScripts(config.rootFolder));
325
+ stageFile(node_path.join(prismaFolder, 'prisma.config.ts'), prismaConfig);
326
+ const contract = new File(node_path.join(prismaFolder, 'contract.prisma'));
327
+ if (!contract.exists) contract.data = '// use prisma-8\n\n// Add your application models here before running prisma:emit.\n';
328
+ if (withService) {
329
+ stageFile(node_path.join(shared, 'infrastructure/services/prisma-infrastructure-service.ts'), prismaService);
330
+ if (config.domainFirstPackages.includes('@domain-first/wire')) stageFile(node_path.join(shared, 'wiring/infrastructure-services/wire-prisma-infrastructure-service.ts'), prismaWiring);
331
+ }
332
+ if (useByDefault) ConfigFile.write({
333
+ ...config,
334
+ defaultPersistenceLayerImplementation: 'prisma'
335
+ });
336
+ const install = (packages, dev)=>{
337
+ const missing = packages.filter((name)=>!dependencies[name]);
338
+ return missing.length ? [
339
+ ` npm install${dev ? ' --save-dev' : ''} ${missing.join(' ')}`
340
+ ] : [];
341
+ };
342
+ const scriptCommand = (name)=>selected[name] ? `npm run ${selected[name]}` : prismaScripts(config.rootFolder)[name];
343
+ const relativeFolder = node_path.relative(root, prismaFolder).split(node_path.sep).join('/');
344
+ return [
345
+ 'Prisma 8 configuration saved (PostgreSQL, RC preset).',
346
+ 'Next steps (run from the project package directory):',
347
+ ...install(runtimePackages, false),
348
+ ...install(developmentPackages, true),
349
+ ` Add !${relativeFolder} in your linter, to ignore prisma files.`,
350
+ ' Existing dependency versions were kept.',
351
+ ' Use Node.js 22.18+ and TypeScript 5.9+ with ESM and JSON import support.',
352
+ ' Set DATABASE_URL in your project environment (.env for the CLI); load it in the application runtime too.',
353
+ ` Add your models to ${relativeFolder}/contract.prisma.`,
354
+ ` Emit the contract before compiling or importing the service: ${scriptCommand('prisma:emit')}`,
355
+ ` Plan migrations: ${scriptCommand('prisma:migration:plan')}`,
356
+ ` Review the generated migrations, then apply: ${scriptCommand('prisma:migration:apply')}`
357
+ ];
358
+ };
359
+ const storybookFiles = (relativeProjectRoot)=>({
360
+ 'main.ts': `import { resolve } from 'node:path';
361
+ import react from '@vitejs/plugin-react';
362
+ import type { StorybookConfig } from '@storybook/react-vite';
363
+
364
+ const projectRoot = resolve(import.meta.dirname, ${JSON.stringify(relativeProjectRoot)});
365
+
366
+ const config: StorybookConfig = {
367
+ stories: ['../**/*.mdx', '../**/*.stories.@(ts|tsx)'],
368
+ framework: {
369
+ name: '@storybook/react-vite',
370
+ options: {}
371
+ },
372
+ core: {
373
+ disableTelemetry: true
374
+ },
375
+ async viteFinal(viteConfig) {
376
+ const { mergeConfig } = await import('vite');
377
+
378
+ return mergeConfig(viteConfig, {
379
+ plugins: [react()],
380
+ resolve: {
381
+ alias: {
382
+ '@': projectRoot
383
+ }
384
+ }
385
+ });
386
+ }
387
+ };
388
+
389
+ export default config;
390
+ `,
391
+ 'preview.ts': `import type { Preview } from '@storybook/react-vite';
392
+
393
+ const preview: Preview = {
394
+ parameters: {
395
+ controls: {
396
+ matchers: {
397
+ color: /(background|color)$/i,
398
+ date: /Date$/i
399
+ }
400
+ }
401
+ }
402
+ };
403
+
404
+ export default preview;
405
+ `
406
+ });
407
+ const storybookScripts = (rootFolder)=>{
408
+ const folder = node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react');
409
+ const quote = (value)=>JSON.stringify(value);
410
+ return {
411
+ storybook: `storybook dev -p 6006 -c ${quote(`${folder}/.storybook`)}`,
412
+ 'build-storybook': `storybook build -c ${quote(`${folder}/.storybook`)} -o ${quote(`${folder}/storybook-static`)}`
413
+ };
414
+ };
415
+ const addStorybook = async ()=>{
416
+ const config = ConfigFile.Instance.data;
417
+ if ((!config.useReact || config.storybookFramework && '@storybook/react-vite' !== config.storybookFramework) && !await prompts_confirm({
418
+ message: 'Configure React scaffolding with @storybook/react-vite?',
419
+ default: false
420
+ })) return [];
421
+ const root = new ProjectRoot().path;
422
+ const manifestFile = new File(node_path.join(root, 'package.json'));
423
+ const manifest = JSON.parse(manifestFile.data);
424
+ const selected = await addPackageScripts(manifestFile, storybookScripts(config.rootFolder));
425
+ const folder = new Folder(root).subitem([
426
+ config.rootFolder,
427
+ 'presentation',
428
+ 'react',
429
+ '.storybook'
430
+ ]);
431
+ for (const [name, content] of Object.entries(storybookFiles(node_path.relative(folder.path, root).split(node_path.sep).join('/')))){
432
+ const file = new File(node_path.join(folder.path, name));
433
+ if (!file.exists || file.data !== content) file.data = content;
434
+ }
435
+ if (!config.useReact || '@storybook/react-vite' !== config.storybookFramework) ConfigFile.write({
436
+ ...config,
437
+ useReact: true,
438
+ storybookFramework: '@storybook/react-vite'
439
+ });
440
+ const buildFolder = node_path.posix.join(config.rootFolder.replaceAll('\\', '/'), 'presentation/react/storybook-static');
441
+ const ignoreEntry = `/${buildFolder}/`;
442
+ const gitignore = new File(node_path.join(root, '.gitignore'));
443
+ const ignored = gitignore.exists ? gitignore.data : '';
444
+ if (!ignored.split(/\r?\n/).includes(ignoreEntry)) {
445
+ const newline = ignored.includes('\r\n') ? '\r\n' : '\n';
446
+ gitignore.update(`${ignored}${ignored && !ignored.endsWith('\n') ? newline : ''}${ignoreEntry}${newline}`);
447
+ }
448
+ const dependencies = {
449
+ ...manifest.dependencies,
450
+ ...manifest.devDependencies
451
+ };
452
+ const missing = [
453
+ 'storybook',
454
+ '@storybook/react-vite',
455
+ 'vite',
456
+ '@vitejs/plugin-react'
457
+ ].filter((name)=>!dependencies[name]);
458
+ const missingReact = [
459
+ 'react',
460
+ 'react-dom'
461
+ ].filter((name)=>!dependencies[name]);
462
+ return [
463
+ 'Storybook configuration saved (React + Vite).',
464
+ 'Next steps (run from the project package directory):',
465
+ ...missing.length ? [
466
+ ` npm install --save-dev ${missing.join(' ')}`
467
+ ] : [],
468
+ ...missingReact.length ? [
469
+ ` npm install ${missingReact.join(' ')}`
470
+ ] : [],
471
+ ' Existing dependency versions were kept; ensure Storybook packages are compatible.',
472
+ ' Add your CSS imports to .storybook/preview.ts using relative paths or the @/ alias (project root).',
473
+ ' Generate a UI-kit component or widget UI to create a story.',
474
+ ...selected.storybook ? [
475
+ ` npm run ${selected.storybook}`
476
+ ] : [],
477
+ ...selected['build-storybook'] ? [
478
+ ` npm run ${selected['build-storybook']}`
479
+ ] : []
480
+ ];
481
+ };
482
+ const integrations = [
483
+ {
484
+ name: 'Storybook (React + Vite)',
485
+ run: addStorybook
486
+ },
487
+ {
488
+ name: 'Prisma 8 (PostgreSQL, RC)',
489
+ run: addPrisma
490
+ },
491
+ {
492
+ name: 'Missing domain-first packages',
493
+ run: missingDomainFirstPackages
494
+ }
495
+ ];
496
+ const addIntegration = async ()=>{
497
+ const index = await prompts_select({
498
+ message: 'Integration:',
499
+ choices: integrations.map((integration, value)=>({
500
+ name: integration.name,
501
+ value
502
+ }))
503
+ });
504
+ const nextSteps = await integrations[index].run();
505
+ if (await savePendingChanges()) {
506
+ if (nextSteps.length) console.log(nextSteps.map((line)=>/^\s*npm (?:i|install)\b/.test(line) ? styleText([
507
+ 'bold',
508
+ 'cyan'
509
+ ], line) : line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + styleText([
510
+ 'bold',
511
+ 'cyan'
512
+ ], path))).join('\n'));
513
+ }
514
+ };
158
515
  const initializeUseCase = async ()=>{
159
516
  const rootFolderName = await input({
160
517
  message: 'Root folder (use "/" for inner folders):',
@@ -2038,7 +2395,11 @@ const main = async ()=>{
2038
2395
  name: 'Shared Layer',
2039
2396
  action: 'Scaffold in bounded context'
2040
2397
  },
2041
- scaffoldNewBoundedContext
2398
+ scaffoldNewBoundedContext,
2399
+ {
2400
+ name: 'Add integration',
2401
+ action: 'Add integration'
2402
+ }
2042
2403
  ].filter((x)=>!!x);
2043
2404
  const result = await prompts_select({
2044
2405
  message: '@domain-first/project-structure',
@@ -2046,6 +2407,8 @@ const main = async ()=>{
2046
2407
  });
2047
2408
  const { action, name } = options.find((x)=>x.name === result);
2048
2409
  switch(action){
2410
+ case 'Add integration':
2411
+ return void await addIntegration();
2049
2412
  case 'Scaffold React module':
2050
2413
  {
2051
2414
  const reactFolder = new Folder(rootPath).subitem([
@@ -2192,17 +2555,6 @@ const main = async ()=>{
2192
2555
  };
2193
2556
  const run = async ()=>{
2194
2557
  await main();
2195
- const overwrittenFiles = filesToOverwrite();
2196
- if (overwrittenFiles.length) {
2197
- const root = new ProjectRoot().path;
2198
- console.log('These files already exist and will be overwritten:');
2199
- for (const filePath of overwrittenFiles)console.log(` ${node_path.relative(root, filePath)}`);
2200
- const overwrite = await prompts_confirm({
2201
- message: 'Overwrite them?',
2202
- default: false
2203
- });
2204
- if (!overwrite) return void console.log('Cancelled: nothing was written.');
2205
- }
2206
- writePendingChanges();
2558
+ await savePendingChanges();
2207
2559
  };
2208
2560
  run();
@@ -0,0 +1,4 @@
1
+ export * from './missing-domain-first-packages';
2
+ export * from './package-scripts';
3
+ export * from './prisma';
4
+ export * from './storybook';
@@ -0,0 +1 @@
1
+ export declare const missingDomainFirstPackages: () => string[];
@@ -0,0 +1,2 @@
1
+ import type { File } from '../file-system';
2
+ export declare const addPackageScripts: (file: File, additions: Record<string, string>) => Promise<Record<string, string>>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ export declare const prismaScripts: (rootFolder: string) => {
2
+ 'prisma:emit': string;
3
+ 'prisma:migration:plan': string;
4
+ 'prisma:migration:apply': string;
5
+ };
6
+ export declare const addPrisma: () => Promise<string[]>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,9 @@
1
+ export declare const storybookFiles: (relativeProjectRoot: string) => {
2
+ 'main.ts': string;
3
+ 'preview.ts': string;
4
+ };
5
+ export declare const storybookScripts: (rootFolder: string) => {
6
+ storybook: string;
7
+ 'build-storybook': string;
8
+ };
9
+ export declare const addStorybook: () => Promise<string[]>;
@@ -0,0 +1,2 @@
1
+ /** Shared commit step for standalone use cases and the CLI. */
2
+ export declare const savePendingChanges: () => Promise<boolean>;
@@ -0,0 +1 @@
1
+ export declare const addIntegration: () => Promise<void>;
@@ -0,0 +1 @@
1
+ export {};
@@ -1,3 +1,4 @@
1
+ export * from './add-integration';
1
2
  export * from './initialize';
2
3
  export * from './scaffold-new-aggregate';
3
4
  export * from './scaffold-new-application-port';
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": "2.12.0",
4
+ "version": "2.13.1",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",