@domain-first/project-structure 6.0.0 → 7.1.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.
Files changed (53) hide show
  1. package/README.md +20 -19
  2. package/dist/201.js +46 -35
  3. package/dist/287.js +1762 -1250
  4. package/dist/backend-module-move.d.ts +53 -0
  5. package/dist/backend-module-move.spec.d.ts +1 -0
  6. package/dist/config-file.d.ts +2 -2
  7. package/dist/dependency-rules.d.ts +1 -1
  8. package/dist/file-system.d.ts +5 -0
  9. package/dist/in-memory-db.d.ts +9 -0
  10. package/dist/index.cjs +534 -804
  11. package/dist/index.js +9 -47
  12. package/dist/init.cjs +913 -0
  13. package/dist/init.d.ts +2 -0
  14. package/dist/init.js +36 -0
  15. package/dist/integration.cjs +457 -33
  16. package/dist/integration.js +4 -4
  17. package/dist/integrations/in-memory-db.d.ts +6 -0
  18. package/dist/integrations/index.d.ts +2 -0
  19. package/dist/integrations/missing-domain-first-packages.d.ts +8 -0
  20. package/dist/integrations/rest-endpoint-generator.d.ts +18 -0
  21. package/dist/integrations/rest-endpoint-generator.spec.d.ts +1 -0
  22. package/dist/lint.cjs +8 -8
  23. package/dist/lint.js +7 -7
  24. package/dist/module-move.d.ts +58 -0
  25. package/dist/print-next-steps.d.ts +2 -2
  26. package/dist/react-module-move.d.ts +2 -6
  27. package/dist/react.cjs +986 -0
  28. package/dist/react.d.ts +2 -0
  29. package/dist/react.js +73 -0
  30. package/dist/use-cases/index.d.ts +1 -0
  31. package/dist/use-cases/move-backend-unit.d.ts +7 -0
  32. package/dist/use-cases/rest-endpoint-generator.d.ts +1 -1
  33. package/package.json +3 -1
  34. package/skills/df-ps-implement/SKILL.md +11 -56
  35. package/skills/df-ps-plan-feature/SKILL.md +6 -6
  36. package/skills/df-ps-project-scripts/SKILL.md +1 -1
  37. package/skills/df-ps-react/SKILL.md +82 -0
  38. package/skills/df-ps-react/references/generators.md +80 -0
  39. package/skills/df-ps-scaffold/SKILL.md +39 -20
  40. package/skills/df-ps-scaffold/references/choosing-components.md +7 -28
  41. package/skills/df-ps-scaffold/references/generators.md +6 -179
  42. package/skills/df-ps-scaffold/references/units/aggregate.md +47 -0
  43. package/skills/df-ps-scaffold/references/units/bounded-context.md +13 -0
  44. package/skills/df-ps-scaffold/references/units/command-query.md +32 -0
  45. package/skills/df-ps-scaffold/references/units/endpoint.md +28 -0
  46. package/skills/df-ps-scaffold/references/units/entity-value-object.md +27 -0
  47. package/skills/df-ps-scaffold/references/units/errors.md +26 -0
  48. package/skills/df-ps-scaffold/references/units/move-or-rename.md +21 -0
  49. package/skills/df-ps-scaffold/references/units/port.md +23 -0
  50. package/skills/df-ps-scaffold/references/units/services.md +28 -0
  51. package/skills/df-ps-scaffold/references/units/use-case.md +25 -0
  52. package/skills/df-ps-scaffold/references/units/wire-dependency.md +15 -0
  53. package/skills/df-ps-scaffold/scripts/drive.mjs +12 -4
package/README.md CHANGED
@@ -17,6 +17,7 @@ Domain First Project Structure removes that choice: **the cleanest path is also
17
17
 
18
18
  ```
19
19
  npm i -D @domain-first/project-structure
20
+ npx df-init
20
21
  npx df-scaffold
21
22
  ```
22
23
 
@@ -28,10 +29,10 @@ The full technical specification lives in [API.md](./API.md).
28
29
 
29
30
  ### How to initialize a project
30
31
 
