nestjs-docfy 0.8.0 → 0.9.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
@@ -274,14 +274,14 @@ Verify that every controller is fully documented before merging. Exits with code
274
274
  npx nestjs-docfy check [options]
275
275
  ```
276
276
 
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 |
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 |
285
285
 
286
286
  **What it checks:**
287
287
 
@@ -323,15 +323,15 @@ Measure what percentage of your endpoints are documented. Useful as an objective
323
323
  npx nestjs-docfy coverage [options]
324
324
  ```
325
325
 
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` |
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
332
  | `--min <percent>` | none | Minimum coverage required (0-100), exits `1` if below |
333
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 |
334
+ | `--quiet` | `false` | Suppress all output except errors |
335
335
 
336
336
  **Example output:**
337
337
 
@@ -495,12 +495,12 @@ export default async function () {
495
495
  npx nestjs-docfy export --entry docfy-export.ts --out openapi.json
496
496
  ```
497
497
 
498
- | Option | Default | Description |
499
- | ---------------- | ------------ | -------------------------------------------------------------------- |
500
- | `--entry <path>` | _(required)_ | `.ts`/`.js` file whose default export returns `{ app, document }` |
501
- | `--out <path>` | stdout | Where to write the document |
502
- | `--root <path>` | `.` | Project root — where `ts-node`/`tsconfig-paths` are resolved from |
503
- | `--quiet` | `false` | Suppress informational output (errors still go to stderr) |
498
+ | Option | Default | Description |
499
+ | ---------------- | ------------ | ----------------------------------------------------------------- |
500
+ | `--entry <path>` | _(required)_ | `.ts`/`.js` file whose default export returns `{ app, document }` |
501
+ | `--out <path>` | stdout | Where to write the document |
502
+ | `--root <path>` | `.` | Project root — where `ts-node`/`tsconfig-paths` are resolved from |
503
+ | `--quiet` | `false` | Suppress informational output (errors still go to stderr) |
504
504
 
505
505
  A `.ts` entry file needs `ts-node` as a devDependency of your project (for `tsconfig-paths` support too, if your project uses path aliases like `@app/common`). Informational output always goes to stderr, never stdout — safe to pipe: `npx nestjs-docfy export --entry docfy-export.ts > openapi.json`.
506
506
 
@@ -634,9 +634,12 @@ await app.listen(3000);
634
634
 
635
635
  Visit `/docs`: no further configuration needed, since `docfy-ui` fetches `/api-json` same-origin by default.
636
636
 
637
- | Option | Type | Default | Description |
638
- | ---------------- | -------- | ------- | --------------------------------------------------------------------------------------------- |
639
- | `staticSpecPath` | `string` | — | Path to a pre-built OpenAPI JSON file, served at `/api-json` _instead of_ the app's live one. |
637
+ | Option | Type | Default | Description |
638
+ | ------------------------ | --------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------- |
639
+ | `staticSpecPath` | `string` | — | Path to a pre-built OpenAPI JSON file, served at `/api-json` _instead of_ the app's live one. |
640
+ | `specs` | `{ name: string; url: string }[]` | — | Extra OpenAPI specs to offer in `docfy-ui`'s spec switcher, so one deployed instance can browse more than one service's documentation. |
641
+ | `openApiDocument` | `{ servers?: { url: string }[] }` | — | Enables the "Try it out" same-origin proxy — pass the same object you already have from `SwaggerModule.createDocument()`. See below. |
642
+ | `additionalProxyOrigins` | `string[]` | — | Extra origins the proxy is allowed to forward requests to, beyond what `openApiDocument.servers` declares. |
640
643
 
641
644
  **`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:
642
645
 
@@ -656,6 +659,18 @@ Call this **before** `SwaggerModule.setup()`: Express resolves routes in registr
656
659
  >
657
660
  > `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 `/`.
658
661
 
