@domain-first/project-structure 7.2.0 → 8.0.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 (64) hide show
  1. package/README.md +124 -25
  2. package/dist/201.js +87 -338
  3. package/dist/287.js +1183 -568
  4. package/dist/561.js +518 -0
  5. package/dist/711.js +22 -0
  6. package/dist/870.js +438 -0
  7. package/dist/agent-cli.d.ts +378 -0
  8. package/dist/agent-cli.spec.d.ts +1 -0
  9. package/dist/agent-identifiers.d.ts +4 -0
  10. package/dist/agent-requests.d.ts +488 -0
  11. package/dist/config-file.d.ts +231 -26
  12. package/dist/config-file.spec.d.ts +1 -0
  13. package/dist/context-dependencies.d.ts +16 -0
  14. package/dist/dependency-rules.d.ts +17 -17
  15. package/dist/file-system.d.ts +10 -1
  16. package/dist/implementation-choices.d.ts +8 -0
  17. package/dist/implementation-choices.spec.d.ts +1 -0
  18. package/dist/implementation-options-schema.d.ts +14 -0
  19. package/dist/index.cjs +3598 -583
  20. package/dist/index.js +20 -7
  21. package/dist/init.cjs +717 -122
  22. package/dist/init.js +24 -12
  23. package/dist/integration.cjs +3737 -186
  24. package/dist/integration.js +29 -17
  25. package/dist/integrations/rest-endpoint-generator.d.ts +4 -2
  26. package/dist/integrations/storybook.d.ts +1 -0
  27. package/dist/interaction.d.ts +41 -0
  28. package/dist/lint.cjs +165 -41
  29. package/dist/lint.js +22 -7
  30. package/dist/next-app.d.ts +7 -0
  31. package/dist/react.cjs +5128 -414
  32. package/dist/react.js +72 -60
  33. package/dist/system-implementations.d.ts +6 -0
  34. package/dist/upgrade-steps.d.ts +81 -0
  35. package/dist/upgrade-steps.spec.d.ts +1 -0
  36. package/dist/upgrade.cjs +593 -0
  37. package/dist/upgrade.d.ts +2 -0
  38. package/dist/upgrade.js +235 -0
  39. package/dist/use-cases/add-integration.d.ts +16 -1
  40. package/dist/use-cases/cross-context-dependencies.spec.d.ts +1 -0
  41. package/dist/use-cases/initialize.d.ts +4 -4
  42. package/dist/use-cases/initialize.spec.d.ts +1 -0
  43. package/dist/use-cases/prompt-implementation-type.d.ts +20 -0
  44. package/dist/use-cases/scaffold-react-page.d.ts +3 -1
  45. package/dist/wire-branches.d.ts +26 -0
  46. package/dist/wiring.d.ts +3 -2
  47. package/package.json +3 -2
  48. package/skills/df-ps-implement/SKILL.md +9 -8
  49. package/skills/df-ps-plan-feature/SKILL.md +8 -7
  50. package/skills/df-ps-react/SKILL.md +13 -7
  51. package/skills/df-ps-react/references/generators.md +6 -2
  52. package/skills/df-ps-scaffold/SKILL.md +28 -17
  53. package/skills/df-ps-scaffold/references/agent-mode.md +72 -0
  54. package/skills/df-ps-scaffold/references/agent-operations.md +155 -0
  55. package/skills/df-ps-scaffold/references/choosing-components.md +13 -13
  56. package/skills/df-ps-scaffold/references/generators.md +20 -3
  57. package/skills/df-ps-scaffold/references/units/aggregate.md +4 -3
  58. package/skills/df-ps-scaffold/references/units/bounded-context.md +1 -1
  59. package/skills/df-ps-scaffold/references/units/command-query.md +12 -12
  60. package/skills/df-ps-scaffold/references/units/implementation.md +2 -2
  61. package/skills/df-ps-scaffold/references/units/move-or-rename.md +1 -1
  62. package/skills/df-ps-scaffold/references/units/port.md +7 -4
  63. package/skills/df-ps-scaffold/references/units/use-case.md +1 -1
  64. package/skills/df-ps-scaffold/scripts/drive.mjs +9 -1
