@domain-first/project-structure 2.18.0 → 3.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.
package/README.md CHANGED
@@ -1,503 +1,220 @@
1
- # @domain-first/project-structure
1
+ # Domain First Project Structure
2
2
 
3
- **Spend less time setting up files. Spend more time building your domain.**
3
+ <p>
4
+ <img src="https://img.shields.io/npm/v/%40domain-first%2Fproject-structure" alt="version">
5
+ <img src="https://img.shields.io/badge/TypeScript-ready-3178C6?logo=typescript&logoColor=white?style=for-the-badge" alt="TypeScript ready">
6
+ <img src="https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release" alt="semver">
7
+ <img src="https://img.shields.io/npm/l/%40domain-first%2Fproject-structure" alt="license">
8
+ </p>
4
9
 
5
- An interactive CLI for growing TypeScript applications around business domains. Scaffold bounded contexts, aggregates, use cases, commands, queries, adapters, REST endpoints, and React modules with a consistent structure.
10
+ Spend less time setting up files. Spend more time building your domain.
6
11
 
7
- Choose what you need, answer a few prompts, and get the source files, optional test skeletons, and wiring to start implementing the feature.
12
+ ## What is it?
8
13
 
9
- ```bash
10
- npm install --save-dev @domain-first/project-structure
11
- npx df-ps
12
- ```
13
-
14
- [Quick start](#quick-start) · [Project structure](#project-structure) · [Generators](#generators) · [Configuration](#configuration) · [Agent skills](#agent-skills) · [Example workflow](#example-workflow)
15
-
16
- ## Why use it?
14
+ In most TypeScript codebases you choose between convenience and architecture. Clear boundaries and roles around the domain mean more files, more contracts and more wiring, so under deadline pressure the logic ends up wherever it is quickest to write it. The boundaries blur one shortcut at a time.
17
15
 
18
- Adding an aggregate often means adding a repository contract, infrastructure implementations, tests, and dependency wiring too. Repeating that setup by hand takes time and lets conventions drift.
16
+ Domain First Project Structure removes that choice: **the cleanest path is also the shortest one**. An interactive CLI asks which bounded context, layer and role a new piece of code has, and generates it in its place, with contracts, implementations, test skeletons and wiring that respect the boundaries. Dependencies are offered only where the layers allow them. Doing it right takes a few prompts; doing it wrong takes extra effort. It knows the `@domain-first` packages: types, errors, handlers, wire and handlers-rest. The generated files belong to your project; you write the business rules.
19
17
 
20
- `df-ps` turns those recurring decisions into a guided workflow:
18
+ ```
19
+ npm i -D @domain-first/project-structure
20
+ npx df-ps
21
+ ```
21
22
 
22
- - **Keep the team consistent.** Give each kind of component a predictable home, filename, and class name.
23
- - **Grow feature by feature.** Add a bounded context or a single component as the application evolves.
24
- - **Keep business code organized.** Group code by bounded context, with domain, application, infrastructure, and presentation layers inside it.
25
- - **Prepare for multiple implementations.** Generate primary and test implementations of repositories, execution commands, queries, and application ports.
26
- - **Use the integrations you need.** Enable templates for the `@domain-first` packages in your project and optional React scaffolding.
23
+ ## API
27
24
 
28
- The generated files belong to your project. Fill in the business rules, schemas, dependencies, and integration code as you would with any other source file.
25
+ The full technical specification lives in [API.md](./API.md).
29
26
 
30
- ## Quick start
27
+ ## Guide
31
28
 
32
- Run the CLI inside a project that has a `package.json`. For a new project, create one with `npm init -y` first. Use Node.js 22.13+ within the Node 22 release line, or Node.js 24+.
29
+ ### How to initialize a project
33
30
 
34
- ### 1. Install and initialize
31
+ Run `df-ps` 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, 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).
35
32
 
36
- ```bash
37
- npm install --save-dev @domain-first/project-structure
33
+ ```
38
34
  npx df-ps
39
35
  ```
40
36
 
41
- You can also run it without adding it as a development dependency:
42
-
43
- ```bash
44
- npm exec --package=@domain-first/project-structure -- df-ps
37
+ ```json
38
+ {
39
+ "rootFolder": "src",
40
+ "domainFirstPackages": [
41
+ "@domain-first/types",
42
+ "@domain-first/errors",
43
+ "@domain-first/handlers",
44
+ "@domain-first/wire"
45
+ ],
46
+ "defaultPersistenceLayerImplementation": "prisma",
47
+ "useReact": false,
48
+ "testingLibrary": "vitest"
49
+ }
45
50
  ```
46
51
 