662
+ **`openApiDocument` / `additionalProxyOrigins`: enables `docfy-ui`'s "Try it out" same-origin proxy.** Without it, "Try it out" does a direct `fetch()` from the browser to the target API, subject to that API's own CORS policy. With it, the browser instead calls a same-origin route this module registers (`POST {mountPath}/__docfy_proxy`), and the proxy makes the real request server-to-server — CORS never applies.
663
+
664
+ ```ts
665
+ const document = SwaggerModule.createDocument(app, new DocumentBuilder().build());
666
+ SwaggerModule.setup('api', app, document);
667
+ DocfyUiModule.setup('/docs', app, { openApiDocument: document });
668
+ ```
669
+
670
+ The proxy's allowlist is built **only** from absolute URLs in the OpenAPI document's `servers[]` array (plus anything in `additionalProxyOrigins`) — a request for any other origin gets rejected with `403` and an `X-Docfy-Proxy-Error: origin_not_allowed` response header. There is deliberately no implicit "same origin as this request" fallback: that would have to be derived from client-controlled request headers (`Host`), which is a classic SSRF vector — someone hitting the proxy endpoint directly (not through a browser, no CORS involved) could forge it to reach an internal-only origin. Declare `servers[]` in your `DocumentBuilder` config to opt an origin in; without any absolute `servers[]` entry, the route exists but always returns `403`.
671
+
672
+ Every other proxy failure (target unreachable, timeout) also sets `X-Docfy-Proxy-Error`, so `docfy-ui` can tell a proxy-level failure apart from a real `4xx`/`5xx` response coming from your API — those pass through untouched, with their real status/headers/body.
673
+
659
674
  ## Interface-typed DTOs
660
675
 
661
676
  When a response or body type is a TypeScript `interface` (not a class), Swagger cannot use it as a `type:` value because interfaces are erased at runtime. `nestjs-docfy` detects this automatically and generates an inline `schema:` object instead. **No changes to your code required.**
