@domain-first/project-structure 8.9.1 → 8.10.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.
@@ -33,23 +33,126 @@ const external_node_path_namespaceObject = require("node:path");
33
33
  var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_namespaceObject);
34
34
  const external_zod_namespaceObject = require("zod");
35
35
  var external_zod_default = /*#__PURE__*/ __webpack_require__.n(external_zod_namespaceObject);
36
+ class UnknownFormatNaming {
37
+ rawSource;
38
+ camelCase;
39
+ PascalCase;
40
+ constructor(rawSource){
41
+ this.rawSource = rawSource;
42
+ const source = rawSource.trim();
43
+ if (!source.includes('-')) {
44
+ this.camelCase = source.substring(0, 1).toLowerCase() + source.substring(1);
45
+ this.PascalCase = source.substring(0, 1).toUpperCase() + source.substring(1);
46
+ }
47
+ const words = source.split('-').filter((word)=>!!word);
48
+ this.camelCase = words.map((word, index)=>0 === index ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
49
+ this.PascalCase = words.map((word)=>word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
50
+ }
51
+ get fileName() {
52
+ return this.rawSource;
53
+ }
54
+ get variableName() {
55
+ return this.camelCase;
56
+ }
57
+ get ClassName() {
58
+ return this.PascalCase;
59
+ }
60
+ get withSpaces() {
61
+ return this.fileName.replaceAll('-', ' ');
62
+ }
63
+ }
64
+ const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
65
+ class NestedName {
66
+ folders;
67
+ folderName;
68
+ fileName;
69
+ ClassName;
70
+ classNameSegments;
71
+ constructor(rawSource){
72
+ const segments = splitSegments(rawSource);
73
+ this.folders = segments.slice(0, -1);
74
+ this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
75
+ this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
76
+ this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
77
+ this.ClassName = this.classNameSegments.join('');
78
+ }
79
+ static validate = (rawSource)=>{
80
+ const segments = splitSegments(rawSource);
81
+ if (!segments.length) return 'Name is required';
82
+ if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
83
+ return true;
84
+ };
85
+ }
86
+ const boundedContextsFolderName = 'bounded-contexts';
87
+ const contextLayerFolders = [
88
+ 'domain',
89
+ 'application',
90
+ 'infrastructure',
91
+ 'presentation',
92
+ 'wiring'
93
+ ];
94
+ const subfolders = (folder)=>external_node_fs_default().existsSync(folder) ? external_node_fs_default().readdirSync(folder, {
95
+ withFileTypes: true
96
+ }).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name) : [];
97
+ const isBoundedContextFolder = (folder)=>{
98
+ const names = subfolders(folder);
99
+ return !names.length || names.some((name)=>contextLayerFolders.includes(name));
100
+ };
101
+ const boundedContextNames = (contextsFolder)=>{
102
+ const walk = (folder, prefix)=>subfolders(folder).flatMap((name)=>{
103
+ const child = external_node_path_default().join(folder, name);
104
+ return isBoundedContextFolder(child) ? [
105
+ [
106
+ ...prefix,
107
+ name
108
+ ].join('/')
109
+ ] : walk(child, [
110
+ ...prefix,
111
+ name
112
+ ]);
113
+ });
114
+ return walk(contextsFolder, []).sort();
115
+ };
116
+ const contextClassName = (name)=>new NestedName(name).ClassName;
117
+ const splitContextSegments = (segments)=>{
118
+ const layer = segments.findIndex((segment)=>contextLayerFolders.includes(segment));
119
+ const length = layer > 0 ? layer : 1;
120
+ return {
121
+ name: segments.slice(0, length).join('/'),
122
+ segments: segments.slice(length)
123
+ };
124
+ };
125
+ const validateBoundedContextName = (contextsFolder, name)=>{
126
+ const valid = NestedName.validate(name);
127
+ if (true !== valid) return valid;
128
+ const segments = name.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
129
+ const reserved = segments.find((segment)=>contextLayerFolders.includes(segment));
130
+ if (reserved) return `"${reserved}" is a layer folder of a bounded context and can't name one`;
131
+ for(let index = 1; index < segments.length; index++){
132
+ const parent = external_node_path_default().join(contextsFolder, ...segments.slice(0, index));
133
+ if (external_node_fs_default().existsSync(parent) && isBoundedContextFolder(parent)) return `${segments.slice(0, index).join('/')} is a bounded context: contexts can't be nested in one`;
134
+ }
135
+ const folder = external_node_path_default().join(contextsFolder, ...segments);
136
+ if (external_node_fs_default().existsSync(folder) && !isBoundedContextFolder(folder)) return `${segments.join('/')} groups bounded contexts: pick a name inside it`;
137
+ return true;
138
+ };
36
139
  const crossContextImplementation = 'cross-context';
37
140
  const hasNeighboringBoundedContext = (ownerPath)=>{
38
- const contextsPath = external_node_path_default().dirname(ownerPath);
39
- return 'bounded-contexts' === external_node_path_default().basename(contextsPath) && external_node_fs_default().existsSync(contextsPath) && external_node_fs_default().readdirSync(contextsPath, {
40
- withFileTypes: true
41
- }).some((entry)=>entry.isDirectory() && entry.name !== external_node_path_default().basename(ownerPath));
141
+ const location = boundedContextLocation(external_node_path_default().join(ownerPath, 'domain'));
142
+ if (!location) return false;
143
+ const contextsPath = external_node_path_default().join(location.root, boundedContextsFolderName);
144
+ return boundedContextNames(contextsPath).some((name)=>name !== location.name);
42
145
  };
43
146
  const boundedContextLocation = (file)=>{
44
147
  const parts = external_node_path_default().resolve(file).split(external_node_path_default().sep);
45
- const index = parts.lastIndexOf('bounded-contexts');
148
+ const index = parts.lastIndexOf(boundedContextsFolderName);
46
149
  if (-1 === index || parts.length < index + 3) return;
47
150
  return {
48
151
  root: parts.slice(0, index).join(external_node_path_default().sep),
49
- name: parts[index + 1],
50
- segments: parts.slice(index + 2)
152
+ ...splitContextSegments(parts.slice(index + 1))
51
153
  };
52
154
  };
155
+ const boundedContextName = (folder)=>boundedContextLocation(external_node_path_default().join(folder, 'domain'))?.name;
53
156
  const isCrossContextImplementation = (file)=>{
54
157
  const location = boundedContextLocation(file);
55
158
  const [layer, kind, label] = location?.segments ?? [];
@@ -844,34 +947,6 @@ const addDrizzle = async ()=>{
844
947
  })
845
948
  ];