31
- Run `df-scaffold` in a project with a `package.json`. The first run asks for the source folder, the `@domain-first` packages you use, the default persistence implementation, whether to scaffold a shared in-memory DB for test implementations, React, Storybook and the testing library, then writes `domain-first.project-structure.config.json` and exits. With `@domain-first/handlers-rest`, it also scaffolds the [endpoint generator](#how-to-add-a-rest-endpoint); if `next` is among your dependencies, it offers to connect `nextAdapter` from `@domain-first/handlers-next` right away and prints the install command for it when it's missing.
32
+ Run `df-init` in a project with a `package.json`. It asks for the source folder, the `@domain-first` packages you use, the default persistence implementation, whether to scaffold a shared in-memory DB for test implementations, React, Storybook and the testing library, then writes `domain-first.project-structure.config.json` and the Shared Kernel files these answers need. With `@domain-first/handlers-rest`, it also scaffolds the [endpoint generator](#how-to-add-a-rest-endpoint); if `next` is among your dependencies, it offers to connect `nextAdapter` from `@domain-first/handlers-next` right away and adds the catch-all route `app/api/[...path]/route.ts`. Finally it prints one command that installs the missing packages.
32
33
 
33
34
  ```
34
- npx df-scaffold
35
+ npx df-init
35
36
  ```
36
37
 
37
38
  ```json
@@ -50,15 +51,11 @@ npx df-scaffold
50
51
  }
51
52
  ```
52
53
 
53
- Commit the config to share it with your team. Every next run performs one operation from the menu.
54
+ Commit the config to share it with your team. `df-init` runs once: with a config in place it exits with an error. Change the config by hand; add the endpoint generator or the in-memory DB later with [`df-integration`](#how-to-add-tooling). The other commands need the config and point to `df-init` without it. Every `df-scaffold` run performs one operation from the menu.
54
55
 
55
56
  ### How to create a bounded context
56
57
 
57
- Choose **Scaffold new bounded context** and enter a name, such as `sales`. With `@domain-first/errors`, its error namespace is created too.
58
-
59
- ```text
60
- src/bounded-contexts/sales/domain/errors/index.ts // SalesErrors = errorNamespace('sales')
61
- ```
58
+ Choose **Scaffold new bounded context** and enter a name, such as `sales`. It starts empty: no error namespace until the first error.
62
59
 
63
60
  Use lowercase kebab-case for every name: `place-order` becomes `PlaceOrderUseCase`.
64
61
 
@@ -119,7 +116,7 @@ Tests get the test implementation, everything else gets the primary one.
119
116
 
120
117
  ### How to wire dependencies
121
118
 
122
- As the last step, generators with wiring offer the modules the new one may depend on, from the same bounded context and the Shared Layer. Each choice is added to the factory and to the constructor:
119
+ As the last step, generators with wiring offer the modules the new one may depend on, from the same bounded context and the Shared Kernel. Each choice is added to the factory and to the constructor:
123
120
 
124
121
  ```ts
125
122
  export class PlaceOrderUseCase {
@@ -133,19 +130,23 @@ export const wirePlaceOrderUseCase = wireClass(PlaceOrderUseCase, [
133
130
 
134
131
  Only the dependencies that respect the layers are offered: a use case can't take another use case, the domain can't take the application. To add a dependency later, choose **Wire dependency** in the context menu.
135
132
 
133
+ ### How to move or rename a module
134
+
135
+ Choose **Move or rename** in the context menu: rename an aggregate, entity, value object, service, port, query, command or use case, move it to another bounded context or to the Shared Kernel, or move an entity in or out of an aggregate. Its files, implementations, wire, specs and every import and derived name in the project follow it: `OrderRepository`, `PrismaOrderRepository`, `wireOrderRepository`, the `orderRepository` parameter of a use case, the in-memory DB section. A move that would make one context import another is refused, with the list of imports that would cross the boundary.
136
+
136
137
  ### How to add errors
137
138
 
138
- Choose **Domain → Errors** to add an error to the context namespace, create a nested namespace, or add an error to it.
139
+ Choose **Domain → Errors** to add an error to the context namespace, create a nested namespace, or add an error to it. The context namespace (`SalesErrors = errorNamespace('sales')` in `domain/errors/index.ts`) is created with the first error added without a namespace.
139
140
 
140
141
  ```ts
141
142
  export class OutOfStock extends SalesErrors.define('out-of-stock') {}
142
143
  ```
143
144
 
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
+ Names don't repeat the context: an error of the `payment` namespace in `sales` is `PaymentDeclined`. In the Shared Kernel they end with `SharedKernelError`: `TimeoutSharedKernelError`.
145
146
 
146
147
  ### How to share code between contexts
147
148
 
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.
149
+ Bounded contexts don't import each other. Put cross-context errors, entities, value objects, ports and services into the **Shared Kernel** (`src/shared-kernel`). Its modules are offered as dependencies in every context.
149
150
 
150
151
  ### How to add a REST endpoint
151
152
 
@@ -155,7 +156,7 @@ With `@domain-first/handlers-rest`, choose **Presentation → New Handlers-REST
155
156
  src/bounded-contexts/sales/presentation/rest/orders/recent/GET.ts // GET /sales/orders/recent
156
157
  ```
157
158
 
158
- Every endpoint uses the one endpoint generator of the project, `RestEndpointGeneratorPresentationService` in `src/shared/presentation/services/`. Initialization scaffolds it as a regular Shared Layer presentation service (class, spec and wire):
159
+ Every endpoint uses the one endpoint generator of the project, `RestEndpointGeneratorPresentationService` in `src/shared-kernel/presentation/services/`. Initialization scaffolds it as a regular Shared Kernel presentation service (class, spec and wire):
159
160
 
160
161
  ```ts
161
162
  /**
@@ -172,13 +173,13 @@ export class RestEndpointGeneratorPresentationService {
172
173
  }
173
174
  ```
174
175
 
175
- Set the module-level `adapter` constant above the class to the adapter of your HTTP framework; the class uses it through closure. If you connected the Next adapter during initialization, the file imports `nextAdapter` from `@domain-first/handlers-next` instead, with nothing to set. Each generating method is a getter returning `EndpointGenerator`: add one per kind of endpoint (for example `withAuth`, with its `context` and error mappings). Keep `invalidRequest()` of `@domain-first/handlers-rest` there for invalid requests (`400`) and add your own mappings: `errors: [httpError(MyError, 404), invalidRequest()]`. A new endpoint calls `this.endpointGenerator(...)` and doesn't compile on purpose: choose the getter yourself in its `get handle()`, e.g. `this.endpointGenerator.withoutGuards(...)`.
176
+ Set the module-level `adapter` constant above the class to the adapter of your HTTP framework; the class uses it through closure. If you connected the Next adapter, the file imports `nextAdapter` from `@domain-first/handlers-next` instead, with nothing to set, and `app/api/[...path]/route.ts` (`src/app/…` when that folder exists) serves the endpoints with `nextEndpoints`. With wiring, the route serves `restHandlers`, so every new endpoint works without touching it; before the first endpoint the route doesn't compile, and the CLI says so. Each generating method is a getter returning `EndpointGenerator`: add one per kind of endpoint (for example `withAuth`, with its `context` and error mappings). Keep `invalidRequest()` of `@domain-first/handlers-rest` there for invalid requests (`400`) and add your own mappings: `errors: [httpError(MyError, 404), invalidRequest()]`. A new endpoint calls `this.endpointGenerator(...)` and doesn't compile on purpose: choose the getter yourself in its `get handle()`, e.g. `this.endpointGenerator.withoutGuards(...)`.
176
177
 
177
178
  With wiring, the endpoint takes the generator and a handler you pick from the context's queries, commands and use cases, and all endpoints are collected as `restHandlers` in `src/presentation/rest/index.ts`. Connect them to your HTTP server.
178
179
 
179
180
  ### How to scaffold React modules
180
181
 
181
- With `useReact`, choose **Scaffold React module**: pages, widgets (monolithic, with separated UI, or headless), UI-kit components with Storybook stories, and shared hooks. Names may include folders:
182
+ With `useReact`, run `npx df-react`: pages, widgets (monolithic, with separated UI, or headless), UI-kit components with Storybook stories, and shared hooks. Names may include folders:
182
183
 
183
184
  ```text
184
185
  admin/panel/users → pages/admin/panel/admin-panel-users-page.tsx (AdminPanelUsersPage)
@@ -188,9 +189,9 @@ admin/panel/users → pages/admin/panel/admin-panel-users-page.tsx (AdminPane
188
189
 
189
190
  ### How to add tooling
190
191
 
191
- Run `npx df-integration` to configure one or several of Storybook, Prisma 8, Vitest, Playwright, integration tests on PostgreSQL in Testcontainers, OpenAPI generation or an Orval API client (typed client and React Query hooks). Integrations add config files, package scripts and `.gitignore` entries, then print the install commands. Nothing is installed or run for you.
192
+ Run `npx df-integration` to configure one or several of the REST endpoint generator, the shared in-memory DB, Storybook, Prisma 8, Vitest, Playwright, integration tests on PostgreSQL in Testcontainers, OpenAPI generation or an Orval API client (typed client and React Query hooks). Integrations add config files, package scripts and `.gitignore` entries, then print one install command to copy. Nothing is installed or run for you.
192
193
 
193
- **Missing domain-first packages** prints the `npm i` command for packages from the config that are not in `package.json`.
194
+ The endpoint generator and the in-memory DB are what `df-init` scaffolds; as integrations they add them later or restore missing files, and never overwrite existing ones.
194
195
 
195
196
  ### How to check the rules
196
197
 
@@ -204,7 +205,7 @@ The rules are a default. Teams that work differently change them in the config:
204
205
 
205
206
  - Kinds in `rules.dependencies` (as keys and in lists): `repositories`, `domain-services`, `application-ports`, `application-services`, `use-cases`, `commands`, `queries`, `infrastructure-services`, `presentation-services`.
206
207
  - A kind's value: a list that replaces its defaults, or `{ "add": [...], "remove": [...] }`.
207
- - Checks in `rules.lint`: `context-isolation`, `shared-layer`, `layers`, `dependencies`, `react`, `clock`.
208
+ - Checks in `rules.lint`: `context-isolation`, `shared-kernel`, `layers`, `dependencies`, `react`, `clock`.
208
209
 
209
210
  Defaults and details: [Dependency rules](API.md#dependency-rules), [`df-lint`](API.md#df-lint).
210
211
 
@@ -219,7 +220,7 @@ Defaults and details: [Dependency rules](API.md#dependency-rules), [`df-lint`](A
219
220
 
220
221
  ### How to teach your coding agent
221
222
 
222
- The package ships skills that teach coding agents to plan features, scaffold with `df-scaffold` and implement the generated code.
223
+ The package ships skills that teach coding agents to plan features, scaffold with `df-scaffold`, build the React part with `df-react` and implement the generated code.
223
224
 
224
225
  ```
225
226
  npx df-skills --claude
package/dist/201.js CHANGED
@@ -123,6 +123,17 @@ const pendingDeletions = new Map();
123
123
  const filesToOverwrite = ()=>[
124
124
  ...pendingFiles
125
125
  ].filter(([filePath, { replacesFile }])=>replacesFile && node_fs.existsSync(filePath)).map(([filePath])=>filePath);
126
+ const withoutOverwrites = (generate)=>{
127
+ const before = new Map(pendingFiles);
128
+ const result = generate();
129
+ for (const [filePath, change] of pendingFiles){
130
+ if (before.get(filePath) === change || !change.replacesFile || !node_fs.existsSync(filePath)) continue;
131
+ const previous = before.get(filePath);
132
+ if (previous) pendingFiles.set(filePath, previous);
133
+ else pendingFiles.delete(filePath);
134
+ }
135
+ return result;
136
+ };
126
137
  const discardPendingChanges = ()=>{
127
138
  pendingFolders.clear();
128
139
  pendingFiles.clear();
@@ -267,7 +278,7 @@ class ProjectRoot {
267
278
  }
268
279
  const lintChecks = [
269
280
  'context-isolation',
270
- 'shared-layer',
281
+ 'shared-kernel',
271
282
  'layers',
272
283
  'dependencies',
273
284
  'react',
@@ -316,39 +327,6 @@ class ConfigFile {
316
327
  };
317
328
  }
318
329
  const configuredDependencyRules = ()=>resolveDependencyRules(ConfigFile.exists ? ConfigFile.Instance.data.rules?.dependencies : void 0);
319
- const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
320
- const resolveExtends = (fromFile, target)=>{
321
- if (target.startsWith('.') || node_path.isAbsolute(target)) {
322
- const resolved = node_path.resolve(node_path.dirname(fromFile), target);
323
- return resolved.endsWith('.json') ? resolved : `${resolved}.json`;
324
- }
325
- const require = createRequire(fromFile);
326
- for (const candidate of [
327
- target,
328
- `${target}/tsconfig.json`
329
- ])try {
330
- return require.resolve(candidate);
331
- } catch {}
332
- };
333
- const compilerOption = (configFile, name, seen = new Set())=>{
334
- if (seen.has(configFile) || !node_fs.existsSync(configFile)) return null;
335
- seen.add(configFile);
336
- let config;
337
- try {
338
- config = JSON.parse(stripJsonComments(node_fs.readFileSync(configFile, 'utf8')));
339
- } catch {
340
- return null;
341
- }
342
- if (config.compilerOptions && name in config.compilerOptions) return config.compilerOptions[name];
343
- const parents = [
344
- config.extends ?? []
345
- ].flat().reverse();
346
- for (const parent of parents){
347
- const parentFile = resolveExtends(configFile, parent);
348
- const value = parentFile ? compilerOption(parentFile, name, seen) : null;
349
- if (void 0 !== value) return value;
350
- }
351
- };
352
330
  class UnknownFormatNaming {
353
331
  rawSource;
354
332
  camelCase;
@@ -684,4 +662,37 @@ const wireDependencies = (consumer, implementation, dependencies)=>{
684
662
  for (const dependency of dependencies)classSource = addImport(classSource, `import type { ${dependency.typeName} } from '${relativeImport(implementation.file, dependency.typeFile)}'`);
685
663
  classFile.update(addConstructorParameters(classSource, implementation.className, dependencies.map((x)=>`private readonly ${parameterName(x.typeName)}: ${x.typeName}`)));
686
664
  };
687
- export { ConfigFile, File, Folder, ProjectRoot, UnknownFormatNaming, addClassMember, addConstructorParameters, addImport, addWireDependencies, availableDependencies, canDependOn, compilerOption, configuredDependencyRules, defaultDependencyRules, discardPendingChanges, fileModuleKind, filesToOverwrite, findWiredModules, implementationType, isSuggestedFor, moduleKindOf, readWiredModule, relativeImport, stripJsonComments, wireDependencies, wiredDependencyNames, writePendingChanges };
665
+ const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
666
+ const resolveExtends = (fromFile, target)=>{
667
+ if (target.startsWith('.') || node_path.isAbsolute(target)) {
668
+ const resolved = node_path.resolve(node_path.dirname(fromFile), target);
669
+ return resolved.endsWith('.json') ? resolved : `${resolved}.json`;
670
+ }
671
+ const require = createRequire(fromFile);
672
+ for (const candidate of [
673
+ target,
674
+ `${target}/tsconfig.json`
675
+ ])try {
676
+ return require.resolve(candidate);
677
+ } catch {}
678
+ };
679
+ const compilerOption = (configFile, name, seen = new Set())=>{
680
+ if (seen.has(configFile) || !node_fs.existsSync(configFile)) return null;
681
+ seen.add(configFile);
682
+ let config;
683
+ try {
684
+ config = JSON.parse(stripJsonComments(node_fs.readFileSync(configFile, 'utf8')));
685
+ } catch {
686
+ return null;
687
+ }
688
+ if (config.compilerOptions && name in config.compilerOptions) return config.compilerOptions[name];
689
+ const parents = [
690
+ config.extends ?? []
691
+ ].flat().reverse();
692
+ for (const parent of parents){
693
+ const parentFile = resolveExtends(configFile, parent);
694
+ const value = parentFile ? compilerOption(parentFile, name, seen) : null;
695
+ if (void 0 !== value) return value;
696
+ }
697
+ };
698
+ export { ConfigFile, File, Folder, ProjectRoot, UnknownFormatNaming, addClassMember, addConstructorParameters, addImport, addWireDependencies, availableDependencies, canDependOn, compilerOption, configuredDependencyRules, defaultDependencyRules, discardPendingChanges, fileModuleKind, filesToOverwrite, findWiredModules, implementationType, isSuggestedFor, moduleKindOf, readWiredModule, relativeImport, stripJsonComments, wireDependencies, wiredDependencyNames, withoutOverwrites, writePendingChanges };