47
- On the first run, the CLI asks for:
48
-
49
- | Setting | What to enter |
50
- | ---------------------------------- | ---------------------------------------------------------------------------------------------------- |
51
- | Root folder | The source directory, such as `src` or `src/server`. Default: `src`. |
52
- | `@domain-first` packages | The integrations to use in generated templates. |
53
- | Default persistence implementation | A label such as `prisma`, used as the suggested implementation for execution commands and queries. |
54
- | React | Whether to show the React module menu. |
55
- | Unit tests | Whether to generate tests, and which module to import test helpers from. Suggested module: `vitest`. |
56
-
57
- Setup writes `domain-first.project-structure.config.json` beside your `package.json` and creates shared helpers for the selected `wire` and `errors` integrations. That first run then exits.
58
-
59
- The CLI uses the nearest `package.json` found by walking up from the current directory. In a monorepo, run it inside the package you want to scaffold.
60
-
61
- ### 2. Create a bounded context
62
-
63
- Run `npx df-ps` again, choose **Scaffold new bounded context**, and enter a name such as `sales`.
52
+ Commit the config to share it with your team. Every next run performs one operation from the menu.
64
53
 
65
- ### 3. Add a component
54
+ ### How to create a bounded context
66
55
 
67
- Run `npx df-ps`, choose **Bounded Context: sales**, select a layer, and choose a generator. For example:
56
+ Choose **Scaffold new bounded context** and enter a name, such as `sales`. With `@domain-first/errors`, its error namespace is created too.
68
57
 
69
58
  ```text
70
- Bounded Context: sales → Domain → New Aggregate
59
+ src/bounded-contexts/sales/domain/errors/index.ts // SalesErrors = errorNamespace('sales')
71
60
  ```
72
61
 
73
- Each invocation performs one scaffolding operation. Run the command again to add the next component. Folders are created as needed.
62
+ Use lowercase kebab-case for every name: `place-order` becomes `PlaceOrderUseCase`.
74
63
 
75
- ## Project structure
64
+ ### How to add an aggregate
76
65
 
77
- A bounded context groups a business area and its implementation. Within it, each layer has a specific role:
78
-
79
- | Location | Purpose |
80
- | ----------------- | ----------------------------------------------------------------------------------------------------- |
81
- | `domain/` | Aggregates, repository contracts, domain services, and business errors. |
82
- | `application/` | Use cases, commands, queries, ports, and application services. |
83
- | `infrastructure/` | Concrete repositories, adapters, execution handlers, and infrastructure services. |
84
- | `presentation/` | REST endpoints and presentation services. |
85
- | `wiring/` | Factories that construct components and select implementations, when `@domain-first/wire` is enabled. |
86
-
87
- The **Shared Layer** menu provides cross-context errors, entities and value objects, application ports, and domain, application, infrastructure, and presentation services under `<rootFolder>/shared`.
88
-
89
- A project using handler and wiring integrations can grow into this structure:
66
+ Choose **Bounded Context: sales → Domain → New Aggregate**, name it `order`, and add a repository with a `prisma` implementation and an `in-memory` test one.
90
67
 
91
68
  ```text
92
- src/
93
- ├── bounded-contexts/
94
- │ └── sales/
95
- │ ├── domain/
96
- │ │ ├── aggregates/order/
97
- │ │ ├── errors/
98
- │ │ └── services/
99
- │ ├── application/
100
- │ │ ├── commands/ # execution/ and orchestration/
101
- │ │ ├── queries/ # execution/ and orchestration/
102
- │ │ ├── ports/
103
- │ │ ├── services/
104
- │ │ └── use-cases/
105
- │ ├── infrastructure/
106
- │ │ ├── application-adapters/
107
- │ │ ├── commands/
108
- │ │ ├── queries/
109
- │ │ ├── repositories/
110
- │ │ └── services/
111
- │ ├── presentation/
112
- │ │ ├── rest/
113
- │ │ └── services/
114
- │ └── wiring/
115
- ├── shared/
116
- └── presentation/
117
- ├── rest/
118
- └── react/
119
- ├── pages/
120
- ├── widgets/
121
- ├── ui-kit/
122
- └── hooks/
69
+ src/bounded-contexts/sales/
70
+ ├── domain/aggregates/order/
71
+ │ ├── index.ts
72
+ │ ├── order.aggregate-root.ts
73
+ │ └── order-repository.ts
74
+ ├── infrastructure/repositories/
75
+ │ ├── prisma/prisma-order-repository.ts
76
+ │ └── in-memory/in-memory-order-repository.ts
77
+ └── wiring/repositories/wire-order-repository.ts
123
78
  ```
124
79
 
