@domain-first/project-structure 2.14.1 → 2.15.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
@@ -46,13 +46,13 @@ npm exec --package=@domain-first/project-structure -- df-ps
46
46
 
47
47
  On the first run, the CLI asks for:
48
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`. |
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
56
 
57
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
58
 
@@ -128,19 +128,19 @@ This is an example of the accumulated output; creating a context alone creates i
128
128
 
129
129
  Choose a bounded context, then a layer:
130
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. |
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
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. |
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
144
 
145
145
  ### Commands and queries
146
146
 
@@ -165,12 +165,12 @@ Implementation names such as `prisma`, `api`, `in-memory`, and `mock` determine
165
165
 
166
166
  The list depends on the layer of the class being built:
167
167
 
168
- | Layer | Can depend on |
169
- | -------------- | -------------------------------------------- |
170
- | Domain | Domain |
171
- | Application | Domain, application |
172
- | Infrastructure | Domain, infrastructure |
173
- | Presentation | Application, presentation |
168
+ | Layer | Can depend on |
169
+ | -------------- | ------------------------- |
170
+ | Domain | Domain |
171
+ | Application | Domain, application |
172
+ | Infrastructure | Domain, infrastructure |
173
+ | Presentation | Application, presentation |
174
174
 
175
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**.
176
176
 
@@ -192,16 +192,16 @@ With wiring enabled, the generator also adds endpoint factories and exports coll
192
192
 
193
193
  Enable `useReact` and choose **Scaffold React module** from the main menu. Modules are created under `<rootFolder>/presentation/react`.
194
194
 
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`. |
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
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. |
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
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/users-page.tsx` as `AdminPanelUsersPage`, and a widget with the same name at `widgets/admin/panel/users/` as `AdminPanelUsersWidget` with the story title `Widgets/Admin/Panel/Users`. File names use only the last segment; code names use the whole path.
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
205
 
206
206
  ### Project integrations
207
207
 
@@ -218,8 +218,8 @@ It adds these package scripts, with paths adjusted to your `rootFolder`:
218
218
 
219
219
  ```json
220
220
  {
221
- "storybook": "storybook dev -p 6006 -c \"src/presentation/react/.storybook\"",
222
- "build-storybook": "storybook build -c \"src/presentation/react/.storybook\" -o \"src/presentation/react/storybook-static\""
221
+ "storybook": "storybook dev -p 6006 -c \"src/presentation/react/.storybook\"",
222
+ "build-storybook": "storybook build -c \"src/presentation/react/.storybook\" -o \"src/presentation/react/storybook-static\""
223
223
  }
224
224
  ```
225
225
 
@@ -298,8 +298,8 @@ adds `/coverage/` to the project `.gitignore` and these package scripts:
298
298
 
299
299
  ```json
300
300
  {
301
- "test": "vitest run --reporter=dot --silent=passed-only",
302
- "test:coverage": "vitest run --coverage --reporter=dot --silent=passed-only"
301
+ "test": "vitest run --reporter=dot --silent=passed-only",
302
+ "test:coverage": "vitest run --coverage --reporter=dot --silent=passed-only"
303
303
  }