package/dist/cli/index.js CHANGED
File without changes
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Loads a .ts companion docs file at runtime without relying on a
3
+ * pre-registered TypeScript loader (ts-node, tsx, etc.).
4
+ *
5
+ * Why this is needed: docs files are intentionally never imported by
6
+ * application code (that's the whole point of the *.controller.docs.ts
7
+ * convention — they attach metadata from outside the controller). Under
8
+ * NestJS CLI's `webpack: true` build mode, that means they're never part
9
+ * of the bundle's reachable module graph, so they never get compiled to
10
+ * .js even when the rest of the app is — there's nothing for a plain
11
+ * `require()` to load. resolveDocsPath can correctly locate the original
12
+ * .ts file (see resolve-source-from-stack.ts), but loading it still needs
13
+ * this.
14
+ *
15
+ * Registers `require.extensions['.ts']` — exactly the mechanism ts-node's
16
+ * own `register()` uses — rather than manually constructing a `Module`
17
+ * instance and calling `_compile()` directly. That distinction matters for
18
+ * correctness, not just style: Node's module *resolution* (not just
19
+ * compilation) only tries an extension if it's a registered key of
20
+ * `require.extensions`. A docs file importing a sibling relative path
21
+ * (`import { UsersController } from './users.controller'`) needs Node to
22
+ * try `./users.controller.ts` while resolving — manually compiling just
23
+ * the entry file doesn't make Node try `.ts` for anything *it* requires
24
+ * in turn, so any relative import inside the docs file would still throw
25
+ * "Cannot find module" one level down.
26
+ *
27
+ * Transpiles with esbuild — type-stripping only, since docs files call
28
+ * decorator factories as plain functions (`docs(Controller, { classDecorators:
29
+ * [ApiTags('x')] })`) rather than using TypeScript decorator syntax
30
+ * themselves, so no decorator-metadata emulation is needed.
31
+ */
32
+ export declare function requireTypeScriptFile(absPath: string): unknown;
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.requireTypeScriptFile = requireTypeScriptFile;
37
+ const fs = __importStar(require("fs"));
38
+ /**
39
+ * Loads a .ts companion docs file at runtime without relying on a
40
+ * pre-registered TypeScript loader (ts-node, tsx, etc.).
41
+ *
42
+ * Why this is needed: docs files are intentionally never imported by
43
+ * application code (that's the whole point of the *.controller.docs.ts
44
+ * convention — they attach metadata from outside the controller). Under
45
+ * NestJS CLI's `webpack: true` build mode, that means they're never part
46
+ * of the bundle's reachable module graph, so they never get compiled to
47
+ * .js even when the rest of the app is — there's nothing for a plain
48
+ * `require()` to load. resolveDocsPath can correctly locate the original
49
+ * .ts file (see resolve-source-from-stack.ts), but loading it still needs
50
+ * this.
51
+ *
52
+ * Registers `require.extensions['.ts']` — exactly the mechanism ts-node's
53
+ * own `register()` uses — rather than manually constructing a `Module`
54
+ * instance and calling `_compile()` directly. That distinction matters for
55
+ * correctness, not just style: Node's module *resolution* (not just
56
+ * compilation) only tries an extension if it's a registered key of
57
+ * `require.extensions`. A docs file importing a sibling relative path
58
+ * (`import { UsersController } from './users.controller'`) needs Node to
59
+ * try `./users.controller.ts` while resolving — manually compiling just
60
+ * the entry file doesn't make Node try `.ts` for anything *it* requires
61
+ * in turn, so any relative import inside the docs file would still throw
62
+ * "Cannot find module" one level down.
63
+ *
64
+ * Transpiles with esbuild — type-stripping only, since docs files call
65
+ * decorator factories as plain functions (`docs(Controller, { classDecorators:
66
+ * [ApiTags('x')] })`) rather than using TypeScript decorator syntax
67
+ * themselves, so no decorator-metadata emulation is needed.
68
+ */
69
+ function requireTypeScriptFile(absPath) {
70
+ console.error('[DEBUG requireTypeScriptFile]', JSON.stringify(absPath), 'exists=', fs.existsSync(absPath));
71
+ if (!fs.existsSync(absPath)) {
72
+ // Matches the shape of Node's own require() MODULE_NOT_FOUND error, so
73
+ // callers that distinguish "file doesn't exist" from "file threw while
74
+ // loading" (DocfyModule's isMissingDocsFile) work the same regardless
75
+ // of which loader actually handled the path.
76
+ throw Object.assign(new Error(`Cannot find module '${absPath}'`), {
77
+ code: 'MODULE_NOT_FOUND',
78
+ });
79
+ }
80
+ registerTsExtension();
81
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
82
+ return require(absPath);
83
+ }
84
+ let registered = false;
85
+ function registerTsExtension() {
86
+ if (registered || require.extensions['.ts'])
87
+ return;
88
+ const esbuild = loadEsbuild();
89
+ if (!esbuild) {
90
+ throw new Error(`[nestjs-docfy] Cannot load a .ts docs file: no TypeScript loader is registered ` +
91
+ `(e.g. ts-node) and the "esbuild" dependency isn't available. Install esbuild ` +
92
+ `(it's a direct dependency of nestjs-docfy and should already be present — ` +
93
+ `check your install), or disable webpack bundling ("webpack": false in ` +
94
+ `nest-cli.json) so docs files get compiled to .js like everything else.`);
95
+ }
96
+ require.extensions['.ts'] = (mod, filename) => {
97
+ const source = fs.readFileSync(filename, 'utf8');
98
+ const { code } = esbuild.transformSync(source, {
99
+ loader: 'ts',
100
+ format: 'cjs',
101
+ target: 'es2019',
102
+ sourcefile: filename,
103
+ // A docs file's own relative imports can pull in real application
104
+ // source (e.g. the controller it documents), which legitimately uses
105
+ // NestJS's decorator syntax — without this, esbuild rejects parameter
106
+ // decorators like `@Body()` outright.
107
+ tsconfigRaw: { compilerOptions: { experimentalDecorators: true, emitDecoratorMetadata: true } },
108
+ });
109
+ mod._compile(code, filename);
110
+ };
111
+ registered = true;
112
+ }
113
+ function loadEsbuild() {
114
+ try {
115
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
116
+ return require('esbuild');
117
+ }
118
+ catch {
119
+ return null;
120
+ }
121
+ }
122
+ //# sourceMappingURL=require-ts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"require-ts.js","sourceRoot":"","sources":["../src/require-ts.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,sDAeC;AAtDD,uCA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,QAAQ;YAChB,UAAU,EAAE,QAAQ;YACpB,kEAAkE;YAClE,qEAAqE;YACrE,sEAAsE;YACtE,sCAAsC;YACtC,WAAW,EAAE,EAAE,eAAe,EAAE,EAAE,sBAAsB,EAAE,IAAI,EAAE,qBAAqB,EAAE,IAAI,EAAE,EAAE;SAChG,CAAC,CAAC;QACF,GAAqC,CAAC,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IAClE,CAAC,CAAC;IACF,UAAU,GAAG,IAAI,CAAC;AACpB,CAAC;AAED,SAAS,WAAW;IAClB,IAAI,CAAC;QACH,iEAAiE;QACjE,OAAO,OAAO,CAAC,SAAS,CAAkB,CAAC;IAC7C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nestjs-docfy",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Keep your NestJS controllers clean — Swagger docs live in a separate companion file by naming convention",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -116,7 +116,7 @@
116
116
  },
117
117
  "dependencies": {
118
118
  "commander": "^15.0.0",
119
- "docfy-ui": "^0.4.0",
119
+ "docfy-ui": "^0.5.0",
120
120
  "express": "^5.0.0",
121
121
  "openapi-typescript": "^7.13.0",
122
122
  "picocolors": "^1.1.1",