125
- This is an example of the accumulated output; creating a context alone creates its directory and, when enabled, its error namespace.
126
-
127
- ## Generators
128
-
129
- Choose a bounded context, then a layer:
130
-
131
- | Layer / menu option | Generated output |
132
- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
133
- | Domain → New Aggregate | Aggregate root and barrel export; optional repository contract, primary and test implementations, tests, and repository wiring. |
134
- | Domain → New Entity / New Value Object | Entity or value object class with tests, in the `entities/` or `value-objects/` folder of a chosen aggregate (exported from its barrel) or of the context's `domain/`. Also in the Shared Layer, under `shared/domain/`. |
135
- | Domain → Errors | Errors in the context namespace, nested namespaces, and exports. Uses `@domain-first/errors`. |
136
- | Domain → New Service | Domain service class, with optional tests and wiring. |
137
- | Application → New Use Case | Use case class; handler schemas and `handle` when enabled; optional tests and wiring. |
138
- | Application → New Command / New Query | Execution or orchestration templates, with optional tests and wiring. |
139
- | Application → New Port | Abstract port and an adapter implementation, with an optional test adapter, tests, and wiring. |
140
- | Application → New Service | Application service class, with optional tests and wiring. |
141
- | Infrastructure → New Service | Infrastructure service class, with optional tests and wiring. |
142
- | Presentation → New Service | Presentation service class, with optional tests and wiring. |
143
- | Presentation → New Handlers-REST Endpoint | Endpoint class for a controller, method, and relative path; wiring and handler exports when enabled. Requires `@domain-first/handlers-rest` to appear in the menu. |
144
-
145
- ### Commands and queries
146
-
147
- Both generators offer two modes:
148
-
149
- - **Execution (with infrastructure implementation):** creates an abstract application contract and a concrete implementation under `infrastructure/commands/<implementation>` or `infrastructure/queries/<implementation>`. You can add a separate implementation for tests.
150
- - **Orchestrator (no infrastructure implementation):** creates an application class under `application/commands/orchestration` or `application/queries/orchestration`, ready for coordinating other operations.
151
-
152
- With `@domain-first/handlers`, templates include input/output schemas and a typed handler contract or `defineHandler` implementation. Execution contracts go in the corresponding `execution/` directory; without that integration, they go directly in `application/commands` or `application/queries`.
153
-
154
- ### Wiring and tests
155
-
156
- With `@domain-first/wire`, generators create `wireClass` factories. Repositories, execution commands, queries, and ports use the shared `envBranchedWire` helper to choose an implementation based on `NODE_ENV`:
157
-
158
- | Environment | Implementation |
159
- | ------------- | ---------------------------------------------------------------------------- |
160
- | `test` | The test implementation, if requested; otherwise the primary implementation. |
161
- | `development` | The primary implementation. Also used when `NODE_ENV` is unset. |
162
- | `production` | The primary implementation. |
163
-
164
- Implementation names such as `prisma`, `api`, `in-memory`, and `mock` determine names and locations for generated classes. Add the database queries, API calls, or in-memory behavior yourself. As the last step, generators that create a wiring factory offer to pick its dependencies from wired modules of the same bounded context and the Shared Layer. Each selected module is added to the factory's dependency list and to the constructor, for example `private readonly userRepository: UserRepository`. Environment-branched factories (repositories, execution commands and queries, ports) wire each implementation in isolation: you pick dependencies separately for each one, for example for `PrismaUserRepository` and then for `InMemoryUserRepository`. Each list starts with a **Suggested** group when infrastructure modules match the implementation name: `prisma-infrastructure-service` for a `prisma` implementation, or `in-memory-db-infrastructure-service` for an `in-memory` one. To add dependencies to an existing module later, select **Wire dependency** in the bounded context or Shared Layer menu. Environment-branched modules are listed there once per implementation, such as `UserRepository (prisma)` and `UserRepository (in-memory)`, and only the chosen one is changed.
165
-
166
- The list depends on the layer of the class being built:
167
-
168
- | Layer | Can depend on |
169
- | -------------- | ------------------------- |
170
- | Domain | Domain |
171
- | Application | Domain, application |
172
- | Infrastructure | Domain, infrastructure |
173
- | Presentation | Application, presentation |
80
+ Entities and value objects go into an aggregate (**New Entity**, **New Value Object**) or into the context's `domain/`.
174
81
 
175
- Some kinds of modules have narrower rules. From the application layer, application services can use only ports. Use cases can't use other use cases, and repository implementations can't use other repositories. Execution commands and queries can't use other commands or queries. From the application layer, orchestration commands and queries can use only execution commands and queries. Repository, execution command, execution query, and port implementations belong to infrastructure: they implement application modules but can't take them as dependencies. REST endpoints are not offered as dependencies. Their dependencies are chosen when they are generated (see REST endpoints) and are not available in **Wire dependency**.
82
+ ### How to add a use case, a command or a query
176
83
 
177
- When `testingLibrary` is configured, supported generators always add `.spec.ts` files. These start with construction or wiring checks; extend them with tests for your business behavior. Repository, command, query, and port test templates reference wiring factories, so use the wiring integration or adapt those tests to your own construction setup.
84
+ Choose **Application → New Use Case**, **New Command** or **New Query**. With `@domain-first/handlers`, the class gets schema placeholders and a `handle` built with `defineHandler`.
178
85
 
