nestjs-docfy 0.4.0 → 0.6.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 (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +177 -84
  3. package/dist/apply-docfy-metadata.d.ts +37 -0
  4. package/dist/apply-docfy-metadata.js +55 -0
  5. package/dist/apply-docfy-metadata.js.map +1 -0
  6. package/dist/cli/build-openapi-patch.d.ts +16 -12
  7. package/dist/cli/build-openapi-patch.js +98 -15
  8. package/dist/cli/build-openapi-patch.js.map +1 -1
  9. package/dist/cli/check.js.map +1 -1
  10. package/dist/cli/coverage.js +1 -3
  11. package/dist/cli/coverage.js.map +1 -1
  12. package/dist/cli/detect-project.d.ts +8 -0
  13. package/dist/cli/detect-project.js +28 -5
  14. package/dist/cli/detect-project.js.map +1 -1
  15. package/dist/cli/errors.js.map +1 -1
  16. package/dist/cli/eval-decorator-args.d.ts +5 -3
  17. package/dist/cli/eval-decorator-args.js +64 -11
  18. package/dist/cli/eval-decorator-args.js.map +1 -1
  19. package/dist/cli/extract-docs-config.d.ts +21 -1
  20. package/dist/cli/extract-docs-config.js +18 -6
  21. package/dist/cli/extract-docs-config.js.map +1 -1
  22. package/dist/cli/extract-methods.d.ts +11 -0
  23. package/dist/cli/extract-methods.js +113 -29
  24. package/dist/cli/extract-methods.js.map +1 -1
  25. package/dist/cli/generate-client.d.ts +15 -0
  26. package/dist/cli/generate-client.js +62 -0
  27. package/dist/cli/generate-client.js.map +1 -0
  28. package/dist/cli/generate-file.js +24 -24
  29. package/dist/cli/generate-file.js.map +1 -1
  30. package/dist/cli/index.js +140 -53
  31. package/dist/cli/index.js.map +1 -1
  32. package/dist/cli/lint.js +1 -3
  33. package/dist/cli/lint.js.map +1 -1
  34. package/dist/cli/logger.js +12 -6
  35. package/dist/cli/logger.js.map +1 -1
  36. package/dist/cli/merge-docs.js.map +1 -1
  37. package/dist/cli/merge-spec-patch.d.ts +15 -8
  38. package/dist/cli/merge-spec-patch.js +20 -4
  39. package/dist/cli/merge-spec-patch.js.map +1 -1
  40. package/dist/cli/parse-args.d.ts +2 -0
  41. package/dist/cli/parse-args.js +3 -6
  42. package/dist/cli/parse-args.js.map +1 -1
  43. package/dist/cli/patch-spec.d.ts +32 -8
  44. package/dist/cli/patch-spec.js +37 -15
  45. package/dist/cli/patch-spec.js.map +1 -1
  46. package/dist/cli/read-spec-source.d.ts +7 -0
  47. package/dist/cli/read-spec-source.js +74 -0
  48. package/dist/cli/read-spec-source.js.map +1 -0
  49. package/dist/cli/register-webpack-plugin.d.ts +16 -0
  50. package/dist/cli/register-webpack-plugin.js +46 -0
  51. package/dist/cli/register-webpack-plugin.js.map +1 -0
  52. package/dist/cli/resolve-tsconfig.js +1 -5
  53. package/dist/cli/resolve-tsconfig.js.map +1 -1
  54. package/dist/cli/scan-controllers.d.ts +11 -0
  55. package/dist/cli/scan-controllers.js +10 -3
  56. package/dist/cli/scan-controllers.js.map +1 -1
  57. package/dist/cli/watch.js +3 -1
  58. package/dist/cli/watch.js.map +1 -1
  59. package/dist/cli/writer.js.map +1 -1
  60. package/dist/docfy-ui.module.d.ts +13 -0
  61. package/dist/docfy-ui.module.js +6 -3
  62. package/dist/docfy-ui.module.js.map +1 -1
  63. package/dist/docfy.module.js +1 -1
  64. package/dist/docfy.module.js.map +1 -1
  65. package/dist/docs.js.map +1 -1
  66. package/dist/index.d.ts +2 -1
  67. package/dist/index.js +3 -1
  68. package/dist/index.js.map +1 -1
  69. package/dist/plugin/generate-metadata.d.ts +35 -0
  70. package/dist/plugin/generate-metadata.js +46 -0
  71. package/dist/plugin/generate-metadata.js.map +1 -0
  72. package/dist/plugin/index.d.ts +30 -0
  73. package/dist/plugin/index.js +62 -0
  74. package/dist/plugin/index.js.map +1 -0
  75. package/dist/registry.d.ts +3 -3
  76. package/dist/registry.js.map +1 -1
  77. package/dist/resolve-docs-path.d.ts +1 -1
  78. package/dist/resolve-docs-path.js.map +1 -1
  79. package/dist/resolve-source-from-stack.js.map +1 -1
  80. package/dist/with-docs.decorator.js.map +1 -1
  81. package/package.json +25 -4
  82. package/dist/require-ts.d.ts +0 -32
  83. package/dist/require-ts.js +0 -122
  84. package/dist/require-ts.js.map +0 -1
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Marvin Rocha
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,11 +1,8 @@
1
1
  <p align="center">
2
- <a href="http://nestjs.com"><img alt="Nest Logo" src="https://nestjs.com/img/logo-small.svg" width="120"></a>
2
+ <img alt="nestjs-docfy banner" src="./assets/banner.png" width="100%">
3
3
  </p>
4
4
 
5
- <h1 align="center">
6
- nestjs-docfy
7
- </h1>
8
-
5
+ [![CI](https://github.com/MarvinRF/nest-docfy/actions/workflows/ci.yml/badge.svg)](https://github.com/MarvinRF/nest-docfy/actions/workflows/ci.yml)
9
6
  [![NPM version](https://img.shields.io/npm/v/nestjs-docfy.svg)](https://www.npmjs.com/package/nestjs-docfy)
10
7
  [![NPM downloads](https://img.shields.io/npm/dw/nestjs-docfy.svg)](https://www.npmjs.com/package/nestjs-docfy)
11
8
  [![GitHub last commit](https://img.shields.io/github/last-commit/MarvinRF/nest-docfy)](https://github.com/MarvinRF/nest-docfy/commits/main)
@@ -14,6 +11,8 @@
14
11
 
15
12
  Keep your NestJS controllers clean. Swagger documentation lives in a dedicated companion file — by naming convention, zero boilerplate.
16
13
 
14
+ 📖 **[Full documentation](https://www.nestdocfy.com/)**
15
+
17
16
  ## Table of contents
18
17
 
19
18
  - [Motivation](#motivation)
@@ -31,17 +30,20 @@ Keep your NestJS controllers clean. Swagger documentation lives in a dedicated c
31
30
  - [CLI — coverage](#cli--coverage)
32
31
  - [CLI — lint](#cli--lint)
33
32
  - [CLI — patch-spec](#cli--patch-spec)
33
+ - [CLI — generate-client](#cli--generate-client)
34
34
  - [API reference](#api-reference)
35
35
  - [DocfyModule.forRoot()](#docfymoduleforrootoptions)
36
36
  - [@WithDocs()](#withdocs)
37
37
  - [docs()](#docscontrollerclass-config)
38
38
  - [attachTagGroups()](#attachtaggroupsdocument)
39
+ - [applyDocfyMetadata()](#applydocfymetadatadocument-options)
39
40
  - [DocfyUiModule.setup()](#docfyuimodulesetupmountpath-app-options)
40
41
  - [Interface-typed DTOs](#interface-typed-dtos)
41
42
  - [class-validator inference](#class-validator-inference)
42
43
  - [@HttpCode() support](#httpcode-support)
43
44
  - [Tag groups (x-tagGroups)](#tag-groups-x-taggroups)
44
45
  - [File naming convention](#file-naming-convention)
46
+ - [webpack: true build mode](#webpack-true-build-mode)
45
47
  - [Testing](#testing)
46
48
  - [How it works](#how-it-works)
47
49
  - [License](#license)
@@ -54,21 +56,21 @@ Swagger decorators are documentation. They have nothing to do with routing logic
54
56
 
55
57
  ```ts
56
58
  // users.controller.ts
57
- @ApiTags("users")
58
- @Controller("users")
59
+ @ApiTags('users')
60
+ @Controller('users')
59
61
  export class UsersController {
60
62
  @Get()
61
- @ApiOperation({ summary: "List all users" })
62
- @ApiResponse({ status: 200, description: "OK", type: [UserEntity] })
63
+ @ApiOperation({ summary: 'List all users' })
64
+ @ApiResponse({ status: 200, description: 'OK', type: [UserEntity] })
63
65
  findAll(): Promise<UserEntity[]> {
64
66
  return this.usersService.findAll();
65
67
  }
66
68
 
67
69
  @Post()
68
- @ApiOperation({ summary: "Create a user" })
70
+ @ApiOperation({ summary: 'Create a user' })
69
71
  @ApiBody({ type: CreateUserDto })
70
- @ApiResponse({ status: 201, description: "Created", type: UserEntity })
71
- @ApiResponse({ status: 400, description: "Bad Request" })
72
+ @ApiResponse({ status: 201, description: 'Created', type: UserEntity })
73
+ @ApiResponse({ status: 400, description: 'Bad Request' })
72
74
  create(@Body() dto: CreateUserDto): Promise<UserEntity> {
73
75
  return this.usersService.create(dto);
74
76
  }
@@ -80,7 +82,7 @@ export class UsersController {
80
82
  ```ts
81
83
  // users.controller.ts
82
84
  @WithDocs()
83
- @Controller("users")
85
+ @Controller('users')
84
86
  export class UsersController {
85
87
  findAll(): Promise<UserEntity[]> {
86
88
  return this.usersService.findAll();
@@ -95,17 +97,17 @@ export class UsersController {
95
97
  ```ts
96
98
  // users.controller.docs.ts — all documentation in one place
97
99
  docs(UsersController, {
98
- classDecorators: [ApiTags("users")],
100
+ classDecorators: [ApiTags('users')],
99
101
  methods: {
100
102
  findAll: [
101
- ApiOperation({ summary: "List all users" }),
102
- ApiResponse({ status: 200, description: "OK", type: [UserEntity] }),
103
+ ApiOperation({ summary: 'List all users' }),
104
+ ApiResponse({ status: 200, description: 'OK', type: [UserEntity] }),
103
105
  ],
104
106
  create: [
105
- ApiOperation({ summary: "Create a user" }),
107
+ ApiOperation({ summary: 'Create a user' }),
106
108
  ApiBody({ type: CreateUserDto }),
107
- ApiResponse({ status: 201, description: "Created", type: UserEntity }),
108
- ApiResponse({ status: 400, description: "Bad Request" }),
109
+ ApiResponse({ status: 201, description: 'Created', type: UserEntity }),
110
+ ApiResponse({ status: 400, description: 'Bad Request' }),
109
111
  ],
110
112
  },
111
113
  });
@@ -131,8 +133,8 @@ npm install @nestjs/common @nestjs/swagger reflect-metadata
131
133
 
132
134
  ```ts
133
135
  // app.module.ts
134
- import { Module } from "@nestjs/common";
135
- import { DocfyModule } from "nestjs-docfy";
136
+ import { Module } from '@nestjs/common';
137
+ import { DocfyModule } from 'nestjs-docfy';
136
138
 
137
139
  @Module({
138
140
  imports: [DocfyModule.forRoot()],
@@ -150,11 +152,11 @@ DocfyModule.forRoot({ strict: true });
150
152
 
151
153
  ```ts
152
154
  // users.controller.ts
153
- import { Controller, Get, Post, Body } from "@nestjs/common";
154
- import { WithDocs } from "nestjs-docfy";
155
+ import { Controller, Get, Post, Body } from '@nestjs/common';
156
+ import { WithDocs } from 'nestjs-docfy';
155
157
 
156
158
  @WithDocs()
157
- @Controller("users")
159
+ @Controller('users')
158
160
  export class UsersController {
159
161
  // route handlers only — no Swagger decorators here
160
162
  }
@@ -182,27 +184,27 @@ The generated file comes pre-populated with inferred summaries, response types,
182
184
 
183
185
  ```ts
184
186
  // Generated by nestjs-docfy — edit freely, use --force to merge new methods
185
- import { docs } from "nestjs-docfy";
186
- import { ApiTags, ApiOperation, ApiResponse, ApiBody } from "@nestjs/swagger";
187
- import { UsersController } from "./users.controller";
188
- import { CreateUserDto } from "./dto/create-user.dto";
189
- import { UserEntity } from "./entities/user.entity";
187
+ import { docs } from 'nestjs-docfy';
188
+ import { ApiTags, ApiOperation, ApiResponse, ApiBody } from '@nestjs/swagger';
189
+ import { UsersController } from './users.controller';
190
+ import { CreateUserDto } from './dto/create-user.dto';
191
+ import { UserEntity } from './entities/user.entity';
190
192
 
191
193
  docs(UsersController, {
192
- classDecorators: [ApiTags("users")],
194
+ classDecorators: [ApiTags('users')],
193
195
  methods: {
194
196
  // GET / → async findAll(): Promise<UserEntity[]>
195
197
  findAll: [
196
- ApiOperation({ summary: "Find all" }),
197
- ApiResponse({ status: 200, description: "OK", type: [UserEntity] }),
198
+ ApiOperation({ summary: 'Find all' }),
199
+ ApiResponse({ status: 200, description: 'OK', type: [UserEntity] }),
198
200
  ],
199
201
 
200
202
  // POST / → async create(dto: CreateUserDto): Promise<UserEntity>
201
203
  create: [
202
- ApiOperation({ summary: "Create" }),
204
+ ApiOperation({ summary: 'Create' }),
203
205
  ApiBody({ type: CreateUserDto }),
204
- ApiResponse({ status: 201, description: "Created", type: UserEntity }),
205
- ApiResponse({ status: 400, description: "Bad Request" }),
206
+ ApiResponse({ status: 201, description: 'Created', type: UserEntity }),
207
+ ApiResponse({ status: 400, description: 'Bad Request' }),
206
208
  ],
207
209
  },
208
210
  });
@@ -220,16 +222,18 @@ npx nestjs-docfy generate [options]
220
222
 
221
223
  ### Options
222
224
 
223
- | Option | Default | Description |
224
- | ------------------- | ------------------------- | ----------------------------------------------------------------- |
225
- | `--root <path>` | `.` | Project root directory |
226
- | `--tsconfig <path>` | auto-detected | Path to `tsconfig.json` |
227
- | `--pattern <glob>` | `**/*.controller.ts` | Glob pattern to find controllers |
228
- | `--out <path>` | alongside each controller | Output directory for generated files |
229
- | `--force` | `false` | Merge new methods into existing docs files (preserves user edits) |
230
- | `--dry-run` | `false` | Print what would be generated without writing files |
231
- | `--quiet` | `false` | Suppress all output except errors (CI-friendly) |
232
- | `--format` | `ts` | Output format: `ts` or `js` |
225
+ | Option | Default | Description |
226
+ | ------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------- |
227
+ | `--root <path>` | `.` | Project root directory |
228
+ | `--tsconfig <path>` | auto-detected | Path to `tsconfig.json` |
229
+ | `--pattern <glob>` | `**/*.controller.ts` | Glob pattern to find controllers |
230
+ | `--out <path>` | alongside each controller | Output directory for generated files |
231
+ | `--force` | `false` | Merge new methods into existing docs files (preserves user edits) |
232
+ | `--dry-run` | `false` | Print what would be generated without writing files |
233
+ | `--quiet` | `false` | Suppress all output except errors (CI-friendly) |
234
+ | `--format` | `ts` | Output format: `ts` or `js` |
235
+ | `--watch` | `false` | Re-generate on controller file changes |
236
+ | `--register-plugin` | `false` | If `webpack: true` is set without the CLI plugin, add `nestjs-docfy` to `nest-cli.json`'s `compilerOptions.plugins` |
233
237
 
234
238
  ### Project types
235
239
 
@@ -270,13 +274,14 @@ Verify that every controller is fully documented before merging. Exits with code
270
274
  npx nestjs-docfy check [options]
271
275
  ```
272
276
 
273
- | Option | Default | Description |
274
- | ------------------- | ------------------------- | ------------------------------------------- |
275
- | `--root <path>` | `.` | Project root directory |
276
- | `--tsconfig <path>` | auto-detected | Path to `tsconfig.json` |
277
- | `--pattern <glob>` | `**/*.controller.ts` | Glob pattern to find controllers |
278
- | `--format <format>` | `ts` | Docs file format to look for: `ts` or `js` |
279
- | `--quiet` | `false` | Suppress all output except errors |
277
+ | Option | Default | Description |
278
+ | ------------------- | -------------------- | ----------------------------------------------------------------------------------------------------------------- |
279
+ | `--root <path>` | `.` | Project root directory |
280
+ | `--tsconfig <path>` | auto-detected | Path to `tsconfig.json` |
281
+ | `--pattern <glob>` | `**/*.controller.ts` | Glob pattern to find controllers |
282
+ | `--format <format>` | `ts` | Docs file format to look for: `ts` or `js` |
283
+ | `--json` | `false` | Output a single machine-readable JSON object instead of formatted text — `{ controllersChecked, issues, passed }` |
284
+ | `--quiet` | `false` | Suppress all output except errors |
280
285
 
281
286
  **What it checks:**
282
287
 
@@ -318,14 +323,15 @@ Measure what percentage of your endpoints are documented. Useful as an objective
318
323
  npx nestjs-docfy coverage [options]
319
324
  ```
320
325
 
321
- | Option | Default | Description |
322
- | ------------------- | -------------------- | ------------------------------------------------------ |
323
- | `--root <path>` | `.` | Project root directory |
324
- | `--tsconfig <path>` | auto-detected | Path to `tsconfig.json` |
325
- | `--pattern <glob>` | `**/*.controller.ts` | Glob pattern to find controllers |
326
- | `--format <format>` | `ts` | Docs file format to look for: `ts` or `js` |
327
- | `--min <percent>` | none | Minimum coverage required (0-100) — exits `1` if below |
328
- | `--quiet` | `false` | Suppress all output except errors |
326
+ | Option | Default | Description |
327
+ | ------------------- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
328
+ | `--root <path>` | `.` | Project root directory |
329
+ | `--tsconfig <path>` | auto-detected | Path to `tsconfig.json` |
330
+ | `--pattern <glob>` | `**/*.controller.ts` | Glob pattern to find controllers |
331
+ | `--format <format>` | `ts` | Docs file format to look for: `ts` or `js` |
332
+ | `--min <percent>` | none | Minimum coverage required (0-100) — exits `1` if below |
333
+ | `--json` | `false` | Output a single machine-readable JSON object instead of formatted text — the `CoverageReport` fields plus `min` and `passed` |
334
+ | `--quiet` | `false` | Suppress all output except errors |
329
335
 
330
336
  **Example output:**
331
337
 
@@ -363,6 +369,8 @@ Or as an npm script:
363
369
  }
364
370
  ```
365
371
 
372
+ **PR bot**: this repo's own [`.github/workflows/pr-check.yml`](.github/workflows/pr-check.yml) is a real example of a GitHub Actions job that runs `check --json` and `coverage --json --min` against a project and posts (and updates, never spams) a single PR comment summarizing the result — see [`.github/scripts/pr-comment.mjs`](.github/scripts/pr-comment.mjs) for the comment logic, built entirely on `--json` output and native `fetch`, no extra dependencies.
373
+
366
374
  ## CLI — lint
367
375
 
368
376
  Checks documentation **quality**, not just presence — catches incomplete `ApiOperation`, `ApiResponse`, and `ApiBody` decorators that `check` and `coverage` wouldn't flag (the method is documented, just incompletely).
@@ -424,21 +432,21 @@ Or as an npm script:
424
432
 
425
433
  Patches an **already-built** OpenAPI document with every controller's companion docs file, entirely via static analysis (`ts-morph`) — no `require()` of any docs file, no decorators applied to any class, no dependency on a live class reference matching the one the running app actually uses.
426
434
 
427
- This is the workaround for the one thing `DocfyModule`'s runtime pipeline structurally cannot do: work under NestJS CLI's `webpack: true` build mode (see "Not supported" under [File naming convention](#file-naming-convention) for why). `patch-spec` sidesteps that entirely by matching on **path + HTTP method**, computed the same way `check`/`coverage`/`lint` already do, instead of needing the live controller class.
435
+ This is a manual, CI-driven way to work around the one thing `DocfyModule`'s runtime pipeline structurally cannot do: work under NestJS CLI's `webpack: true` build mode (see [`webpack: true` build mode](#webpack-true-build-mode) for why, and for the **CLI plugin**, which does the same analysis automatically on every build instead of a separate step). `patch-spec` sidesteps the webpack wall by matching on **path + HTTP method**, computed the same way `check`/`coverage`/`lint` already do, instead of needing the live controller class.
428
436
 
429
437
  ```bash
430
438
  npx nestjs-docfy patch-spec --spec <path-or-url> [options]
431
439
  ```
432
440
 
433
- | Option | Default | Description |
434
- | --- | --- | --- |
435
- | `--spec <path\|url>` | *(required)* | A local `openapi.json`, or a URL (e.g. a running app's `/api-json`) |
436
- | `--out <path>` | stdout | Where to write the patched document |
437
- | `--root <path>` | `.` | Project root directory |
438
- | `--tsconfig <path>` | auto-detected | Path to `tsconfig.json` |
439
- | `--pattern <glob>` | `**/*.controller.ts` | Glob pattern to find controllers |
440
- | `--format <format>` | `ts` | Docs file format to look for: `ts` or `js` |
441
- | `--quiet` | `false` | Suppress all output except errors |
441
+ | Option | Default | Description |
442
+ | -------------------- | -------------------- | ------------------------------------------------------------------- |
443
+ | `--spec <path\|url>` | _(required)_ | A local `openapi.json`, or a URL (e.g. a running app's `/api-json`) |
444
+ | `--out <path>` | stdout | Where to write the patched document |
445
+ | `--root <path>` | `.` | Project root directory |
446
+ | `--tsconfig <path>` | auto-detected | Path to `tsconfig.json` |
447
+ | `--pattern <glob>` | `**/*.controller.ts` | Glob pattern to find controllers |
448
+ | `--format <format>` | `ts` | Docs file format to look for: `ts` or `js` |
449
+ | `--quiet` | `false` | Suppress all output except errors |
442
450
 
443
451
  ```bash
444
452
  # Patch a running app's served document
@@ -452,12 +460,47 @@ npx nestjs-docfy patch-spec --spec dist/openapi.json --out dist/openapi.json
452
460
 
453
461
  - `ApiTags` → unioned into `tags` (never drops tags the base document already had)
454
462
  - `ApiOperation({ summary, description, deprecated })` → overwrites those fields
455
- - `ApiResponse({ status, description, schema })` → merged per status code (other status codes untouched); when no `schema`/`type` is given, falls back to the method's own resolved return type — same DTO/class-validator/interface inference `generate` already does
456
- - `ApiBody({ schema })` → sets `requestBody`, with the same return-type-style fallback to the `@Body()` parameter's resolved type
463
+ - `ApiResponse({ status, description, schema, example, examples })` → merged per status code (other status codes untouched); when no `schema`/`type` is given, falls back to the method's own resolved return type — same DTO/class-validator/interface inference `generate` already does, including a `oneOf` of `$ref`s when the return type is a union of ≥2 named DTOs/entities (e.g. `Promise<UserDto | AdminDto>`)
464
+ - `ApiBody({ schema, examples })` → sets `requestBody`, with the same return-type-style fallback to the `@Body()` parameter's resolved type, including the same union → `oneOf` handling (`example` is intentionally not read here — `@nestjs/swagger`'s real `ApiBodyOptions` type only has `examples`, unlike `ApiResponse`, which supports both)
457
465
  - `ApiBearerAuth()` → appended to `security`
458
- - `ApiParam` / `ApiQuery` / `ApiHeader` → appended to `parameters`, deduplicated by name + location
466
+ - `ApiParam` / `ApiQuery` / `ApiHeader` → merged into `parameters` by name + location: a genuinely new parameter is appended, but one that already exists (e.g. `@nestjs/swagger` auto-generates a bare `required: true` entry from reflection alone for any `@Query()`/`@Param()`-decorated argument, with zero `@Api*` decorators needed) gets its fields overlaid, not discarded — an `ApiQuery({ enum, required: false })` in a docs file for a parameter Nest already knew about actually takes effect. `enum` is read from an array literal (`enum: ['a', 'b']`) or a reference to a TS `enum`, including one imported from another file (`enum: Role`) — the schema's `type` is inferred as `number` when every resolved value is numeric, `string` otherwise
467
+
468
+ `example`/`examples` (and `schema`) are only applied when every value inside them is a literal — if even one nested value is a variable, function call, or other non-literal expression, the whole field is left out rather than risk leaking an internal "unresolved" marker into the document as if it were real data.
469
+
470
+ **What this does _not_ do** (yet — this command is intentionally scoped, not a full reimplementation of `@nestjs/swagger`'s decorator semantics): `anyOf` (no TS construct maps onto "any of" the way a union type naturally maps onto `oneOf`), `links`/`callbacks` (`@nestjs/swagger` itself has no decorator option for either, so there's nothing in a `.docs.ts` file to read), and any decorator argument that isn't a literal (a variable, a function call, a spread) are left alone rather than guessed at — better to leave a field as the base document already had it than patch in something wrong. A union return type or `@Body()` payload only becomes a `oneOf` when _every_ branch resolves to a named DTO/entity — a partial guess is avoided by leaving the field alone entirely (falling back to no schema, same as an unresolvable type) if even one branch doesn't resolve. Routes a docs file documents that don't exist in `--spec` are reported as warnings, not silently dropped or errored on.
459
471
 
460
- **What this does *not* do** (yet — this command is intentionally scoped, not a full reimplementation of `@nestjs/swagger`'s decorator semantics): enums, `oneOf`/`anyOf`, examples, links, callbacks, and any decorator argument that isn't a literal (a variable, a function call, a spread) are left alone rather than guessed at — better to leave a field as the base document already had it than patch in something wrong. Routes a docs file documents that don't exist in `--spec` are reported as warnings, not silently dropped or errored on.
472
+ ## CLI — generate-client
473
+
474
+ Generates a typed TypeScript client from an OpenAPI document — a thin wrapper over [`openapi-typescript`](https://openapi-ts.dev) (types) and [`openapi-fetch`](https://openapi-ts.dev/openapi-fetch) (the runtime client), not a from-scratch code generator.
475
+
476
+ ```bash
477
+ npx nestjs-docfy generate-client --spec <path-or-url> [options]
478
+ ```
479
+
480
+ | Option | Default | Description |
481
+ | -------------------- | -------------------- | ------------------------------------------------------------------- |
482
+ | `--spec <path\|url>` | _(required)_ | A local `openapi.json`, or a URL (e.g. a running app's `/api-json`) |
483
+ | `--out <path>` | `./generated-client` | Output directory for `schema.d.ts` and `client.ts` |
484
+ | `--root <path>` | `.` | Project root directory |
485
+ | `--quiet` | `false` | Suppress all output except errors |
486
+
487
+ ```bash
488
+ npx nestjs-docfy generate-client --spec http://localhost:3000/api-json --out src/api-client
489
+ ```
490
+
491
+ Writes two files:
492
+
493
+ - **`schema.d.ts`** — the generated types (`paths`, `components`, `operations`), via `openapi-typescript`.
494
+ - **`client.ts`** — a small wrapper exporting `createApiClient(baseUrl)`, typed against `schema.d.ts`.
495
+
496
+ ```ts
497
+ import { createApiClient } from './api-client/client';
498
+
499
+ const api = createApiClient('https://api.example.com');
500
+ const { data, error } = await api.GET('/users/{id}', { params: { path: { id: '123' } } });
501
+ ```
502
+
503
+ `openapi-fetch` is **not** a dependency of `nestjs-docfy` itself — only the generated `client.ts` imports it, so install it in your own project: `npm install openapi-fetch`.
461
504
 
462
505
  ## API reference
463
506
 
@@ -482,7 +525,7 @@ export class ProductsController { ... }
482
525
  Also sets `DOCFY_MARKER` metadata on the class, available for external introspection:
483
526
 
484
527
  ```ts
485
- import { DOCFY_MARKER } from "nestjs-docfy";
528
+ import { DOCFY_MARKER } from 'nestjs-docfy';
486
529
 
487
530
  Reflect.getMetadata(DOCFY_MARKER, ProductsController); // true
488
531
  ```
@@ -517,6 +560,24 @@ If a method key does not exist on the controller at runtime, a warning is logged
517
560
 
518
561
  Adds the `x-tagGroups` extension to a Swagger document, built from groups registered via `docs({ group, tags })`. Call after `SwaggerModule.createDocument()` and before `SwaggerModule.setup()`. Returns the document unchanged if no groups were registered. See [Tag groups](#tag-groups-x-taggroups) for a full example.
519
562
 
563
+ ### `applyDocfyMetadata(document, options?)`
564
+
565
+ Merges the build-time metadata produced by the `nestjs-docfy` [CLI plugin](#webpack-true-build-mode) into an already-built OpenAPI document. Call after `SwaggerModule.createDocument()`, same as `attachTagGroups()`. This is the automatic, `webpack: true`-compatible alternative to manually running `patch-spec`.
566
+
567
+ ```ts
568
+ import { applyDocfyMetadata } from 'nestjs-docfy';
569
+
570
+ const document = SwaggerModule.createDocument(app, config);
571
+ SwaggerModule.setup('api', app, applyDocfyMetadata(document));
572
+ ```
573
+
574
+ | Option | Type | Default | Description |
575
+ | -------------- | --------- | ---------------------------------------------------- | ---------------------------------------------------------------------- |
576
+ | `metadataPath` | `string` | `docfy-metadata.json` next to the running entry file | Where to read the plugin-generated metadata from. |
577
+ | `strict` | `boolean` | `false` | Throw instead of warning when the metadata file is missing or invalid. |
578
+
579
+ If the metadata file isn't found (e.g. the plugin isn't registered in `nest-cli.json`), it warns and returns the document unchanged — same fail-open default as `DocfyModule.forRoot()`.
580
+
520
581
  ### `DocfyUiModule.setup(mountPath, app, options?)`
521
582
 
522
583
  Serves [`docfy-ui`](https://www.npmjs.com/package/docfy-ui) — the AI-first documentation UI companion to this package — at `mountPath`, the same role `SwaggerModule.setup()` + `swagger-ui-express` play for raw Swagger UI. Works on both Express (`@nestjs/platform-express`) and Fastify (`@nestjs/platform-fastify`) apps. On Fastify, static asset serving needs the optional peer dependency [`@fastify/static`](https://www.npmjs.com/package/@fastify/static) (`npm install @fastify/static`) — the same package `@nestjs/swagger` itself relies on for Fastify Swagger UI support.
@@ -538,11 +599,11 @@ await app.listen(3000);
538
599
 
539
600
  Visit `/docs` — no further configuration needed, since `docfy-ui` fetches `/api-json` same-origin by default.
540
601
 
541
- | Option | Type | Default | Description |
542
- | --- | --- | --- | --- |
543
- | `staticSpecPath` | `string` | — | Path to a pre-built OpenAPI JSON file, served at `/api-json` *instead of* the app's live one. |
602
+ | Option | Type | Default | Description |
603
+ | ---------------- | -------- | ------- | --------------------------------------------------------------------------------------------- |
604
+ | `staticSpecPath` | `string` | — | Path to a pre-built OpenAPI JSON file, served at `/api-json` _instead of_ the app's live one. |
544
605
 
545
- **`staticSpecPath` — required if your app builds with `"webpack": true`.** `DocfyModule`'s runtime metadata pipeline cannot apply docs files there (see [Not supported: webpack: true](#not-supported-nestjs-clis-webpack-true-build-mode)), so the live `/api-json` will be missing everything docs files would otherwise add. Generate a patched document ahead of time —
606
+ **`staticSpecPath` — needed if your app builds with `"webpack": true`, and you're not using the [CLI plugin](#webpack-true-build-mode).** `DocfyModule`'s runtime metadata pipeline cannot apply docs files there, so the live `/api-json` will be missing everything docs files would otherwise add. Generate a patched document ahead of time —
546
607
 
547
608
  ```bash
548
609
  npx nestjs-docfy patch-spec --spec http://localhost:3000/api-json --out openapi.patched.json
@@ -558,7 +619,7 @@ Call this **before** `SwaggerModule.setup()`: Express resolves routes in registr
558
619
 
559
620
  > **Fastify caveat**: `SwaggerModule.setup()` also registers its own `/api-json` route by default. On Express, whichever route is registered first silently wins. On Fastify, registering the same exact route twice throws `FST_ERR_DUPLICATED_ROUTE` at startup instead — registration order does not save you. When using `staticSpecPath` together with Fastify, point `SwaggerModule.setup()` at a different `jsonDocumentUrl`, or pass `{ raw: false }`, so it doesn't also claim `/api-json`.
560
621
  >
561
- > **Caveat**: `docfy-ui` renders with React Router's `BrowserRouter` and no configurable `basename` yet, so deep client-side routes (e.g. reloading an endpoint's detail page directly) only resolve correctly when `mountPath` is `/` — the application's root. Mounting elsewhere (e.g. `/docs`) still serves the UI and its initial load works fine; in-app navigation to a specific endpoint and then reloading that URL does not yet work at a non-root mount path.
622
+ > `docfy-ui` reads the mount prefix `DocfyUiModule.setup()` injects (`window.__DOCFY_BASE_PATH__`) and passes it as `BrowserRouter`'s `basename`, so deep client-side routes (e.g. reloading an endpoint's detail page directly) resolve correctly at any `mountPath`, not just `/`.
562
623
 
563
624
  ## Interface-typed DTOs
564
625
 
@@ -713,22 +774,54 @@ Discovery is automatic. `DocfyModule` locates each controller's source file via
713
774
 
714
775
  > **Barrel re-exports**: if your controller is also exported from an `index.ts` barrel, make sure the class is exported directly from its own module file. `nestjs-docfy` prefers `.controller.ts` over barrel files.
715
776
 
716
- ### Not supported: NestJS CLI's `webpack: true` build mode
777
+ ### `webpack: true` build mode
717
778
 
718
- If your `nest-cli.json` has `"webpack": true` under `compilerOptions` — the documented default for monorepos with multiple apps — `nestjs-docfy` **will not work**, and there is no configuration that makes it work. This is architectural, not a bug to be patched around:
779
+ If your `nest-cli.json` has `"webpack": true` under `compilerOptions` — the documented default for monorepos with multiple apps — `DocfyModule`'s **runtime** pipeline (the `@WithDocs()` + `require.cache` discovery described above) will not work, and there is no configuration that makes it work. This is architectural, not a bug to be patched around:
719
780
 
720
781
  - Webpack inlines every module into one bundle file and never populates Node's `require.cache` with an entry per original source file, which is what the discovery mechanism above depends on. You'll see `Could not locate source file for X` for every `@WithDocs()` controller.
721
782
  - Even if that lookup is worked around (e.g. by recovering the original path from the bundle's source map, sidestepping `require.cache` entirely), there's a second, unavoidable wall: a docs file required from outside the bundle creates a structurally different class object than the one the running app actually uses internally. Decorating that fresh copy has no effect on the document `SwaggerModule.createDocument()` actually serves — silently, with no error. This path-recovery layer was built and tested before discovering this; it isn't shipped, because "looks like it loaded, does nothing" is worse than the current loud, accurate warning.
722
783
  - The only way around this would be for the controller's own file to import its `.docs.ts` companion (forcing webpack to bundle them together) — which defeats the entire point of the convention: zero coupling between a controller and its documentation.
723
784
 
724
- **If you need `nestjs-docfy`, disable webpack bundling**: remove `"webpack": true` (or set it to `false`) in `nest-cli.json`. Under `nest build`'s default `tsc`-based compilation, every source file — including each `*.controller.docs.ts` — gets compiled to its own `.js` file in `dist/`, so `require.cache` naturally has one entry per file and discovery works exactly as documented above, no special configuration needed.
785
+ There are two ways to get full docs under `webpack: true`, in order of preference:
786
+
787
+ #### 1. The CLI plugin (recommended) — fixes it at the root, automatically, on every build
788
+
789
+ Register `nestjs-docfy` as a NestJS CLI compiler plugin in `nest-cli.json`:
790
+
791
+ ```json
792
+ {
793
+ "compilerOptions": {
794
+ "webpack": true,
795
+ "plugins": ["nestjs-docfy"]
796
+ }
797
+ }
798
+ ```
799
+
800
+ This is the same mechanism `@nestjs/swagger`'s own CLI plugin uses to work under `webpack: true` — it's why `@ApiProperty()` isn't required on every DTO property even in a webpack build. The Nest CLI feeds a TypeScript compiler-plugin hook (`compilerOptions.plugins`) into both the `tsc` and the `webpack` (`ts-loader`) builder identically. `nestjs-docfy`'s plugin doesn't rewrite any decorator syntax or touch the AST at all — on every compilation it re-runs the exact same static analysis `generate`/`check`/`patch-spec` already do (via `ts-morph`, against the source tree, not the bundle) and writes the resulting patch to `docfy-metadata.json` next to your build output. There's no `require.cache` involved and no bundled-class-identity problem, because it never needs the running app to compute anything.
801
+
802
+ Then, right after `SwaggerModule.createDocument()`, merge that file into the document:
803
+
804
+ ```ts
805
+ import { applyDocfyMetadata } from 'nestjs-docfy';
806
+
807
+ const document = SwaggerModule.createDocument(app, config);
808
+ SwaggerModule.setup('api', app, applyDocfyMetadata(document));
809
+ ```
810
+
811
+ `applyDocfyMetadata()` reads `docfy-metadata.json` from next to your compiled entry file by default — pass `{ metadataPath }` to point somewhere else. If the file is missing (e.g. the plugin isn't registered), it warns and returns the document unchanged; pass `{ strict: true }` to throw instead, the same `strict` convention `DocfyModule.forRoot()` already uses.
812
+
813
+ #### 2. `patch-spec` (manual, CI-driven) — the same analysis, run as a separate step
814
+
815
+ If you'd rather not add a compiler plugin (e.g. a build pipeline that isn't the Nest CLI, or a stricter policy about what runs during compilation), [`patch-spec`](#cli--patch-spec) computes the identical patch by hand against an already-built document — see that section for usage. This was the only option before the CLI plugin existed, and remains useful for one-off patching (e.g. patching a document fetched from a _different_ running instance than the one being built).
816
+
817
+ Disabling webpack entirely (`"webpack": false` or removing the key) also works, if you don't need it for another reason: under `nest build`'s default `tsc`-based compilation, every source file — including each `*.controller.docs.ts` — gets compiled to its own `.js` file in `dist/`, so `require.cache` naturally has one entry per file and `DocfyModule`'s runtime discovery works exactly as documented above, no special configuration needed.
725
818
 
726
819
  ## Testing
727
820
 
728
821
  Reset the controller registry between test suites to avoid cross-contamination:
729
822
 
730
823
  ```ts
731
- import { resetDocfyRegistry } from "nestjs-docfy/testing";
824
+ import { resetDocfyRegistry } from 'nestjs-docfy/testing';
732
825
 
733
826
  beforeEach(() => resetDocfyRegistry());
734
827
  ```
@@ -0,0 +1,37 @@
1
+ export interface ApplyDocfyMetadataOptions {
2
+ /** Absolute path to the metadata file. Defaults to `docfy-metadata.json` next to the running entry file. */
3
+ metadataPath?: string;
4
+ /** Throw instead of warning when the metadata file is missing or unparseable — mirrors `DocfyModule.forRoot({ strict })`. */
5
+ strict?: boolean;
6
+ }
7
+ /**
8
+ * Deliberately looser than `OpenApiDocument` (no `[key: string]: unknown`
9
+ * catch-all) — that catch-all exists so patch-spec/tests can freely type a
10
+ * fresh object literal with arbitrary extra OpenAPI fields, but it makes
11
+ * `OpenApiDocument` unable to structurally accept a real, concretely-typed
12
+ * document like `@nestjs/swagger`'s `OpenAPIObject` (which has no index
13
+ * signature of its own) as a generic constraint. This type only asserts the
14
+ * one field `applyDocfyMetadata` actually needs to reason about.
15
+ */
16
+ interface OpenApiDocumentLike {
17
+ paths?: unknown;
18
+ }
19
+ /**
20
+ * Merges the build-time metadata produced by the `nestjs-docfy` CLI plugin
21
+ * (`nest-cli.json`'s `compilerOptions.plugins`) into an already-built OpenAPI
22
+ * document. Call this right after `SwaggerModule.createDocument()` — the
23
+ * same lifecycle point a manually-run `patch-spec` output would be merged
24
+ * at, except this runs automatically on every build instead of requiring a
25
+ * separate CLI step.
26
+ *
27
+ * This is the path that actually works under NestJS CLI's `webpack: true`
28
+ * build mode — see the README's "Not supported: webpack: true" section for
29
+ * why `DocfyModule`'s `require.cache`-based discovery structurally cannot.
30
+ *
31
+ * Generic over the input document type so it returns exactly what was
32
+ * passed in (e.g. `@nestjs/swagger`'s `OpenAPIObject`, as returned by
33
+ * `SwaggerModule.createDocument()`) instead of the loosely-typed
34
+ * `OpenApiDocument` shape `mergeSpecPatch` uses internally.
35
+ */
36
+ export declare function applyDocfyMetadata<T extends OpenApiDocumentLike>(document: T, options?: ApplyDocfyMetadataOptions): T;
37
+ export {};
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.applyDocfyMetadata = applyDocfyMetadata;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const merge_spec_patch_1 = require("./cli/merge-spec-patch");
10
+ const generate_metadata_1 = require("./plugin/generate-metadata");
11
+ /**
12
+ * Merges the build-time metadata produced by the `nestjs-docfy` CLI plugin
13
+ * (`nest-cli.json`'s `compilerOptions.plugins`) into an already-built OpenAPI
14
+ * document. Call this right after `SwaggerModule.createDocument()` — the
15
+ * same lifecycle point a manually-run `patch-spec` output would be merged
16
+ * at, except this runs automatically on every build instead of requiring a
17
+ * separate CLI step.
18
+ *
19
+ * This is the path that actually works under NestJS CLI's `webpack: true`
20
+ * build mode — see the README's "Not supported: webpack: true" section for
21
+ * why `DocfyModule`'s `require.cache`-based discovery structurally cannot.
22
+ *
23
+ * Generic over the input document type so it returns exactly what was
24
+ * passed in (e.g. `@nestjs/swagger`'s `OpenAPIObject`, as returned by
25
+ * `SwaggerModule.createDocument()`) instead of the loosely-typed
26
+ * `OpenApiDocument` shape `mergeSpecPatch` uses internally.
27
+ */
28
+ function applyDocfyMetadata(document, options = {}) {
29
+ const metadataPath = options.metadataPath ?? path_1.default.join(path_1.default.dirname(require.main?.filename ?? process.cwd()), generate_metadata_1.DOCFY_METADATA_FILENAME);
30
+ let raw;
31
+ try {
32
+ raw = fs_1.default.readFileSync(metadataPath, 'utf8');
33
+ }
34
+ catch {
35
+ const message = `[nestjs-docfy] No build-time metadata found at ${metadataPath}. Did you register the CLI plugin in ` +
36
+ 'nest-cli.json (`"compilerOptions": { "plugins": ["nestjs-docfy"] }`)?';
37
+ if (options.strict)
38
+ throw new Error(message);
39
+ console.warn(message);
40
+ return document;
41
+ }
42
+ let patch;
43
+ try {
44
+ patch = JSON.parse(raw);
45
+ }
46
+ catch (err) {
47
+ const message = `[nestjs-docfy] Failed to parse build-time metadata at ${metadataPath}: ${err instanceof Error ? err.message : String(err)}`;
48
+ if (options.strict)
49
+ throw new Error(message, { cause: err });
50
+ console.warn(message);
51
+ return document;
52
+ }
53
+ return (0, merge_spec_patch_1.mergeSpecPatch)(document, patch).document;
54
+ }
55
+ //# sourceMappingURL=apply-docfy-metadata.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apply-docfy-metadata.js","sourceRoot":"","sources":["../src/apply-docfy-metadata.ts"],"names":[],"mappings":";;;;;AA2CA,gDA8BC;AAzED,4CAAoB;AACpB,gDAAwB;AACxB,6DAAyE;AAEzE,kEAAqE;AAsBrE;;;;;;;;;;;;;;;;GAgBG;AACH,SAAgB,kBAAkB,CAChC,QAAW,EACX,UAAqC,EAAE;IAEvC,MAAM,YAAY,GAChB,OAAO,CAAC,YAAY,IAAI,cAAI,CAAC,IAAI,CAAC,cAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC,EAAE,2CAAuB,CAAC,CAAC;IAEpH,IAAI,GAAW,CAAC;IAChB,IAAI,CAAC;QACH,GAAG,GAAG,YAAE,CAAC,YAAY,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;IAC9C,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,OAAO,GACX,kDAAkD,YAAY,uCAAuC;YACrG,uEAAuE,CAAC;QAC1E,IAAI,OAAO,CAAC,MAAM;YAAE,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;QAC7C,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACtB,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,IAAI,KAAgB,CAAC;IACrB,IAAI,CAAC;QACH,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAc,CAAC;IACvC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,OAAO,GAAG,yDAAyD,YAAY,KAAK,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC;QAC7I,IAAI,OAAO,CAAC,MAAM;YAAE,MAAM,IAAI,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;QAC7D,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACtB,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,OAAO,IAAA,iCAAc,EAAC,QAAsC,EAAE,KAAK,CAAC,CAAC,QAAwB,CAAC;AAChG,CAAC"}