@@ -0,0 +1,235 @@
1
+ #!/usr/bin/env node
2
+ import node_path from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import { confirm as prompts_confirm } from "@inquirer/prompts";
5
+ import zod from "zod";
6
+ import { implementationLabelSchema, domainFirstPackages as config_file_domainFirstPackages, configSchema, discardPendingChanges, rulesSchema, ConfigFile, isOutdatedConfig, writePendingChanges, File, configFileName, ProjectRoot } from "./870.js";
7
+ import { hasDependency } from "./711.js";
8
+ const record = (value)=>'object' != typeof value || null === value || Array.isArray(value) ? {} : value;
9
+ const flatConfigSchema = zod.object({
10
+ rootFolder: zod.string().min(1),
11
+ domainFirstPackages: zod.array(zod["enum"](config_file_domainFirstPackages)),
12
+ withInMemoryDb: zod.boolean().optional(),
13
+ testingLibrary: zod.string().optional(),
14
+ useReact: zod.boolean().optional(),
15
+ storybookFramework: zod.string().optional(),
16
+ defaultPersistenceLayerImplementation: zod.string().optional(),
17
+ rules: rulesSchema.optional()
18
+ }).passthrough();
19
+ const sectionsStep = {
20
+ id: 'config-sections',
21
+ kind: 'required',
22
+ title: 'Split the config into project, backend and frontend sections',
23
+ detect: ({ config })=>isOutdatedConfig(config),
24
+ plan: ({ config })=>{
25
+ const flat = flatConfigSchema.parse(config);
26
+ const backend = [
27
+ 'domainFirstPackages',
28
+ 'withInMemoryDb',
29
+ 'testingLibrary',
30
+ 'rules'
31
+ ].filter((key)=>key in flat);
32
+ return [
33
+ 'rootFolder → project.rootFolder',
34
+ `${backend.join(', ')} → backend`,
35
+ flat.useReact ? `useReact${flat.storybookFramework ? ', storybookFramework' : ''} → frontend.react` : 'useReact: false → no frontend section'
36
+ ];
37
+ },
38
+ apply: (context)=>{
39
+ const { rootFolder, domainFirstPackages, withInMemoryDb, testingLibrary, useReact, storybookFramework, defaultPersistenceLayerImplementation, rules, ...other } = flatConfigSchema.parse(context.config);
40
+ context.config = {
41
+ ...other,
42
+ project: {
43
+ rootFolder
44
+ },
45
+ backend: {
46
+ domainFirstPackages,
47
+ withInMemoryDb,
48
+ testingLibrary,
49
+ rules,
50
+ defaultPersistenceLayerImplementation
51
+ },
52
+ ...useReact ? {
53
+ frontend: {
54
+ react: {
55
+ storybookFramework
56
+ }
57
+ }
58
+ } : {}
59
+ };
60
+ }
61
+ };
62
+ const reactOf = (config)=>record(record(config.frontend).react);
63
+ const frameworkStep = {
64
+ id: 'react-framework',
65
+ kind: 'required',
66
+ title: 'Record the frontend framework explicitly',
67
+ detect: ({ config })=>'react' in record(config.frontend) && !reactOf(config).framework,
68
+ plan: ()=>[
69
+ hasDependency('next') ? 'frontend.react.framework: "next" (next is in package.json)' : 'frontend.react.framework: "react" (next is not in package.json)'
70
+ ],
71
+ apply: ({ config })=>{
72
+ const frontend = record(config.frontend);
73
+ config.frontend = {
74
+ ...frontend,
75
+ react: {
76
+ ...reactOf(config),
77
+ framework: hasDependency('next') ? 'next' : 'react'
78
+ }
79
+ };
80
+ }
81
+ };
82
+ const persistenceKinds = [
83
+ 'repositories',
84
+ 'commands',
85
+ 'queries'
86
+ ];
87
+ const persistenceStep = {
88
+ id: 'persistence-default',
89
+ kind: 'required',
90
+ title: 'Move the default persistence implementation to saved implementation types',
91
+ detect: ({ config })=>'defaultPersistenceLayerImplementation' in record(config.backend),
92
+ plan: ({ config })=>{
93
+ const label = record(config.backend).defaultPersistenceLayerImplementation;
94
+ if (void 0 === label) return [];
95
+ return implementationLabelSchema.safeParse(label).success ? [
96
+ `defaultPersistenceLayerImplementation "${label}" → first primary type of backend.implementations.${persistenceKinds.join(', ')}`
97
+ ] : [
98
+ `defaultPersistenceLayerImplementation "${String(label)}" is removed: it is not a kebab-case implementation type`
99
+ ];
100
+ },
101
+ apply: ({ config })=>{
102
+ const { defaultPersistenceLayerImplementation: label, ...backend } = record(config.backend);
103
+ const implementations = record(backend.implementations);
104
+ if (implementationLabelSchema.safeParse(label).success) {
105
+ for (const kind of persistenceKinds){
106
+ const group = record(implementations[kind]);
107
+ const primary = Array.isArray(group.primary) ? group.primary : [];
108
+ implementations[kind] = {
109
+ primary: [
110
+ label,
111
+ ...primary.filter((x)=>x !== label)
112
+ ],
113
+ test: Array.isArray(group.test) ? group.test : []
114
+ };
115
+ }
116
+ backend.implementations = implementations;
117
+ }
118
+ config.backend = backend;
119
+ }
120
+ };
121
+ const upgradeSteps = [
122
+ sectionsStep,
123
+ frameworkStep,
124
+ persistenceStep
125
+ ];
126
+ const skillsNote = 'Update the agent skills to this version: npx df-skills';
127
+ const planUpgrade = async (config, acceptOptional = ()=>true, steps = upgradeSteps)=>{
128
+ const context = {
129
+ config: structuredClone(record(config))
130
+ };
131
+ const planned = [];
132
+ for (const step of steps){
133
+ if (!step.detect(context)) continue;
134
+ const entry = {
135
+ step,
136
+ changes: step.plan(context)
137
+ };
138
+ if ('optional' !== step.kind || await acceptOptional(entry)) {
139
+ planned.push(entry);
140
+ step.apply?.(context);
141
+ }
142
+ }
143
+ const changed = planned.some(({ step })=>'manual' !== step.kind);
144
+ return {
145
+ planned,
146
+ changed,
147
+ config: changed ? configSchema.parse(context.config) : void 0
148
+ };
149
+ };
150
+ const help = `Usage: df-upgrade [--dry-run] [--yes]
151
+
152
+ Brings the project up to date after upgrading @domain-first/project-structure
153
+ to a new major version. Finds the steps the project needs, shows what each
154
+ one changes, asks once and applies them together. Other commands refuse a
155
+ config of an earlier major version until it is upgraded.
156
+
157
+ Options:
158
+ --dry-run show the plan without writing anything
159
+ --yes apply without asking, optional steps included
160
+ -h, --help show this help`;
161
+ const { values: values } = parseArgs({
162
+ options: {
163
+ help: {
164
+ type: 'boolean',
165
+ short: 'h',
166
+ default: false
167
+ },
168
+ 'dry-run': {
169
+ type: 'boolean',
170
+ default: false
171
+ },
172
+ yes: {
173
+ type: 'boolean',
174
+ short: 'y',
175
+ default: false
176
+ }
177
+ }
178
+ });
179
+ if (values.help) {
180
+ console.log(help);
181
+ process.exit(0);
182
+ }
183
+ const printStep = ({ step, changes })=>{
184
+ console.log(`\n${step.title}${'optional' === step.kind ? ' (optional)' : ''}`);
185
+ for (const change of changes)console.log(` ${change}`);
186
+ };
187
+ const run = async ()=>{
188
+ const root = new ProjectRoot().path;
189
+ const configPath = node_path.join(root, configFileName);
190
+ if (!ConfigFile.exists) {
191
+ console.log(`No ${configFileName} found: run df-init to initialize the project.`);
192
+ process.exit(1);
193
+ }
194
+ let raw;
195
+ try {
196
+ raw = JSON.parse(new File(configPath).data);
197
+ } catch {
198
+ console.log(`${configFileName} is not valid JSON: fix it first.`);
199
+ process.exit(1);
200
+ }
201
+ const dryRun = values['dry-run'];
202
+ const { planned, changed, config } = await planUpgrade(raw, (entry)=>{
203
+ if (dryRun || values.yes) return true;
204
+ printStep(entry);
205
+ return prompts_confirm({
206
+ message: 'Apply this optional step?',
207
+ default: true
208
+ });
209
+ });
210
+ if (!changed) return void console.log('Everything is up to date.');
211
+ console.log('Upgrade plan:');
212
+ for (const entry of planned.filter(({ step })=>'manual' !== step.kind))printStep(entry);
213
+ const manual = [
214
+ ...planned.filter(({ step })=>'manual' === step.kind).flatMap(({ changes })=>changes),
215
+ skillsNote
216
+ ];
217
+ if (dryRun) return void console.log('\nDry run: nothing was written.');
218
+ if (!values.yes && !await prompts_confirm({
219
+ message: 'Apply?',
220
+ default: true
221
+ })) {
222
+ discardPendingChanges();
223
+ console.log('Cancelled: nothing was written.');
224
+ return;
225
+ }
226
+ if (config) ConfigFile.write(config);
227
+ writePendingChanges();
228
+ console.log(`\nUpgraded ${configFileName}.`);
229
+ console.log('\nDo it yourself:');
230
+ for (const note of manual)console.log(` ${note}`);
231
+ };
232
+ run().catch((error)=>{
233
+ console.error(error instanceof Error ? error.message : error);
234
+ process.exitCode = 1;
235
+ });
@@ -1 +1,16 @@
1
- export declare const addIntegration: () => Promise<void>;
1
+ /**
2
+ * Integrations are shown by group, but selected ones run in this order, each one seeing the changes of
3
+ * the previous ones: Storybook configures `frontend.react` for the Swagger UI page
4
+ * of OpenAPI, integration tests read the Prisma config and the Vitest
5
+ * config, Orval reads the OpenAPI document path.
6
+ */
7
+ export declare const integrationIds: readonly ["storybook", "rest-endpoint-generator", "in-memory-db", "prisma", "vitest", "playwright", "testcontainers", "openapi", "orval"];
8
+ export declare const addIntegration: ({ save }?: {
9
+ save?: boolean;
10
+ }) => Promise<string[]>;
11
+ export declare const integrationDescriptions: () => {
12
+ id: "openapi" | "orval" | "prisma" | "rest-endpoint-generator" | "storybook" | "vitest" | "testcontainers" | "in-memory-db" | "playwright";
13
+ name: string;
14
+ group: "backend" | "frontend";
15
+ available: boolean;
16
+ }[];
@@ -1,4 +1,4 @@
1
- /**
2
- * Initializes the project and returns the steps left to the user.
3
- */
4
- export declare const initializeUseCase: () => Promise<string[]>;
1
+ export declare const configurationSections: readonly ["project", "backend", "frontend"];
2
+ export type ConfigurationSection = (typeof configurationSections)[number];
3
+ /** New projects walk all sections; existing projects can resume any section. */
4
+ export declare const initializeUseCase: (section?: ConfigurationSection) => Promise<string[]>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,20 @@
1
+ import { type ImplementationKind, type ImplementationPurpose } from '../implementation-choices';
2
+ export declare const enterImplementationTypeOnce: unique symbol;
3
+ export declare const implementationTypeEntryChoices: readonly [{
4
+ readonly name: "Enter implementation type and save for future use";
5
+ readonly value: null;
6
+ }, {
7
+ readonly name: "Enter implementation type for this run only";
8
+ readonly value: typeof enterImplementationTypeOnce;
9
+ }];
10
+ export type ImplementationTypeSelection = {
11
+ label: string;
12
+ saveForFutureUse: boolean;
13
+ };
14
+ /** Saved choices, active system implementations, and explicit manual entry. */
15
+ export declare const promptImplementationType: (message: string, kind: ImplementationKind, { existing, purpose, crossContext, remember }?: {
16
+ existing?: string[];
17
+ purpose?: ImplementationPurpose | "all";
18
+ crossContext?: boolean;
19
+ remember?: boolean;
20
+ }) => Promise<ImplementationTypeSelection>;
@@ -1,4 +1,4 @@
1
- import type { Folder } from '../file-system';
1
+ import { type Folder } from '../file-system';
2
2
  /**
3
3
  * Content of `<file>-page.tsx`: imports go before React's, `body` is
4
4
  * what the page returns.
@@ -7,4 +7,6 @@ export declare const reactPageContent: (ClassName: string, { imports, body }?: {
7
7
  imports?: string[];
8
8
  body?: string;
9
9
  }) => string;
10
+ /** A thin App Router route that renders the page component. */
11
+ export declare const nextRouteContent: (ClassName: string, pageImport: string) => string;
10
12
  export declare const scaffoldReactPage: (presentationReactFolder: Folder) => Promise<void>;
