@domain-first/project-structure 3.3.0 → 3.3.2

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
@@ -138,10 +138,11 @@ Only the dependencies that respect the layers are offered: a use case can't take
138
138
  Choose **Domain → Errors** to add an error to the context namespace, create a nested namespace, or add an error to it.
139
139
 
140
140
  ```ts
141
- export const OutOfStockSalesError =
142
- SalesErrors.define("out-of-stock");
141
+ export class OutOfStock extends SalesErrors.define('out-of-stock') {}
143
142
  ```
144
143
 
144
+ Names don't repeat the context: an error of the `payment` namespace in `sales` is `PaymentDeclined`. In the Shared Layer they end with `SharedError`: `TimeoutSharedError`.
145
+
145
146
  ### How to share code between contexts
146
147
 
147
148
  Bounded contexts don't import each other. Put cross-context errors, entities, value objects, ports and services into the **Shared Layer** (`src/shared`). Its modules are offered as dependencies in every context.
package/dist/index.cjs CHANGED
@@ -3022,11 +3022,25 @@ export const wire${naming.ClassName}DomainService = wireClass(
3022
3022
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
3023
3023
  }
3024
3024
  };
3025
+ const errorNames = (boundedContextFolder)=>{
3026
+ const isShared = boundedContextFolder.path === new Folder(new ProjectRoot().path).subitem([
3027
+ ConfigFile.Instance.data.rootFolder,
3028
+ 'shared'
3029
+ ]).path;
3030
+ return {
3031
+ namespace: (namespaceName)=>`${namespaceName}${isShared ? 'Shared' : ''}Errors`,
3032
+ error: (errorName)=>`${errorName}${isShared ? 'SharedError' : ''}`
3033
+ };
3034
+ };
3035
+ const exportedNamespace = (file, fallback)=>/export\s+const\s+(\w+)\s*=\s*errorNamespace\b/.exec(file.data)?.[1] ?? fallback;
3036
+ const errorClass = (className, namespace, code)=>`export class ${className} extends ${namespace}.define('${code}') {}`;
3025
3037
  const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
3026
3038
  const currentErrorFolder = boundedContextFolder.subitem([
3027
3039
  'domain',
3028
3040
  'errors'
3029
3041
  ]);
3042
+ const names = errorNames(boundedContextFolder);
3043
+ const contextNaming = new UnknownFormatNaming(boundedContextFolder.name);
3030
3044
  const currentErrorNamespaces = currentErrorFolder.content.fileNames.filter((x)=>'index' !== x);
3031
3045
  const variants = [
3032
3046
  'New error without namespace',
@@ -3042,7 +3056,8 @@ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
3042
3056
  message: 'Error name:'
3043
3057
  });
3044
3058
  const naming = new UnknownFormatNaming(errorName);
3045
- currentErrorFolder.file('index.ts').addLineIfMissing(`export const ${naming.ClassName}${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Error = ${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Errors.define('${naming.fileName}')`, '\n\n');
3059
+ const indexFile = currentErrorFolder.file('index.ts');
3060
+ indexFile.addLineIfMissing(errorClass(names.error(naming.ClassName), exportedNamespace(indexFile, `${contextNaming.ClassName}Errors`), naming.fileName), '\n\n');
3046
3061
  return;
3047
3062
  }
3048
3063
  if ('New namespace' === selectedVariant) {
@@ -3053,7 +3068,7 @@ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
3053
3068
  if (!currentErrorFolder.file(`${fileName}.ts`).exists) currentErrorFolder.createFile(`${fileName}.ts`, `
3054
3069
  import { errorNamespace } from '@domain-first/errors'
3055
3070
 
3056
- export const ${ClassName}${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Errors = errorNamespace('${boundedContextFolder.name}').subnamespace('${fileName}')
3071
+ export const ${names.namespace(ClassName)} = errorNamespace('${boundedContextFolder.name}').subnamespace('${fileName}')
3057
3072
  `.trim());
3058
3073
  currentErrorFolder.file('index.ts').addLineIfMissing(`export * from './${fileName}'`, '\n\n');
3059
3074
  return;
@@ -3064,7 +3079,8 @@ export const ${ClassName}${new UnknownFormatNaming(boundedContextFolder.name).Cl
3064
3079
  message: 'Error name:'
3065
3080
  });