304
304
  ```
305
305
 
@@ -329,6 +329,65 @@ After writing, the CLI prints `npm install --save-dev @playwright/test` if the
329
329
  package is missing and `npx playwright install --with-deps` for the browsers and
330
330
  their system dependencies. Then run `npm run test:e2e`.
331
331
 
332
+ ### OpenAPI
333
+
334
+ Choose **Add integration → OpenAPI**. The item is listed only when
335
+ `domainFirstPackages` includes `@domain-first/handlers-rest`. The integration asks for the route prefix
336
+ your HTTP server serves `restHandlers` under (`/api` by default) and for the
337
+ document path (`public/openapi.json` when `next` is declared, otherwise
338
+ `openapi.json`). It creates `scripts/generate-openapi.ts` in the project root,
339
+ which passes `restHandlers` from `<rootFolder>/presentation/rest` to
340
+ `generateOpenAPI` from `@domain-first/handlers-rest`. The document title comes from the package name. It adds this package script:
341
+
342
+ ```json
343
+ {
344
+ "openapi": "tsx --env-file-if-exists=.env scripts/generate-openapi.ts"
345
+ }
346
+ ```
347
+
348
+ `.env` is loaded because wiring imported through `restHandlers` may read the
349
+ environment. Script conflicts and overwrite confirmation work as in the other
350
+ integrations. After writing, the CLI prints `npm install --save-dev tsx` and
351
+ `npm install @domain-first/handlers-rest` for missing packages. `restHandlers`
352
+ are created with the first REST endpoint generated with `@domain-first/wire`;
353
+ until then, the CLI reminds you about it. Run `npm run openapi` after adding or
354
+ changing endpoints, then regenerate your API client, if you have one.
355
+
356
+ ### Orval (React Query client)
357
+
358
+ Choose **Add integration → Orval (React Query client)**. The item is listed only
359
+ when `domainFirstPackages` includes `@domain-first/handlers-rest` and `useReact`
360
+ is enabled. The integration asks for the OpenAPI document path; the default is
361
+ read from `scripts/generate-openapi.ts` created by the OpenAPI integration. It
362
+ creates:
363
+
364
+ - `<rootFolder>/presentation/react/data-layer/orval.config.ts`: TanStack Query
365
+ v5 hooks on `fetch`, split by tags into `data-layer/orval`, with schemas in
366
+ its `model` folder. Orval resolves paths relative to the config, so they
367
+ point to the OpenAPI document and the data layer from there. When `next` is
368
+ declared, request URLs start with `NEXT_PUBLIC_API_BASE_URL`.
369
+ - `data-layer/api-client/mutator.ts`: `customInstance`, which every generated
370
+ request goes through. It calls `fetch` and throws `ApiError` with the status
371
+ and the parsed body on non-2xx responses; the hooks type that body per
372
+ endpoint. Add auth headers, token refresh and other shared request logic here.
373
+ - `data-layer/query-provider.tsx`: `QueryProvider` with one `QueryClient` per
374
+ browser session. Wrap your app in it.
375
+
376
+ The mutator and the provider are starting points and are never overwritten.
377
+
378
+ The generated `data-layer/orval/` folder is added to `.gitignore`, and this
379
+ package script is added, with the path adjusted to your `rootFolder`:
380
+
381
+ ```json
382
+ {
383
+ "client:orval": "orval --config \"src/presentation/react/data-layer/orval.config.ts\""
384
+ }
385
+ ```
386
+
387
+ After writing, the CLI prints `npm install @tanstack/react-query` and
388
+ `npm install --save-dev orval` for missing packages. Run `npm run openapi`, then
389
+ `npm run client:orval`, and import hooks and types from `data-layer/orval`.
390
+
332
391
  ## Configuration
333
392
 
334
393
  The project configuration is stored in `domain-first.project-structure.config.json`. Commit it to share generation settings with your team. For example:
@@ -350,14 +409,14 @@ The project configuration is stored in `domain-first.project-structure.config.js
350
409
  }
351
410
  ```
352
411
 
353
- | Field | Effect |
354
- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
355
- | `rootFolder` | Base path for generated source, relative to the project root. |
356
- | `domainFirstPackages` | Explicit list of integrations used by templates. An empty array selects basic class templates where supported. |
357
- | `defaultPersistenceLayerImplementation` | Suggested implementation label for execution commands and queries. |
358
- | `useReact` | Shows or hides the React module menu. |
412
+ | Field | Effect |
413
+ | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
414
+ | `rootFolder` | Base path for generated source, relative to the project root. |
415
+ | `domainFirstPackages` | Explicit list of integrations used by templates. An empty array selects basic class templates where supported. |
416
+ | `defaultPersistenceLayerImplementation` | Suggested implementation label for execution commands and queries. |
417
+ | `useReact` | Shows or hides the React module menu. |
359
418
  | `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. |
360
- | `testingLibrary` | Module imported by generated tests. Omit this field to disable test generation. Templates expect helpers such as `describe`, `test`, `expect`, and `beforeEach`. |
419
+ | `testingLibrary` | Module imported by generated tests. Omit this field to disable test generation. Templates expect helpers such as `describe`, `test`, `expect`, and `beforeEach`. |
361
420
 
362
421
  ### Package integrations
363
422
 
package/dist/index.cjs CHANGED
@@ -258,6 +258,74 @@ const addPackageScripts = async (file, additions)=>{
258
258
  return selected;
259
259
  };
260
260
  const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