179
- ### REST endpoints
86
+ ```ts
87
+ export class PlaceOrderUseCase {
88
+ constructor() {}
180
89
 
181
- Select an existing controller or create one, choose `get`, `post`, `patch`, `delete`, or `put`, and enter a relative path. For example, context `sales`, controller `orders`, path `recent`, and method `get` produce:
90
+ static inputSchema = {};
91
+ static outputSchema = {};
182
92
 
183
- ```text
184
- src/bounded-contexts/sales/presentation/rest/orders/recent/GET.ts
93
+ handle = defineHandler({
94
+ inputSchema: PlaceOrderUseCase.inputSchema,
95
+ outputSchema: PlaceOrderUseCase.outputSchema,
96
+ handler: async (input) => {
97
+ return {};
98
+ },
99
+ });
100
+ }
185
101
  ```
186
102
 
187
- The route metadata uses `/sales/orders/recent`. With `@domain-first/wire`, the generator then asks for the endpoint generator, picked from presentation services of the bounded context and the Shared Layer (services with `endpoint` in the name are suggested first), and for the handler, picked from queries, commands, and use cases of the bounded context. The endpoint's constructor gets the chosen types, and its wiring factory gets their factories. In `get handle()`, call the generating method of the chosen service yourself, for example `this.endpointGenerator.generate(...)` for `readonly generate = createEndpoint(...)(adapter)`. Without wiring, or when there is nothing to pick, the endpoint keeps the `EndpointGenerator` type and a `never` handler placeholder for you to replace.
188
-
189
- With wiring enabled, the generator also adds endpoint factories and exports collected as `restHandlers` in `<rootFolder>/presentation/rest/index.ts`. Connect these handlers to your HTTP server.
103
+ Commands and queries come in two modes. **Execution** creates an abstract contract in `application/` and implementations in `infrastructure/`, like a repository. **Orchestrator** creates one application class that coordinates execution commands and queries.
190
104
 
191
- ### React modules
105
+ ### How to switch implementations
192
106
 
193
- Enable `useReact` and choose **Scaffold React module** from the main menu. Modules are created under `<rootFolder>/presentation/react`.
107
+ With `@domain-first/wire`, repositories, execution commands and queries, and ports get one factory per implementation, selected by `NODE_ENV`:
194
108
 
195
- | Generator | Output |
196
- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
197
- | New page | `pages/<name>-page.tsx` with a typed props object and a component. |
198
- | New widget → monolithic | `widgets/<name>/<name>-widget.tsx` with props and rendering in one file, re-exported from `index.ts`. |
199
- | New widget → with separated ui | `<name>-widget.tsx`, `types.ts`, `ui/<name>-widget-ui.tsx`, `hooks/use-<name>-ui-model.ts`, and `index.ts`; with `storybookFramework`, also `ui/<name>-widget-ui.stories.tsx`. |
200
- | New widget → headless | `<name>-widget.tsx`, types, a UI-model hook, and `index.ts`; the rendering component is supplied through the `UI` prop. |
201
- | New UI-kit component | `ui-kit/<name>/<name>.tsx` with a typed props object and a component, re-exported from `index.ts`; with `storybookFramework`, also `<name>.stories.tsx`. |
202
- | New shared hook | `hooks/use-<name>.ts` with an app-wide hook, such as `use-debounce`; a leading `use-` in the name is not repeated. |
203
-
204
- Page and widget names can include folders split by `/`. For example, a page named `admin/panel/users` is created at `pages/admin/panel/admin-panel-users-page.tsx` as `AdminPanelUsersPage`, and a widget with the same name at `widgets/admin/panel/users/admin-panel-users-widget.tsx` as `AdminPanelUsersWidget` with the story title `Widgets/Admin/Panel/Users`. The widget folder uses only the last segment; file names and code names use the whole path.
205
-
206
- To move or rename a page or a widget, choose **Move or rename page** or
207
- **Move or rename widget**, pick it from the list and enter a new name with
208
- folders. A widget moves with its whole folder (assets included), and a page with
209
- the files next to it that share its name, such as `<name>-page.module.css`. File
210
- names, `<Name>Page`, `<Name>Widget…` and `use<Name>UIModel` follow the new name,
211
- and so does a generated story title. Imports of the module are updated across
212
- the project, both relative ones and `tsconfig.json` `paths` aliases such as `@/`;
213
- files importing it through barrels (`export * from` / `export { … } from`) get
214
- the renamed classes too, and relative imports inside the module are adjusted to its new location. The CLI
215
- lists the files to move and to update and asks before writing; emptied folders
216
- are removed. Entering the same name renames files made before file names used
217
- the whole path, for example `pages/admin/users-page.tsx` to
218
- `pages/admin/admin-users-page.tsx`.
109
+ ```ts
110
+ export const wireOrderRepository = envBranchedWire({
111
+ test: wireInMemoryImplementation,
112
+ development: wirePrismaImplementation,
113
+ production: wirePrismaImplementation,
114
+ });
115
+ ```
219
116
 
220
- ### Project integrations
117
+ Tests get the test implementation, everything else gets the primary one.
221
118
 
222
- Choose **Add integration → Storybook (React + Vite)** to configure Storybook.
223
- The integration creates `main.ts` and `preview.ts` under
224
- `<rootFolder>/presentation/react/.storybook`, enables React scaffolding and sets
225
- `storybookFramework` to `@storybook/react-vite` for future generated stories.
226
- It uses relative story paths and configures the Vite alias `@` to the absolute
227
- project root (the directory containing `package.json`), computed at runtime
228
- from the config location. Add project CSS to `preview.ts` with relative imports
229
- or `@/` imports. The setup includes `@vitejs/plugin-react`.
119
+ ### How to wire dependencies
230
120
 
231
- It adds these package scripts, with paths adjusted to your `rootFolder`:
121
+ 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:
232
122
 
233
- ```json
234
- {
235
- "storybook": "storybook dev -p 6006 -c \"src/presentation/react/.storybook\"",
236
- "build-storybook": "storybook build -c \"src/presentation/react/.storybook\" -o \"src/presentation/react/storybook-static\""
123
+ ```ts
124
+ export class PlaceOrderUseCase {
125
+ constructor(private readonly orderRepository: OrderRepository) {}
237
126
  }
127
+
128
+ export const wirePlaceOrderUseCase = wireClass(PlaceOrderUseCase, [
129
+ wireOrderRepository,
130
+ ]);
238
131
  ```
239
132
 
240
- Existing unrelated scripts and package fields are preserved. If a script name
241
- already has a different command, choose to keep it, replace it, or use another
242
- name. Identical generated configs and scripts are skipped on subsequent runs;
243
- changed config files use the usual overwrite confirmation. Cancelling before
244
- writing leaves all files unchanged.
245
-
246
- After writing, the CLI prints only npm commands for missing dependencies. It
247
- does not install packages or execute scripts. Install commands omit version constraints for Storybook, its React + Vite
248
- framework, Vite and the React plugin; existing dependency versions are preserved
249
- and must be compatible with those packages. Generate a
250
- UI-kit component or a widget with separated UI to add your first story. The
251
- static build goes to `<rootFolder>/presentation/react/storybook-static`; the
252
- integration adds this directory to the project `.gitignore` without duplicating
253
- the entry on subsequent runs.
254
-
255
- ### Missing domain-first packages
256
-
257
- Choose **Add integration → Missing domain-first packages** to compare
258
- `domainFirstPackages` in the configuration with `dependencies`, `devDependencies`
259
- and `optionalDependencies` in the project's `package.json`. The CLI prints one
260
- `npm i` command for missing packages, without version constraints. If none are
261
- missing, it prints nothing. This
262
- checks declared dependencies, not the contents of `node_modules`, and does not
263
- modify files or install packages.
264
-
265
- ### Prisma 8 (PostgreSQL)
266
-
267
- Choose **Add integration → Prisma 8 (PostgreSQL, RC)**. The preset creates
268
- `<rootFolder>/shared/infrastructure/prisma/prisma.config.ts` and a starter
269
- `contract.prisma`. Existing contracts are preserved, including your models.
270
-
271
- You can optionally create `PrismaInfrastructureService` in
272
- `shared/infrastructure/services`; it exposes `orm`, uses the Temporal polyfill,
273
- and reuses the client across development hot reloads. When `@domain-first/wire`
274
- is enabled, the integration also creates its wiring factory. A separate prompt
275
- lets you make `prisma` the default persistence implementation.
276
-
277
- The integration adds three scripts, all pointing to the generated config:
278
-
279
- - `prisma:emit`: emit `contract.json` and `contract.d.ts`.
280
- - `prisma:migration:plan`: emit the contract, then plan a migration.
281
- - `prisma:migration:apply`: apply migrations and advance the `db` ref.
282
-
283
- Script conflicts use the same keep/replace/rename flow as Storybook. File changes
284
- are staged until overwrite confirmation; no packages are installed and no
285
- commands connect to the database during scaffolding.
286
-
287
- The printed install commands omit version constraints for `prisma`,
288
- `@prisma/cli-engine`, `@prisma/orm-postgres`, `temporal-polyfill`, and `dotenv`. Already declared dependencies are kept.
289
- The CLI also reminds you to add `!<rootFolder>/shared/infrastructure/prisma` to
290
- your linter ignores. This is a PostgreSQL
291
- preset for Prisma 8 RC, not a Prisma 7 migration tool.
292
-
293
- After installing dependencies, configure `DATABASE_URL` (the CLI loads `.env`;
294
- your application must load its runtime environment), add your models to the
295
- contract and run the emit script before compiling or importing the service.
296
- Use Node.js 22.18+, TypeScript 5.9+, ESM and JSON import support. Review planned
297
- migrations before running the apply script. Generated contract files and
298
- migration history are managed by Prisma, not by this scaffolder.
299
-
300
- ### Vitest
301
-
302
- Choose **Add integration → Vitest**. The integration creates `vitest.config.ts`
303
- in the project root (the directory containing `package.json`) with
304
- `resolve.tsconfigPaths` and V8 coverage for `<rootFolder>/bounded-contexts` and
305
- `<rootFolder>/shared`. Specs, infrastructure, REST presentation and wiring are
306
- excluded from coverage. When `@domain-first/handlers-next` is declared, the
307
- config also inlines it so Vitest can resolve its `next/headers` import.
308
-
309
- It sets `testingLibrary` to `vitest`, so generators scaffold unit tests; if
310
- another testing library is configured, the CLI asks before replacing it. It also
311
- adds `/coverage/` to the project `.gitignore` and these package scripts:
133
+ 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.
312
134
 
313
- ```json
314
- {
315
- "test": "vitest run --reporter=dot --silent=passed-only",
316
- "test:coverage": "vitest run --coverage --reporter=dot --silent=passed-only"
317
- }
318
- ```
135
+ ### How to add errors
319
136
 
320
- Script conflicts and overwrite confirmation work as in the other integrations.
321
- The printed install command omits version constraints for `vitest` and
322
- `@vitest/coverage-v8`; already declared dependencies are kept.
323
- `resolve.tsconfigPaths` requires Vite 8+. The config excludes `specs/e2e`, which
324
- belongs to Playwright.
325
-
326
- ### Playwright
327
-
328
- Choose **Add integration → Playwright**. The integration creates
329
- `playwright.config.ts` in the project root with `testDir: './specs/e2e'`, an
330
- HTML reporter, traces on retry, screenshots and videos on failure, and projects
331
- for Chromium, Firefox, WebKit, Mobile Chrome and Mobile Safari, all running on
332
- Playwright's own browser builds.
333
- The web server runs `npm run dev` at `http://localhost:3000` and is reused
334
- outside CI; adjust `baseURL` and `webServer.url` for another port.
335
-
336
- A mock example goes to `specs/e2e/home`: `home.e2e.spec.ts` and a `README.MD`
337
- with its user stories. Existing example files are never overwritten. The
338
- integration adds a `test:e2e` script (`playwright test`) and ignores
339
- `/test-results/`, `/playwright-report/`, `/blob-report/`, `/playwright/.cache/`
340
- and `/playwright/.auth/` in `.gitignore`.
341
-
342
- After writing, the CLI prints `npm install --save-dev @playwright/test` if the
343
- package is missing and `npx playwright install --with-deps` for the browsers and
344
- their system dependencies. Then run `npm run test:e2e`.
345
-
346
- ### OpenAPI
347
-
348
- Choose **Add integration → OpenAPI**. The item is listed only when
349
- `domainFirstPackages` includes `@domain-first/handlers-rest`. The integration asks for the route prefix
350
- your HTTP server serves `restHandlers` under (`/api` by default) and for the
351
- document path (`public/openapi.json` when `next` is declared, otherwise
352
- `openapi.json`). It creates `scripts/generate-openapi.ts` in the project root,
353
- which passes `restHandlers` from `<rootFolder>/presentation/rest` to
354
- `generateOpenAPI` from `@domain-first/handlers-rest`. The document title comes from the package name. It adds this package script:
137
+ Choose **Domain → Errors** to add an error to the context namespace, create a nested namespace, or add an error to it.
355
138
 
356
- ```json
357
- {
358
- "openapi": "tsx --env-file-if-exists=.env scripts/generate-openapi.ts"
359
- }
139
+ ```ts
140
+ export const OutOfStockSalesError =
141
+ SalesErrors.define("out-of-stock");
360
142
  ```
361
143
 
362
- `.env` is loaded because wiring imported through `restHandlers` may read the
363
- environment. Script conflicts and overwrite confirmation work as in the other
364
- integrations. After writing, the CLI prints `npm install --save-dev tsx` when
365
- `tsx` is missing. The script needs `@domain-first/handlers-rest` 7.0.2+, where
366
- OpenAPI paths start with `/` without a leading empty prefix segment; when the
367
- package is missing or older (the installed version is checked first, then the
368
- declared range), the CLI prints `npm install @domain-first/handlers-rest@^7.0.2`. `restHandlers`
369
- are created with the first REST endpoint generated with `@domain-first/wire`;
370
- until then, the CLI reminds you about it. Run `npm run openapi` after adding or
371
- changing endpoints, then regenerate your API client, if you have one.
372
-
373
- ### Orval (React Query client)
374
-
375
- Choose **Add integration → Orval (React Query client)**. The item is listed only
376
- when `domainFirstPackages` includes `@domain-first/handlers-rest` and `useReact`
377
- is enabled. The integration asks for the OpenAPI document path; the default is
378
- read from `scripts/generate-openapi.ts` created by the OpenAPI integration. It
379
- creates:
380
-
381
- - `<rootFolder>/presentation/react/data-layer/orval.config.ts`: TanStack Query
382
- v5 hooks on `fetch`, split by tags into `data-layer/orval`, with schemas in
383
- its `model` folder. Orval resolves paths relative to the config, so they
384
- point to the OpenAPI document and the data layer from there. When `next` is
385
- declared, request URLs start with `NEXT_PUBLIC_API_BASE_URL`.
386
- - `data-layer/api-client/mutator.ts`: `customInstance`, which every generated
387
- request goes through. It calls `fetch` and throws `ApiError` with the status
388
- and the parsed body on non-2xx responses; the hooks type that body per
389
- endpoint. Add auth headers, token refresh and other shared request logic here.
390
- - `data-layer/query-provider.tsx`: `QueryProvider` with one `QueryClient` per
391
- browser session. Wrap your app in it.
392
-
393
- The mutator and the provider are starting points and are never overwritten.
394
-
395
- The generated `data-layer/orval/` folder is added to `.gitignore`, and this
396
- package script is added, with the path adjusted to your `rootFolder`:
144
+ ### How to share code between contexts
397
145
 
398
- ```json
399
- {
400
- "client:orval": "orval --config \"src/presentation/react/data-layer/orval.config.ts\""
401
- }
402
- ```
146
+ 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.
403
147
 
404
- After writing, the CLI prints `npm install @tanstack/react-query` and
405
- `npm install --save-dev orval` for missing packages. Run `npm run openapi`, then
406
- `npm run client:orval`, and import hooks and types from `data-layer/orval`.
148
+ ### How to add a REST endpoint
407
149
 
408
- ## Configuration
150
+ With `@domain-first/handlers-rest`, choose **Presentation → New Handlers-REST Endpoint**, pick or create a controller, a method and a relative path. Context `sales`, controller `orders`, path `recent` and `get` give:
409
151
 
410
- The project configuration is stored in `domain-first.project-structure.config.json`. Commit it to share generation settings with your team. For example:
152
+ ```text
153
+ src/bounded-contexts/sales/presentation/rest/orders/recent/GET.ts // GET /sales/orders/recent
154
+ ```
411
155
 
412
- ```json
413
- {
414
- "rootFolder": "src",
415
- "domainFirstPackages": [
416
- "@domain-first/types",
417
- "@domain-first/errors",
418
- "@domain-first/handlers",
419
- "@domain-first/wire",
420
- "@domain-first/handlers-rest"
421
- ],
422
- "defaultPersistenceLayerImplementation": "prisma",
423
- "useReact": true,
424
- "storybookFramework": "@storybook/react-vite",
425
- "testingLibrary": "vitest"
156
+ 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):
157
+
158
+ ```ts
159
+ export class RestEndpointGeneratorPresentationService {
160
+ get withoutGuards(): EndpointGenerator {
161
+ return createEndpoint({
162
+ errorStatuses: {
163
+ 400: {
164
+ checks: this.invalidRequestChecks,
165
+ description: 'Invalid request'
166
+ }
167
+ }
168
+ })(this.adapter) as EndpointGenerator
169
+ }
170
+
171
+ /**
172
+ * Default checks of an invalid request, to spread into a generator's
173
+ * own checks.
174
+ */
175
+ private get invalidRequestChecks(): ErrorStatuses[number]['checks'] {
176
+ return [RequestParsingError.is, InputMappingError.is]
177
+ }
178
+
179
+ /**
180
+ * The adapter of your HTTP framework.
181
+ */
182
+ private get adapter(): Adapter<any[], any> {
183
+ throw new Error('REST adapter is not set')
184
+ }
426
185
  }
427
186
  ```
428
187
 
429
- | Field | Effect |
430
- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
431
- | `rootFolder` | Base path for generated source, relative to the project root. |
432
- | `domainFirstPackages` | Explicit list of integrations used by templates. An empty array selects basic class templates where supported. |
433
- | `defaultPersistenceLayerImplementation` | Suggested implementation label for execution commands and queries. |
434
- | `useReact` | Shows or hides the React module menu. |
435
- | `storybookFramework` | Storybook framework package imported by generated stories (`Meta`, `StoryObj`), e.g. `@storybook/react-vite`. Omit this field to skip stories for UI-kit components and widget UI. Asked during setup only when React is enabled. |
436
- | `testingLibrary` | Module imported by generated tests. Omit this field to disable test generation. Templates expect helpers such as `describe`, `test`, `expect`, and `beforeEach`. |
437
-
438
- ### Package integrations
188
+ Set `adapter` to the adapter of your HTTP framework. Each generating method is a getter returning `EndpointGenerator`: add one per kind of endpoint (for example `withAuth`, with its `context` and error statuses). Reuse the default checks there and add your own: `checks: [...this.invalidRequestChecks, MyError.is]`. 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(...)`.
439
189
 
440
- | Package | What it enables |
441
- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------ |
442
- | `@domain-first/types` | Aggregate roots extending `domainType()`. |
443
- | `@domain-first/errors` | Context and shared error namespaces initialized during setup/context creation. Error generation uses this package. |
444
- | `@domain-first/handlers` | Handler contracts, `defineHandler`, and input/output schema placeholders for use cases, commands, and queries. |
445
- | `@domain-first/wire` | Construction factories and environment-based implementation selection. |
446
- | `@domain-first/handlers-rest` | The REST endpoint generator using `EndpointGenerator`. |
190
+ 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.
447
191
 
448
- Select the packages you intend to use and install them in your application separately. The CLI reads this list from configuration; it does not detect or install dependencies. React and your testing library also need their own project setup.
192
+ ### How to scaffold React modules
449
193
 
450
- You can edit the configuration for future runs. Existing files are left as they are when you edit settings; enabling `wire` or `errors` later also requires adding the shared helpers that initial setup would create, plus context error namespaces where needed.
194
+ 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:
451
195
 
452
- ## Agent skills
453
-
454
- The package ships skills that teach coding agents to plan features, scaffold components with `df-ps`, and implement the generated code. Copy them into your project:
455
-
456
- ```bash
457
- npx df-skills
196
+ ```text
197
+ admin/panel/users → pages/admin/panel/admin-panel-users-page.tsx (AdminPanelUsersPage)
458
198
  ```
459
199
 
460
- Choose the agents and whether to install into the project or your home directory. Or pass flags:
200
+ **Move or rename page** and **Move or rename widget** move the files and update every import in the project.
461
201
 
462
- | Flag | Installs into |
463
- | --- | --- |
464
- | `--claude` | `.claude/skills` (Claude Code) |
465
- | `--codex` | `.agents/skills` (Codex) |
466
- | `--global` | the home directory instead of the current project |
202
+ ### How to add tooling
467
203
 
468
- Run it again after upgrading the package: existing `df-ps-*` skill folders are replaced with the new versions.
204
+ Choose **Add integration** to configure Storybook, Prisma 8, Vitest, Playwright, OpenAPI generation or an Orval React Query client. Integrations add config files, package scripts and `.gitignore` entries, then print the install commands. Nothing is installed or run for you.
469
205
 
470
- ## Example workflow
206
+ **Missing domain-first packages** prints the `npm i` command for packages from the config that are not in `package.json`.
471
207
 
472
- To start an order feature, enable `@domain-first/wire` during initialization and run `npx df-ps` for each step:
208
+ ### How to teach your coding agent
473
209
 
474
- 1. Choose **Scaffold new bounded context** and name it `sales`.
475
- 2. Choose **Bounded Context: sales → Domain → New Aggregate**, name it `order`, and add a repository with `prisma` and an `in-memory` test implementation.
476
- 3. Choose **Application → New Use Case** within `sales` and name it `place-order`.
477
- 4. Implement the aggregate's rules, repository operations, and use case; connect their dependencies in the generated wiring files.
210
+ The package ships skills that teach coding agents to plan features, scaffold with `df-ps` and implement the generated code.
478
211
 
479
- The key files from these selections are:
480
-
481
- ```text
482
- src/bounded-contexts/sales/
483
- ├── domain/aggregates/order/
484
- │ ├── index.ts
485
- │ ├── order.aggregate-root.ts
486
- │ └── order-repository.ts
487
- ├── application/use-cases/
488
- │ └── place-order-use-case.ts
489
- ├── infrastructure/repositories/
490
- │ ├── prisma/prisma-order-repository.ts
491
- │ └── in-memory/in-memory-order-repository.ts
492
- └── wiring/
493
- ├── repositories/wire-order-repository.ts
494
- └── use-cases/wire-place-order-use-case.ts
212
+ ```
213
+ npx df-skills --claude
495
214
  ```
496
215
 
497
- Use lowercase kebab-case for entered names, such as `place-order` and `payment-gateway`. Names are used in paths, and class and variable names are derived from their hyphen-separated words: `place-order` becomes `PlaceOrderUseCase` for a use case.
498
-
499
- Nothing is written until a run finishes. If the run would replace existing files, the CLI lists them and asks `Overwrite them?` (default: No). Answering No, or interrupting the CLI at any prompt, leaves the project unchanged. Lines added to existing barrels, error files, and wiring indexes are not overwrites and are never duplicated. Use a new name for a new component, and review the generated changes before continuing implementation.
216
+ Run it again after upgrading the package to get the new versions.
500
217
 
501
218
  ## License
502
219
 
503
- [MIT](./LICENSE)
220
+ MIT