3066
3081
  const { ClassName, fileName } = new UnknownFormatNaming(errorName);
3067
- currentErrorFolder.file(`${namespace}.ts`).addLineIfMissing(`export const ${ClassName}${namespaceNaming.ClassName}${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Error = ${namespaceNaming.ClassName}${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Errors.define('${fileName}')`, '\n\n');
3082
+ const namespaceFile = currentErrorFolder.file(`${namespace}.ts`);
3083
+ namespaceFile.addLineIfMissing(errorClass(names.error(`${namespaceNaming.ClassName}${ClassName}`), exportedNamespace(namespaceFile, names.namespace(namespaceNaming.ClassName)), fileName), '\n\n');
3068
3084
  };
3069
3085
  const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
3070
3086
  const restPresentationFolder = boundedContextFolder.subitem([
package/dist/index.js CHANGED
@@ -2992,11 +2992,25 @@ export const wire${naming.ClassName}DomainService = wireClass(
2992
2992
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
2993
2993
  }
2994
2994
  };
2995
+ const errorNames = (boundedContextFolder)=>{
2996
+ const isShared = boundedContextFolder.path === new Folder(new ProjectRoot().path).subitem([
2997
+ ConfigFile.Instance.data.rootFolder,
2998
+ 'shared'
2999
+ ]).path;
3000
+ return {
3001
+ namespace: (namespaceName)=>`${namespaceName}${isShared ? 'Shared' : ''}Errors`,
3002
+ error: (errorName)=>`${errorName}${isShared ? 'SharedError' : ''}`
3003
+ };
3004
+ };
3005
+ const exportedNamespace = (file, fallback)=>/export\s+const\s+(\w+)\s*=\s*errorNamespace\b/.exec(file.data)?.[1] ?? fallback;
3006
+ const errorClass = (className, namespace, code)=>`export class ${className} extends ${namespace}.define('${code}') {}`;
2995
3007
  const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
2996
3008
  const currentErrorFolder = boundedContextFolder.subitem([
2997
3009
  'domain',
2998
3010
  'errors'
2999
3011
  ]);
3012
+ const names = errorNames(boundedContextFolder);
3013
+ const contextNaming = new UnknownFormatNaming(boundedContextFolder.name);
3000
3014
  const currentErrorNamespaces = currentErrorFolder.content.fileNames.filter((x)=>'index' !== x);
3001
3015
  const variants = [
3002
3016
  'New error without namespace',
@@ -3012,7 +3026,8 @@ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
3012
3026
  message: 'Error name:'
3013
3027
  });
3014
3028
  const naming = new UnknownFormatNaming(errorName);
3015
- currentErrorFolder.file('index.ts').addLineIfMissing(`export const ${naming.ClassName}${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Error = ${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Errors.define('${naming.fileName}')`, '\n\n');
3029
+ const indexFile = currentErrorFolder.file('index.ts');
3030
+ indexFile.addLineIfMissing(errorClass(names.error(naming.ClassName), exportedNamespace(indexFile, `${contextNaming.ClassName}Errors`), naming.fileName), '\n\n');
3016
3031
  return;
3017
3032
  }
