@domain-first/project-structure 3.2.1 → 3.3.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/index.cjs CHANGED
@@ -276,6 +276,113 @@ const missingDomainFirstPackages = ()=>{
276
276
  `npm i ${missing.join(' ')}`
277
277
  ] : [];
278
278
  };
279
+ const external_node_module_namespaceObject = require("node:module");
280
+ const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
281
+ const resolveExtends = (fromFile, target)=>{
282
+ if (target.startsWith('.') || external_node_path_default().isAbsolute(target)) {
283
+ const resolved = external_node_path_default().resolve(external_node_path_default().dirname(fromFile), target);
284
+ return resolved.endsWith('.json') ? resolved : `${resolved}.json`;
285
+ }
286
+ const require1 = (0, external_node_module_namespaceObject.createRequire)(fromFile);
287
+ for (const candidate of [
288
+ target,
289
+ `${target}/tsconfig.json`
290
+ ])try {
291
+ return require1.resolve(candidate);
292
+ } catch {}
293
+ };
294
+ const compilerOption = (configFile, name, seen = new Set())=>{
295
+ if (seen.has(configFile) || !external_node_fs_default().existsSync(configFile)) return null;
296
+ seen.add(configFile);
297
+ let config;
298
+ try {
299
+ config = JSON.parse(stripJsonComments(external_node_fs_default().readFileSync(configFile, 'utf8')));
300
+ } catch {
301
+ return null;
302
+ }
303
+ if (config.compilerOptions && name in config.compilerOptions) return config.compilerOptions[name];
304
+ const parents = [
305
+ config.extends ?? []
306
+ ].flat().reverse();
307
+ for (const parent of parents){
308
+ const parentFile = resolveExtends(configFile, parent);
309
+ const value = parentFile ? compilerOption(parentFile, name, seen) : null;
310
+ if (void 0 !== value) return value;
311
+ }
312
+ };
313
+ class UnknownFormatNaming {
314
+ rawSource;
315
+ camelCase;
316
+ PascalCase;
317
+ constructor(rawSource){
318
+ this.rawSource = rawSource;
319
+ const source = rawSource.trim();
320
+ if (!source.includes('-')) {
321
+ this.camelCase = source.substring(0, 1).toLowerCase() + source.substring(1);
322
+ this.PascalCase = source.substring(0, 1).toUpperCase() + source.substring(1);
323
+ }
324
+ const words = source.split('-').filter((word)=>!!word);
325
+ this.camelCase = words.map((word, index)=>0 === index ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
326
+ this.PascalCase = words.map((word)=>word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
327
+ }
328
+ get fileName() {
329
+ return this.rawSource;
330
+ }
331
+ get variableName() {
332
+ return this.camelCase;
333
+ }
334
+ get ClassName() {
335
+ return this.PascalCase;
336
+ }
337
+ get withSpaces() {
338
+ return this.fileName.replaceAll('-', ' ');
339
+ }
340
+ }
341
+ const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
342
+ class NestedName {
343
+ folders;
344
+ folderName;
345
+ fileName;
346
+ ClassName;
347
+ classNameSegments;
348
+ constructor(rawSource){
349
+ const segments = splitSegments(rawSource);
350
+ this.folders = segments.slice(0, -1);
351
+ this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
352
+ this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
353
+ this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
354
+ this.ClassName = this.classNameSegments.join('');
355
+ }
356
+ static validate = (rawSource)=>{
357
+ const segments = splitSegments(rawSource);
358
+ if (!segments.length) return 'Name is required';
359
+ if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
360
+ return true;
361
+ };
362
+ }
363
+ const reactPageContent = (ClassName, { imports = [], body = '<></>' } = {})=>`
364
+ ${[
365
+ ...imports,
366
+ "import { type FC } from 'react'"
367
+ ].join('\n')}
368
+
369
+ export type ${ClassName}PageProps = {}
370
+
371
+ export const ${ClassName}Page: FC<${ClassName}PageProps> = (props) => {
372
+ return ${body}
373
+ }
374
+ `.trim();
375
+ const scaffoldReactPage = async (presentationReactFolder)=>{
376
+ const name = await (0, prompts_namespaceObject.input)({
377
+ message: 'Provide name (folders split by "/"):',
378
+ validate: NestedName.validate
379
+ });
380
+ const { folders, ClassName, fileName } = new NestedName(name);
381
+ presentationReactFolder.subitem([
382
+ 'pages',
383
+ ...folders
384
+ ]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
385
+ };
279
386
  const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
280
387
  const rootFolderSegments = (rootFolder)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n `).join('');
281
388
  const openapiExtractor = (rootFolder)=>`import path from 'node:path';
@@ -475,6 +582,18 @@ const extractorPackages = [
475
582
  'ts-morph',
476
583
  '@microsoft/tsdoc'
477
584
  ];
585
+ const swaggerPagePath = (rootFolder)=>external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/pages/swagger-page.tsx');
586
+ const swaggerPage = (rootFolder, outputPath)=>{
587
+ const specImport = external_node_path_default().posix.relative(external_node_path_default().posix.dirname(swaggerPagePath(rootFolder)), outputPath);
588
+ return reactPageContent('Swagger', {
589
+ imports: [
590
+ "import 'swagger-ui-react/swagger-ui.css'",
591
+ "import SwaggerUI from 'swagger-ui-react'",
592
+ `import spec from '${specImport.startsWith('.') ? specImport : `./${specImport}`}' with { type: 'json' }`
593
+ ],
594
+ body: '<SwaggerUI displayOperationId spec={spec} />'
595
+ });
596
+ };
478
597
  const openapiScripts = {
479
598
  openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
480
599
  };
@@ -538,6 +657,10 @@ const addOpenapi = async ()=>{
538
657
  message: "Fill operationId, summary and description from the endpoint logic TSDoc?",
539
658
  default: true
540
659
  });
660
+ const withSwaggerPage = ConfigFile.Instance.data.useReact && await (0, prompts_namespaceObject.confirm)({
661
+ message: 'Add a Swagger UI page?',
662
+ default: true
663
+ });
541
664
  const selected = await addPackageScripts(manifestFile, openapiScripts);
542
665
  if (withExtractor) {
543
666
  const extractorFile = new File(external_node_path_default().join(root, openapiExtractorPath));
@@ -547,6 +670,12 @@ const addOpenapi = async ()=>{
547
670
  const generatorFile = new File(external_node_path_default().join(root, openapiScriptPath));
548
671
  const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
549
672
  if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
673
+ if (withSwaggerPage) {
674
+ const pageFile = new File(external_node_path_default().join(root, swaggerPagePath(rootFolder)));
675
+ const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'));
676
+ if (!pageFile.exists || pageFile.data !== page) pageFile.data = page;
677
+ }
678
+ const resolveJsonModule = withSwaggerPage ? compilerOption(external_node_path_default().join(root, 'tsconfig.json'), 'resolveJsonModule') : true;
550
679
  const hasRestHandlers = new File(external_node_path_default().join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
551
680
  const missingExtractorPackages = withExtractor ? extractorPackages.filter((name)=>!dependencies[name]) : [];
552
681
  return [
@@ -559,9 +688,21 @@ const addOpenapi = async ()=>{
559
688
  ...missingExtractorPackages.length ? [
560
689
  `npm install --save-dev ${missingExtractorPackages.join(' ')}`
561
690
  ] : [],
691
+ ...withSwaggerPage && !dependencies['swagger-ui-react'] ? [
692
+ 'npm install swagger-ui-react'
693
+ ] : [],
694
+ ...withSwaggerPage && !dependencies['@types/swagger-ui-react'] ? [
695
+ 'npm install --save-dev @types/swagger-ui-react'
696
+ ] : [],
697
+ ...true === resolveJsonModule || null === resolveJsonModule ? [] : [
698
+ 'set "resolveJsonModule": true in compilerOptions of tsconfig.json — the Swagger UI page imports the OpenAPI document as JSON'
699
+ ],
562
700
  ...describeScripts(selected, {
563
701
  openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
564
702
  }),
703
+ ...withSwaggerPage ? [
704
+ `SwaggerPage from ${swaggerPagePath(rootFolder)} shows ${splitPath(outputPath).join('/')} once it is generated — render it on a route of your app`
705
+ ] : [],
565
706
  ...hasRestHandlers ? [] : [
566
707
  `restHandlers appear in ${external_node_path_default().posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
567
708
  ]
@@ -1186,34 +1327,6 @@ const addIntegration = async ()=>{
1186
1327
  const nextSteps = await integration.run();
1187
1328
  if (await savePendingChanges()) printNextSteps(nextSteps);
1188
1329
  };
1189
- class UnknownFormatNaming {
1190
- rawSource;
1191
- camelCase;
1192
- PascalCase;
1193
- constructor(rawSource){
1194
- this.rawSource = rawSource;
1195
- const source = rawSource.trim();
1196
- if (!source.includes('-')) {
1197
- this.camelCase = source.substring(0, 1).toLowerCase() + source.substring(1);
1198
- this.PascalCase = source.substring(0, 1).toUpperCase() + source.substring(1);
1199
- }
1200
- const words = source.split('-').filter((word)=>!!word);
1201
- this.camelCase = words.map((word, index)=>0 === index ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
1202
- this.PascalCase = words.map((word)=>word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
1203
- }
1204
- get fileName() {
1205
- return this.rawSource;
1206
- }
1207
- get variableName() {
1208
- return this.camelCase;
1209
- }
1210
- get ClassName() {
1211
- return this.PascalCase;
1212
- }
1213
- get withSpaces() {
1214
- return this.fileName.replaceAll('-', ' ');
1215
- }
1216
- }
1217
1330
  const wiring_layers = [
1218
1331
  'domain',
1219
1332
  'application',
@@ -1230,6 +1343,7 @@ const visibleLayers = {
1230
1343
  ],
1231
1344
  infrastructure: [
1232
1345
  'domain',
1346
+ 'application',
1233
1347
  'infrastructure'
1234
1348
  ],
1235
1349
  presentation: [
@@ -1351,6 +1465,9 @@ const findWiredModules = (contextPath)=>{
1351
1465
  const isCommandOrQuery = (module)=>'commands' === module.kind || 'queries' === module.kind;
1352
1466
  const isExecution = (module)=>isCommandOrQuery(module) && 'execution' === external_node_path_default().basename(external_node_path_default().dirname(module.typeFile));
1353
1467
  const commandOrQueryRule = (candidate, consumer)=>isExecution(consumer) ? !isCommandOrQuery(candidate) : 'application' !== candidate.layer || isExecution(candidate);
1468
+ const layerRules = {
1469
+ infrastructure: (candidate)=>'application' !== candidate.layer || 'application-ports' === candidate.kind
1470
+ };
1354
1471
  const kindRules = {
1355
1472
  'application-services': (candidate)=>'application' !== candidate.layer || 'application-ports' === candidate.kind,
1356
1473
  'use-cases': (candidate)=>'use-cases' !== candidate.kind,
@@ -1360,7 +1477,7 @@ const kindRules = {
1360
1477
  };
1361
1478
  const wiring_implementationType = (consumer, implementation)=>consumer.branched ? external_node_path_default().basename(external_node_path_default().dirname(implementation.file)) : void 0;
1362
1479
  const isSuggestedFor = (candidate, implementation)=>'infrastructure' === candidate.layer && `-${external_node_path_default().basename(candidate.typeFile, '.ts')}-`.includes(`-${implementation}-`);
1363
- const canDependOn = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && (kindRules[consumer.kind]?.(candidate, consumer) ?? true);
1480
+ const canDependOn = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && (layerRules[consumer.implementationsLayer]?.(candidate) ?? true) && (kindRules[consumer.kind]?.(candidate, consumer) ?? true);
1364
1481
  const availableDependencies = (consumer, implementation, candidates)=>{
1365
1482
  const wired = wiredDependencyNames(new File(consumer.wireFile).data, implementation.className);
1366
1483
  return candidates.filter((candidate)=>candidate.wireFile !== consumer.wireFile && canDependOn(consumer, candidate) && !wired.includes(candidate.wireName));
@@ -2052,28 +2169,6 @@ export const SharedErrors = errorNamespace('shared')
2052
2169
  }
2053
2170
  return nextSteps;
2054
2171
  };
2055
- const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
2056
- class NestedName {
2057
- folders;
2058
- folderName;
2059
- fileName;
2060
- ClassName;
2061
- classNameSegments;
2062
- constructor(rawSource){
2063
- const segments = splitSegments(rawSource);
2064
- this.folders = segments.slice(0, -1);
2065
- this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
2066
- this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
2067
- this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
2068
- this.ClassName = this.classNameSegments.join('');
2069
- }
2070
- static validate = (rawSource)=>{
2071
- const segments = splitSegments(rawSource);
2072
- if (!segments.length) return 'Name is required';
2073
- if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
2074
- return true;
2075
- };
2076
- }
2077
2172
  const ignoredFolders = new Set([
2078
2173
  'node_modules',
2079
2174
  '.git',
@@ -2149,7 +2244,6 @@ const validateMove = (reactFolder, module, rawName)=>{
2149
2244
  if (target.startsWith(`${module.path}${external_node_path_default().sep}`)) return 'A widget cannot be moved into itself';
2150
2245
  return true;
2151
2246
  };
2152
- const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
2153
2247
  const readAliases = (projectRoot)=>{
2154
2248
  const tsconfig = external_node_path_default().join(projectRoot, 'tsconfig.json');
2155
2249
  if (!external_node_fs_default().existsSync(tsconfig)) return [];
@@ -3404,25 +3498,6 @@ export const wire${naming.ClassName}UseCase = wireClass(
3404
3498
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
3405
3499
  }
3406
3500
  };
3407
- const scaffoldReactPage = async (presentationReactFolder)=>{
3408
- const name = await (0, prompts_namespaceObject.input)({
3409
- message: 'Provide name (folders split by "/"):',
3410
- validate: NestedName.validate
3411
- });
3412
- const { folders, ClassName, fileName } = new NestedName(name);
3413
- presentationReactFolder.subitem([
3414
- 'pages',
3415
- ...folders
3416
- ]).createFile(`${fileName}-page.tsx`, `
3417
- import { type FC } from 'react'
3418
-
3419
- export type ${ClassName}PageProps = {}
3420
-
3421
- export const ${ClassName}Page: FC<${ClassName}PageProps> = (props) => {
3422
- return <></>
3423
- }
3424
- `.trim());
3425
- };
3426
3501
  const scaffoldReactSharedHook = async (presentationReactFolder)=>{
3427
3502
  const name = await (0, prompts_namespaceObject.input)({
3428
3503
  message: 'Name without "use" (e.g. debounce): '
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@ import node_path from "node:path";
4
4
  import zod from "zod";
5
5
  import node_fs from "node:fs";
6
6
  import { styleText } from "node:util";
7
+ import { createRequire } from "node:module";
7
8
  const pendingFiles = new Map();
8
9
  const pendingFolders = new Set();
9
10
  const pendingMoves = new Map();
@@ -246,6 +247,112 @@ const missingDomainFirstPackages = ()=>{
246
247
  `npm i ${missing.join(' ')}`
247
248
  ] : [];
248
249
  };
250
+ const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
251
+ const resolveExtends = (fromFile, target)=>{
252
+ if (target.startsWith('.') || node_path.isAbsolute(target)) {
253
+ const resolved = node_path.resolve(node_path.dirname(fromFile), target);
254
+ return resolved.endsWith('.json') ? resolved : `${resolved}.json`;
255
+ }
256
+ const require = createRequire(fromFile);
257
+ for (const candidate of [
258
+ target,
259
+ `${target}/tsconfig.json`
260
+ ])try {
261
+ return require.resolve(candidate);
262
+ } catch {}
263
+ };
264
+ const compilerOption = (configFile, name, seen = new Set())=>{
265
+ if (seen.has(configFile) || !node_fs.existsSync(configFile)) return null;
266
+ seen.add(configFile);
267
+ let config;
268
+ try {
269
+ config = JSON.parse(stripJsonComments(node_fs.readFileSync(configFile, 'utf8')));
270
+ } catch {
271
+ return null;
272
+ }
273
+ if (config.compilerOptions && name in config.compilerOptions) return config.compilerOptions[name];
274
+ const parents = [
275
+ config.extends ?? []
276
+ ].flat().reverse();
277
+ for (const parent of parents){
278
+ const parentFile = resolveExtends(configFile, parent);
279
+ const value = parentFile ? compilerOption(parentFile, name, seen) : null;
280
+ if (void 0 !== value) return value;
281
+ }
282
+ };
283
+ class UnknownFormatNaming {
284
+ rawSource;
285
+ camelCase;
286
+ PascalCase;
287
+ constructor(rawSource){
288
+ this.rawSource = rawSource;
289
+ const source = rawSource.trim();
290
+ if (!source.includes('-')) {
291
+ this.camelCase = source.substring(0, 1).toLowerCase() + source.substring(1);
292
+ this.PascalCase = source.substring(0, 1).toUpperCase() + source.substring(1);
293
+ }
294
+ const words = source.split('-').filter((word)=>!!word);
295
+ this.camelCase = words.map((word, index)=>0 === index ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
296
+ this.PascalCase = words.map((word)=>word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
297
+ }
298
+ get fileName() {
299
+ return this.rawSource;
300
+ }
301
+ get variableName() {
302
+ return this.camelCase;
303
+ }
304
+ get ClassName() {
305
+ return this.PascalCase;
306
+ }
307
+ get withSpaces() {
308
+ return this.fileName.replaceAll('-', ' ');
309
+ }
310
+ }
311
+ const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
312
+ class NestedName {
313
+ folders;
314
+ folderName;
315
+ fileName;
316
+ ClassName;
317
+ classNameSegments;
318
+ constructor(rawSource){
319
+ const segments = splitSegments(rawSource);
320
+ this.folders = segments.slice(0, -1);
321
+ this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
322
+ this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
323
+ this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
324
+ this.ClassName = this.classNameSegments.join('');
325
+ }
326
+ static validate = (rawSource)=>{
327
+ const segments = splitSegments(rawSource);
328
+ if (!segments.length) return 'Name is required';
329
+ if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
330
+ return true;
331
+ };
332
+ }
333
+ const reactPageContent = (ClassName, { imports = [], body = '<></>' } = {})=>`
334
+ ${[
335
+ ...imports,
336
+ "import { type FC } from 'react'"
337
+ ].join('\n')}
338
+
339
+ export type ${ClassName}PageProps = {}
340
+
341
+ export const ${ClassName}Page: FC<${ClassName}PageProps> = (props) => {
342
+ return ${body}
343
+ }
344
+ `.trim();
345
+ const scaffoldReactPage = async (presentationReactFolder)=>{
346
+ const name = await input({
347
+ message: 'Provide name (folders split by "/"):',
348
+ validate: NestedName.validate
349
+ });
350
+ const { folders, ClassName, fileName } = new NestedName(name);
351
+ presentationReactFolder.subitem([
352
+ 'pages',
353
+ ...folders
354
+ ]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
355
+ };
249
356
  const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
250
357
  const rootFolderSegments = (rootFolder)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n `).join('');
251
358
  const openapiExtractor = (rootFolder)=>`import path from 'node:path';
@@ -445,6 +552,18 @@ const extractorPackages = [
445
552
  'ts-morph',
446
553
  '@microsoft/tsdoc'
447
554
  ];
555
+ const swaggerPagePath = (rootFolder)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/pages/swagger-page.tsx');
556
+ const swaggerPage = (rootFolder, outputPath)=>{
557
+ const specImport = node_path.posix.relative(node_path.posix.dirname(swaggerPagePath(rootFolder)), outputPath);
558
+ return reactPageContent('Swagger', {
559
+ imports: [
560
+ "import 'swagger-ui-react/swagger-ui.css'",
561
+ "import SwaggerUI from 'swagger-ui-react'",
562
+ `import spec from '${specImport.startsWith('.') ? specImport : `./${specImport}`}' with { type: 'json' }`
563
+ ],
564
+ body: '<SwaggerUI displayOperationId spec={spec} />'
565
+ });
566
+ };
448
567
  const openapiScripts = {
449
568
  openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
450
569
  };
@@ -508,6 +627,10 @@ const addOpenapi = async ()=>{
508
627
  message: "Fill operationId, summary and description from the endpoint logic TSDoc?",
509
628
  default: true
510
629
  });
630
+ const withSwaggerPage = ConfigFile.Instance.data.useReact && await prompts_confirm({
631
+ message: 'Add a Swagger UI page?',
632
+ default: true
633
+ });
511
634
  const selected = await addPackageScripts(manifestFile, openapiScripts);
512
635
  if (withExtractor) {
513
636
  const extractorFile = new File(node_path.join(root, openapiExtractorPath));
@@ -517,6 +640,12 @@ const addOpenapi = async ()=>{
517
640
  const generatorFile = new File(node_path.join(root, openapiScriptPath));
518
641
  const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
519
642
  if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
643
+ if (withSwaggerPage) {
644
+ const pageFile = new File(node_path.join(root, swaggerPagePath(rootFolder)));
645
+ const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'));
646
+ if (!pageFile.exists || pageFile.data !== page) pageFile.data = page;
647
+ }
648
+ const resolveJsonModule = withSwaggerPage ? compilerOption(node_path.join(root, 'tsconfig.json'), 'resolveJsonModule') : true;
520
649
  const hasRestHandlers = new File(node_path.join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
521
650
  const missingExtractorPackages = withExtractor ? extractorPackages.filter((name)=>!dependencies[name]) : [];
522
651
  return [
@@ -529,9 +658,21 @@ const addOpenapi = async ()=>{
529
658
  ...missingExtractorPackages.length ? [
530
659
  `npm install --save-dev ${missingExtractorPackages.join(' ')}`
531
660
  ] : [],
661
+ ...withSwaggerPage && !dependencies['swagger-ui-react'] ? [
662
+ 'npm install swagger-ui-react'
663
+ ] : [],
664
+ ...withSwaggerPage && !dependencies['@types/swagger-ui-react'] ? [
665
+ 'npm install --save-dev @types/swagger-ui-react'
666
+ ] : [],
667
+ ...true === resolveJsonModule || null === resolveJsonModule ? [] : [
668
+ 'set "resolveJsonModule": true in compilerOptions of tsconfig.json — the Swagger UI page imports the OpenAPI document as JSON'
669
+ ],
532
670
  ...describeScripts(selected, {
533
671
  openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
534
672
  }),
673
+ ...withSwaggerPage ? [
674
+ `SwaggerPage from ${swaggerPagePath(rootFolder)} shows ${splitPath(outputPath).join('/')} once it is generated — render it on a route of your app`
675
+ ] : [],
535
676
  ...hasRestHandlers ? [] : [
536
677
  `restHandlers appear in ${node_path.posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
537
678
  ]
@@ -1156,34 +1297,6 @@ const addIntegration = async ()=>{
1156
1297
  const nextSteps = await integration.run();
1157
1298
  if (await savePendingChanges()) printNextSteps(nextSteps);
1158
1299
  };
1159
- class UnknownFormatNaming {
1160
- rawSource;
1161
- camelCase;
1162
- PascalCase;
1163
- constructor(rawSource){
1164
- this.rawSource = rawSource;
1165
- const source = rawSource.trim();
1166
- if (!source.includes('-')) {
1167
- this.camelCase = source.substring(0, 1).toLowerCase() + source.substring(1);
1168
- this.PascalCase = source.substring(0, 1).toUpperCase() + source.substring(1);
1169
- }
1170
- const words = source.split('-').filter((word)=>!!word);
1171
- this.camelCase = words.map((word, index)=>0 === index ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
1172
- this.PascalCase = words.map((word)=>word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
1173
- }
1174
- get fileName() {
1175
- return this.rawSource;
1176
- }
1177
- get variableName() {
1178
- return this.camelCase;
1179
- }
1180
- get ClassName() {
1181
- return this.PascalCase;
1182
- }
1183
- get withSpaces() {
1184
- return this.fileName.replaceAll('-', ' ');
1185
- }
1186
- }
1187
1300
  const wiring_layers = [
1188
1301
  'domain',
1189
1302
  'application',
@@ -1200,6 +1313,7 @@ const visibleLayers = {
1200
1313
  ],
1201
1314
  infrastructure: [
1202
1315
  'domain',
1316
+ 'application',
1203
1317
  'infrastructure'
1204
1318
  ],
1205
1319
  presentation: [
@@ -1321,6 +1435,9 @@ const findWiredModules = (contextPath)=>{
1321
1435
  const isCommandOrQuery = (module)=>'commands' === module.kind || 'queries' === module.kind;
1322
1436
  const isExecution = (module)=>isCommandOrQuery(module) && 'execution' === node_path.basename(node_path.dirname(module.typeFile));
1323
1437
  const commandOrQueryRule = (candidate, consumer)=>isExecution(consumer) ? !isCommandOrQuery(candidate) : 'application' !== candidate.layer || isExecution(candidate);
1438
+ const layerRules = {
1439
+ infrastructure: (candidate)=>'application' !== candidate.layer || 'application-ports' === candidate.kind
1440
+ };
1324
1441
  const kindRules = {
1325
1442
  'application-services': (candidate)=>'application' !== candidate.layer || 'application-ports' === candidate.kind,
1326
1443
  'use-cases': (candidate)=>'use-cases' !== candidate.kind,
@@ -1330,7 +1447,7 @@ const kindRules = {
1330
1447
  };
1331
1448
  const wiring_implementationType = (consumer, implementation)=>consumer.branched ? node_path.basename(node_path.dirname(implementation.file)) : void 0;
1332
1449
  const isSuggestedFor = (candidate, implementation)=>'infrastructure' === candidate.layer && `-${node_path.basename(candidate.typeFile, '.ts')}-`.includes(`-${implementation}-`);
1333
- const canDependOn = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && (kindRules[consumer.kind]?.(candidate, consumer) ?? true);
1450
+ const canDependOn = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && (layerRules[consumer.implementationsLayer]?.(candidate) ?? true) && (kindRules[consumer.kind]?.(candidate, consumer) ?? true);
1334
1451
  const availableDependencies = (consumer, implementation, candidates)=>{
1335
1452
  const wired = wiredDependencyNames(new File(consumer.wireFile).data, implementation.className);
1336
1453
  return candidates.filter((candidate)=>candidate.wireFile !== consumer.wireFile && canDependOn(consumer, candidate) && !wired.includes(candidate.wireName));
@@ -2022,28 +2139,6 @@ export const SharedErrors = errorNamespace('shared')
2022
2139
  }
2023
2140
  return nextSteps;
2024
2141
  };
2025
- const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
2026
- class NestedName {
2027
- folders;
2028
- folderName;
2029
- fileName;
2030
- ClassName;
2031
- classNameSegments;
2032
- constructor(rawSource){
2033
- const segments = splitSegments(rawSource);
2034
- this.folders = segments.slice(0, -1);
2035
- this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
2036
- this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
2037
- this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
2038
- this.ClassName = this.classNameSegments.join('');
2039
- }
2040
- static validate = (rawSource)=>{
2041
- const segments = splitSegments(rawSource);
2042
- if (!segments.length) return 'Name is required';
2043
- if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
2044
- return true;
2045
- };
2046
- }
2047
2142
  const ignoredFolders = new Set([
2048
2143
  'node_modules',
2049
2144
  '.git',
@@ -2119,7 +2214,6 @@ const validateMove = (reactFolder, module, rawName)=>{
2119
2214
  if (target.startsWith(`${module.path}${node_path.sep}`)) return 'A widget cannot be moved into itself';
2120
2215
  return true;
2121
2216
  };
2122
- const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
2123
2217
  const readAliases = (projectRoot)=>{
2124
2218
  const tsconfig = node_path.join(projectRoot, 'tsconfig.json');
2125
2219
  if (!node_fs.existsSync(tsconfig)) return [];
@@ -3374,25 +3468,6 @@ export const wire${naming.ClassName}UseCase = wireClass(
3374
3468
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
3375
3469
  }
3376
3470
  };
3377
- const scaffoldReactPage = async (presentationReactFolder)=>{
3378
- const name = await input({
3379
- message: 'Provide name (folders split by "/"):',
3380
- validate: NestedName.validate
3381
- });
3382
- const { folders, ClassName, fileName } = new NestedName(name);
3383
- presentationReactFolder.subitem([
3384
- 'pages',
3385
- ...folders
3386
- ]).createFile(`${fileName}-page.tsx`, `
3387
- import { type FC } from 'react'
3388
-
3389
- export type ${ClassName}PageProps = {}
3390
-
3391
- export const ${ClassName}Page: FC<${ClassName}PageProps> = (props) => {
3392
- return <></>
3393
- }
3394
- `.trim());
3395
- };
3396
3471
  const scaffoldReactSharedHook = async (presentationReactFolder)=>{
3397
3472
  const name = await input({
3398
3473
  message: 'Name without "use" (e.g. debounce): '
@@ -1,5 +1,10 @@
1
1
  export declare const openapiScriptPath = "scripts/generate-openapi.ts";
2
2
  export declare const defaultOpenapiPath: (withNext: boolean) => "public/openapi.json" | "openapi.json";
3
+ export declare const swaggerPagePath: (rootFolder: string) => string;
4
+ /**
5
+ * A React page rendering the OpenAPI document with Swagger UI.
6
+ */
7
+ export declare const swaggerPage: (rootFolder: string, outputPath: string) => string;
3
8
  export declare const openapiScripts: {
4
9
  openapi: string;
5
10
  };
@@ -0,0 +1,10 @@
1
+ /**
2
+ * tsconfig is JSON with comments and trailing commas.
3
+ */
4
+ export declare const stripJsonComments: (source: string) => string;
5
+ /**
6
+ * The compiler option as the config sets it, through its `extends`
7
+ * chain: the nearest config that sets it wins. Undefined when no config
8
+ * sets it; null when a config can't be read, so the value is unknown.
9
+ */
10
+ export declare const compilerOption: (configFile: string, name: string, seen?: Set<string>) => unknown;
@@ -0,0 +1 @@
1
+ export {};
@@ -1,2 +1,10 @@
1
1
  import type { Folder } from '../file-system';
2
+ /**
3
+ * Content of `<file>-page.tsx`: imports go before React's, `body` is
4
+ * what the page returns.
5
+ */
6
+ export declare const reactPageContent: (ClassName: string, { imports, body }?: {
7
+ imports?: string[];
8
+ body?: string;
9
+ }) => string;
2
10
  export declare const scaffoldReactPage: (presentationReactFolder: Folder) => Promise<void>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@domain-first/project-structure",
3
3
  "description": "Build and manage your Domain-First project structure with CLI",
4
- "version": "3.2.1",
4
+ "version": "3.3.0",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -11,7 +11,7 @@ Generated files contain placeholders: empty classes, `{}` schemas, `[]` dependen
11
11
 
12
12
  - New files need an approved work plan (`df-ps-scaffold`, rule 1) and come only via df-ps or its listed exceptions (rule 2). Edits to existing files don't need approval; report them.
13
13
  - Keep generated names and paths: barrels, wiring, specs, and `presentation/rest/wires.ts` import them.
14
- - Layers: domain imports nothing from other layers. Application uses domain and its own abstractions. Infrastructure implements repositories, contracts, and ports. Presentation calls application handlers. Only `wiring/` knows concrete classes.
14
+ - Layers: domain imports nothing from other layers. Application uses domain and its own abstractions. Infrastructure implements repositories, contracts, and ports, and may use application ports (of its context and the Shared Layer), never other application modules. Infrastructure needing logic from an application service means the logic is misplaced: pure logic without ports → a domain service; logic over ports → call those ports directly; technical logic (mapping, retries, formatting for an external API) → an infrastructure service. Presentation calls application handlers. Only `wiring/` knows concrete classes.
15
15
  - Constructors take abstractions (`OrderRepository`, abstract `PlaceOrderCommand`, port `PaymentGateway`), never `PrismaOrderRepository`.
16
16
  - Implementation order: domain → application → schema tool runs (migrations, only if infrastructure needs data the database lacks) → infrastructure (repositories, execution commands/queries, adapters) → endpoints → other tool runs (OpenAPI, API client) → React. Widgets need the regenerated client. How to run tools and handle their output: the project's scripts skill (`project-scripts`), if there is one.
17
17
  - Run the project's tsc/lint/tests after each component.
@@ -53,6 +53,7 @@ Example: `order-confirmation` prepares a message and calls the injected `mailer`
53
53
  | Use case / application service | Use case = one action with `handle`. Application service = helper used by use cases. |
54
54
  | Use case / orchestrator | Use case = action exposed outside. Orchestrator = reusable operation called by use cases. |
55
55
  | Application / infrastructure service | Used by use cases → application. Only by adapters/repositories → infrastructure. |
56
+ | Logic infrastructure needs from an application service | Infrastructure never sees application services. Pure logic without ports → domain service. Logic over ports → infrastructure calls the ports directly. Technical (mapping, retries, external API formats) → infrastructure service. |
56
57
  | Clock | Always a port (`clock`, usually in Shared Layer). |
57
58
 
58
59
  ## React page, widget, UI-kit component or shared hook
@@ -6,7 +6,7 @@ Every step list starts with `"pick:Bounded Context: <ctx>"` or `"pick:Shared Lay
6
6
 
7
7
  Any generator: if the run would replace existing files, the last prompt is the confirm `Overwrite them?` (the files are listed above it). Without it, nothing extra is asked. Added lines (barrels, errors, wiring indexes) never trigger it.
8
8
 
9
- {wire} Generators that create a wire (all below except endpoints, which ask their own two selects) then ask the checkbox `Dependencies:`, before `Overwrite them?`. It lists wired modules of `<C>` and of the Shared Layer (`(shared)` suffix), grouped under headers in this order: Repositories, Domain services, Ports, Application services, Queries, Commands, Use cases, Infrastructure services, Presentation services. Inside a group: by type name, `<C>` first. Headers are not counted: `toggle:<n,..>` numbers only modules, top to bottom. Answer `toggle:<n,..>` or `none`. It is skipped when nothing fits, so check `<C>/wiring/` and `<rootFolder>/shared/wiring/` before counting steps. What fits depends on the layer of the class the wire builds: domain → domain; application → domain, application; infrastructure (repository, execution command/query, and port implementations) → domain, infrastructure (it implements application modules, never depends on them); presentation → application, presentation. On top of that, application services see only ports from application, use cases never see use cases, repository implementations never see repositories, execution command/query implementations never see commands or queries, and orchestration commands/queries see only execution commands and queries from application. Endpoints are never listed. Each chosen module goes into the wire (`wireClass(X, [wireUserRepository])`) and the constructor (`private readonly userRepository: UserRepository`, with `import type`), in the same order. An env-branched wire (repository, execution command/query, port) wires each implementation in isolation: instead of `Dependencies:` it asks `Dependencies for <Implementation>:` once per implementation, in the order of the wire (main, then test). Each list leaves out only what that implementation already has, and a list with nothing to choose is skipped. It may start with a `Suggested` group: infrastructure modules whose file name has the implementation label (its folder, e.g. `prisma`, `in-memory`) as whole words, such as `in-memory-db-infrastructure-service` for `in-memory`. They are listed there only, so numbering starts with them, and they are **checked**: `none` keeps them, `toggle:<n>` on one of them unchecks it.
9
+ {wire} Generators that create a wire (all below except endpoints, which ask their own two selects) then ask the checkbox `Dependencies:`, before `Overwrite them?`. It lists wired modules of `<C>` and of the Shared Layer (`(shared)` suffix), grouped under headers in this order: Repositories, Domain services, Ports, Application services, Queries, Commands, Use cases, Infrastructure services, Presentation services. Inside a group: by type name, `<C>` first. Headers are not counted: `toggle:<n,..>` numbers only modules, top to bottom. Answer `toggle:<n,..>` or `none`. It is skipped when nothing fits, so check `<C>/wiring/` and `<rootFolder>/shared/wiring/` before counting steps. What fits depends on the layer of the class the wire builds: domain → domain; application → domain, application; infrastructure (repository, execution command/query, and port implementations, infrastructure services) → domain, application ports (of `<C>` and the Shared Layer; no other application modules), infrastructure; presentation → application, presentation. On top of that, application services see only ports from application, use cases never see use cases, repository implementations never see repositories, execution command/query implementations never see commands or queries, and orchestration commands/queries see only execution commands and queries from application. Endpoints are never listed. Each chosen module goes into the wire (`wireClass(X, [wireUserRepository])`) and the constructor (`private readonly userRepository: UserRepository`, with `import type`), in the same order. An env-branched wire (repository, execution command/query, port) wires each implementation in isolation: instead of `Dependencies:` it asks `Dependencies for <Implementation>:` once per implementation, in the order of the wire (main, then test). Each list leaves out only what that implementation already has, and a list with nothing to choose is skipped. It may start with a `Suggested` group: infrastructure modules whose file name has the implementation label (its folder, e.g. `prisma`, `in-memory`) as whole words, such as `in-memory-db-infrastructure-service` for `in-memory`. They are listed there only, so numbering starts with them, and they are **checked**: `none` keeps them, `toggle:<n>` on one of them unchecks it.
10
10
 
11
11
  ## Bounded context
12
12