846
949
  };
847
- class UnknownFormatNaming {
848
- rawSource;
849
- camelCase;
850
- PascalCase;
851
- constructor(rawSource){
852
- this.rawSource = rawSource;
853
- const source = rawSource.trim();
854
- if (!source.includes('-')) {
855
- this.camelCase = source.substring(0, 1).toLowerCase() + source.substring(1);
856
- this.PascalCase = source.substring(0, 1).toUpperCase() + source.substring(1);
857
- }
858
- const words = source.split('-').filter((word)=>!!word);
859
- this.camelCase = words.map((word, index)=>0 === index ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
860
- this.PascalCase = words.map((word)=>word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
861
- }
862
- get fileName() {
863
- return this.rawSource;
864
- }
865
- get variableName() {
866
- return this.camelCase;
867
- }
868
- get ClassName() {
869
- return this.PascalCase;
870
- }
871
- get withSpaces() {
872
- return this.fileName.replaceAll('-', ' ');
873
- }
874
- }
875
950
  const wiring_layers = [
876
951
  'domain',
877
952
  'application',
@@ -1214,7 +1289,7 @@ const wireDependencies = (consumer, implementation, dependencies)=>{
1214
1289
  const bindings = dependencies.map((dependency)=>{
1215
1290
  const crossContext = crossContextImportAllowed(consumer.wireFile, dependency.wireFile);
1216
1291
  const context = crossContext ? boundedContextLocation(dependency.wireFile) : void 0;
1217
- const prefix = context ? new UnknownFormatNaming(context.name).ClassName : '';
1292
+ const prefix = context ? contextClassName(context.name) : '';
1218
1293
  const wireName = dependencyBinding(wireSource, consumer.wireFile, dependency.wireFile, dependency.wireName, context ? `wire${prefix}${dependency.typeName}` : dependency.wireName);
1219
1294
  const typeName = dependencyBinding(classSource, implementation.file, dependency.typeFile, dependency.typeName, `${prefix}${dependency.typeName}`);
1220
1295
  wireSource = addImport(wireSource, `import { ${importedAs(dependency.wireName, wireName)} } from '${relativeImport(consumer.wireFile, dependency.wireFile)}'`);
@@ -1550,28 +1625,6 @@ const compilerOption = (configFile, name, seen = new Set())=>{
1550
1625
  if (void 0 !== value) return value;
1551
1626
  }
1552
1627
  };
1553
- const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
1554
- class NestedName {
1555
- folders;
1556
- folderName;
1557
- fileName;
1558
- ClassName;
1559
- classNameSegments;
1560
- constructor(rawSource){
1561
- const segments = splitSegments(rawSource);
1562
- this.folders = segments.slice(0, -1);
1563
- this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
1564
- this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
1565
- this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
1566
- this.ClassName = this.classNameSegments.join('');
1567
- }
1568
- static validate = (rawSource)=>{
1569
- const segments = splitSegments(rawSource);
1570
- if (!segments.length) return 'Name is required';
1571
- if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
1572
- return true;
1573
- };
1574
- }
1575
1628
  const reactPageContent = (ClassName, { imports = [], body = '<></>' } = {})=>`
1576
1629
  ${[
1577
1630
  ...imports,
@@ -1591,13 +1644,14 @@ export default function Page() {
1591
1644
  return <${ClassName}Page />
1592
1645
  }
1593
1646
  `.trim();
1594
- const scaffoldNextRoute = (name, pageFile)=>{
1647
+ const scaffoldNextRoute = (name, pagePath)=>{
1595
1648
  const root = new project_root_ProjectRoot().path;
1596
1649
  const route = external_node_path_default().join(root, nextAppFolder(root), ...name.folders, name.folderName, 'page.tsx');
1597
1650
  const relativeRoute = external_node_path_default().relative(root, route).split(external_node_path_default().sep).join('/');
1598
1651
  const routeFile = new file_system_File(route);
1599
- if (routeFile.exists) return void report(`${relativeRoute} already exists: render ${name.ClassName}Page there yourself.`);
1600
- routeFile.data = nextRouteContent(name.ClassName, relativeImport(route, pageFile.path.replace(/\.tsx$/, '')));
1652
+ const content = nextRouteContent(name.ClassName, relativeImport(route, pagePath.replace(/\.tsx$/, '')));
1653
+ if (routeFile.exists) return routeFile.data === content ? void 0 : `${relativeRoute} already exists: render ${name.ClassName}Page there yourself.`;
1654
+ routeFile.data = content;
1601
1655
  };
1602
1656
  const scaffoldReactPage = async (presentationReactFolder)=>{
1603
1657
  const name = await interaction_input({
@@ -1611,33 +1665,43 @@ const scaffoldReactPage = async (presentationReactFolder)=>{
1611
1665
  'pages',
1612
1666
  ...folders
1613
1667
  ]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
1614
- if (usesNext()) scaffoldNextRoute(nestedName, pageFile);
1668
+ if (usesNext()) {
1669
+ const hint = scaffoldNextRoute(nestedName, pageFile.path);
1670
+ if (hint) report(hint);
1671
+ }
1615
1672
  };
1616
1673
  const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
1617
1674
  const rootFolderSegments = (rootFolder, indent = 20)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n${' '.repeat(indent)}`).join('');
1618
- const endpointFileLookup = (rootFolder)=>` const [currentBoundedContext, ...relativePath] = routeMetadata.path;
1619
-
1620
- if (!currentBoundedContext) {
1621
- return undefined;
1622
- }
1623
-
1624
- // A controller is the first folder of the path; other routes
1625
- // belong to the context root in presentation/rest/(root).
1626
- const restFolder = path.join(
1627
- ${rootFolderSegments(rootFolder, 16)}'bounded-contexts',
1628
- currentBoundedContext,
1629
- 'presentation',
1630
- 'rest'
1675
+ const endpointFileLookup = (rootFolder)=>` // A context is the start of the route, nested ones included
1676
+ // (/sales/orders/...). A controller is the next folder; other
1677
+ // routes belong to the context root in presentation/rest/(root).
1678
+ const contextsFolder = path.join(
1679
+ ${rootFolderSegments(rootFolder, 16)}'bounded-contexts'
1631
1680
  );
1632
- const endpointPath = [
1633
- ...relativePath.map(pathParameterAsName),
1634
- \`\${routeMetadata.method.toUpperCase()}.ts\`
1635
- ];
1636
- const endpointFile =
1637
- project.getSourceFile(path.join(restFolder, ...endpointPath)) ??
1638
- project.getSourceFile(
1639
- path.join(restFolder, '(root)', ...endpointPath)
1640
- );
1681
+ const endpointFile = Array.from(
1682
+ { length: routeMetadata.path.length },
1683
+ (_, index) => index + 1
1684
+ )
1685
+ .flatMap((contextLength) => {
1686
+ const restFolder = path.join(
1687
+ contextsFolder,
1688
+ ...routeMetadata.path.slice(0, contextLength),
1689
+ 'presentation',
1690
+ 'rest'
1691
+ );
1692
+ const endpointPath = [
1693
+ ...routeMetadata.path
1694
+ .slice(contextLength)
1695
+ .map(pathParameterAsName),
1696
+ \`\${routeMetadata.method.toUpperCase()}.ts\`
1697
+ ];
1698
+ return [
1699
+ path.join(restFolder, ...endpointPath),
1700
+ path.join(restFolder, '(root)', ...endpointPath)
1701
+ ];
1702
+ })
1703
+ .map((file) => project.getSourceFile(file))
1704
+ .find((file) => !!file);
1641
1705
  `;
1642
1706
  const openapiExtractor = (rootFolder)=>`import path from 'node:path';
1643
1707
  import {
@@ -1784,9 +1848,9 @@ const extractorPackages = [
1784
1848
  '@microsoft/tsdoc'
1785
1849
  ];
1786
1850
  const swaggerPagePath = (rootFolder)=>external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/pages/swagger-page.tsx');
1787
- const swaggerPage = (rootFolder, outputPath)=>{
1851
+ const swaggerPage = (rootFolder, outputPath, withNext = false)=>{
1788
1852
  const specImport = external_node_path_default().posix.relative(external_node_path_default().posix.dirname(swaggerPagePath(rootFolder)), outputPath);
1789
- return reactPageContent('Swagger', {
1853
+ const page = reactPageContent('Swagger', {
1790
1854
  imports: [
1791
1855
  "import 'swagger-ui-react/swagger-ui.css'",
1792
1856
  "import SwaggerUI from 'swagger-ui-react'",
@@ -1794,6 +1858,7 @@ const swaggerPage = (rootFolder, outputPath)=>{
1794
1858
  ],
1795
1859
  body: '<SwaggerUI displayOperationId spec={spec} />'
1796
1860
  });
1861
+ return withNext ? `'use client'\n\n${page}` : page;
1797
1862
  };
1798
1863
  const openapiScripts = {
1799
1864
  openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
@@ -1875,10 +1940,14 @@ const addOpenapi = async ()=>{
1875
1940
  const generatorFile = new file_system_File(external_node_path_default().join(root, openapiScriptPath));
1876
1941
  const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
1877
1942
  if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
1943
+ const withNextRoute = withSwaggerPage && usesNext();
1944
+ let nextRouteHint;
1878
1945
  if (withSwaggerPage) {
1879
- const pageFile = new file_system_File(external_node_path_default().join(root, swaggerPagePath(rootFolder)));
1880
- const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'));
1946
+ const pagePath = external_node_path_default().join(root, swaggerPagePath(rootFolder));
1947
+ const pageFile = new file_system_File(pagePath);
1948
+ const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'), withNextRoute);
1881
1949
  if (!pageFile.exists || pageFile.data !== page) pageFile.data = page;
1950
+ if (withNextRoute) nextRouteHint = scaffoldNextRoute(new NestedName('swagger'), pagePath);
1882
1951
  }
1883
1952
  const resolveJsonModule = withSwaggerPage ? compilerOption(external_node_path_default().join(root, 'tsconfig.json'), 'resolveJsonModule') : true;
1884
1953
  const hasRestHandlers = new file_system_File(external_node_path_default().join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
@@ -1905,9 +1974,12 @@ const addOpenapi = async ()=>{
1905
1974
  ...describeScripts(selected, {
1906
1975
  openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
1907
1976
  }),
1908
- ...withSwaggerPage ? [
1977
+ ...withSwaggerPage && !withNextRoute ? [
1909
1978
  `SwaggerPage from ${swaggerPagePath(rootFolder)} shows ${splitPath(outputPath).join('/')} once it is generated — render it on a route of your app`
1910
1979
  ] : [],
1980
+ ...withNextRoute ? [
1981
+ nextRouteHint ?? `/swagger shows ${splitPath(outputPath).join('/')} once it is generated — the route is ${nextAppFolder(root)}/swagger/page.tsx`
1982
+ ] : [],
1911
1983
  ...hasRestHandlers ? [] : [
1912
1984
  `restHandlers appear in ${external_node_path_default().posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
1913
1985
  ]
@@ -2397,9 +2469,7 @@ const dependencyOptions = (boundedContextFolder)=>{
2397
2469
  module: x,
2398
2470
  label: `${x.typeName} (shared-kernel)`
2399
2471
  })),
2400
- ...isShared ? [] : contextsFolder.content.subfolderNames.filter((name)=>name !== boundedContextFolder.name).sort().flatMap((name)=>findWiredModules(contextsFolder.subitem([
2401
- name
2402
- ]).path).map((module)=>({
2472
+ ...isShared ? [] : boundedContextNames(contextsFolder.path).filter((name)=>name !== boundedContextName(boundedContextFolder.path)).flatMap((name)=>findWiredModules(contextsFolder.subitem(name.split('/')).path).map((module)=>({
2403
2473
  module,
2404
2474
  label: `${module.typeName} (${name})`
2405
2475
  })))
@@ -3013,7 +3083,7 @@ const integrationSpecFile = (unit, label)=>{
3013
3083
  ]).find((file)=>file.startsWith(`${layout.implementations}/${label}/`)) : void 0;
3014
3084
  const projectRoot = projectRootOf(unit.ownerPath);
3015
3085
  if (!source || !projectRoot) return;
3016
- return external_node_path_default().join(projectRoot, integrationSpecsFolder, external_node_path_default().basename(unit.ownerPath), source.slice(15).replace(/\.ts$/, '.spec.ts'));
3086
+ return external_node_path_default().join(projectRoot, integrationSpecsFolder, ...(boundedContextName(unit.ownerPath) ?? external_node_path_default().basename(unit.ownerPath)).split('/'), source.slice(15).replace(/\.ts$/, '.spec.ts'));
3017
3087
  };
3018
3088
  const integrationSpecSubjects = (unit)=>'infrastructure-service' === unit.kind ? [
3019
3089
  void 0
@@ -3024,21 +3094,21 @@ const integrationSpecsStop = (file)=>{
3024
3094
  const folder = external_node_path_default().join(projectRoot, integrationSpecsFolder);
3025
3095
  return file.startsWith(`${folder}${external_node_path_default().sep}`) ? folder : void 0;
3026
3096
  };
3027
- const subfolders = (folder)=>external_node_fs_default().existsSync(folder) ? external_node_fs_default().readdirSync(folder, {
3097
+ const backend_module_move_subfolders = (folder)=>external_node_fs_default().existsSync(folder) ? external_node_fs_default().readdirSync(folder, {
3028
3098
  withFileTypes: true
3029
3099
  }).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name).sort() : [];
3030
3100
  const namesBySuffix = (folder, suffix)=>external_node_fs_default().existsSync(folder) ? external_node_fs_default().readdirSync(folder).filter((file)=>file.endsWith(suffix) && !file.endsWith('.spec.ts')).map((file)=>file.slice(0, -suffix.length)).sort() : [];
3031
3101
  const labelsOf = (ownerPath, kind, name)=>{
3032
3102
  const { implementations } = kindLayouts[kind];
3033
3103
  if (!implementations) return [];
3034
- return subfolders(external_node_path_default().join(ownerPath, implementations)).filter((label)=>kindLayouts[kind].files({
3104
+ return backend_module_move_subfolders(external_node_path_default().join(ownerPath, implementations)).filter((label)=>kindLayouts[kind].files({
3035
3105
  ownerPath,
3036
3106
  name
3037
3107
  }, [
3038
3108
  label
3039
3109
  ]).some((file)=>file.startsWith(`${implementations}/`) && external_node_fs_default().existsSync(external_node_path_default().join(ownerPath, file))));
3040
3110
  };
3041
- const aggregatesOf = (ownerPath)=>subfolders(external_node_path_default().join(ownerPath, 'domain/aggregates')).filter((name)=>external_node_fs_default().existsSync(external_node_path_default().join(ownerPath, 'domain/aggregates', name, `${name}.aggregate-root.ts`)));
3111
+ const aggregatesOf = (ownerPath)=>backend_module_move_subfolders(external_node_path_default().join(ownerPath, 'domain/aggregates')).filter((name)=>external_node_fs_default().existsSync(external_node_path_default().join(ownerPath, 'domain/aggregates', name, `${name}.aggregate-root.ts`)));
3042
3112
  const findBackendUnits = (ownerPath)=>{
3043
3113
  const unit = (kind, name, aggregate)=>({
3044
3114
  kind,
@@ -3102,11 +3172,14 @@ const validateBackendMove = (unit, target, sharedKernelPath)=>{
3102
3172
  return true;
3103
3173
  };
3104
3174
  const ownerOf = (rootFolderPath, file)=>{
3105
- const [area, context] = external_node_path_default().relative(rootFolderPath, file).split(external_node_path_default().sep);
3106
- if ('bounded-contexts' === area && context) return {
3107
- context,
3108
- path: external_node_path_default().join(rootFolderPath, area, context)
3109
- };
3175
+ const [area, ...segments] = external_node_path_default().relative(rootFolderPath, file).split(external_node_path_default().sep);
3176
+ if ('bounded-contexts' === area && segments.length) {
3177
+ const context = splitContextSegments(segments).name;
3178
+ return {
3179
+ context,
3180
+ path: external_node_path_default().join(rootFolderPath, area, ...context.split('/'))
3181
+ };
3182
+ }
3110
3183
  if ('shared-kernel' === area) return {
3111
3184
  context: void 0,
3112
3185
  path: external_node_path_default().join(rootFolderPath, area)
@@ -3618,6 +3691,10 @@ const envBranchedWireArgument = (testWire, primaryWire)=>{
3618
3691
  ...primary.map((name)=>` ${name}: ${primaryWire}`)
3619
3692
  ].join(',\n')}\n}`;
3620
3693
  };
3694
+ const envBranchedWireImport = (wireFolder)=>{
3695
+ const relativePath = external_node_path_default().relative(wireFolder, external_node_path_default().join(new project_root_ProjectRoot().path, config_file_ConfigFile.Instance.data.project.rootFolder, 'shared-kernel', 'wiring', 'env-branched-wire')).split(external_node_path_default().sep).join('/');
3696
+ return `import { envBranchedWire } from '${relativePath.startsWith('.') ? relativePath : `./${relativePath}`}'`;
3697
+ };
3621
3698
  const integrationFolder = 'specs/integration';
3622
3699
  const testcontainersScripts = {
3623
3700
  'test:integration': `vitest run --config ${integrationFolder}/vitest.config.ts --reporter=dot --silent=passed-only`
@@ -3778,11 +3855,11 @@ const configureIntegrationTests = async (root)=>{
3778
3855
  source.subitem([
3779
3856
  'shared-kernel'
3780
3857
  ]),
3781
- ...source.subitem([
3858
+ ...boundedContextNames(source.subitem([
3782
3859
  'bounded-contexts'
3783
- ]).content.subfolderNames.sort().map((name)=>source.subitem([
3860
+ ]).path).map((name)=>source.subitem([
3784
3861
  'bounded-contexts',
3785
- name
3862
+ ...name.split('/')
3786
3863
  ]))
3787
3864
  ];
3788
3865
  for (const owner of owners)for (const unit of findContracts(owner.path)){
@@ -3888,10 +3965,10 @@ export default defineConfig({
3888
3965
  exclude: [
3889
3966
  '**/*.spec.ts',
3890
3967
  ${folder('shared-kernel/infrastructure/**')},
3891
- ${folder('bounded-contexts/*/infrastructure/**')},
3892
- ${folder('bounded-contexts/*/presentation/rest/**')},
3968
+ ${folder('bounded-contexts/**/infrastructure/**')},
3969
+ ${folder('bounded-contexts/**/presentation/rest/**')},
3893
3970
  ${folder('shared-kernel/wiring/**')},
3894
- ${folder('bounded-contexts/*/wiring/**')}
3971
+ ${folder('bounded-contexts/**/wiring/**')}
3895
3972
  ],
3896
3973
  reporter: [['text', { skipFull: true }], 'html']
3897
3974
  }${server}
@@ -4158,7 +4235,7 @@ const common = {
4158
4235
  dryRun: external_zod_default().boolean().optional()
4159
4236
  };
4160
4237
  const agent_requests_owner = {
4161
- context: agent_requests_name.describe('A bounded-context name, or shared-kernel.')
4238
+ context: agent_requests_nestedName.describe('A bounded-context name (nested ones as paths, e.g. sales/orders), or shared-kernel.')
4162
4239
  };
4163
4240
  const agent_requests_wired = {
4164
4241
  dependencies: agent_requests_dependencies.optional()
@@ -4180,7 +4257,7 @@ const agent_requests_operation = (value, shape)=>external_zod_default().strictOb
4180
4257
  const scaffoldRequestSchema = external_zod_default().discriminatedUnion('operation', [
4181
4258
  agent_requests_operation('bounded-context', {
4182
4259
  ...common,
4183
- name: agent_requests_name.refine((value)=>'shared-kernel' !== value, 'shared-kernel is reserved for the Shared Kernel.')
4260
+ name: agent_requests_nestedName.describe('Folders split by "/", e.g. sales/orders.').refine((value)=>'shared-kernel' !== value, 'shared-kernel is reserved for the Shared Kernel.')
4184
4261
  }),
4185
4262
  agent_requests_operation('aggregate', {
4186
4263
  ...named,
@@ -4278,7 +4355,7 @@ const scaffoldRequestSchema = external_zod_default().discriminatedUnion('operati
4278
4355
  ...common,
4279
4356
  ...agent_requests_owner,
4280
4357
  module: agent_requests_id.describe('Exact unit ID from --describe.'),
4281
- targetContext: agent_requests_name.optional(),
4358
+ targetContext: agent_requests_nestedName.optional(),
4282
4359
  name: agent_requests_name.optional(),
4283
4360
  aggregate: agent_requests_name.optional()
4284
4361
  })
@@ -4788,10 +4865,8 @@ const moveBackendUnitUseCase = async (ownerFolder)=>{
4788
4865
  }),
4789
4866
  pageSize: 20
4790
4867
  });
4791
- const placeName = (ownerPath)=>ownerPath === sharedKernelPath ? 'Shared Kernel' : `Bounded Context: ${external_node_path_default().basename(ownerPath)}`;
4792
- const contexts = new file_system_Folder(rootFolderPath).subitem([
4793
- 'bounded-contexts'
4794
- ]).content.subfolderNames.map((name)=>external_node_path_default().join(rootFolderPath, 'bounded-contexts', name));
4868
+ const placeName = (ownerPath)=>ownerPath === sharedKernelPath ? 'Shared Kernel' : `Bounded Context: ${boundedContextName(ownerPath)}`;
4869
+ const contexts = boundedContextNames(external_node_path_default().join(rootFolderPath, 'bounded-contexts')).map((name)=>external_node_path_default().join(rootFolderPath, 'bounded-contexts', ...name.split('/')));
4795
4870
  const places = [
4796
4871
  unit.ownerPath,
4797
4872
  ...contexts,
@@ -4801,7 +4876,7 @@ const moveBackendUnitUseCase = async (ownerFolder)=>{
4801
4876
  ].filter((place, index, all)=>all.indexOf(place) === index);
4802
4877
  const ownerPath = await interaction_select({
4803
4878
  key: 'targetContext',
4804
- id: (owner)=>owner === sharedKernelPath ? 'shared-kernel' : external_node_path_default().basename(owner),
4879
+ id: (owner)=>owner === sharedKernelPath ? 'shared-kernel' : boundedContextName(owner) ?? external_node_path_default().basename(owner),
4805
4880
  message: 'Move to:',
4806
4881
  choices: places.map((value)=>({
4807
4882
  name: value === unit.ownerPath ? `${placeName(value)} (stays)` : placeName(value),
@@ -5094,7 +5169,10 @@ describe('${aggregateNaming.withSpaces}', () => {
5094
5169
  'repositories'
5095
5170
  ]).createFile(`wire-${aggregateNaming.fileName}-repository.ts`, `
5096
5171
  import { wireClass } from '@domain-first/wire'
5097
- import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
5172
+ ${envBranchedWireImport(boundedContextFolder.subitem([
5173
+ 'wiring',
5174
+ 'repositories'
5175
+ ]).path)}
5098
5176
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${aggregateNaming.ClassName}Repository } from '../../infrastructure/repositories/${fileName}/${fileName}-${aggregateNaming.fileName}-repository'`).join('\n')}
5099
5177
 
5100
5178
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${aggregateNaming.ClassName}Repository, [])`).join('\n\n')}
@@ -5163,7 +5241,7 @@ export abstract class ${naming.ClassName} {
5163
5241
  if (config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) {
5164
5242
  const wireFile = wiringFolder.createFile(`wire-${naming.fileName}.ts`, `
5165
5243
  import { wireClass } from '@domain-first/wire'
5166
- import { envBranchedWire } from '../../../${'shared-kernel' === boundedContextFolder.name ? '' : '../'}shared-kernel/wiring/env-branched-wire'
5244
+ ${envBranchedWireImport(wiringFolder.path)}
5167
5245
  ${implementationTypes.map((x)=>({
5168
5246
  naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
5169
5247
  implementation: x
@@ -5237,19 +5315,19 @@ export const wire${naming.ClassName}ApplicationService = wireClass(
5237
5315
  }
5238
5316
  };
5239
5317
  const scaffoldNewBoundedContextUseCase = async ()=>{
5318
+ const rootFolder = new file_system_Folder(new project_root_ProjectRoot().path).subitem([
5319
+ config_file_ConfigFile.Instance.data.project.rootFolder
5320
+ ]);
5321
+ const contextsFolder = external_node_path_default().join(rootFolder.path, boundedContextsFolderName);
5240
5322
  const name = await interaction_input({
5241
5323
  key: 'name',
5242
- message: 'Name:',
5243
- validate: (x)=>!!x.length
5324
+ message: 'Name (folders split by "/"):',
5325
+ validate: (value)=>validateBoundedContextName(contextsFolder, value)
5244
5326
  });
5245
- const { path } = new project_root_ProjectRoot();
5246
- const rootFolder = new file_system_Folder(path);
5247
- const folder = rootFolder.subitem([
5248
- config_file_ConfigFile.Instance.data.project.rootFolder,
5249
- 'bounded-contexts',
5250
- name
5251
- ]);
5252
- folder.createIfNotExisted();
5327
+ rootFolder.subitem([
5328
+ boundedContextsFolderName,
5329
+ ...name.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment)
5330
+ ]).createIfNotExisted();
5253
5331
  };
5254
5332
  const scaffoldNewCommand = async (boundedContextFolder)=>{
5255
5333
  const commandsFolder = boundedContextFolder.subitem([
@@ -5311,7 +5389,10 @@ export abstract class ${naming.ClassName}Command {
5311
5389
  'commands'
5312
5390
  ]).createFile(`wire-${naming.fileName}-command.ts`, `
5313
5391
  import { wireClass } from '@domain-first/wire'
5314
- import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
5392
+ ${envBranchedWireImport(boundedContextFolder.subitem([
5393
+ 'wiring',
5394
+ 'commands'
5395
+ ]).path)}
5315
5396
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${naming.ClassName}Command } from '../../infrastructure/commands/${fileName}/${fileName}-${naming.fileName}-command'`).join('\n')}
5316
5397
 
5317
5398
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${naming.ClassName}Command, [])`).join('\n\n')}
@@ -5463,7 +5544,8 @@ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
5463
5544
  'errors'
5464
5545
  ]);
5465
5546
  const names = errorNames(boundedContextFolder);
5466
- const contextNaming = new UnknownFormatNaming(boundedContextFolder.name);
5547
+ const contextName = boundedContextName(boundedContextFolder.path) ?? boundedContextFolder.name;
5548
+ const contextNaming = new NestedName(contextName);
5467
5549
  const currentErrorNamespaces = currentErrorFolder.content.fileNames.filter((x)=>'index' !== x);
5468
5550
  const variants = [
5469
5551
  'New error without namespace',
@@ -5482,7 +5564,7 @@ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
5482
5564
  });
5483
5565
  const naming = new UnknownFormatNaming(errorName);
5484
5566
  const indexFile = currentErrorFolder.file('index.ts');
5485
- indexFile.addLineIfMissing(errorClass(names.error(naming.ClassName), rootNamespace(indexFile, `${contextNaming.ClassName}Errors`, boundedContextFolder.name), naming.fileName), '\n\n');
5567
+ indexFile.addLineIfMissing(errorClass(names.error(naming.ClassName), rootNamespace(indexFile, `${contextNaming.ClassName}Errors`, contextName), naming.fileName), '\n\n');
5486
5568
  return;
5487
5569
  }
5488
5570
  if ('New namespace' === selectedVariant) {
@@ -5494,7 +5576,7 @@ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
5494
5576
  if (!currentErrorFolder.file(`${fileName}.ts`).exists) currentErrorFolder.createFile(`${fileName}.ts`, `
5495
5577
  import { errorNamespace } from '@domain-first/errors'
5496
5578
 
5497
- export const ${names.namespace(ClassName)} = errorNamespace('${boundedContextFolder.name}').subnamespace('${fileName}')
5579
+ export const ${names.namespace(ClassName)} = errorNamespace('${contextName}').subnamespace('${fileName}')
5498
5580
  `.trim());
5499
5581
  currentErrorFolder.file('index.ts').addLineIfMissing(`export * from './${fileName}'`, '\n\n');
5500
5582
  return;
@@ -5511,15 +5593,17 @@ export const ${names.namespace(ClassName)} = errorNamespace('${boundedContextFol
5511
5593
  };
5512
5594
  const newController = 'New controller';
5513
5595
  const rootControllerChoice = 'No controller (context root)';
5514
- const sharedRestFolder = (boundedContextFolder)=>boundedContextFolder.subitem([
5515
- '..',
5516
- '..',
5596
+ const sourceFolder = ()=>new file_system_Folder(new project_root_ProjectRoot().path).subitem([
5597
+ config_file_ConfigFile.Instance.data.project.rootFolder
5598
+ ]);
5599
+ const sharedRestFolder = ()=>sourceFolder().subitem([
5517
5600
  'presentation',
5518
5601
  'rest'
5519
5602
  ]);
5520
5603
  const legacyRootEndpointsMessage = (context)=>`${context} keeps its context-root endpoints in the 8.5 layout (presentation/rest/<METHOD>.ts, _param_/). Run npx df-upgrade to move them to presentation/rest/(root)/ first.`;
5521
5604
  const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
5522
- const context = boundedContextFolder.name;
5605
+ const context = boundedContextName(boundedContextFolder.path) ?? boundedContextFolder.name;
5606
+ const contextSegments = context.split('/');
5523
5607
  const restPresentationFolder = boundedContextFolder.subitem([
5524
5608
  'presentation',
5525
5609
  'rest'
@@ -5577,7 +5661,7 @@ const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
5577
5661
  ...routeSegments
5578
5662
  ];
5579
5663
  const routePath = [
5580
- context,
5664
+ ...contextSegments,
5581
5665
  ...controller ? [
5582
5666
  controller
5583
5667
  ] : [],
@@ -5585,7 +5669,9 @@ const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
5585
5669
  ];
5586
5670
  const endpointFolder = restPresentationFolder.subitem(folderSegments.map(pathParameterAsName));
5587
5671
  const nameSegments = [
5588
- controller ?? context,
5672
+ ...controller ? [
5673
+ controller
5674
+ ] : contextSegments,
5589
5675
  ...routeSegments
5590
5676
  ];
5591
5677
  const nameBase = `${[
@@ -5597,9 +5683,7 @@ const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
5597
5683
  method,
5598
5684
  'endpoint'
5599
5685
  ].map((segment)=>segment.startsWith(':') ? pathParameterAsName(segment) : new UnknownFormatNaming(segment).ClassName).join('');
5600
- const endpointGenerator = findRestEndpointGenerator(boundedContextFolder.subitem([
5601
- '..',
5602
- '..',
5686
+ const endpointGenerator = findRestEndpointGenerator(sourceFolder().subitem([
5603
5687
  'shared-kernel'
5604
5688
  ]));
5605
5689
  const handler = withWiring ? await promptEndpointHandler(boundedContextFolder) : void 0;
@@ -5652,9 +5736,9 @@ export const wire${endpointClassName} = wireClass(
5652
5736
  'presentation',
5653
5737
  'rest'
5654
5738
  ]).file('index.ts').addLineIfMissing(`export * from './${group}'`);
5655
- sharedRestFolder(boundedContextFolder).file('wires.ts').addLineIfMissing(`export * from '../../bounded-contexts/${context}/wiring/presentation/rest/${group}'`);
5656
- const restHandlersFile = sharedRestFolder(boundedContextFolder).file('index.ts');
5657
- if (!restHandlersFile.exists) sharedRestFolder(boundedContextFolder).createFile('index.ts', `
5739
+ sharedRestFolder().file('wires.ts').addLineIfMissing(`export * from '../../bounded-contexts/${context}/wiring/presentation/rest/${group}'`);
5740
+ const restHandlersFile = sharedRestFolder().file('index.ts');
5741
+ if (!restHandlersFile.exists) sharedRestFolder().createFile('index.ts', `
5658
5742
  import * as wires from './wires'
5659
5743
 
5660
5744
  const restWires = Object.values(wires)
@@ -5915,7 +5999,10 @@ export abstract class ${naming.ClassName}Query {
5915
5999
  'queries'
5916
6000
  ]).createFile(`wire-${naming.fileName}-query.ts`, `
5917
6001
  import { wireClass } from '@domain-first/wire'
5918
- import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
6002
+ ${envBranchedWireImport(boundedContextFolder.subitem([
6003
+ 'wiring',
6004
+ 'queries'
6005
+ ]).path)}
5919
6006
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${naming.ClassName}Query } from '../../infrastructure/queries/${fileName}/${fileName}-${naming.fileName}-query'`).join('\n')}
5920
6007
 
5921
6008
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${naming.ClassName}Query, [])`).join('\n\n')}
@@ -6206,13 +6293,13 @@ const ownerFolders = (root)=>{
6206
6293
  'shared-kernel'
6207
6294
  ])
6208
6295
  },
6209
- ...source.subitem([
6296
+ ...boundedContextNames(source.subitem([
6210
6297
  'bounded-contexts'
6211
- ]).content.subfolderNames.sort().map((name)=>({
6298
+ ]).path).map((name)=>({
6212
6299
  name,
6213
6300
  folder: source.subitem([
6214
6301
  'bounded-contexts',
6215
- name
6302
+ ...name.split('/')
6216
6303
  ])
6217
6304
  }))
6218
6305
  ];