3018
3033
  if ('New namespace' === selectedVariant) {
@@ -3023,7 +3038,7 @@ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
3023
3038
  if (!currentErrorFolder.file(`${fileName}.ts`).exists) currentErrorFolder.createFile(`${fileName}.ts`, `
3024
3039
  import { errorNamespace } from '@domain-first/errors'
3025
3040
 
3026
- export const ${ClassName}${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Errors = errorNamespace('${boundedContextFolder.name}').subnamespace('${fileName}')
3041
+ export const ${names.namespace(ClassName)} = errorNamespace('${boundedContextFolder.name}').subnamespace('${fileName}')
3027
3042
  `.trim());
3028
3043
  currentErrorFolder.file('index.ts').addLineIfMissing(`export * from './${fileName}'`, '\n\n');
3029
3044
  return;
@@ -3034,7 +3049,8 @@ export const ${ClassName}${new UnknownFormatNaming(boundedContextFolder.name).Cl
3034
3049
  message: 'Error name:'
3035
3050
  });
3036
3051
  const { ClassName, fileName } = new UnknownFormatNaming(errorName);
3037
- currentErrorFolder.file(`${namespace}.ts`).addLineIfMissing(`export const ${ClassName}${namespaceNaming.ClassName}${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Error = ${namespaceNaming.ClassName}${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Errors.define('${fileName}')`, '\n\n');
3052
+ const namespaceFile = currentErrorFolder.file(`${namespace}.ts`);
3053
+ namespaceFile.addLineIfMissing(errorClass(names.error(`${namespaceNaming.ClassName}${ClassName}`), exportedNamespace(namespaceFile, names.namespace(namespaceNaming.ClassName)), fileName), '\n\n');
3038
3054
  };
3039
3055
  const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