261
+ const openapiScriptPath = "scripts/generate-openapi.ts";
262
+ const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
263
+ const openapiScripts = {
264
+ openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
265
+ };
266
+ const splitPath = (value)=>value.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
267
+ const apiTitle = (packageName)=>{
268
+ const words = String(packageName ?? '').replace(/^@[^/]*\//, '').split(/[^a-zA-Z0-9]+/).filter((word)=>!!word).map((word)=>word[0].toUpperCase() + word.slice(1));
269
+ return [
270
+ ...words,
271
+ 'API'
272
+ ].join(' ');
273
+ };
274
+ const openapiGenerator = (rootFolder, title, routePrefix, outputPath)=>{
275
+ const restFolder = external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/rest');
276
+ const restImport = external_node_path_default().posix.relative(external_node_path_default().posix.dirname(openapiScriptPath), restFolder);
277
+ const apiRoutePrefix = [
278
+ '',
279
+ ...splitPath(routePrefix)
280
+ ].map((segment)=>`'${segment}'`).join(', ');
281
+ return `import { generateOpenAPI } from '@domain-first/handlers-rest';
282
+ import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}';
283
+
284
+ generateOpenAPI(restHandlers, {
285
+ document: { info: { title: '${title}', version: '1.0.0' } },
286
+ apiRoutePrefix: [${apiRoutePrefix}],
287
+ outputFile: { path: '${outputPath}' }
288
+ });
289
+ `;
290
+ };
291
+ const addOpenapi = async ()=>{
292
+ const { rootFolder } = ConfigFile.Instance.data;
293
+ const root = new ProjectRoot().path;
294
+ const manifestFile = new File(external_node_path_default().join(root, 'package.json'));
295
+ const manifest = JSON.parse(manifestFile.data);
296
+ const dependencies = {
297
+ ...manifest.dependencies,
298
+ ...manifest.devDependencies
299
+ };
300
+ const routePrefix = await (0, prompts_namespaceObject.input)({
301
+ message: 'Route prefix the REST handlers are served under:',
302
+ default: '/api'
303
+ });
304
+ const outputPath = await (0, prompts_namespaceObject.input)({
305
+ message: 'OpenAPI document path:',
306
+ default: defaultOpenapiPath(Boolean(dependencies.next)),
307
+ validate: (value)=>splitPath(value).length ? true : 'Path is required'
308
+ });
309
+ const selected = await addPackageScripts(manifestFile, openapiScripts);
310
+ const generatorFile = new File(external_node_path_default().join(root, openapiScriptPath));
311
+ const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'));
312
+ if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
313
+ const hasRestHandlers = new File(external_node_path_default().join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
314
+ return [
315
+ ...dependencies['@domain-first/handlers-rest'] ? [] : [
316
+ 'npm install @domain-first/handlers-rest'
317
+ ],
318
+ ...dependencies.tsx ? [] : [
319
+ 'npm install --save-dev tsx'
320
+ ],
321
+ ...describeScripts(selected, {
322
+ openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
323
+ }),
324
+ ...hasRestHandlers ? [] : [
325
+ `restHandlers appear in ${external_node_path_default().posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
326
+ ]
327
+ ];
328
+ };
261
329
  const addGitignoreEntry = (root, entry)=>{
262
330
  const gitignore = new File(external_node_path_default().join(root, '.gitignore'));
263
331
  const ignored = gitignore.exists ? gitignore.data : '';
@@ -265,6 +333,154 @@ const addGitignoreEntry = (root, entry)=>{
265
333
  const newline = ignored.includes('\r\n') ? '\r\n' : '\n';
266
334
  gitignore.update(`${ignored}${ignored && !ignored.endsWith('\n') ? newline : ''}${entry}${newline}`);
267
335
  };
336
+ const dataLayerFolder = (rootFolder)=>external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/data-layer');
337
+ const orvalScripts = (rootFolder)=>({
338
+ 'client:orval': `orval --config ${JSON.stringify(`${dataLayerFolder(rootFolder)}/orval.config.ts`)}`
339
+ });
340
+ const orvalConfig = (rootFolder, openapiPath, withNext)=>{
341
+ const inputPath = external_node_path_default().posix.relative(dataLayerFolder(rootFolder), openapiPath);
342
+ const baseUrl = withNext ? `
343
+ baseUrl: {
344
+ runtime: 'process.env.NEXT_PUBLIC_API_BASE_URL ?? ""'
345
+ },` : '';
346
+ return `import { defineConfig } from 'orval';
347
+
348
+ export default defineConfig({
349
+ api: {
350
+ input: '${inputPath.startsWith('.') ? inputPath : `./${inputPath}`}',
351
+ output: {
352
+ mode: 'tags-split',
353
+ target: './orval',
354
+ schemas: './orval/model',
355
+ client: 'react-query',
356
+ httpClient: 'fetch',${baseUrl}
357
+ clean: true,
358
+ override: {
359
+ mutator: {
360
+ path: './api-client/mutator.ts',
361
+ name: 'customInstance'
362
+ },
363
+ fetch: {
364
+ includeHttpResponseReturnType: false
365
+ },
366
+ query: {
367
+ version: 5
368
+ }
369
+ }
370
+ }
371
+ }
372
+ });
373
+ `;
374
+ };
375
+ const orvalMutator = `/** Error of the generated hooks, with the parsed response body. */
376
+ export class ApiError<Body = unknown> extends Error {
377
+ constructor(
378
+ public readonly status: number,
379
+ public readonly body: Body
380
+ ) {
381
+ super(\`API error \${status}\`);
382
+ this.name = 'ApiError';
383
+ }
384
+ }
385
+
386
+ /** Error type of the generated hooks, typed per endpoint by Orval. */
387
+ export type ErrorType<Body> = ApiError<Body>;
388
+
389
+ /** Every generated request goes through here: add auth headers, token refresh, logging. */
390
+ export const customInstance = async <T>(
391
+ url: string,
392
+ init?: RequestInit
393
+ ): Promise<T> => {
394
+ const response = await fetch(url, init);
395
+ const text = await response.text();
396
+ const body = text ? JSON.parse(text) : undefined;
397
+
398
+ if (!response.ok) {
399
+ throw new ApiError(response.status, body);
400
+ }
401
+
402
+ return body as T;
403
+ };
404
+ `;
405
+ const queryProvider = `'use client';
406
+
407
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
408
+ import { type FC, type ReactNode, useState } from 'react';
409
+
410
+ export const QueryProvider: FC<{ children: ReactNode }> = ({ children }) => {
411
+ // One client per browser session; a module-level client would be shared between requests on the server
412
+ const [queryClient] = useState(() => new QueryClient());
413
+
414
+ return (
415
+ <QueryClientProvider client={queryClient}>
416
+ {children}
417
+ </QueryClientProvider>
418
+ );
419
+ };
420
+ `;
421
+ const openapiOutputPath = (root)=>{
422
+ const generator = new File(external_node_path_default().join(root, openapiScriptPath));
423
+ if (!generator.exists) return;
424
+ return generator.data.match(/outputFile:\s*{\s*path:\s*'([^']+)'/)?.[1];
425
+ };
426
+ const addOrval = async ()=>{
427
+ const { rootFolder } = ConfigFile.Instance.data;
428
+ const root = new ProjectRoot().path;
429
+ const manifestFile = new File(external_node_path_default().join(root, 'package.json'));
430
+ const manifest = JSON.parse(manifestFile.data);
431
+ const dependencies = {
432
+ ...manifest.dependencies,
433
+ ...manifest.devDependencies
434
+ };
435
+ const withNext = Boolean(dependencies.next);
436
+ const generatedOpenapiPath = openapiOutputPath(root);
437
+ const openapiPath = await (0, prompts_namespaceObject.input)({
438
+ message: 'OpenAPI document path:',
439
+ default: generatedOpenapiPath ?? defaultOpenapiPath(withNext),
440
+ validate: (value)=>value.trim() ? true : 'Path is required'
441
+ });
442
+ const selected = await addPackageScripts(manifestFile, orvalScripts(rootFolder));
443
+ const dataLayer = dataLayerFolder(rootFolder);
444
+ const configFile = new File(external_node_path_default().join(root, dataLayer, 'orval.config.ts'));
445
+ const content = orvalConfig(rootFolder, external_node_path_default().posix.normalize(openapiPath.trim().replaceAll('\\', '/')), withNext);
446
+ if (!configFile.exists || configFile.data !== content) configFile.data = content;
447
+ for (const [name, fileContent] of [
448
+ [
449
+ 'api-client/mutator.ts',
450
+ orvalMutator
451
+ ],
452
+ [
453
+ 'query-provider.tsx',
454
+ queryProvider
455
+ ]
456
+ ]){
457
+ const file = new File(external_node_path_default().join(root, dataLayer, name));
458
+ if (!file.exists) file.data = fileContent;
459
+ }
460
+ addGitignoreEntry(root, `/${dataLayer}/orval/`);
461
+ const missing = (names)=>names.filter((name)=>!dependencies[name]);
462
+ const runtime = missing([
463
+ '@tanstack/react-query'
464
+ ]);
465
+ const development = missing([
466
+ 'orval'
467
+ ]);
468
+ return [
469
+ ...runtime.length ? [
470
+ `npm install ${runtime.join(' ')}`
471
+ ] : [],
472
+ ...development.length ? [
473
+ `npm install --save-dev ${development.join(' ')}`
474
+ ] : [],
475
+ ...describeScripts(selected, {
476
+ 'client:orval': `generate React Query hooks from ${openapiPath.trim()} in ${dataLayer}/orval`
477
+ }),
478
+ `Wrap your app in QueryProvider from ${dataLayer}/query-provider.tsx`,
479
+ ...generatedOpenapiPath ? [] : [
480
+ 'Add integration → OpenAPI generates the OpenAPI document the client is built from'
481
+ ]
482
+ ];
483
+ };
268
484
  const playwrightScripts = {
269
485
  'test:e2e': 'playwright test'
270
486
  };
@@ -685,6 +901,7 @@ const addVitest = async ()=>{
685
901
  })
686
902
  ];
687
903
  };
904
+ const withHandlersRest = ()=>ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers-rest');
688
905
  const integrations = [
689
906
  {
690
907
  name: 'Storybook (React + Vite)',
@@ -702,20 +919,30 @@ const integrations = [
702
919
  name: 'Playwright',
703
920
  run: addPlaywright
704
921
  },
922
+ {
923
+ name: 'OpenAPI',
924
+ run: addOpenapi,
925
+ available: ()=>withHandlersRest()
926
+ },
927
+ {
928
+ name: 'Orval (React Query client)',
929
+ run: addOrval,
930
+ available: ()=>withHandlersRest() && ConfigFile.Instance.data.useReact
931
+ },
705
932
  {
706
933
  name: 'Missing domain-first packages',
707
934
  run: missingDomainFirstPackages
708
935
  }
709
936
  ];
710
937
  const addIntegration = async ()=>{
711
- const index = await (0, prompts_namespaceObject.select)({
938
+ const integration = await (0, prompts_namespaceObject.select)({
712
939
  message: 'Integration:',
713
- choices: integrations.map((integration, value)=>({
714
- name: integration.name,
940
+ choices: integrations.filter(({ available })=>available?.() ?? true).map((value)=>({
941
+ name: value.name,
715
942
  value
716
943
  }))
717
944
  });
718
- const nextSteps = await integrations[index].run();
945
+ const nextSteps = await integration.run();
719
946
  if (await savePendingChanges()) {
720
947
  const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
721
948
  const commands = nextSteps.filter(isCommand);
@@ -2375,13 +2602,15 @@ export const wire${naming.ClassName}UseCase = wireClass(
2375
2602
  const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
2376
2603
  class NestedName {
2377
2604
  folders;
2605
+ folderName;
2378
2606
  fileName;
2379
2607
  ClassName;
2380
2608
  classNameSegments;
2381
2609
  constructor(rawSource){
2382
2610
  const segments = splitSegments(rawSource);
2383
2611
  this.folders = segments.slice(0, -1);
2384
- this.fileName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
2612
+ this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
2613
+ this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
2385
2614
  this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
2386
2615
  this.ClassName = this.classNameSegments.join('');
2387
2616
  }
@@ -2475,11 +2704,11 @@ const scaffoldReactWidget = async (presentationReactFolder)=>{
2475
2704
  ],
2476
2705
  message: 'Type: '
2477
2706
  });
2478
- const { folders, ClassName, fileName, classNameSegments } = new NestedName(widgetName);
2707
+ const { folders, folderName, ClassName, fileName, classNameSegments } = new NestedName(widgetName);
2479
2708
  const folder = presentationReactFolder.subitem([
2480
2709
  'widgets',
2481
2710
  ...folders,
2482
- fileName
2711
+ folderName
2483
2712
  ]);
2484
2713
  const storyTitle = [
2485
2714
  'Widgets',
package/dist/index.js CHANGED
@@ -228,6 +228,74 @@ const addPackageScripts = async (file, additions)=>{
228
228
  return selected;
229
229
  };
230
230
  const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
231
+ const openapiScriptPath = "scripts/generate-openapi.ts";
232
+ const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
233
+ const openapiScripts = {
234
+ openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
235
+ };
236
+ const splitPath = (value)=>value.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
237
+ const apiTitle = (packageName)=>{
238
+ const words = String(packageName ?? '').replace(/^@[^/]*\//, '').split(/[^a-zA-Z0-9]+/).filter((word)=>!!word).map((word)=>word[0].toUpperCase() + word.slice(1));
239
+ return [
240
+ ...words,
241
+ 'API'
242
+ ].join(' ');
243
+ };
244
+ const openapiGenerator = (rootFolder, title, routePrefix, outputPath)=>{
245
+ const restFolder = node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/rest');
246
+ const restImport = node_path.posix.relative(node_path.posix.dirname(openapiScriptPath), restFolder);
247
+ const apiRoutePrefix = [
248
+ '',
249
+ ...splitPath(routePrefix)
250
+ ].map((segment)=>`'${segment}'`).join(', ');
251
+ return `import { generateOpenAPI } from '@domain-first/handlers-rest';
252
+ import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}';
253
+
254
+ generateOpenAPI(restHandlers, {
255
+ document: { info: { title: '${title}', version: '1.0.0' } },
256
+ apiRoutePrefix: [${apiRoutePrefix}],
257
+ outputFile: { path: '${outputPath}' }
258
+ });
259
+ `;
260
+ };
261
+ const addOpenapi = async ()=>{
262
+ const { rootFolder } = ConfigFile.Instance.data;
263
+ const root = new ProjectRoot().path;
264
+ const manifestFile = new File(node_path.join(root, 'package.json'));
265
+ const manifest = JSON.parse(manifestFile.data);
266
+ const dependencies = {
267
+ ...manifest.dependencies,
268
+ ...manifest.devDependencies
269
+ };
270
+ const routePrefix = await input({
271
+ message: 'Route prefix the REST handlers are served under:',
272
+ default: '/api'
273
+ });
274
+ const outputPath = await input({
275
+ message: 'OpenAPI document path:',
276
+ default: defaultOpenapiPath(Boolean(dependencies.next)),
277
+ validate: (value)=>splitPath(value).length ? true : 'Path is required'
278
+ });
279
+ const selected = await addPackageScripts(manifestFile, openapiScripts);
280
+ const generatorFile = new File(node_path.join(root, openapiScriptPath));
281
+ const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'));
282
+ if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
283
+ const hasRestHandlers = new File(node_path.join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
284
+ return [
285
+ ...dependencies['@domain-first/handlers-rest'] ? [] : [
286
+ 'npm install @domain-first/handlers-rest'
287
+ ],
288
+ ...dependencies.tsx ? [] : [
289
+ 'npm install --save-dev tsx'
290
+ ],
291
+ ...describeScripts(selected, {
292
+ openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
293
+ }),
294
+ ...hasRestHandlers ? [] : [
295
+ `restHandlers appear in ${node_path.posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
296
+ ]
297
+ ];
298
+ };
231
299
  const addGitignoreEntry = (root, entry)=>{
232
300
  const gitignore = new File(node_path.join(root, '.gitignore'));
233
301
  const ignored = gitignore.exists ? gitignore.data : '';
@@ -235,6 +303,154 @@ const addGitignoreEntry = (root, entry)=>{
235
303
  const newline = ignored.includes('\r\n') ? '\r\n' : '\n';
236
304
  gitignore.update(`${ignored}${ignored && !ignored.endsWith('\n') ? newline : ''}${entry}${newline}`);
237
305
  };
306
+ const dataLayerFolder = (rootFolder)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/data-layer');
307
+ const orvalScripts = (rootFolder)=>({
308
+ 'client:orval': `orval --config ${JSON.stringify(`${dataLayerFolder(rootFolder)}/orval.config.ts`)}`
309
+ });
310
+ const orvalConfig = (rootFolder, openapiPath, withNext)=>{
311
+ const inputPath = node_path.posix.relative(dataLayerFolder(rootFolder), openapiPath);
312
+ const baseUrl = withNext ? `
313
+ baseUrl: {
314
+ runtime: 'process.env.NEXT_PUBLIC_API_BASE_URL ?? ""'
315
+ },` : '';
316
+ return `import { defineConfig } from 'orval';
317
+
318
+ export default defineConfig({
319
+ api: {
320
+ input: '${inputPath.startsWith('.') ? inputPath : `./${inputPath}`}',
321
+ output: {
322
+ mode: 'tags-split',
323
+ target: './orval',
324
+ schemas: './orval/model',
325
+ client: 'react-query',
326
+ httpClient: 'fetch',${baseUrl}
327
+ clean: true,
328
+ override: {
329
+ mutator: {
330
+ path: './api-client/mutator.ts',
331
+ name: 'customInstance'
332
+ },
333
+ fetch: {
334
+ includeHttpResponseReturnType: false
335
+ },
336
+ query: {
337
+ version: 5
338
+ }
339
+ }
340
+ }
341
+ }
342
+ });
343
+ `;
344
+ };
345
+ const orvalMutator = `/** Error of the generated hooks, with the parsed response body. */
346
+ export class ApiError<Body = unknown> extends Error {
347
+ constructor(
348
+ public readonly status: number,
349
+ public readonly body: Body
350
+ ) {
351
+ super(\`API error \${status}\`);
352
+ this.name = 'ApiError';
353
+ }
354
+ }
355
+
356
+ /** Error type of the generated hooks, typed per endpoint by Orval. */
357
+ export type ErrorType<Body> = ApiError<Body>;
358
+
359
+ /** Every generated request goes through here: add auth headers, token refresh, logging. */
360
+ export const customInstance = async <T>(
361
+ url: string,
362
+ init?: RequestInit
363
+ ): Promise<T> => {
364
+ const response = await fetch(url, init);
365
+ const text = await response.text();
366
+ const body = text ? JSON.parse(text) : undefined;
367
+
368
+ if (!response.ok) {
369
+ throw new ApiError(response.status, body);
370
+ }
371
+
372
+ return body as T;
373
+ };
374
+ `;
375
+ const queryProvider = `'use client';
376
+
377
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
378
+ import { type FC, type ReactNode, useState } from 'react';
379
+
380
+ export const QueryProvider: FC<{ children: ReactNode }> = ({ children }) => {
381
+ // One client per browser session; a module-level client would be shared between requests on the server
382
+ const [queryClient] = useState(() => new QueryClient());
383
+
384
+ return (
385
+ <QueryClientProvider client={queryClient}>
386
+ {children}
387
+ </QueryClientProvider>
388
+ );
389
+ };
390
+ `;
391
+ const openapiOutputPath = (root)=>{
392
+ const generator = new File(node_path.join(root, openapiScriptPath));
393
+ if (!generator.exists) return;
394
+ return generator.data.match(/outputFile:\s*{\s*path:\s*'([^']+)'/)?.[1];
395
+ };
396
+ const addOrval = async ()=>{
397
+ const { rootFolder } = ConfigFile.Instance.data;
398
+ const root = new ProjectRoot().path;
399
+ const manifestFile = new File(node_path.join(root, 'package.json'));
400
+ const manifest = JSON.parse(manifestFile.data);
401
+ const dependencies = {
402
+ ...manifest.dependencies,
403
+ ...manifest.devDependencies
404
+ };
405
+ const withNext = Boolean(dependencies.next);
406
+ const generatedOpenapiPath = openapiOutputPath(root);
407
+ const openapiPath = await input({
408
+ message: 'OpenAPI document path:',
409
+ default: generatedOpenapiPath ?? defaultOpenapiPath(withNext),
410
+ validate: (value)=>value.trim() ? true : 'Path is required'
411
+ });
412
+ const selected = await addPackageScripts(manifestFile, orvalScripts(rootFolder));
413
+ const dataLayer = dataLayerFolder(rootFolder);
414
+ const configFile = new File(node_path.join(root, dataLayer, 'orval.config.ts'));
415
+ const content = orvalConfig(rootFolder, node_path.posix.normalize(openapiPath.trim().replaceAll('\\', '/')), withNext);
416
+ if (!configFile.exists || configFile.data !== content) configFile.data = content;
417
+ for (const [name, fileContent] of [
418
+ [
419
+ 'api-client/mutator.ts',
420
+ orvalMutator
421
+ ],
422
+ [
423
+ 'query-provider.tsx',
424
+ queryProvider
425
+ ]
426
+ ]){
427
+ const file = new File(node_path.join(root, dataLayer, name));
428
+ if (!file.exists) file.data = fileContent;
429
+ }
430
+ addGitignoreEntry(root, `/${dataLayer}/orval/`);
431
+ const missing = (names)=>names.filter((name)=>!dependencies[name]);
432
+ const runtime = missing([
433
+ '@tanstack/react-query'
434
+ ]);
435
+ const development = missing([
436
+ 'orval'
437
+ ]);
438
+ return [
439
+ ...runtime.length ? [
440
+ `npm install ${runtime.join(' ')}`
441
+ ] : [],
442
+ ...development.length ? [
443
+ `npm install --save-dev ${development.join(' ')}`
444
+ ] : [],
445
+ ...describeScripts(selected, {
446
+ 'client:orval': `generate React Query hooks from ${openapiPath.trim()} in ${dataLayer}/orval`
447
+ }),
448
+ `Wrap your app in QueryProvider from ${dataLayer}/query-provider.tsx`,
449
+ ...generatedOpenapiPath ? [] : [
450
+ 'Add integration → OpenAPI generates the OpenAPI document the client is built from'
451
+ ]
452
+ ];
453
+ };
238
454
  const playwrightScripts = {
239
455
  'test:e2e': 'playwright test'
240
456
  };
@@ -655,6 +871,7 @@ const addVitest = async ()=>{
655
871
  })
656
872
  ];
657
873
  };
874
+ const withHandlersRest = ()=>ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers-rest');
658
875
  const integrations = [
659
876
  {
660
877
  name: 'Storybook (React + Vite)',
@@ -672,20 +889,30 @@ const integrations = [
672
889
  name: 'Playwright',
673
890
  run: addPlaywright
674
891
  },
892
+ {
893
+ name: 'OpenAPI',
894
+ run: addOpenapi,
895
+ available: ()=>withHandlersRest()
896
+ },
897
+ {
898
+ name: 'Orval (React Query client)',
899
+ run: addOrval,
900
+ available: ()=>withHandlersRest() && ConfigFile.Instance.data.useReact
901
+ },
675
902
  {
676
903
  name: 'Missing domain-first packages',
677
904
  run: missingDomainFirstPackages
678
905
  }
679
906
  ];
680
907
  const addIntegration = async ()=>{
681
- const index = await prompts_select({
908
+ const integration = await prompts_select({
682
909
  message: 'Integration:',
683
- choices: integrations.map((integration, value)=>({
684
- name: integration.name,
910
+ choices: integrations.filter(({ available })=>available?.() ?? true).map((value)=>({
911
+ name: value.name,
685
912
  value
686
913
  }))
687
914
  });
688
- const nextSteps = await integrations[index].run();
915
+ const nextSteps = await integration.run();
689
916
  if (await savePendingChanges()) {
690
917
  const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
691
918
  const commands = nextSteps.filter(isCommand);
@@ -2345,13 +2572,15 @@ export const wire${naming.ClassName}UseCase = wireClass(
2345
2572
  const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
2346
2573
  class NestedName {
2347
2574
  folders;
2575
+ folderName;
2348
2576
  fileName;
2349
2577
  ClassName;
2350
2578
  classNameSegments;
2351
2579
  constructor(rawSource){
2352
2580
  const segments = splitSegments(rawSource);
2353
2581
  this.folders = segments.slice(0, -1);
2354
- this.fileName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
2582
+ this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
2583
+ this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
2355
2584
  this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
2356
2585
  this.ClassName = this.classNameSegments.join('');
2357
2586
  }
@@ -2445,11 +2674,11 @@ const scaffoldReactWidget = async (presentationReactFolder)=>{
2445
2674
  ],
2446
2675
  message: 'Type: '
2447
2676
  });
2448
- const { folders, ClassName, fileName, classNameSegments } = new NestedName(widgetName);
2677
+ const { folders, folderName, ClassName, fileName, classNameSegments } = new NestedName(widgetName);
2449
2678
  const folder = presentationReactFolder.subitem([
2450
2679
  'widgets',
2451
2680
  ...folders,
2452
- fileName
2681
+ folderName
2453
2682
  ]);
2454
2683
  const storyTitle = [
2455
2684
  'Widgets',
@@ -1,4 +1,6 @@
1
1
  export * from './missing-domain-first-packages';
2
+ export * from './openapi';
3
+ export * from './orval';
2
4
  export * from './package-scripts';
3
5
  export * from './playwright';
4
6
  export * from './prisma';
@@ -0,0 +1,8 @@
1
+ export declare const openapiScriptPath = "scripts/generate-openapi.ts";
2
+ export declare const defaultOpenapiPath: (withNext: boolean) => "public/openapi.json" | "openapi.json";
3
+ export declare const openapiScripts: {
4
+ openapi: string;
5
+ };
6
+ export declare const apiTitle: (packageName: unknown) => string;
7
+ export declare const openapiGenerator: (rootFolder: string, title: string, routePrefix: string, outputPath: string) => string;
8
+ export declare const addOpenapi: () => Promise<string[]>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ export declare const orvalScripts: (rootFolder: string) => {
2
+ 'client:orval': string;
3
+ };
4
+ /**
5
+ * Orval resolves paths relative to the config, which lives in the data layer
6
+ * folder next to the generated client.
7
+ */
8
+ export declare const orvalConfig: (rootFolder: string, openapiPath: string, withNext: boolean) => string;
9
+ export declare const orvalMutator = "/** Error of the generated hooks, with the parsed response body. */\nexport class ApiError<Body = unknown> extends Error {\n constructor(\n public readonly status: number,\n public readonly body: Body\n ) {\n super(`API error ${status}`);\n this.name = 'ApiError';\n }\n}\n\n/** Error type of the generated hooks, typed per endpoint by Orval. */\nexport type ErrorType<Body> = ApiError<Body>;\n\n/** Every generated request goes through here: add auth headers, token refresh, logging. */\nexport const customInstance = async <T>(\n url: string,\n init?: RequestInit\n): Promise<T> => {\n const response = await fetch(url, init);\n const text = await response.text();\n const body = text ? JSON.parse(text) : undefined;\n\n if (!response.ok) {\n throw new ApiError(response.status, body);\n }\n\n return body as T;\n};\n";
10
+ export declare const queryProvider = "'use client';\n\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query';\nimport { type FC, type ReactNode, useState } from 'react';\n\nexport const QueryProvider: FC<{ children: ReactNode }> = ({ children }) => {\n // One client per browser session; a module-level client would be shared between requests on the server\n const [queryClient] = useState(() => new QueryClient());\n\n return (\n <QueryClientProvider client={queryClient}>\n {children}\n </QueryClientProvider>\n );\n};\n";
11
+ export declare const addOrval: () => Promise<string[]>;
@@ -0,0 +1 @@
1
+ export {};
@@ -1,10 +1,12 @@
1
1
  /**
2
2
  * A name with optional folders before it, e.g. `admin/panel/users`.
3
- * The last segment names the files; the whole path names the code
4
- * (`AdminPanelUsers`), so equal names in different folders don't clash.
3
+ * The last segment names the folder; the whole path names the files
4
+ * (`admin-panel-users`) and the code (`AdminPanelUsers`), so equal names
5
+ * in different folders don't clash.
5
6
  */
6
7
  export declare class NestedName {
7
8
  readonly folders: string[];
9
+ readonly folderName: string;
8
10
  readonly fileName: string;
9
11
  readonly ClassName: string;
10
12
  /**
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": "2.14.1",
4
+ "version": "2.15.0",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",