@@ -0,0 +1,26 @@
1
+ export declare const defaultEnvBranches: {
2
+ names: string[];
3
+ test?: string;
4
+ };
5
+ /**
6
+ * The branches every `envBranchedWire` has: the test one gets the test
7
+ * implementation, the others (`primary`) the primary one.
8
+ */
9
+ export declare const envBranches: () => {
10
+ names: string[];
11
+ test: string | undefined;
12
+ primary: string[];
13
+ custom: boolean;
14
+ };
15
+ /**
16
+ * Whether generators ask for test implementations: not when the wire has
17
+ * custom branches without a test one, since nothing would select them.
18
+ */
19
+ export declare const offersTestImplementation: () => boolean;
20
+ /**
21
+ * The `envBranchedWire({...})` argument: the test branch first, then the
22
+ * others in their configured order.
23
+ */
24
+ export declare const envBranchedWireArgument: (testWire: string, primaryWire: string) => string;
25
+ /** `env-branched-wire.ts` of the Shared Kernel for the configured branches. */
26
+ export declare const envBranchedWireSource: () => string;
package/dist/wiring.d.ts CHANGED
@@ -42,12 +42,13 @@ export type WiredModule = {
42
42
  */
43
43
  kind: string;
44
44
  };
45
+ export declare const namedImportFiles: (source: string, fromFile: string, resolve?: (specifier: string, file: string) => string | undefined) => Map<string, string>;
45
46
  export declare const readWiredModule: (wireFile: string, contextPath: string) => WiredModule | undefined;
