nestjs-docfy 0.7.0 → 0.8.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/dist/docfy-ui.module.d.ts +18 -0
- package/dist/docfy-ui.module.js +23 -2
- package/dist/docfy-ui.module.js.map +1 -1
- package/dist/proxy-handler.d.ts +40 -0
- package/dist/proxy-handler.js +213 -0
- package/dist/proxy-handler.js.map +1 -0
- package/package.json +2 -2
|
@@ -8,6 +8,7 @@ export interface DocfyUiHttpAdapter {
|
|
|
8
8
|
getType(): string;
|
|
9
9
|
getInstance(): unknown;
|
|
10
10
|
get(path: string, handler: (req: unknown, res: unknown) => unknown): unknown;
|
|
11
|
+
post(path: string, handler: (req: unknown, res: unknown) => unknown): unknown;
|
|
11
12
|
}
|
|
12
13
|
/**
|
|
13
14
|
* Minimal structural shape of what `DocfyUiModule.setup()` needs from a
|
|
@@ -56,6 +57,23 @@ export interface DocfyUiSetupOptions {
|
|
|
56
57
|
name: string;
|
|
57
58
|
url: string;
|
|
58
59
|
}[];
|
|
60
|
+
/**
|
|
61
|
+
* Enables the "Try it out" server-side proxy: docfy-ui's browser calls a same-origin
|
|
62
|
+
* route on this app instead of the target API directly, sidestepping CORS entirely.
|
|
63
|
+
* Requires explicit opt-in — pass the same `OpenAPIObject` you already have from
|
|
64
|
+
* `SwaggerModule.createDocument()`. Its `servers[]` becomes the proxy's allowlist;
|
|
65
|
+
* there is deliberately no implicit "same origin as this request" fallback (that would
|
|
66
|
+
* be derived from client-controlled headers, an SSRF risk — see docfy-ui.module.ts).
|
|
67
|
+
* Only absolute server URLs count. Omit entirely to leave the proxy disabled (no new
|
|
68
|
+
* route registered at all).
|
|
69
|
+
*/
|
|
70
|
+
openApiDocument?: {
|
|
71
|
+
servers?: {
|
|
72
|
+
url: string;
|
|
73
|
+
}[];
|
|
74
|
+
};
|
|
75
|
+
/** Extra allowed origins for the proxy, beyond what `openApiDocument.servers` declares. */
|
|
76
|
+
additionalProxyOrigins?: string[];
|
|
59
77
|
}
|
|
60
78
|
/**
|
|
61
79
|
* Serves the published `docfy-ui` package's static build at `mountPath`,
|
package/dist/docfy-ui.module.js
CHANGED
|
@@ -37,6 +37,7 @@ exports.DocfyUiModule = void 0;
|
|
|
37
37
|
const fs = __importStar(require("fs"));
|
|
38
38
|
const path = __importStar(require("path"));
|
|
39
39
|
const express = __importStar(require("express"));
|
|
40
|
+
const proxy_handler_1 = require("./proxy-handler");
|
|
40
41
|
function loadFastifyStatic() {
|
|
41
42
|
try {
|
|
42
43
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
@@ -72,15 +73,35 @@ class DocfyUiModule {
|
|
|
72
73
|
res.send(specJson);
|
|
73
74
|
});
|
|
74
75
|
}
|
|
76
|
+
const basePath = mountPath === '/' ? '/' : `${mountPath.replace(/\/+$/, '')}/`;
|
|
77
|
+
let proxyPath;
|
|
78
|
+
if (options.openApiDocument || options.additionalProxyOrigins) {
|
|
79
|
+
const allowedOrigins = (0, proxy_handler_1.buildAllowedOrigins)(options.openApiDocument?.servers, options.additionalProxyOrigins);
|
|
80
|
+
if (allowedOrigins.size === 0) {
|
|
81
|
+
console.warn('DocfyUiModule.setup(): "Try it out" proxy enabled but no absolute server URLs were found — ' +
|
|
82
|
+
'every request will be rejected. Declare an absolute URL in your OpenAPI "servers" array ' +
|
|
83
|
+
'(or pass `additionalProxyOrigins`) to allow it.');
|
|
84
|
+
}
|
|
85
|
+
proxyPath = `${basePath}__docfy_proxy`.replace(/\/+/g, '/');
|
|
86
|
+
httpAdapter.post(proxyPath, (req, res) => {
|
|
87
|
+
(0, proxy_handler_1.readJsonBody)(req)
|
|
88
|
+
.then((body) => (0, proxy_handler_1.handleProxyRequest)(body, allowedOrigins, res))
|
|
89
|
+
.catch((err) => {
|
|
90
|
+
console.error('DocfyUiModule: "Try it out" proxy handler failed unexpectedly:', err);
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
}
|
|
75
94
|
const indexHtmlPath = require.resolve('docfy-ui/dist/index.html');
|
|
76
95
|
const uiDir = path.dirname(indexHtmlPath);
|
|
77
|
-
const basePath = mountPath === '/' ? '/' : `${mountPath.replace(/\/+$/, '')}/`;
|
|
78
96
|
const specsScript = options.specs
|
|
79
97
|
? `\n <script>window.__DOCFY_SPECS__ = ${JSON.stringify(options.specs)};</script>`
|
|
80
98
|
: '';
|
|
99
|
+
const proxyScript = proxyPath
|
|
100
|
+
? `\n <script>window.__DOCFY_PROXY_PATH__ = ${JSON.stringify(proxyPath)};</script>`
|
|
101
|
+
: '';
|
|
81
102
|
const indexHtml = fs
|
|
82
103
|
.readFileSync(indexHtmlPath, 'utf8')
|
|
83
|
-
.replace('<head>', `<head>\n <base href="${basePath}" />\n <script>window.__DOCFY_BASE_PATH__ = ${JSON.stringify(basePath)};</script>${specsScript}`);
|
|
104
|
+
.replace('<head>', `<head>\n <base href="${basePath}" />\n <script>window.__DOCFY_BASE_PATH__ = ${JSON.stringify(basePath)};</script>${specsScript}${proxyScript}`);
|
|
84
105
|
if (isFastify) {
|
|
85
106
|
const fastifyStatic = loadFastifyStatic();
|
|
86
107
|
const instance = httpAdapter.getInstance();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"docfy-ui.module.js","sourceRoot":"","sources":["../src/docfy-ui.module.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uCAAyB;AACzB,2CAA6B;AAC7B,iDAAmC;
|
|
1
|
+
{"version":3,"file":"docfy-ui.module.js","sourceRoot":"","sources":["../src/docfy-ui.module.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uCAAyB;AACzB,2CAA6B;AAC7B,iDAAmC;AACnC,mDAA4G;AAkF5G,SAAS,iBAAiB;IACxB,IAAI,CAAC;QACH,iEAAiE;QACjE,OAAO,OAAO,CAAC,iBAAiB,CAAC,CAAC;IACpC,CAAC;IAAC,MAAM,CAA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AAM,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE;gBACtB,MAAM,CAAC,QAAQ,CAAC,aAAa,EAAE;oBAC7B,IAAI,EAAE,KAAK;oBACX,gEAAgE;oBAChE,+DAA+D;oBAC/D,QAAQ,EAAE,KAAK;oBACf,gEAAgE;oBAChE,oDAAoD;oBACpD,6DAA6D;oBAC7D,YAAY;oBACZ,KAAK,EAAE,KAAK;oBACZ,aAAa,EAAE,KAAK;iBACrB,CAAC,CAAC;gBACH,MAAM,CAAC,kBAAkB,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;oBACxC,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;gBAC1C,CAAC,CAAC,CAAC;gBACH,IAAI,EAAE,CAAC;YACT,CAAC,EACD,EAAE,MAAM,EAAE,SAAS,EAAE,CACtB,CAAC;YACF,OAAO;QACT,CAAC;QAED,wEAAwE;QACxE,+DAA+D;QAC/D,2CAA2C;QAC3C,GAAG,CAAC,GAAG,CAAC,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;QAC5D,GAAG,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,IAAqB,EAAE,GAAqB,EAAE,EAAE;YAClE,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YACtB,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACtB,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAtFD,sCAsFC"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export declare const PROXY_ERROR_HEADER = "x-docfy-proxy-error";
|
|
2
|
+
interface RawRequestLike {
|
|
3
|
+
body?: unknown;
|
|
4
|
+
on(event: 'data' | 'end' | 'error', listener: (arg?: unknown) => void): unknown;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Reads the proxy envelope from the request. Prefers an already-parsed `req.body` (Fastify
|
|
8
|
+
* parses JSON bodies unconditionally as a core feature, so this is always populated there;
|
|
9
|
+
* Express only populates it if a JSON body-parser middleware happened to run *before* this
|
|
10
|
+
* route in the stack — not something `DocfyUiModule.setup()` can guarantee, since it's called
|
|
11
|
+
* directly against the app's HTTP adapter, outside Nest's own route pipeline). Falls back to
|
|
12
|
+
* reading and parsing the raw stream itself so Express works with no assumptions either way.
|
|
13
|
+
*/
|
|
14
|
+
export declare function readJsonBody(req: RawRequestLike): Promise<unknown>;
|
|
15
|
+
export interface ProxyRequestBody {
|
|
16
|
+
method?: string;
|
|
17
|
+
url?: string;
|
|
18
|
+
headers?: Record<string, string>;
|
|
19
|
+
body?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface ProxyResponderLike {
|
|
22
|
+
status(code: number): this;
|
|
23
|
+
header(name: string, value: string): this;
|
|
24
|
+
send(body: string): unknown;
|
|
25
|
+
}
|
|
26
|
+
/** Builds the allowlist of origins the proxy is permitted to forward requests to.
|
|
27
|
+
* Only absolute server URLs count — see docfy-ui.module.ts for why there's no
|
|
28
|
+
* implicit "same origin as this request" fallback. */
|
|
29
|
+
export declare function buildAllowedOrigins(servers: {
|
|
30
|
+
url: string;
|
|
31
|
+
}[] | undefined, additional: string[] | undefined): Set<string>;
|
|
32
|
+
/**
|
|
33
|
+
* Validates and forwards a "Try it out" request to its real target, server-to-server —
|
|
34
|
+
* the browser only ever talks to this same-origin endpoint, so CORS never applies.
|
|
35
|
+
* Success responses are passed through transparently (real status/headers/body from the
|
|
36
|
+
* target); only proxy-level failures set `X-Docfy-Proxy-Error` so the client can tell the
|
|
37
|
+
* two apart.
|
|
38
|
+
*/
|
|
39
|
+
export declare function handleProxyRequest(requestBody: unknown, allowedOrigins: Set<string>, res: ProxyResponderLike): Promise<void>;
|
|
40
|
+
export {};
|
|
@@ -0,0 +1,213 @@
|
|
|
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.PROXY_ERROR_HEADER = void 0;
|
|
37
|
+
exports.readJsonBody = readJsonBody;
|
|
38
|
+
exports.buildAllowedOrigins = buildAllowedOrigins;
|
|
39
|
+
exports.handleProxyRequest = handleProxyRequest;
|
|
40
|
+
const http = __importStar(require("http"));
|
|
41
|
+
const https = __importStar(require("https"));
|
|
42
|
+
const MAX_BODY_BYTES = 10 * 1024 * 1024; // 10MB
|
|
43
|
+
const TIMEOUT_MS = 20000;
|
|
44
|
+
const ALLOWED_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
|
|
45
|
+
// Stripped in both directions — connection-management headers make no sense relayed
|
|
46
|
+
// through a second hop, `transfer-encoding`/`content-length` would corrupt a buffered
|
|
47
|
+
// body relayed as a fresh single write, and `content-encoding` is dropped because the
|
|
48
|
+
// response is buffered/decoded as raw bytes here (no zlib re-encoding) — forwarding a
|
|
49
|
+
// compressed body labeled with its original encoding would make the browser fail to
|
|
50
|
+
// (or wrongly) decode it.
|
|
51
|
+
const HOP_BY_HOP_HEADERS = new Set([
|
|
52
|
+
'connection',
|
|
53
|
+
'keep-alive',
|
|
54
|
+
'transfer-encoding',
|
|
55
|
+
'content-length',
|
|
56
|
+
'content-encoding',
|
|
57
|
+
'upgrade',
|
|
58
|
+
'proxy-authorization',
|
|
59
|
+
'proxy-authenticate',
|
|
60
|
+
'te',
|
|
61
|
+
'trailer',
|
|
62
|
+
]);
|
|
63
|
+
exports.PROXY_ERROR_HEADER = 'x-docfy-proxy-error';
|
|
64
|
+
/**
|
|
65
|
+
* Reads the proxy envelope from the request. Prefers an already-parsed `req.body` (Fastify
|
|
66
|
+
* parses JSON bodies unconditionally as a core feature, so this is always populated there;
|
|
67
|
+
* Express only populates it if a JSON body-parser middleware happened to run *before* this
|
|
68
|
+
* route in the stack — not something `DocfyUiModule.setup()` can guarantee, since it's called
|
|
69
|
+
* directly against the app's HTTP adapter, outside Nest's own route pipeline). Falls back to
|
|
70
|
+
* reading and parsing the raw stream itself so Express works with no assumptions either way.
|
|
71
|
+
*/
|
|
72
|
+
function readJsonBody(req) {
|
|
73
|
+
if (req.body !== undefined)
|
|
74
|
+
return Promise.resolve(req.body);
|
|
75
|
+
return new Promise((resolve) => {
|
|
76
|
+
let raw = '';
|
|
77
|
+
req.on('data', (chunk) => {
|
|
78
|
+
raw += chunk;
|
|
79
|
+
});
|
|
80
|
+
req.on('end', () => {
|
|
81
|
+
try {
|
|
82
|
+
resolve(raw ? JSON.parse(raw) : undefined);
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
resolve(undefined);
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
req.on('error', () => resolve(undefined));
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
/** Builds the allowlist of origins the proxy is permitted to forward requests to.
|
|
92
|
+
* Only absolute server URLs count — see docfy-ui.module.ts for why there's no
|
|
93
|
+
* implicit "same origin as this request" fallback. */
|
|
94
|
+
function buildAllowedOrigins(servers, additional) {
|
|
95
|
+
const origins = new Set();
|
|
96
|
+
for (const url of [...(servers ?? []).map((s) => s.url), ...(additional ?? [])]) {
|
|
97
|
+
try {
|
|
98
|
+
origins.add(new URL(url).origin);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
// Relative or malformed server URL — no safe base to resolve it against, skip.
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return origins;
|
|
105
|
+
}
|
|
106
|
+
function sendProxyError(res, status, error, message) {
|
|
107
|
+
res
|
|
108
|
+
.status(status)
|
|
109
|
+
.header(exports.PROXY_ERROR_HEADER, error)
|
|
110
|
+
.header('Content-Type', 'application/json')
|
|
111
|
+
.send(JSON.stringify({ error, message }));
|
|
112
|
+
}
|
|
113
|
+
function filterHeaders(headers) {
|
|
114
|
+
const result = {};
|
|
115
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
116
|
+
if (value === undefined || HOP_BY_HOP_HEADERS.has(name.toLowerCase()))
|
|
117
|
+
continue;
|
|
118
|
+
result[name] = Array.isArray(value) ? value.join(', ') : value;
|
|
119
|
+
}
|
|
120
|
+
return result;
|
|
121
|
+
}
|
|
122
|
+
function forward(target, method, headers, body) {
|
|
123
|
+
return new Promise((resolve, reject) => {
|
|
124
|
+
const transport = target.protocol === 'https:' ? https : http;
|
|
125
|
+
// Force uncompressed responses — the body is buffered as raw bytes below with no
|
|
126
|
+
// zlib decoding, so a compressed response would otherwise come through corrupted.
|
|
127
|
+
const outgoingHeaders = { ...headers, 'accept-encoding': 'identity' };
|
|
128
|
+
const req = transport.request(target, { method, headers: outgoingHeaders, timeout: TIMEOUT_MS }, (res) => {
|
|
129
|
+
const chunks = [];
|
|
130
|
+
let receivedBytes = 0;
|
|
131
|
+
let truncated = false;
|
|
132
|
+
res.on('data', (chunk) => {
|
|
133
|
+
receivedBytes += chunk.length;
|
|
134
|
+
if (receivedBytes > MAX_BODY_BYTES) {
|
|
135
|
+
truncated = true;
|
|
136
|
+
res.destroy();
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
chunks.push(chunk);
|
|
140
|
+
});
|
|
141
|
+
res.on('end', () => {
|
|
142
|
+
if (truncated) {
|
|
143
|
+
reject(new Error('Response body exceeded the proxy size limit.'));
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
resolve({
|
|
147
|
+
status: res.statusCode ?? 502,
|
|
148
|
+
headers: res.headers,
|
|
149
|
+
bodyText: Buffer.concat(chunks).toString('utf8'),
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
res.on('error', reject);
|
|
153
|
+
});
|
|
154
|
+
req.on('timeout', () => req.destroy(new Error('Request to the target API timed out.')));
|
|
155
|
+
req.on('error', reject);
|
|
156
|
+
if (body)
|
|
157
|
+
req.write(body);
|
|
158
|
+
req.end();
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Validates and forwards a "Try it out" request to its real target, server-to-server —
|
|
163
|
+
* the browser only ever talks to this same-origin endpoint, so CORS never applies.
|
|
164
|
+
* Success responses are passed through transparently (real status/headers/body from the
|
|
165
|
+
* target); only proxy-level failures set `X-Docfy-Proxy-Error` so the client can tell the
|
|
166
|
+
* two apart.
|
|
167
|
+
*/
|
|
168
|
+
async function handleProxyRequest(requestBody, allowedOrigins, res) {
|
|
169
|
+
if (!requestBody || typeof requestBody !== 'object') {
|
|
170
|
+
sendProxyError(res, 400, 'bad_request', 'Missing or malformed JSON body.');
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const { method, url, headers, body } = requestBody;
|
|
174
|
+
if (!method || !url) {
|
|
175
|
+
sendProxyError(res, 400, 'bad_request', 'Both "method" and "url" are required.');
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const upperMethod = method.toUpperCase();
|
|
179
|
+
if (!ALLOWED_METHODS.has(upperMethod)) {
|
|
180
|
+
sendProxyError(res, 400, 'bad_request', `Unsupported method "${method}".`);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
let target;
|
|
184
|
+
try {
|
|
185
|
+
target = new URL(url);
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
sendProxyError(res, 400, 'invalid_url', `"${url}" is not a valid URL.`);
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (target.protocol !== 'http:' && target.protocol !== 'https:') {
|
|
192
|
+
sendProxyError(res, 400, 'invalid_url', `Unsupported protocol "${target.protocol}".`);
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (!allowedOrigins.has(target.origin)) {
|
|
196
|
+
sendProxyError(res, 403, 'origin_not_allowed', `"${target.origin}" is not in the allowed server list for this API. Declare it in your OpenAPI "servers" array to allow it.`);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
try {
|
|
200
|
+
const result = await forward(target, upperMethod, filterHeaders(headers ?? {}), body);
|
|
201
|
+
res.status(result.status);
|
|
202
|
+
for (const [name, value] of Object.entries(filterHeaders(result.headers))) {
|
|
203
|
+
res.header(name, value);
|
|
204
|
+
}
|
|
205
|
+
res.send(result.bodyText);
|
|
206
|
+
}
|
|
207
|
+
catch (err) {
|
|
208
|
+
const message = err instanceof Error ? err.message : 'Unknown error reaching the target API.';
|
|
209
|
+
const isTimeout = message.includes('timed out');
|
|
210
|
+
sendProxyError(res, isTimeout ? 504 : 502, isTimeout ? 'timeout' : 'network_error', message);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
//# sourceMappingURL=proxy-handler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"proxy-handler.js","sourceRoot":"","sources":["../src/proxy-handler.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,oCAiBC;AAkBD,kDAaC;AA+ED,gDAwDC;AAhOD,2CAA6B;AAC7B,6CAA+B;AAE/B,MAAM,cAAc,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC,CAAC,OAAO;AAChD,MAAM,UAAU,GAAG,KAAM,CAAC;AAC1B,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;AAE9F,oFAAoF;AACpF,sFAAsF;AACtF,sFAAsF;AACtF,sFAAsF;AACtF,oFAAoF;AACpF,0BAA0B;AAC1B,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC;IACjC,YAAY;IACZ,YAAY;IACZ,mBAAmB;IACnB,gBAAgB;IAChB,kBAAkB;IAClB,SAAS;IACT,qBAAqB;IACrB,oBAAoB;IACpB,IAAI;IACJ,SAAS;CACV,CAAC,CAAC;AAEU,QAAA,kBAAkB,GAAG,qBAAqB,CAAC;AAOxD;;;;;;;GAOG;AACH,SAAgB,YAAY,CAAC,GAAmB;IAC9C,IAAI,GAAG,CAAC,IAAI,KAAK,SAAS;QAAE,OAAO,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAE7D,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,IAAI,GAAG,GAAG,EAAE,CAAC;QACb,GAAG,CA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;QACF,OAAO;IACT,CAAC;IAED,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,MAAM,EAAE,WAAW,EAAE,aAAa,CAAC,OAAO,IAAI,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC;QACtF,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC1B,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC;YAC1E,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAC1B,CAAC;QACD,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAC5B,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,OAAO,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,wCAAwC,CAAC;QAC9F,MAAM,SAAS,GAAG,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;QAChD,cAAc,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,eAAe,EAAE,OAAO,CAAC,CAAC;IAC/F,CAAC;AACH,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nestjs-docfy",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.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.
|
|
119
|
+
"docfy-ui": "^0.4.0",
|
|
120
120
|
"express": "^5.0.0",
|
|
121
121
|
"openapi-typescript": "^7.13.0",
|
|
122
122
|
"picocolors": "^1.1.1",
|