3040
3056
  const restPresentationFolder = boundedContextFolder.subitem([
@@ -1,2 +1,2 @@
1
- import type { Folder } from '../file-system';
1
+ import { Folder } from '../file-system';
2
2
  export declare const scaffoldNewErrorUseCase: (boundedContextFolder: Folder) => Promise<void>;
@@ -0,0 +1 @@
1
+ export {};
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.3.0",
4
+ "version": "3.3.2",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -23,7 +23,7 @@ A file in context A imports **nothing** from context B: no types (`import type`
23
23
  - A needs B's data or behavior → an **execution query** (read) or **execution command** (write) in A. Its input/output are A's own models, duplicated in A's terms; B's models never appear in A.
24
24
  - Its infrastructure implementation reaches B's data **the simplest available way**: a shared database → query it directly (e.g. `prisma`); otherwise the way chosen in the plan (`df-ps-plan-feature`, step 3, rule 4), by default B's REST endpoint (`http`), like an external service. Either way it maps the result to A's models and errors and imports nothing from B. Its test implementation returns fixed data, so A's tests never run B.
25
25
  - Refer to B's entities by id only.
26
- - `shared/` may import any context's **`domain/errors`** (e.g. to map them to HTTP statuses), and nothing else from a context. Don't move a context's domain concepts into `shared/` to share them between contexts; only universal entities / value objects (`money`, `email`) live there.
26
+ - `shared/` may import any context's **`domain/errors`** (e.g. to map them to HTTP statuses), and nothing else from a context. The one exception: the shared in-memory DB, `shared/infrastructure/services/in-memory-db-infrastructure-service.ts`, may also import any context's **domain models** (aggregate roots, entities, value objects: the `domainType` classes under `domain/aggregates/`, `domain/entities/`, `domain/value-objects/`) to type its sections, never repository contracts or anything outside `domain/`. Don't move a context's domain concepts into `shared/` to share them between contexts; only universal entities / value objects (`money`, `email`) live there.
27
27
  - `<rootFolder>/presentation/rest/` (the generated `wires.ts`, `index.ts`) may import every context's REST wiring.
28
28
  - `<rootFolder>/presentation/react/` imports **nothing** from contexts whenever it can avoid it (`ui-kit/` never does). If the project has a generated API client (orval, openapi-typescript, … from the OpenAPI document built by `generateOpenAPI`), use its hooks and types only. As a fallback, without such a client, it may import **only endpoint contract types**: `import type` from `<C>/presentation/rest/**`, e.g. `type Contract = EndpointContract<OrdersRecentGetEndpoint['handle']>`. No value imports, no `import { type X }`, nothing from other layers.
29
29
  - Need a forbidden import? A's own execution query or command is missing. Plan it and generate it.
@@ -77,7 +77,7 @@ export const wirePlaceOrderUseCase = wireClass(PlaceOrderUseCase, [wireOrderRepo
77
77
 
78
78
  ## REST endpoints ({handlers-rest})
79
79
 
80
- 1. Generator: initialization creates `RestEndpointGeneratorPresentationService` in `<rootFolder>/shared/presentation/services/`; every endpoint uses it. Set the module-level `const adapter` above the class (`undefined` until set) to the HTTP framework's adapter; the class reads it through closure. If initialization connected the Next adapter, the file already imports `nextAdapter` from `@domain-first/handlers-next` and passes it instead; just make sure that package is installed. The default `400` checks live in the private `defaultClientRequestErrors` getter; extend a status with `checks: [...this.defaultClientRequestErrors, MyError.is]`. Map domain errors to statuses in the generator's `errorStatuses`, importing them from the contexts' `domain/errors` (the only thing `shared/` may import from a context). A new kind of endpoint (auth, other context) is a new getter returning `createEndpoint({ context, errorStatuses })(adapter) as EndpointGenerator` (`nextAdapter` with the Next adapter), next to `withoutGuards`. Generate the exposed handler before the endpoint: with wire, the `Handler:` pick fills its type and the wire (`[wireRestEndpointGeneratorPresentationService, wireGetRecentOrdersUseCase]`).
80
+ 1. Generator: initialization creates `RestEndpointGeneratorPresentationService` in `<rootFolder>/shared/presentation/services/`; every endpoint uses it. Set the module-level `const adapter` above the class (`undefined` until set) to the HTTP framework's adapter; the class reads it through closure. If initialization connected the Next adapter, the file already imports `nextAdapter` from `@domain-first/handlers-next` and passes it instead; just make sure that package is installed. The default `400` checks live in the private `defaultClientRequestErrors` getter; extend a status with `checks: [...this.defaultClientRequestErrors, MyError.is]`. Map domain errors to statuses in the generator's `errorStatuses`, importing them from the contexts' `domain/errors` (the only thing `shared/` may import from a context, besides domain models in the in-memory DB). A new kind of endpoint (auth, other context) is a new getter returning `createEndpoint({ context, errorStatuses })(adapter) as EndpointGenerator` (`nextAdapter` with the Next adapter), next to `withoutGuards`. Generate the exposed handler before the endpoint: with wire, the `Handler:` pick fills its type and the wire (`[wireRestEndpointGeneratorPresentationService, wireGetRecentOrdersUseCase]`).
81
81
  2. If `handler: never` is left (no handler existed at generation), re-run the endpoint generator as an approved overwrite to pick it (rule 3); don't replace it by hand.
82
82
  3. Complete `get handle()`: the generated `this.endpointGenerator(...)` doesn't compile on purpose. Pick the generating getter that fits the endpoint (`this.endpointGenerator.withoutGuards(...)`, or one with the needed guards), then `.input(...)`, `.mapInput(...)`, optional `.output(...)`, `.mapOutput(...)`.
83
83
  4. Register `restHandlers` from `<rootFolder>/presentation/rest/index.ts` in the server bootstrap (rule 2, exception 5).
@@ -7,7 +7,10 @@
7
7
  * rootFolder defaults to `rootFolder` in domain-first.project-structure.config.json.
8
8
  *
9
9
  * Bounded contexts never import each other (no exceptions).
10
- * Allowed: shared/** may import any context's domain/errors; presentation/react/** may only
10
+ * Allowed: shared/** may import any context's domain/errors; the shared in-memory DB
11
+ * (shared/infrastructure/services/in-memory-db-infrastructure-service.ts) may also import any
12
+ * context's domain models: domain/aggregates/** (barrels included, `*-repository` files not),
13
+ * domain/entities/**, domain/value-objects/**; presentation/react/** may only
11
14
  * `import type` from a context's presentation/rest/; presentation/react/ui-kit/** imports
12
15
  * nothing from bounded contexts, widgets or pages.
13
16
  * Widgets never import each other: a file of one widget (the nearest folder under widgets/
@@ -36,6 +39,13 @@ const sharedDir = path.join(root, 'shared');
36
39
  const reactDir = path.join(root, 'presentation', 'react');
37
40
  const uiKitDir = path.join(reactDir, 'ui-kit');
38
41
  const widgetsDir = path.join(reactDir, 'widgets');
42
+ const inMemoryDbFile = path.join(sharedDir, 'infrastructure', 'services', 'in-memory-db-infrastructure-service.ts');
43
+
44
+ // Domain models of a context: aggregate roots, entities and value objects, not repository contracts.
45
+ const isDomainModel = (target, layer, part) =>
46
+ layer === 'domain' &&
47
+ ['aggregates', 'entities', 'value-objects'].includes(part) &&
48
+ !/-repository(\.tsx?)?$/.test(path.basename(target));
39
49
 
40
50
  // tsconfig `paths` → [{ prefix, wildcard, targets }]
41
51
  const readTsconfig = (file) => {
@@ -157,12 +167,13 @@ for (const file of scanned) {
157
167
  for (const imp of importsOf(file)) {
158
168
  if (!imp.target) continue;
159
169
  const [targetContext, layer, part] = inside(contextsDir, imp.target) ?? [];
170
+ const allowedInMemoryDbImport = file === inMemoryDbFile && isDomainModel(imp.target, layer, part);
160
171
 
161
172
  if (ownContext) {
162
173
  if (targetContext && targetContext !== ownContext) report(`[${ownContext}] imports another context:`, file, imp);
163
174
  } else if (inside(sharedDir, file)) {
164
- if (targetContext && !(layer === 'domain' && part === 'errors')) {
165
- report('[shared] imports a bounded context outside its domain/errors:', file, imp);
175
+ if (targetContext && !(layer === 'domain' && part === 'errors') && !allowedInMemoryDbImport) {
176
+ report('[shared] imports a bounded context outside its domain/errors (and domain models for the in-memory DB):', file, imp);
166
177
  }
167
178
  } else if (inside(uiKitDir, file)) {
168
179
  const [area] = inside(reactDir, imp.target) ?? [];
@@ -42,9 +42,10 @@ First prompt (select): `New error without namespace` | `New namespace` | `New er
42
42
  `… pick:Domain pick:Errors "pick:New error in namespace order" text:not-found`
43
43
  `… pick:Domain pick:Errors "pick:New error without" text:order-closed`
44
44
 
45
- - Without namespace: appends `export const NCtxError = CtxErrors.define('n')` to `<C>/domain/errors/index.ts`
46
- - New namespace: `<C>/domain/errors/ns.ts` (`NsCtxErrors = errorNamespace('ctx').subnamespace('ns')`) + `export * from './ns'` in `index.ts`
47
- - In namespace: appends `NNsCtxError = NsCtxErrors.define('n')` to `ns.ts`
45
+ - Without namespace: appends `export class N extends CtxErrors.define('n') {}` to `<C>/domain/errors/index.ts`
46
+ - New namespace: `<C>/domain/errors/ns.ts` (`NsErrors = errorNamespace('ctx').subnamespace('ns')`) + `export * from './ns'` in `index.ts`
47
+ - In namespace: appends `export class NsN extends NsErrors.define('n') {}` to `ns.ts` (namespace first), extending the namespace the file exports
48
+ - Shared Layer: errors end with `SharedError`, namespaces with `SharedErrors`: `NSharedError`, `NsSharedErrors`, `NsNSharedError`
48
49
 
49
50
  Re-running is safe: an existing namespace file is kept, and a line already in the file isn't added again.
50
51