46
47
  export declare const findWiredModules: (contextPath: string) => WiredModule[];
47
48
  /**
48
49
  * The kind a module has in the dependency rules.
49
50
  */
50
- export declare const moduleKindOf: (module: WiredModule) => "repositories" | "domain-services" | "application-ports" | "application-services" | "use-cases" | "commands" | "queries" | "infrastructure-services" | "presentation-services" | undefined;
51
+ export declare const moduleKindOf: (module: WiredModule) => "queries" | "commands" | "use-cases" | "application-ports" | "repositories" | "domain-services" | "application-services" | "infrastructure-services" | "presentation-services" | undefined;
51
52
  /**
52
53
  * The implementation label of a branched wire's class, taken from its
53
54
  * folder: `infrastructure/repositories/prisma/…` → `prisma`.
@@ -58,7 +59,7 @@ export declare const implementationType: (consumer: WiredModule, implementation:
58
59
  * as whole words: `in-memory-db-infrastructure-service` for `in-memory`.
59
60
  */
60
61
  export declare const isSuggestedFor: (candidate: WiredModule, implementation: string) => boolean;
61
- export declare const canDependOn: (consumer: WiredModule, candidate: WiredModule, rules?: DependencyRules) => boolean;
62
+ export declare const canDependOn: (consumer: WiredModule, candidate: WiredModule, rules?: DependencyRules, implementation?: WiredClass) => boolean;
62
63
  /**
63
64
  * What an implementation of the consumer can depend on by the project's
64
65
  * rules, except the consumer and what this implementation already
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": "7.2.0",
4
+ "version": "8.0.0",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -21,7 +21,8 @@
21
21
  "df-react": "./dist/react.js",
22
22
  "df-integration": "./dist/integration.js",
23
23
  "df-skills": "./bin/df-skills.mjs",
24
- "df-lint": "./dist/lint.js"
24
+ "df-lint": "./dist/lint.js",
25
+ "df-upgrade": "./dist/upgrade.js"
25
26
  },
26
27
  "main": "./dist/index.cjs",
27
28
  "homepage": "https://domain-first-landing.vercel.app/scaffolder/",
@@ -11,23 +11,24 @@ 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-scaffold 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. To rename or move a module, use `Move or rename` of df-scaffold (`df-ps-scaffold/references/units/move-or-rename.md`), never by hand.
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 Kernel), 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.
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 Kernel). Cross-context port adapters may also inject neighboring application handlers under the boundary rules below. 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, 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.
18
- - What each kind of module may use follows the defaults in these skills unless `rules.dependencies` in the config changes them; then follow the config, in imports as well as in wiring.
18
+ - What each kind of module may use follows the defaults in these skills unless `backend.rules.dependencies` in the config changes them; then follow the config, in imports as well as in wiring.
19
19
 
20
20
  ## Bounded context isolation
21
21
 
22
- A file in context A imports **nothing** from context B: no types (`import type` too), barrels, aliases, errors, or wiring. No exceptions: every context must be movable to its own service.
22
+ Context A's domain and application import nothing from B. Direct calls are confined to port adapters under `infrastructure/application-adapters/cross-context/` and their matching wiring, so their implementation can be replaced when B becomes a separate service. All other cross-context imports remain forbidden, including domain models, errors, repositories, services, concrete infrastructure and barrels.
23
23
 
24
- - A needs B's data or behavior → a **query** (read) or **command** (write) in A. Its input/output are A's own models, duplicated in A's terms; B's models never appear in A.
25
- - 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.
24
+ - A needs B's data or behavior → an **application port** in A. Its input/output are A's own models, duplicated in A's terms; B's models never appear in A.
25
+ - A direct port adapter (reserved type `cross-context`) injects B's application queries, commands or use cases. Its constructor imports the handler type; its wire imports B's matching factory. Use the CLI's context-qualified aliases (`BillingInvoiceQuery`, `wireBillingInvoiceQuery`) and map input, output and errors to A's contract. Never expose B's models through A's application contract.
26
+ - Database and transport implementations use the integration chosen in the plan (`df-ps-plan-feature`, step 3, rule 4) and import nothing from B. The test implementation returns fixed data, so A's tests never run B.
26
27
  - Refer to B's entities by id only.
27
28
  - `shared-kernel/` 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-kernel/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-kernel/` to share them between contexts; only universal entities / value objects (`money`, `email`) live there.
28
29
  - `<rootFolder>/presentation/rest/` (the generated `wires.ts`, `index.ts`) may import every context's REST wiring.
29
30
  - `<rootFolder>/presentation/react/` imports **nothing** from contexts whenever it can avoid it: a generated API client first, `import type` of endpoint contracts only without one (`df-ps-react`, "Talking to the backend").
30
- - Need a forbidden import? A's own query or command is missing. Plan it and generate it.
31
+ - Need a forbidden import? A's own port or its cross-context adapter is missing. Plan it and generate it.
31
32
 
32
33
  Check before reporting done; fix every finding:
33
34
 
@@ -43,7 +44,7 @@ Run it from the project root; `rootFolder` defaults to the config's. It resolves
43
44
  - a widget importing another widget (a widget = the nearest folder under `presentation/react/widgets/` with a `*-widget.tsx`, nested widgets included), UI-kit importing widgets, pages or contexts, shared hooks importing UI-kit, widgets, pages or contexts;
44
45
  - `new Date()` / `Date.now()` in domain or application (use the `clock` port).
45
46
 
46
- It exits with 1 when anything is found. Checks turned off in the config (`rules.lint`) aren't reported; don't turn checks off yourself.
47
+ It exits with 1 when anything is found. Checks turned off in the config (`backend.rules.lint`) aren't reported; don't turn checks off yourself.
47
48
 
48
49
  ## Units
49
50
 
@@ -61,7 +62,7 @@ export const wirePlaceOrderUseCase = wireClass(PlaceOrderUseCase, [
61
62
  ```
62
63
 
63
64
  - Use the injected dependencies in the class body; don't edit the parameter list or the wire list.
64
- - Env-branched files (repositories, commands/queries, ports): each `wire<Impl>Implementation` has its own dependencies, added per implementation. `NODE_ENV=test` selects the test one; vitest sets it.
65
+ - Env-branched files (repositories, commands/queries, ports): each `wire<Impl>Implementation` has its own dependencies, added per implementation. `NODE_ENV=test` selects the test one by default (vitest sets it); with `backend.envBranches` the project's `currentBranch` in `env-branched-wire.ts` selects the branch, and `backend.envBranches.test` is the test one. If `currentBranch` has no body yet, ask the user how the branch is chosen; don't invent it.
65
66
  - External clients and config values: an infrastructure service ([services](../df-ps-scaffold/references/units/services.md)), never a `wireValue(...)`.
66
67
  - A needed dependency the CLI doesn't offer: see rule 3 (change the design).
67
68
 
@@ -19,7 +19,7 @@ Use the overview to identify likely owners and related contexts. Search for the
19
19
 
20
20
  Read the relevant code in the affected contexts: aggregates and their rules, use cases, commands/queries, ports, and behavior tests. Follow their dependencies into adapters, wiring, relevant `shared-kernel/` components, and the REST endpoints of any providing context. Note how contexts can reach each other: which database each one uses, and any message queue, RPC, or event setup. Expand the search when ownership or a dependency remains unclear; unrelated implementations do not need a full read.
21
21
 
22
- For each affected context, note what it owns, what it does, its language, and the ports and other-context queries/commands involved in the feature. Stop expanding when you can justify ownership, identify reusable components, and verify both sides of each required cross-context interaction. Mark unresolved assumptions in the plan. If there are no contexts yet, propose an initial split in step 3.
22
+ For each affected context, note what it owns, what it does, its language, and the ports to neighboring contexts and external systems involved in the feature. Stop expanding when you can justify ownership, identify reusable components, and verify both sides of each required cross-context interaction. Mark unresolved assumptions in the plan. If there are no contexts yet, propose an initial split in step 3.
23
23
 
24
24
  ## 2. Decompose
25
25
 
@@ -30,12 +30,13 @@ Split the request into pieces of logic and choose each piece's component with `d
30
30
  1. A component goes where the data and rules it depends on live.
31
31
  2. Extend an existing context when the concept fits its language and lifecycle (the normal case).
32
32
  3. Create a new context only for a concept with its own lifecycle and vocabulary, or a different business owner. Never one context per feature.
33
- 4. Contexts are fully isolated and never import each other, so each can become its own service. Every need for another context's data or behavior is a **query or command** in the consuming context, with its own duplicated models, implemented the simplest available way. Find it in the code:
34
- - Both contexts use the same database → query it directly (the persistence label, e.g. `prisma`).
33
+ 4. Domain and application stay isolated. Every need for another context's data or behavior is an **application port** in the consuming context, with its own duplicated models. The implementation can be replaced when a context becomes a separate service. Choose the simplest available way, respecting the user's requested transport:
34
+ - Both contexts run in the same application → a port adapter with the reserved type `cross-context`. It may inject the neighboring context's queries, commands and use cases. Only the adapter imports the handler type; its wiring imports the handler factory. No transport or endpoint is needed. Check that the providing handler exists; plan it if missing.
35
+ - A direct handler call is unavailable or a database integration is requested, and both contexts use the same database → query it directly (the persistence label, e.g. `prisma`).
35
36
  - Otherwise, look for the ways the project already reaches a context besides its REST endpoints: message queue, RPC, events, generated API clients. Several options (REST counts) → ask the user which one in "Decisions for you", with a recommendation. Never pick silently.
36
37
  - Nothing besides REST → the providing context's REST endpoint (`http`).
37
38
 
38
- Unless it's the database, plan **both sides**: check that the providing context exposes what the call needs (endpoint, queue consumer…). If not, add it (and the handler behind it: a query or command, or a use case only when one query or command isn't enough) to the plan.
39
+ For transport implementations, plan **both sides**: check that the providing context exposes what the call needs (endpoint, queue consumer…). If not, add it (and the handler behind it: a query or command, or a use case only when one query or command isn't enough) to the plan.
39
40
  5. `shared-kernel/` holds technical, ownerless pieces and universal entities / value objects (`money`, `email`): the same meaning in every context, owned by none. Never a concept with one context's meaning or rules.
40
41
  6. Names: kebab-case, in the context's language. Contexts are business areas (`sales`, `reviews`), not features.
41
42
 
@@ -46,8 +47,8 @@ If two placements are plausible, ask the user and give your recommendation.
46
47
  Find out why, then act:
47
48
 
48
49
  - **You don't understand the domain** (unknown term, unclear who changes the data). Ask business questions, not "which context?": Who changes it, and when? What rule does it protect? What changes together with it? Who decides when the rule changes? The answers point to the owner. Check whether the code already has the concept under another name.
49
- - **The logic spans several contexts** (e.g. "cancel only if not shipped and refunded"). It's a process: each context owns its part, and the initiating context gets the coordinating use case and reaches the others through its own queries and commands.
50
- - **Nobody knows, including the user.** Pick a reversible default: the initiating or closest context, other contexts behind its own queries and commands, and mark it **(provisional)** with the reason.
50
+ - **The logic spans several contexts** (e.g. "cancel only if not shipped and refunded"). It's a process: each context owns its part, and the initiating context gets the coordinating use case and reaches the others through its own ports.
51
+ - **Nobody knows, including the user.** Pick a reversible default: the initiating or closest context, other contexts behind its own ports, and mark it **(provisional)** with the reason.
51
52
 
52
53
  Never: pick silently, put one context's domain logic in `shared-kernel/`, create a catch-all context (`common`, `core`, `misc`), or split arbitrarily.
53
54
 
@@ -62,7 +63,7 @@ One message: the architectural part plus the work plan in the `df-ps-scaffold` r
62
63
  **Work plan**
63
64
  (df-ps-scaffold format: new contexts first; mark (new) and (provisional))
64
65
 
65
- **Why:** own lifecycle and vocabulary → own context (step 3, rule 3); review → aggregate (choosing-components, step 4). "Only buyers" needs `sales` data → query `customer-purchase` in `reviews` with its own models, implementation `prisma`: same database, so no `sales` endpoint is needed (choosing-components, step 9; step 3, rule 4).
66
+ **Why:** own lifecycle and vocabulary → own context (step 3, rule 3); review → aggregate (choosing-components, step 4). "Only buyers" needs `sales` data → port `customer-purchase` in `reviews` with its own models, implementation `prisma`: same database, so no `sales` endpoint is needed (choosing-components, step 9; step 3, rule 4).
66
67
 
67
68
  **Decisions for you:**
68
69
  1. Separate `reviews` context (recommended) or part of `catalog`?
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: df-ps-react
3
- description: Build the React part of a Domain-First project with the `df-react` CLI (@domain-first/project-structure) — choose between pages, widgets (separated UI, headless, monolithic), UI-kit components and shared hooks, generate them with Storybook stories, move or rename pages and widgets, and implement them against the backend without importing bounded contexts. Use when the project has domain-first.project-structure.config.json with "useReact": true and the user asks for screens, UI blocks, components, hooks or stories, or to move, rename or regroup a page or widget.
3
+ description: Build the React part of a Domain-First project with the `df-react` CLI (@domain-first/project-structure) — choose between pages, widgets (separated UI, headless, monolithic), UI-kit components and shared hooks, generate them with Storybook stories, move or rename pages and widgets, and implement them against the backend without importing bounded contexts. Use when the project has domain-first.project-structure.config.json with frontend.react configured and the user asks for screens, UI blocks, components, hooks or stories, or to move, rename or regroup a page or widget.
4
4
  ---
5
5
 
6
6
  # React modules with df-react
@@ -9,11 +9,11 @@ React modules live in `<rootFolder>/presentation/react/` (`…/react/` below) an
9
9
 
10
10
  ## Workflow
11
11
 
12
- 1. Read `domain-first.project-structure.config.json`. Without it, tell the user to run `npx df-init`. With `"useReact": false`, `df-react` refuses to run: tell the user to turn React on (or add Storybook with `! npx df-integration`); don't edit the config yourself.
12
+ 1. Read `domain-first.project-structure.config.json`: source root is `project.rootFolder`; React is enabled by `frontend.react`; `frontend.react.framework` is `react` or `next`, and both use `df-react`. Stories use `frontend.react.storybookFramework` (initialization uses `@storybook/react-vite` for both React and Next.js via the shared Storybook integration). A config of an earlier major version (`CONFIG_OUTDATED`): ask the user to run `npx df-upgrade`; never run it yourself. Without the config, tell the user to run `npx df-init`; without React configured, tell them to run `npx df-init --section frontend`. Initialization and configuration belong to the human: do not run `df-init` or edit these settings yourself.
13
13
  2. A feature that also needs backend work → plan it with `df-ps-plan-feature`; React runs come last in the plan.
14
14
  3. Choose a module for each piece of UI ("Choosing the module").
15
15
  4. Show the work plan in the `df-ps-scaffold` rule 1 format and **stop until it's approved**. CLI paths are `df-react → New widget` etc.; list every answer and the files from `references/generators.md`.
16
- 5. Run the generators with the driver in plan order (shared hooks → UI-kit → widgets → pages); check each output.
16
+ 5. Run the generators with `df-react --request` JSON in plan order (shared hooks → UI-kit → widgets → pages); check each output.
17
17
  6. Implement ("Implementing"), after the backend and the regenerated API client.
18
18
  7. Run `npx df-lint` and the project's tsc/lint/tests. Report against the plan.
19
19
 
@@ -41,16 +41,22 @@ A business element goes to UI-kit only when several widgets contain the same ele
41
41
 
42
42
  ## Running df-react
43
43
 
44
- `df-react` is interactive. Drive it with the driver of `df-ps-scaffold` and `--bin df-react`; it answers the prompts, then lists created (`+`) and changed (`~`) files:
44
+ Prefer `npx df-react --describe` and `npx df-react --request` JSON. The installed schema lists operations (`page`, `widget`, `ui-kit-component`, `shared-hook`, `move-page`, `move-widget`), fields and current React modules. For example:
45
+
46
+ ```bash
47
+ npx df-react --request '{"operation":"widget","name":"cart","widgetType":"separated"}'
48
+ ```
49
+
50
+ Read `df-ps-scaffold` [agent-mode.md](../df-ps-scaffold/references/agent-mode.md) for previews, overwrite control and JSON result checks; [agent-operations.md](../df-ps-scaffold/references/agent-operations.md#react-operations-df-react) covers all React operations and naming conditions. Initialization remains a human task. For older CLI versions without JSON support, use the interactive driver with `--bin df-react`:
45
51
 
46
52
  ```bash
47
53
  node <df-ps-scaffold-skill-dir>/scripts/drive.mjs --bin df-react [--cwd <dir>] [--delay <ms>] <step>...
48
54
  node <df-ps-scaffold-skill-dir>/scripts/drive.mjs --bin df-react "pick:New widget" text:cart "pick:with separated ui"
49
55
  ```
50
56
 
51
- Steps and checks are the same as for `df-scaffold` ("Running the driver" in `df-ps-scaffold`). Its menu: `New widget`, `New page`, `New UI-kit component`, `New shared hook`, `Move or rename widget`, `Move or rename page`. Prompts and output of each: `references/generators.md`.
57
+ Steps and checks are the same as for `df-scaffold` ("Legacy interactive driver" in `df-ps-scaffold`). Its menu: `New widget`, `New page`, `New UI-kit component`, `New shared hook`, `Move or rename widget`, `Move or rename page`. Prompts and output of each: `references/generators.md`.
52
58
 
53
- If the CLI can't run, give the user the menu path and answers to run `! npx df-react` themselves. Never hand-write its output.
59
+ If the CLI cannot run, report the failure and give the user the prepared JSON command (a menu path only for a legacy CLI). Never hand-write its output.
54
60
 
55
61
  ### Moving and renaming
56
62
 
@@ -70,7 +76,7 @@ Only these (`df-ps-scaffold`, rule 2, exceptions 3–4), for modules generated b
70
76
  - Widgets never import other widgets (their component, `ui/`, `hooks/` or `types.ts`). Shared markup → UI-kit, shared logic → a shared hook, combining widgets → the page.
71
77
  - UI-kit components: presentational, driven only by props; no API client, no data loading, no imports from widgets, pages, or contexts. Other UI-kit components and shared hooks (`hooks/`) are fine. Business terms only in a domain UI-kit component; its props describe what it shows, not domain types.
72
78
  - Shared hooks (`…/react/hooks/use-<name>.ts`): generic app-wide logic, driven only by arguments; no business terms, no API client, no imports from UI-kit, widgets, pages, or contexts.
73
- - Stories (`storybookFramework`): fill `args` of `Default` with valid props and add one story per meaningful state (`Disabled`, `Loading`, `WithError`). Keep `meta`, the file name, and the title (`UI-kit/N` or `Widgets/N`). For widget UI, the stories cover the UI states that its UI model produces.
79
+ - Stories (`frontend.react.storybookFramework`): fill `args` of `Default` with valid props and add one story per meaningful state (`Disabled`, `Loading`, `WithError`). Keep `meta`, the file name, and the title (`UI-kit/N` or `Widgets/N`). For widget UI, the stories cover the UI states that its UI model produces.
74
80
 
75
81
  ### Talking to the backend
76
82
 
@@ -1,10 +1,14 @@
1
- # df-react generators: prompts and output
1
+ # df-react generators: operations and output
2
+
3
+ Prefer JSON requests; [agent operations](../../df-ps-scaffold/references/agent-operations.md#react-operations-df-react) maps all six React operations and fields. The scripted prompt sequences below are the legacy interactive fallback. Generated files and story templates apply to both modes.
4
+
5
+ Settings: `project.rootFolder` and `frontend.react.storybookFramework`. The frontend section must be configured by the user before these runs.
2
6
 
3
7
  Notation: `…/react/` = `<rootFolder>/presentation/react/`. `n` = the entered kebab-case name, `N` = PascalCase. Every step list goes after `--bin df-react`; the first prompt is the module menu. If the run would replace existing files, the last prompt is the confirm `Overwrite them?` (the files are listed above it).
4
8
 
5
9
  ## New page
6
10
 
7
- `"pick:New page" text:checkout` → `…/react/pages/n-page.tsx`
11
+ `"pick:New page" text:checkout` → `…/react/pages/n-page.tsx`; with Next.js (`frontend.react.framework: next`) also `app/n/page.tsx` (`src/app/…` when that folder exists) rendering `NPage`, unless that route already exists. A nested name nests the route too: `admin/users` → `app/admin/users/page.tsx`.
8
12
 
9
13
  ## New widget
10
14