nestjs-docfy 0.3.6 → 0.5.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/LICENSE +21 -0
- package/README.md +122 -67
- package/dist/apply-docfy-metadata.d.ts +37 -0
- package/dist/apply-docfy-metadata.js +55 -0
- package/dist/apply-docfy-metadata.js.map +1 -0
- package/dist/cli/build-openapi-patch.d.ts +16 -12
- package/dist/cli/build-openapi-patch.js +98 -15
- package/dist/cli/build-openapi-patch.js.map +1 -1
- package/dist/cli/check.js.map +1 -1
- package/dist/cli/coverage.js +1 -3
- package/dist/cli/coverage.js.map +1 -1
- package/dist/cli/detect-project.js +1 -5
- package/dist/cli/detect-project.js.map +1 -1
- package/dist/cli/errors.js.map +1 -1
- package/dist/cli/eval-decorator-args.d.ts +5 -3
- package/dist/cli/eval-decorator-args.js +64 -11
- package/dist/cli/eval-decorator-args.js.map +1 -1
- package/dist/cli/extract-docs-config.d.ts +21 -1
- package/dist/cli/extract-docs-config.js +18 -6
- package/dist/cli/extract-docs-config.js.map +1 -1
- package/dist/cli/extract-methods.d.ts +11 -0
- package/dist/cli/extract-methods.js +113 -29
- package/dist/cli/extract-methods.js.map +1 -1
- package/dist/cli/generate-file.js +24 -24
- package/dist/cli/generate-file.js.map +1 -1
- package/dist/cli/index.js +5 -6
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/lint.js +1 -3
- package/dist/cli/lint.js.map +1 -1
- package/dist/cli/logger.js +12 -6
- package/dist/cli/logger.js.map +1 -1
- package/dist/cli/merge-docs.js.map +1 -1
- package/dist/cli/merge-spec-patch.d.ts +15 -8
- package/dist/cli/merge-spec-patch.js +20 -4
- package/dist/cli/merge-spec-patch.js.map +1 -1
- package/dist/cli/parse-args.js +2 -6
- package/dist/cli/parse-args.js.map +1 -1
- package/dist/cli/patch-spec.d.ts +32 -8
- package/dist/cli/patch-spec.js +37 -15
- package/dist/cli/patch-spec.js.map +1 -1
- package/dist/cli/resolve-tsconfig.js +1 -5
- package/dist/cli/resolve-tsconfig.js.map +1 -1
- package/dist/cli/scan-controllers.d.ts +11 -0
- package/dist/cli/scan-controllers.js +10 -3
- package/dist/cli/scan-controllers.js.map +1 -1
- package/dist/cli/watch.js +3 -1
- package/dist/cli/watch.js.map +1 -1
- package/dist/cli/writer.js.map +1 -1
- package/dist/docfy-ui.module.d.ts +26 -10
- package/dist/docfy-ui.module.js +42 -6
- package/dist/docfy-ui.module.js.map +1 -1
- package/dist/docfy.module.js +1 -1
- package/dist/docfy.module.js.map +1 -1
- package/dist/docs.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/plugin/generate-metadata.d.ts +35 -0
- package/dist/plugin/generate-metadata.js +46 -0
- package/dist/plugin/generate-metadata.js.map +1 -0
- package/dist/plugin/index.d.ts +30 -0
- package/dist/plugin/index.js +62 -0
- package/dist/plugin/index.js.map +1 -0
- package/dist/registry.d.ts +3 -3
- package/dist/registry.js.map +1 -1
- package/dist/resolve-docs-path.d.ts +1 -1
- package/dist/resolve-docs-path.js.map +1 -1
- package/dist/resolve-source-from-stack.js.map +1 -1
- package/dist/with-docs.decorator.js.map +1 -1
- package/package.json +32 -3
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
|
-
<
|
|
2
|
+
<img alt="nestjs-docfy banner" src="./assets/banner.png" width="100%">
|
|
3
3
|
</p>
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
nestjs-docfy
|
|
7
|
-
</h1>
|
|
8
|
-
|
|
5
|
+
[](https://github.com/MarvinRF/nest-docfy/actions/workflows/ci.yml)
|
|
9
6
|
[](https://www.npmjs.com/package/nestjs-docfy)
|
|
10
7
|
[](https://www.npmjs.com/package/nestjs-docfy)
|
|
11
8
|
[](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)
|
|
@@ -36,12 +35,14 @@ Keep your NestJS controllers clean. Swagger documentation lives in a dedicated c
|
|
|
36
35
|
- [@WithDocs()](#withdocs)
|
|
37
36
|
- [docs()](#docscontrollerclass-config)
|
|
38
37
|
- [attachTagGroups()](#attachtaggroupsdocument)
|
|
38
|
+
- [applyDocfyMetadata()](#applydocfymetadatadocument-options)
|
|
39
39
|
- [DocfyUiModule.setup()](#docfyuimodulesetupmountpath-app-options)
|
|
40
40
|
- [Interface-typed DTOs](#interface-typed-dtos)
|
|
41
41
|
- [class-validator inference](#class-validator-inference)
|
|
42
42
|
- [@HttpCode() support](#httpcode-support)
|
|
43
43
|
- [Tag groups (x-tagGroups)](#tag-groups-x-taggroups)
|
|
44
44
|
- [File naming convention](#file-naming-convention)
|
|
45
|
+
- [webpack: true build mode](#webpack-true-build-mode)
|
|
45
46
|
- [Testing](#testing)
|
|
46
47
|
- [How it works](#how-it-works)
|
|
47
48
|
- [License](#license)
|
|
@@ -54,21 +55,21 @@ Swagger decorators are documentation. They have nothing to do with routing logic
|
|
|
54
55
|
|
|
55
56
|
```ts
|
|
56
57
|
// users.controller.ts
|
|
57
|
-
@ApiTags(
|
|
58
|
-
@Controller(
|
|
58
|
+
@ApiTags('users')
|
|
59
|
+
@Controller('users')
|
|
59
60
|
export class UsersController {
|
|
60
61
|
@Get()
|
|
61
|
-
@ApiOperation({ summary:
|
|
62
|
-
@ApiResponse({ status: 200, description:
|
|
62
|
+
@ApiOperation({ summary: 'List all users' })
|
|
63
|
+
@ApiResponse({ status: 200, description: 'OK', type: [UserEntity] })
|
|
63
64
|
findAll(): Promise<UserEntity[]> {
|
|
64
65
|
return this.usersService.findAll();
|
|
65
66
|
}
|
|
66
67
|
|
|
67
68
|
@Post()
|
|
68
|
-
@ApiOperation({ summary:
|
|
69
|
+
@ApiOperation({ summary: 'Create a user' })
|
|
69
70
|
@ApiBody({ type: CreateUserDto })
|
|
70
|
-
@ApiResponse({ status: 201, description:
|
|
71
|
-
@ApiResponse({ status: 400, description:
|
|
71
|
+
@ApiResponse({ status: 201, description: 'Created', type: UserEntity })
|
|
72
|
+
@ApiResponse({ status: 400, description: 'Bad Request' })
|
|
72
73
|
create(@Body() dto: CreateUserDto): Promise<UserEntity> {
|
|
73
74
|
return this.usersService.create(dto);
|
|
74
75
|
}
|
|
@@ -80,7 +81,7 @@ export class UsersController {
|
|
|
80
81
|
```ts
|
|
81
82
|
// users.controller.ts
|
|
82
83
|
@WithDocs()
|
|
83
|
-
@Controller(
|
|
84
|
+
@Controller('users')
|
|
84
85
|
export class UsersController {
|
|
85
86
|
findAll(): Promise<UserEntity[]> {
|
|
86
87
|
return this.usersService.findAll();
|
|
@@ -95,17 +96,17 @@ export class UsersController {
|
|
|
95
96
|
```ts
|
|
96
97
|
// users.controller.docs.ts — all documentation in one place
|
|
97
98
|
docs(UsersController, {
|
|
98
|
-
classDecorators: [ApiTags(
|
|
99
|
+
classDecorators: [ApiTags('users')],
|
|
99
100
|
methods: {
|
|
100
101
|
findAll: [
|
|
101
|
-
ApiOperation({ summary:
|
|
102
|
-
ApiResponse({ status: 200, description:
|
|
102
|
+
ApiOperation({ summary: 'List all users' }),
|
|
103
|
+
ApiResponse({ status: 200, description: 'OK', type: [UserEntity] }),
|
|
103
104
|
],
|
|
104
105
|
create: [
|
|
105
|
-
ApiOperation({ summary:
|
|
106
|
+
ApiOperation({ summary: 'Create a user' }),
|
|
106
107
|
ApiBody({ type: CreateUserDto }),
|
|
107
|
-
ApiResponse({ status: 201, description:
|
|
108
|
-
ApiResponse({ status: 400, description:
|
|
108
|
+
ApiResponse({ status: 201, description: 'Created', type: UserEntity }),
|
|
109
|
+
ApiResponse({ status: 400, description: 'Bad Request' }),
|
|
109
110
|
],
|
|
110
111
|
},
|
|
111
112
|
});
|
|
@@ -131,8 +132,8 @@ npm install @nestjs/common @nestjs/swagger reflect-metadata
|
|
|
131
132
|
|
|
132
133
|
```ts
|
|
133
134
|
// app.module.ts
|
|
134
|
-
import { Module } from
|
|
135
|
-
import { DocfyModule } from
|
|
135
|
+
import { Module } from '@nestjs/common';
|
|
136
|
+
import { DocfyModule } from 'nestjs-docfy';
|
|
136
137
|
|
|
137
138
|
@Module({
|
|
138
139
|
imports: [DocfyModule.forRoot()],
|
|
@@ -150,11 +151,11 @@ DocfyModule.forRoot({ strict: true });
|
|
|
150
151
|
|
|
151
152
|
```ts
|
|
152
153
|
// users.controller.ts
|
|
153
|
-
import { Controller, Get, Post, Body } from
|
|
154
|
-
import { WithDocs } from
|
|
154
|
+
import { Controller, Get, Post, Body } from '@nestjs/common';
|
|
155
|
+
import { WithDocs } from 'nestjs-docfy';
|
|
155
156
|
|
|
156
157
|
@WithDocs()
|
|
157
|
-
@Controller(
|
|
158
|
+
@Controller('users')
|
|
158
159
|
export class UsersController {
|
|
159
160
|
// route handlers only — no Swagger decorators here
|
|
160
161
|
}
|
|
@@ -182,27 +183,27 @@ The generated file comes pre-populated with inferred summaries, response types,
|
|
|
182
183
|
|
|
183
184
|
```ts
|
|
184
185
|
// Generated by nestjs-docfy — edit freely, use --force to merge new methods
|
|
185
|
-
import { docs } from
|
|
186
|
-
import { ApiTags, ApiOperation, ApiResponse, ApiBody } from
|
|
187
|
-
import { UsersController } from
|
|
188
|
-
import { CreateUserDto } from
|
|
189
|
-
import { UserEntity } from
|
|
186
|
+
import { docs } from 'nestjs-docfy';
|
|
187
|
+
import { ApiTags, ApiOperation, ApiResponse, ApiBody } from '@nestjs/swagger';
|
|
188
|
+
import { UsersController } from './users.controller';
|
|
189
|
+
import { CreateUserDto } from './dto/create-user.dto';
|
|
190
|
+
import { UserEntity } from './entities/user.entity';
|
|
190
191
|
|
|
191
192
|
docs(UsersController, {
|
|
192
|
-
classDecorators: [ApiTags(
|
|
193
|
+
classDecorators: [ApiTags('users')],
|
|
193
194
|
methods: {
|
|
194
195
|
// GET / → async findAll(): Promise<UserEntity[]>
|
|
195
196
|
findAll: [
|
|
196
|
-
ApiOperation({ summary:
|
|
197
|
-
ApiResponse({ status: 200, description:
|
|
197
|
+
ApiOperation({ summary: 'Find all' }),
|
|
198
|
+
ApiResponse({ status: 200, description: 'OK', type: [UserEntity] }),
|
|
198
199
|
],
|
|
199
200
|
|
|
200
201
|
// POST / → async create(dto: CreateUserDto): Promise<UserEntity>
|
|
201
202
|
create: [
|
|
202
|
-
ApiOperation({ summary:
|
|
203
|
+
ApiOperation({ summary: 'Create' }),
|
|
203
204
|
ApiBody({ type: CreateUserDto }),
|
|
204
|
-
ApiResponse({ status: 201, description:
|
|
205
|
-
ApiResponse({ status: 400, description:
|
|
205
|
+
ApiResponse({ status: 201, description: 'Created', type: UserEntity }),
|
|
206
|
+
ApiResponse({ status: 400, description: 'Bad Request' }),
|
|
206
207
|
],
|
|
207
208
|
},
|
|
208
209
|
});
|
|
@@ -270,13 +271,13 @@ Verify that every controller is fully documented before merging. Exits with code
|
|
|
270
271
|
npx nestjs-docfy check [options]
|
|
271
272
|
```
|
|
272
273
|
|
|
273
|
-
| Option | Default
|
|
274
|
-
| ------------------- |
|
|
275
|
-
| `--root <path>` | `.`
|
|
276
|
-
| `--tsconfig <path>` | auto-detected
|
|
277
|
-
| `--pattern <glob>` | `**/*.controller.ts`
|
|
278
|
-
| `--format <format>` | `ts`
|
|
279
|
-
| `--quiet` | `false`
|
|
274
|
+
| Option | Default | Description |
|
|
275
|
+
| ------------------- | -------------------- | ------------------------------------------ |
|
|
276
|
+
| `--root <path>` | `.` | Project root directory |
|
|
277
|
+
| `--tsconfig <path>` | auto-detected | Path to `tsconfig.json` |
|
|
278
|
+
| `--pattern <glob>` | `**/*.controller.ts` | Glob pattern to find controllers |
|
|
279
|
+
| `--format <format>` | `ts` | Docs file format to look for: `ts` or `js` |
|
|
280
|
+
| `--quiet` | `false` | Suppress all output except errors |
|
|
280
281
|
|
|
281
282
|
**What it checks:**
|
|
282
283
|
|
|
@@ -424,21 +425,21 @@ Or as an npm script:
|
|
|
424
425
|
|
|
425
426
|
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
427
|
|
|
427
|
-
This is
|
|
428
|
+
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
429
|
|
|
429
430
|
```bash
|
|
430
431
|
npx nestjs-docfy patch-spec --spec <path-or-url> [options]
|
|
431
432
|
```
|
|
432
433
|
|
|
433
|
-
| Option
|
|
434
|
-
|
|
|
435
|
-
| `--spec <path\|url>` |
|
|
436
|
-
| `--out <path>`
|
|
437
|
-
| `--root <path>`
|
|
438
|
-
| `--tsconfig <path>`
|
|
439
|
-
| `--pattern <glob>`
|
|
440
|
-
| `--format <format>`
|
|
441
|
-
| `--quiet`
|
|
434
|
+
| Option | Default | Description |
|
|
435
|
+
| -------------------- | -------------------- | ------------------------------------------------------------------- |
|
|
436
|
+
| `--spec <path\|url>` | _(required)_ | A local `openapi.json`, or a URL (e.g. a running app's `/api-json`) |
|
|
437
|
+
| `--out <path>` | stdout | Where to write the patched document |
|
|
438
|
+
| `--root <path>` | `.` | Project root directory |
|
|
439
|
+
| `--tsconfig <path>` | auto-detected | Path to `tsconfig.json` |
|
|
440
|
+
| `--pattern <glob>` | `**/*.controller.ts` | Glob pattern to find controllers |
|
|
441
|
+
| `--format <format>` | `ts` | Docs file format to look for: `ts` or `js` |
|
|
442
|
+
| `--quiet` | `false` | Suppress all output except errors |
|
|
442
443
|
|
|
443
444
|
```bash
|
|
444
445
|
# Patch a running app's served document
|
|
@@ -452,12 +453,14 @@ npx nestjs-docfy patch-spec --spec dist/openapi.json --out dist/openapi.json
|
|
|
452
453
|
|
|
453
454
|
- `ApiTags` → unioned into `tags` (never drops tags the base document already had)
|
|
454
455
|
- `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
|
|
456
|
+
- `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>`)
|
|
457
|
+
- `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
458
|
- `ApiBearerAuth()` → appended to `security`
|
|
458
|
-
- `ApiParam` / `ApiQuery` / `ApiHeader` →
|
|
459
|
+
- `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
|
|
460
|
+
|
|
461
|
+
`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.
|
|
459
462
|
|
|
460
|
-
**What this does
|
|
463
|
+
**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.
|
|
461
464
|
|
|
462
465
|
## API reference
|
|
463
466
|
|
|
@@ -482,7 +485,7 @@ export class ProductsController { ... }
|
|
|
482
485
|
Also sets `DOCFY_MARKER` metadata on the class, available for external introspection:
|
|
483
486
|
|
|
484
487
|
```ts
|
|
485
|
-
import { DOCFY_MARKER } from
|
|
488
|
+
import { DOCFY_MARKER } from 'nestjs-docfy';
|
|
486
489
|
|
|
487
490
|
Reflect.getMetadata(DOCFY_MARKER, ProductsController); // true
|
|
488
491
|
```
|
|
@@ -517,9 +520,27 @@ If a method key does not exist on the controller at runtime, a warning is logged
|
|
|
517
520
|
|
|
518
521
|
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
522
|
|
|
523
|
+
### `applyDocfyMetadata(document, options?)`
|
|
524
|
+
|
|
525
|
+
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`.
|
|
526
|
+
|
|
527
|
+
```ts
|
|
528
|
+
import { applyDocfyMetadata } from 'nestjs-docfy';
|
|
529
|
+
|
|
530
|
+
const document = SwaggerModule.createDocument(app, config);
|
|
531
|
+
SwaggerModule.setup('api', app, applyDocfyMetadata(document));
|
|
532
|
+
```
|
|
533
|
+
|
|
534
|
+
| Option | Type | Default | Description |
|
|
535
|
+
| -------------- | --------- | ---------------------------------------------------- | ---------------------------------------------------------------------- |
|
|
536
|
+
| `metadataPath` | `string` | `docfy-metadata.json` next to the running entry file | Where to read the plugin-generated metadata from. |
|
|
537
|
+
| `strict` | `boolean` | `false` | Throw instead of warning when the metadata file is missing or invalid. |
|
|
538
|
+
|
|
539
|
+
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()`.
|
|
540
|
+
|
|
520
541
|
### `DocfyUiModule.setup(mountPath, app, options?)`
|
|
521
542
|
|
|
522
|
-
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.
|
|
543
|
+
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.
|
|
523
544
|
|
|
524
545
|
```ts
|
|
525
546
|
import { NestFactory } from '@nestjs/core';
|
|
@@ -538,11 +559,11 @@ await app.listen(3000);
|
|
|
538
559
|
|
|
539
560
|
Visit `/docs` — no further configuration needed, since `docfy-ui` fetches `/api-json` same-origin by default.
|
|
540
561
|
|
|
541
|
-
| Option
|
|
542
|
-
|
|
|
543
|
-
| `staticSpecPath` | `string` | —
|
|
562
|
+
| Option | Type | Default | Description |
|
|
563
|
+
| ---------------- | -------- | ------- | --------------------------------------------------------------------------------------------- |
|
|
564
|
+
| `staticSpecPath` | `string` | — | Path to a pre-built OpenAPI JSON file, served at `/api-json` _instead of_ the app's live one. |
|
|
544
565
|
|
|
545
|
-
**`staticSpecPath` —
|
|
566
|
+
**`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
567
|
|
|
547
568
|
```bash
|
|
548
569
|
npx nestjs-docfy patch-spec --spec http://localhost:3000/api-json --out openapi.patched.json
|
|
@@ -556,7 +577,9 @@ DocfyUiModule.setup('/docs', app, { staticSpecPath: './openapi.patched.json' });
|
|
|
556
577
|
|
|
557
578
|
Call this **before** `SwaggerModule.setup()`: Express resolves routes in registration order, so the static, patched document takes precedence over the live one for any request to `/api-json`.
|
|
558
579
|
|
|
559
|
-
> **
|
|
580
|
+
> **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`.
|
|
581
|
+
>
|
|
582
|
+
> `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 `/`.
|
|
560
583
|
|
|
561
584
|
## Interface-typed DTOs
|
|
562
585
|
|
|
@@ -711,22 +734,54 @@ Discovery is automatic. `DocfyModule` locates each controller's source file via
|
|
|
711
734
|
|
|
712
735
|
> **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.
|
|
713
736
|
|
|
714
|
-
###
|
|
737
|
+
### `webpack: true` build mode
|
|
715
738
|
|
|
716
|
-
If your `nest-cli.json` has `"webpack": true` under `compilerOptions` — the documented default for monorepos with multiple apps — `
|
|
739
|
+
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:
|
|
717
740
|
|
|
718
741
|
- 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.
|
|
719
742
|
- 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.
|
|
720
743
|
- 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.
|
|
721
744
|
|
|
722
|
-
|
|
745
|
+
There are two ways to get full docs under `webpack: true`, in order of preference:
|
|
746
|
+
|
|
747
|
+
#### 1. The CLI plugin (recommended) — fixes it at the root, automatically, on every build
|
|
748
|
+
|
|
749
|
+
Register `nestjs-docfy` as a NestJS CLI compiler plugin in `nest-cli.json`:
|
|
750
|
+
|
|
751
|
+
```json
|
|
752
|
+
{
|
|
753
|
+
"compilerOptions": {
|
|
754
|
+
"webpack": true,
|
|
755
|
+
"plugins": ["nestjs-docfy"]
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
```
|
|
759
|
+
|
|
760
|
+
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.
|
|
761
|
+
|
|
762
|
+
Then, right after `SwaggerModule.createDocument()`, merge that file into the document:
|
|
763
|
+
|
|
764
|
+
```ts
|
|
765
|
+
import { applyDocfyMetadata } from 'nestjs-docfy';
|
|
766
|
+
|
|
767
|
+
const document = SwaggerModule.createDocument(app, config);
|
|
768
|
+
SwaggerModule.setup('api', app, applyDocfyMetadata(document));
|
|
769
|
+
```
|
|
770
|
+
|
|
771
|
+
`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.
|
|
772
|
+
|
|
773
|
+
#### 2. `patch-spec` (manual, CI-driven) — the same analysis, run as a separate step
|
|
774
|
+
|
|
775
|
+
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).
|
|
776
|
+
|
|
777
|
+
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.
|
|
723
778
|
|
|
724
779
|
## Testing
|
|
725
780
|
|
|
726
781
|
Reset the controller registry between test suites to avoid cross-contamination:
|
|
727
782
|
|
|
728
783
|
```ts
|
|
729
|
-
import { resetDocfyRegistry } from
|
|
784
|
+
import { resetDocfyRegistry } from 'nestjs-docfy/testing';
|
|
730
785
|
|
|
731
786
|
beforeEach(() => resetDocfyRegistry());
|
|
732
787
|
```
|
|
@@ -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"}
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import type { ControllerInfo } from './extract-methods';
|
|
2
2
|
import type { ExtractedDocsConfig } from './extract-docs-config';
|
|
3
3
|
export type OpenApiSchema = Record<string, unknown>;
|
|
4
|
+
export interface MediaTypeContent {
|
|
5
|
+
schema?: OpenApiSchema;
|
|
6
|
+
example?: unknown;
|
|
7
|
+
examples?: Record<string, unknown>;
|
|
8
|
+
}
|
|
4
9
|
export interface OperationPatch {
|
|
5
10
|
tags?: string[];
|
|
6
11
|
summary?: string;
|
|
@@ -15,15 +20,11 @@ export interface OperationPatch {
|
|
|
15
20
|
}>;
|
|
16
21
|
requestBody?: {
|
|
17
22
|
required?: boolean;
|
|
18
|
-
content: Record<string,
|
|
19
|
-
schema: OpenApiSchema;
|
|
20
|
-
}>;
|
|
23
|
+
content: Record<string, MediaTypeContent>;
|
|
21
24
|
};
|
|
22
25
|
responses?: Record<string, {
|
|
23
26
|
description?: string;
|
|
24
|
-
content?: Record<string,
|
|
25
|
-
schema: OpenApiSchema;
|
|
26
|
-
}>;
|
|
27
|
+
content?: Record<string, MediaTypeContent>;
|
|
27
28
|
}>;
|
|
28
29
|
}
|
|
29
30
|
/** path -> httpMethod (lowercase) -> patch */
|
|
@@ -35,11 +36,14 @@ export type SpecPatch = Record<string, Record<string, OperationPatch>>;
|
|
|
35
36
|
*
|
|
36
37
|
* This intentionally does not aim for full parity with what `@nestjs/swagger`
|
|
37
38
|
* decorators would produce when actually applied (that's a much larger
|
|
38
|
-
* surface —
|
|
39
|
-
* the common path: tags,
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
39
|
+
* surface — links, callbacks, etc. that `@nestjs/swagger` itself doesn't
|
|
40
|
+
* expose a decorator option for anyway). It covers the common path: tags,
|
|
41
|
+
* operation summary/description, responses with a status + description +
|
|
42
|
+
* schema (including a `oneOf` when the return type or `@Body()` payload is a
|
|
43
|
+
* union of named DTOs) + example/examples, request bodies, bearer auth, and
|
|
44
|
+
* enum-valued params/headers — enough to validate that statically-computed
|
|
45
|
+
* patches can stand in for runtime decoration where the latter is
|
|
46
|
+
* structurally impossible (see the README's "Not supported: webpack: true"
|
|
47
|
+
* section).
|
|
44
48
|
*/
|
|
45
49
|
export declare function buildOpenApiPatch(ctrl: ControllerInfo, config: ExtractedDocsConfig): SpecPatch;
|