@klnap/next-proxy-chain 1.1.1 → 2.0.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/CHANGELOG.md +20 -0
- package/README.md +195 -79
- package/dist/index.cjs +956 -258
- package/dist/index.d.cts +164 -82
- package/dist/index.d.ts +164 -82
- package/dist/index.js +954 -254
- package/package.json +35 -22
package/dist/index.js
CHANGED
|
@@ -20,7 +20,7 @@ var DEFAULT_BLOCKED_REQUEST_HEADERS = Object.freeze([
|
|
|
20
20
|
"x-middleware-next",
|
|
21
21
|
"x-middleware-override-headers"
|
|
22
22
|
]);
|
|
23
|
-
var
|
|
23
|
+
var DEFINED_HANDLER = /* @__PURE__ */ Symbol.for("proxy-chain.defined-handler");
|
|
24
24
|
|
|
25
25
|
// src/core/actions.ts
|
|
26
26
|
function next(options = {}) {
|
|
@@ -31,11 +31,88 @@ function isNextResult(value) {
|
|
|
31
31
|
}
|
|
32
32
|
|
|
33
33
|
// src/core/engine.ts
|
|
34
|
-
import { NextRequest, NextResponse as NextResponse2 } from "next/server";
|
|
34
|
+
import { NextRequest, NextResponse as NextResponse2 } from "next/server.js";
|
|
35
35
|
|
|
36
36
|
// src/core/context.ts
|
|
37
|
-
|
|
38
|
-
|
|
37
|
+
var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
|
|
38
|
+
"requestId",
|
|
39
|
+
"startedAt",
|
|
40
|
+
"elapsedMs",
|
|
41
|
+
"originalUrl",
|
|
42
|
+
"originalPathname",
|
|
43
|
+
"originalHostname",
|
|
44
|
+
"signal"
|
|
45
|
+
]);
|
|
46
|
+
function createRequestMetadata(request, requestId, startedAt, invocationStartedAt) {
|
|
47
|
+
const metadata = /* @__PURE__ */ Object.create(null);
|
|
48
|
+
Object.defineProperties(metadata, {
|
|
49
|
+
requestId: { value: requestId, enumerable: true },
|
|
50
|
+
startedAt: { value: startedAt, enumerable: true },
|
|
51
|
+
elapsedMs: {
|
|
52
|
+
get: () => performance.now() - invocationStartedAt,
|
|
53
|
+
enumerable: true
|
|
54
|
+
},
|
|
55
|
+
originalUrl: { value: request.url, enumerable: true },
|
|
56
|
+
originalPathname: { value: request.nextUrl.pathname, enumerable: true },
|
|
57
|
+
originalHostname: { value: request.nextUrl.hostname, enumerable: true }
|
|
58
|
+
});
|
|
59
|
+
return metadata;
|
|
60
|
+
}
|
|
61
|
+
function createApplicationState() {
|
|
62
|
+
return /* @__PURE__ */ Object.create(null);
|
|
63
|
+
}
|
|
64
|
+
function createHandlerContext(metadata, applicationState, signal) {
|
|
65
|
+
const target = /* @__PURE__ */ Object.create(null);
|
|
66
|
+
Object.defineProperties(target, {
|
|
67
|
+
requestId: { value: metadata.requestId, enumerable: true },
|
|
68
|
+
startedAt: { value: metadata.startedAt, enumerable: true },
|
|
69
|
+
elapsedMs: { get: () => metadata.elapsedMs, enumerable: true },
|
|
70
|
+
originalUrl: { value: metadata.originalUrl, enumerable: true },
|
|
71
|
+
originalPathname: { value: metadata.originalPathname, enumerable: true },
|
|
72
|
+
originalHostname: { value: metadata.originalHostname, enumerable: true },
|
|
73
|
+
signal: { value: signal, enumerable: true }
|
|
74
|
+
});
|
|
75
|
+
return new Proxy(target, {
|
|
76
|
+
get(view, property) {
|
|
77
|
+
return Reflect.has(view, property) ? Reflect.get(view, property, view) : Reflect.get(applicationState, property, applicationState);
|
|
78
|
+
},
|
|
79
|
+
set(_view, property, value) {
|
|
80
|
+
if (RESERVED_CONTEXT_KEYS.has(property)) return false;
|
|
81
|
+
return Reflect.set(applicationState, property, value, applicationState);
|
|
82
|
+
},
|
|
83
|
+
deleteProperty(_view, property) {
|
|
84
|
+
if (RESERVED_CONTEXT_KEYS.has(property)) return false;
|
|
85
|
+
return Reflect.deleteProperty(applicationState, property);
|
|
86
|
+
},
|
|
87
|
+
defineProperty(_view, property, descriptor) {
|
|
88
|
+
if (RESERVED_CONTEXT_KEYS.has(property)) return false;
|
|
89
|
+
return Reflect.defineProperty(applicationState, property, {
|
|
90
|
+
...descriptor,
|
|
91
|
+
configurable: true
|
|
92
|
+
});
|
|
93
|
+
},
|
|
94
|
+
getPrototypeOf() {
|
|
95
|
+
return null;
|
|
96
|
+
},
|
|
97
|
+
setPrototypeOf() {
|
|
98
|
+
return false;
|
|
99
|
+
},
|
|
100
|
+
has(view, property) {
|
|
101
|
+
return Reflect.has(view, property) || Reflect.has(applicationState, property);
|
|
102
|
+
},
|
|
103
|
+
ownKeys(view) {
|
|
104
|
+
return [.../* @__PURE__ */ new Set([...Reflect.ownKeys(view), ...Reflect.ownKeys(applicationState)])];
|
|
105
|
+
},
|
|
106
|
+
getOwnPropertyDescriptor(view, property) {
|
|
107
|
+
const descriptor = Reflect.getOwnPropertyDescriptor(view, property);
|
|
108
|
+
if (descriptor) return descriptor;
|
|
109
|
+
const applicationDescriptor = Reflect.getOwnPropertyDescriptor(applicationState, property);
|
|
110
|
+
return applicationDescriptor ? { ...applicationDescriptor, configurable: true } : void 0;
|
|
111
|
+
},
|
|
112
|
+
preventExtensions() {
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
});
|
|
39
116
|
}
|
|
40
117
|
|
|
41
118
|
// src/core/headers.ts
|
|
@@ -180,30 +257,6 @@ function applyMergedToResponse(res, headers, cookies, dropHeaders) {
|
|
|
180
257
|
}
|
|
181
258
|
}
|
|
182
259
|
|
|
183
|
-
// src/core/host-folder-prefix.ts
|
|
184
|
-
function physicalFolderPrefix(raw) {
|
|
185
|
-
return "/" + raw.replace(/^\/+|\/+$/g, "").split("/").filter((seg) => !/^\(.*\)$/.test(seg)).join("/");
|
|
186
|
-
}
|
|
187
|
-
function isInsideFolder(pathname, folder) {
|
|
188
|
-
if (folder === "/") return true;
|
|
189
|
-
return pathname === folder || pathname.startsWith(`${folder}/`);
|
|
190
|
-
}
|
|
191
|
-
function applyFolderPrefix(rewriteUrl, folder, baseUrl) {
|
|
192
|
-
try {
|
|
193
|
-
const parsed = new URL(rewriteUrl, baseUrl);
|
|
194
|
-
if (!isInsideFolder(parsed.pathname, folder)) {
|
|
195
|
-
parsed.pathname = folder + (parsed.pathname === "/" ? "" : parsed.pathname);
|
|
196
|
-
return parsed.toString();
|
|
197
|
-
}
|
|
198
|
-
return rewriteUrl;
|
|
199
|
-
} catch {
|
|
200
|
-
if (!isInsideFolder(rewriteUrl, folder)) {
|
|
201
|
-
return folder + (rewriteUrl === "/" ? "" : rewriteUrl);
|
|
202
|
-
}
|
|
203
|
-
return rewriteUrl;
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
|
|
207
260
|
// src/core/logger.ts
|
|
208
261
|
var LEVEL_RANK = {
|
|
209
262
|
debug: 10,
|
|
@@ -230,22 +283,215 @@ function createConsoleLogger(minLevel = "info") {
|
|
|
230
283
|
error: write("error")
|
|
231
284
|
};
|
|
232
285
|
}
|
|
233
|
-
|
|
286
|
+
|
|
287
|
+
// src/core/diagnostics/sanitize.ts
|
|
288
|
+
var MAX_TEXT_LENGTH = 160;
|
|
289
|
+
function safeDiagnosticText(value, limit = MAX_TEXT_LENGTH) {
|
|
290
|
+
let output = "";
|
|
291
|
+
for (const char of value) {
|
|
292
|
+
const code = char.codePointAt(0);
|
|
293
|
+
if (code === 27 || code < 32 || code >= 127 && code <= 159 || code === 173 || code === 1564 || code === 6158 || code >= 8203 && code <= 8207 || code >= 8232 && code <= 8238 || code >= 8288 && code <= 8303 || code === 65279) {
|
|
294
|
+
output += "\uFFFD";
|
|
295
|
+
} else {
|
|
296
|
+
output += char;
|
|
297
|
+
}
|
|
298
|
+
if (output.length >= limit) return `${output.slice(0, limit)}\u2026`;
|
|
299
|
+
}
|
|
300
|
+
return output;
|
|
301
|
+
}
|
|
302
|
+
function safeDestination(value) {
|
|
303
|
+
if (!value) return void 0;
|
|
304
|
+
try {
|
|
305
|
+
const url = new URL(value, "http://proxy-chain.invalid");
|
|
306
|
+
return safeDiagnosticText(`${url.pathname}${url.search ? "?[query]" : ""}`);
|
|
307
|
+
} catch {
|
|
308
|
+
return safeDiagnosticText(value.split(/[?#]/, 1)[0] ?? "");
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// src/core/diagnostics/formatter.ts
|
|
313
|
+
function runtime() {
|
|
314
|
+
return globalThis.process;
|
|
315
|
+
}
|
|
316
|
+
function shouldUseColor() {
|
|
317
|
+
const process = runtime();
|
|
318
|
+
const env = process?.env;
|
|
319
|
+
if (env?.NO_COLOR) return false;
|
|
320
|
+
if (env?.FORCE_COLOR) return env.FORCE_COLOR !== "0";
|
|
321
|
+
if (env?.CI || env?.TERM === "dumb" || !process?.stdout?.isTTY) return false;
|
|
322
|
+
try {
|
|
323
|
+
return process.stdout.getColorDepth?.() !== 1;
|
|
324
|
+
} catch {
|
|
325
|
+
return false;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
function supportsUnicode() {
|
|
329
|
+
const process = runtime();
|
|
330
|
+
if (!process?.env) return false;
|
|
331
|
+
const env = process.env;
|
|
332
|
+
const locale = (env.LC_ALL || env.LC_CTYPE || env.LANG || "").toLowerCase();
|
|
333
|
+
return !/(^|\s)(c|posix)(\.|$|\s)/.test(locale) && !locale.includes("ascii");
|
|
334
|
+
}
|
|
335
|
+
function paint(text, code, enabled) {
|
|
336
|
+
return enabled ? `\x1B[${code}m${text}\x1B[0m` : text;
|
|
337
|
+
}
|
|
338
|
+
function duration(ms) {
|
|
234
339
|
return `${ms.toFixed(2)}ms`;
|
|
235
340
|
}
|
|
236
|
-
function
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
341
|
+
function handlerLabel(handler) {
|
|
342
|
+
switch (handler.outcome) {
|
|
343
|
+
case "continue":
|
|
344
|
+
return { symbol: "\u2713", text: "continue", color: 32 };
|
|
345
|
+
case "rewrite":
|
|
346
|
+
return { symbol: "\u21AA", text: "rewrite", color: 36 };
|
|
347
|
+
case "redirect":
|
|
348
|
+
return { symbol: "\u2197", text: "redirect", color: 33 };
|
|
349
|
+
case "response":
|
|
350
|
+
return { symbol: "\u2713", text: `response ${handler.status}`, color: 32 };
|
|
351
|
+
case "skipped":
|
|
352
|
+
return { symbol: "\u25CB", text: "skipped", color: 2 };
|
|
353
|
+
case "not-reached":
|
|
354
|
+
return { symbol: "\u2013", text: "not reached", color: 2 };
|
|
355
|
+
case "recovered":
|
|
356
|
+
return { symbol: "!", text: "recovered", color: 33 };
|
|
357
|
+
case "timeout":
|
|
358
|
+
return { symbol: "\xD7", text: "timeout", color: 31 };
|
|
359
|
+
case "request-cancelled":
|
|
360
|
+
return { symbol: "\u2298", text: "request cancelled", color: 33 };
|
|
361
|
+
case "failed":
|
|
362
|
+
return { symbol: "\xD7", text: "failed", color: 31 };
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
function outcomeText(outcome) {
|
|
366
|
+
switch (outcome.type) {
|
|
367
|
+
case "next":
|
|
368
|
+
return "NEXT";
|
|
369
|
+
case "rewrite":
|
|
370
|
+
return `REWRITE ${outcome.destination}`;
|
|
371
|
+
case "redirect":
|
|
372
|
+
return `REDIRECT ${outcome.status}${outcome.destination ? ` ${outcome.destination}` : ""}`;
|
|
373
|
+
case "response":
|
|
374
|
+
return `RESPONSE ${outcome.status}`;
|
|
375
|
+
case "error":
|
|
376
|
+
return `ERROR ${outcome.status}`;
|
|
377
|
+
case "timeout":
|
|
378
|
+
return `ERROR ${outcome.status} \xB7 timeout ${outcome.timeoutMs}ms`;
|
|
379
|
+
case "request-cancelled":
|
|
380
|
+
return "REQUEST CANCELLED";
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
function outcomeColor(outcome) {
|
|
384
|
+
switch (outcome.type) {
|
|
243
385
|
case "next":
|
|
244
|
-
return
|
|
245
|
-
case "
|
|
246
|
-
return
|
|
386
|
+
return 32;
|
|
387
|
+
case "rewrite":
|
|
388
|
+
return 36;
|
|
389
|
+
case "redirect":
|
|
390
|
+
return 33;
|
|
391
|
+
case "error":
|
|
392
|
+
case "timeout":
|
|
393
|
+
return 31;
|
|
394
|
+
case "request-cancelled":
|
|
395
|
+
return 33;
|
|
396
|
+
case "response":
|
|
397
|
+
return outcome.status >= 500 ? 31 : 32;
|
|
247
398
|
}
|
|
248
399
|
}
|
|
400
|
+
function formatTrace(trace, level, color = shouldUseColor(), unicode = true) {
|
|
401
|
+
const path2 = trace.pathname ? ` ${safeDiagnosticText(trace.pathname)}` : "";
|
|
402
|
+
const header = `[proxy-chain] ${safeDiagnosticText(trace.method)}${path2}`;
|
|
403
|
+
const rows = [];
|
|
404
|
+
const handlers = trace.handlers;
|
|
405
|
+
if (level === "compact") {
|
|
406
|
+
const reached = handlers.filter((handler) => handler.outcome !== "not-reached").length;
|
|
407
|
+
return `[proxy-chain] ${safeDiagnosticText(trace.requestId)} \xB7 ${safeDiagnosticText(trace.method)}${path2} \xB7 ${paint(outcomeText(trace.outcome), outcomeColor(trace.outcome), color)} \xB7 ${paint(duration(trace.durationMs), 2, color)} \xB7 ${reached}/${handlers.length} handlers`;
|
|
408
|
+
}
|
|
409
|
+
rows.push(header);
|
|
410
|
+
rows.push(` Request: ${safeDiagnosticText(trace.requestId, 64)}`);
|
|
411
|
+
const shown = handlers;
|
|
412
|
+
const symbols = unicode ? {
|
|
413
|
+
pass: "\u2502",
|
|
414
|
+
last: "\u2514",
|
|
415
|
+
continue: "\u2713",
|
|
416
|
+
rewrite: "\u21AA",
|
|
417
|
+
redirect: "\u2197",
|
|
418
|
+
skip: "\u25CB",
|
|
419
|
+
missing: "\u2013",
|
|
420
|
+
error: "\xD7",
|
|
421
|
+
cancelled: "\u2298",
|
|
422
|
+
recovered: "!"
|
|
423
|
+
} : {
|
|
424
|
+
pass: "|",
|
|
425
|
+
last: "`-",
|
|
426
|
+
continue: "+",
|
|
427
|
+
rewrite: "->",
|
|
428
|
+
redirect: "->",
|
|
429
|
+
skip: "o",
|
|
430
|
+
missing: "-",
|
|
431
|
+
error: "x",
|
|
432
|
+
cancelled: "!",
|
|
433
|
+
recovered: "!"
|
|
434
|
+
};
|
|
435
|
+
for (let index = 0; index < shown.length; index++) {
|
|
436
|
+
const handler = shown[index];
|
|
437
|
+
const label = handlerLabel(handler);
|
|
438
|
+
const symbol = handler.outcome === "continue" ? symbols.continue : handler.outcome === "rewrite" ? symbols.rewrite : handler.outcome === "redirect" ? symbols.redirect : handler.outcome === "skipped" ? symbols.skip : handler.outcome === "not-reached" ? symbols.missing : handler.outcome === "recovered" ? symbols.recovered : handler.outcome === "request-cancelled" ? symbols.cancelled : symbols.error;
|
|
439
|
+
const prefix = symbols.pass;
|
|
440
|
+
const name = safeDiagnosticText(handler.name, 32);
|
|
441
|
+
const time = "durationMs" in handler ? paint(duration(handler.durationMs), 2, color) : "";
|
|
442
|
+
rows.push(
|
|
443
|
+
`${prefix} ${paint(symbol, label.color, color)} ${name.padEnd(16)} ${label.text.padEnd(14)} ${time}`.trimEnd()
|
|
444
|
+
);
|
|
445
|
+
if (level === "verbose") {
|
|
446
|
+
if (handler.details?.timeoutMs !== void 0) {
|
|
447
|
+
rows.push(
|
|
448
|
+
`${symbols.pass} timeout: ${handler.details.timeoutMs}ms (${handler.details.timeoutSource ?? "chain"})`
|
|
449
|
+
);
|
|
450
|
+
}
|
|
451
|
+
if (handler.details?.include) {
|
|
452
|
+
rows.push(
|
|
453
|
+
`${symbols.pass} include: ${handler.details.include.join(", ")}${handler.details.includeResult ? ` (${handler.details.includeResult})` : ""}`
|
|
454
|
+
);
|
|
455
|
+
}
|
|
456
|
+
if (handler.details?.exclude) {
|
|
457
|
+
rows.push(
|
|
458
|
+
`${symbols.pass} exclude: ${handler.details.exclude.join(", ")}${handler.details.excludeResult ? ` (${handler.details.excludeResult})` : ""}`
|
|
459
|
+
);
|
|
460
|
+
}
|
|
461
|
+
if (handler.details?.when) {
|
|
462
|
+
rows.push(
|
|
463
|
+
`${symbols.pass} when: ${handler.details.when === "matched" ? "true" : handler.details.when === "false" ? "false" : "not evaluated"}`
|
|
464
|
+
);
|
|
465
|
+
}
|
|
466
|
+
if (handler.outcome === "continue") rows.push(`${symbols.pass} source: ${handler.source}`);
|
|
467
|
+
if (handler.outcome === "skipped") rows.push(`${symbols.pass} reason: ${handler.reason}`);
|
|
468
|
+
if (handler.outcome === "rewrite") {
|
|
469
|
+
rows.push(`${symbols.pass} destination: ${handler.destination}`);
|
|
470
|
+
}
|
|
471
|
+
if (handler.outcome === "redirect" && handler.destination) {
|
|
472
|
+
rows.push(`${symbols.pass} destination: ${handler.destination}`);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
if (handler.outcome === "recovered" || handler.outcome === "failed" || handler.outcome === "timeout" || handler.outcome === "request-cancelled") {
|
|
476
|
+
const policy = handler.policy === "none" ? "chain default" : handler.policy;
|
|
477
|
+
rows.push(
|
|
478
|
+
`${symbols.pass} ${handler.outcome === "request-cancelled" ? "cancellation policy" : "error policy"}: ${policy}`
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
if (handler.outcome === "timeout" && handler.timeoutMs !== void 0) {
|
|
482
|
+
rows.push(`${symbols.pass} deadline: ${handler.timeoutMs}ms`);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
rows.push(
|
|
486
|
+
`${symbols.last} ${paint(outcomeText(trace.outcome), outcomeColor(trace.outcome), color)}`
|
|
487
|
+
);
|
|
488
|
+
rows.push(` Total: ${paint(duration(trace.durationMs), 2, color)}`);
|
|
489
|
+
const output = rows.join("\n");
|
|
490
|
+
if (output.length <= 16384) return output;
|
|
491
|
+
const safeBoundary = output.lastIndexOf("\n", 16384);
|
|
492
|
+
return `${output.slice(0, safeBoundary < 0 ? 16384 : safeBoundary)}
|
|
493
|
+
${unicode ? "\u2026" : "..."} diagnostics truncated`;
|
|
494
|
+
}
|
|
249
495
|
|
|
250
496
|
// src/core/matching.ts
|
|
251
497
|
var RESERVED_FN_NAMES = /* @__PURE__ */ new Set(["", "proxy", "anonymous", "run", "next"]);
|
|
@@ -401,14 +647,25 @@ function withPaths(entry, filter) {
|
|
|
401
647
|
const exclude = compileScopes(filter.exclude);
|
|
402
648
|
const name = filter.name ?? base.name;
|
|
403
649
|
assertIncludeExcludeNoOverlap(include, exclude, name ?? "proxy");
|
|
404
|
-
return {
|
|
650
|
+
return {
|
|
651
|
+
run: base.run,
|
|
652
|
+
include,
|
|
653
|
+
exclude,
|
|
654
|
+
name,
|
|
655
|
+
debug: base.debug,
|
|
656
|
+
timeout: base.timeout,
|
|
657
|
+
when: base.when,
|
|
658
|
+
diagnosticRules: { include: filter.include, exclude: filter.exclude }
|
|
659
|
+
};
|
|
405
660
|
}
|
|
406
|
-
function
|
|
407
|
-
if (rule.exclude?.some((scope) => scopeMatches(pathname, hostname, scope)))
|
|
661
|
+
function ruleMatchReason(pathname, hostname, rule) {
|
|
662
|
+
if (rule.exclude?.some((scope) => scopeMatches(pathname, hostname, scope))) {
|
|
663
|
+
return "exclude-match";
|
|
664
|
+
}
|
|
408
665
|
if (rule.include && !rule.include.some((scope) => scopeMatches(pathname, hostname, scope))) {
|
|
409
|
-
return
|
|
666
|
+
return "include-mismatch";
|
|
410
667
|
}
|
|
411
|
-
return
|
|
668
|
+
return void 0;
|
|
412
669
|
}
|
|
413
670
|
function normalizeHost(raw) {
|
|
414
671
|
if (!raw) return null;
|
|
@@ -446,7 +703,7 @@ function assertIncludeExcludeNoOverlap(include, exclude, label) {
|
|
|
446
703
|
}
|
|
447
704
|
|
|
448
705
|
// src/core/pipeline.ts
|
|
449
|
-
import { NextResponse } from "next/server";
|
|
706
|
+
import { NextResponse } from "next/server.js";
|
|
450
707
|
function safeInternalError() {
|
|
451
708
|
return new NextResponse("Internal Server Error", {
|
|
452
709
|
status: 500,
|
|
@@ -527,14 +784,16 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
|
|
|
527
784
|
if (res instanceof NextResponse && res.headers.get("x-middleware-next") === "1") {
|
|
528
785
|
let request;
|
|
529
786
|
const decoded = decodeOverriddenRequestHeaders(res.headers);
|
|
530
|
-
|
|
787
|
+
const hasRequestOverride = res.headers.has("x-middleware-override-headers");
|
|
788
|
+
if (hasRequestOverride) {
|
|
531
789
|
const target = new Headers();
|
|
532
790
|
mergeRequestHeaderOverrides(target, decoded, requestHeaderPolicy);
|
|
533
|
-
|
|
791
|
+
request = target;
|
|
534
792
|
}
|
|
535
793
|
return {
|
|
536
794
|
kind: "continue",
|
|
537
795
|
request,
|
|
796
|
+
...hasRequestOverride ? { requestMode: "replace" } : {},
|
|
538
797
|
responseHeaders: responseHeaderItems(res.headers),
|
|
539
798
|
cookies: cookieItemsFromHeaders(res.headers)
|
|
540
799
|
};
|
|
@@ -543,14 +802,16 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
|
|
|
543
802
|
if (rewriteHeader && (res.status === 200 || !res.status)) {
|
|
544
803
|
let request;
|
|
545
804
|
const decoded = decodeOverriddenRequestHeaders(res.headers);
|
|
546
|
-
|
|
805
|
+
const hasRequestOverride = res.headers.has("x-middleware-override-headers");
|
|
806
|
+
if (hasRequestOverride) {
|
|
547
807
|
const target = new Headers();
|
|
548
808
|
mergeRequestHeaderOverrides(target, decoded, requestHeaderPolicy);
|
|
549
|
-
|
|
809
|
+
request = target;
|
|
550
810
|
}
|
|
551
811
|
return {
|
|
552
812
|
kind: "continue",
|
|
553
813
|
request,
|
|
814
|
+
...hasRequestOverride ? { requestMode: "replace" } : {},
|
|
554
815
|
responseHeaders: responseHeaderItems(res.headers),
|
|
555
816
|
cookies: cookieItemsFromHeaders(res.headers),
|
|
556
817
|
rewriteUrl: rewriteHeader
|
|
@@ -589,6 +850,7 @@ function finalizeResponse(res, headerWrites, cookieWrites, headerStrategy, cooki
|
|
|
589
850
|
}
|
|
590
851
|
|
|
591
852
|
// src/core/timeout.ts
|
|
853
|
+
var MAX_TIMEOUT_MS = 2147483647;
|
|
592
854
|
var RuleTimeoutError = class extends Error {
|
|
593
855
|
ruleName;
|
|
594
856
|
timeoutMs;
|
|
@@ -599,117 +861,281 @@ var RuleTimeoutError = class extends Error {
|
|
|
599
861
|
this.timeoutMs = timeoutMs;
|
|
600
862
|
}
|
|
601
863
|
};
|
|
602
|
-
|
|
603
|
-
|
|
864
|
+
var RequestCancellationError = class extends Error {
|
|
865
|
+
constructor() {
|
|
866
|
+
super("[proxy-chain] incoming request was cancelled");
|
|
867
|
+
this.name = "AbortError";
|
|
868
|
+
}
|
|
869
|
+
};
|
|
870
|
+
function assertValidTimeout(timeoutMs) {
|
|
871
|
+
if (timeoutMs !== void 0 && (typeof timeoutMs !== "number" || !Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > MAX_TIMEOUT_MS)) {
|
|
604
872
|
throw new RangeError(
|
|
605
|
-
`[proxy-chain]
|
|
873
|
+
`[proxy-chain] timeout must be an integer from 0 through ${MAX_TIMEOUT_MS} milliseconds`
|
|
606
874
|
);
|
|
607
875
|
}
|
|
608
876
|
}
|
|
609
|
-
async function
|
|
610
|
-
|
|
611
|
-
|
|
877
|
+
async function runInExecutionScope(requestSignal, timeoutMs, ruleName, run) {
|
|
878
|
+
assertValidTimeout(timeoutMs);
|
|
879
|
+
const controller = new AbortController();
|
|
880
|
+
if (requestSignal.aborted) {
|
|
881
|
+
controller.abort();
|
|
882
|
+
throw new RequestCancellationError();
|
|
883
|
+
}
|
|
884
|
+
const scopeStartedAt = performance.now();
|
|
885
|
+
const timeoutError = timeoutMs > 0 ? new RuleTimeoutError(ruleName, timeoutMs) : void 0;
|
|
886
|
+
let failure;
|
|
887
|
+
let rejectCancelled;
|
|
888
|
+
const cancelled = new Promise((_resolve, reject) => {
|
|
889
|
+
rejectCancelled = reject;
|
|
890
|
+
});
|
|
891
|
+
const cancel = (error) => {
|
|
892
|
+
if (failure) return;
|
|
893
|
+
failure = error;
|
|
894
|
+
controller.abort();
|
|
895
|
+
rejectCancelled(error);
|
|
896
|
+
};
|
|
897
|
+
const assertActive = () => {
|
|
898
|
+
if (requestSignal.aborted) cancel(new RequestCancellationError());
|
|
899
|
+
else if (timeoutError && !failure && performance.now() - scopeStartedAt >= timeoutMs) {
|
|
900
|
+
cancel(timeoutError);
|
|
901
|
+
}
|
|
902
|
+
if (failure) throw failure;
|
|
903
|
+
};
|
|
904
|
+
const onRequestAbort = () => cancel(new RequestCancellationError());
|
|
905
|
+
requestSignal.addEventListener("abort", onRequestAbort, { once: true });
|
|
612
906
|
let timer;
|
|
613
|
-
|
|
614
|
-
timer = setTimeout(() =>
|
|
907
|
+
if (timeoutError) {
|
|
908
|
+
timer = setTimeout(() => cancel(timeoutError), timeoutMs);
|
|
909
|
+
}
|
|
910
|
+
const work = Promise.resolve().then(async () => {
|
|
911
|
+
if (controller.signal.aborted) throw failure ?? new RequestCancellationError();
|
|
912
|
+
try {
|
|
913
|
+
const result = await run(controller.signal, assertActive);
|
|
914
|
+
if (timeoutError && !failure && performance.now() - scopeStartedAt >= timeoutMs) {
|
|
915
|
+
cancel(timeoutError);
|
|
916
|
+
}
|
|
917
|
+
if (failure) throw failure;
|
|
918
|
+
return result;
|
|
919
|
+
} catch (error) {
|
|
920
|
+
if (timeoutError && !failure && performance.now() - scopeStartedAt >= timeoutMs) {
|
|
921
|
+
cancel(timeoutError);
|
|
922
|
+
}
|
|
923
|
+
throw failure ?? error;
|
|
924
|
+
}
|
|
615
925
|
});
|
|
616
926
|
try {
|
|
617
|
-
return await Promise.race([
|
|
927
|
+
return await Promise.race([work, cancelled]);
|
|
928
|
+
} catch (error) {
|
|
929
|
+
throw failure ?? error;
|
|
618
930
|
} finally {
|
|
619
931
|
if (timer !== void 0) clearTimeout(timer);
|
|
620
|
-
|
|
932
|
+
requestSignal.removeEventListener("abort", onRequestAbort);
|
|
933
|
+
void work.catch(() => {
|
|
621
934
|
});
|
|
622
935
|
}
|
|
623
936
|
}
|
|
937
|
+
async function runInRecoveryScope(requestSignal, run) {
|
|
938
|
+
const controller = new AbortController();
|
|
939
|
+
const abort = () => controller.abort();
|
|
940
|
+
if (requestSignal.aborted) controller.abort();
|
|
941
|
+
else requestSignal.addEventListener("abort", abort, { once: true });
|
|
942
|
+
try {
|
|
943
|
+
return await run(controller.signal);
|
|
944
|
+
} finally {
|
|
945
|
+
requestSignal.removeEventListener("abort", abort);
|
|
946
|
+
}
|
|
947
|
+
}
|
|
624
948
|
|
|
625
949
|
// src/core/engine.ts
|
|
950
|
+
function monotonicNow() {
|
|
951
|
+
return performance.now();
|
|
952
|
+
}
|
|
953
|
+
function normalizeDebugLevel(level) {
|
|
954
|
+
return level === true ? "detailed" : level;
|
|
955
|
+
}
|
|
956
|
+
function responseOutcome(response) {
|
|
957
|
+
const rewrite = response.headers.get("x-middleware-rewrite");
|
|
958
|
+
if (rewrite) {
|
|
959
|
+
return { type: "rewrite", destination: safeDestination(rewrite) ?? "/" };
|
|
960
|
+
}
|
|
961
|
+
const location = response.headers.get("location");
|
|
962
|
+
if (location && response.status >= 300 && response.status < 400) {
|
|
963
|
+
return {
|
|
964
|
+
type: "redirect",
|
|
965
|
+
status: response.status,
|
|
966
|
+
destination: safeDestination(location)
|
|
967
|
+
};
|
|
968
|
+
}
|
|
969
|
+
if (response instanceof NextResponse2 && response.headers.get("x-middleware-next") === "1") {
|
|
970
|
+
return { type: "next" };
|
|
971
|
+
}
|
|
972
|
+
return { type: "response", status: response.status };
|
|
973
|
+
}
|
|
974
|
+
function scopeNames(scopeList) {
|
|
975
|
+
if (scopeList === void 0) return void 0;
|
|
976
|
+
const scopes = Array.isArray(scopeList) ? scopeList : [scopeList];
|
|
977
|
+
return scopes.map((scope) => {
|
|
978
|
+
if (typeof scope === "string") return safeDiagnosticText(scope, 96);
|
|
979
|
+
if (scope instanceof RegExp) return safeDiagnosticText(scope.toString(), 96);
|
|
980
|
+
if (typeof scope !== "object" || scope === null) return "";
|
|
981
|
+
const value = scope;
|
|
982
|
+
const parts = [
|
|
983
|
+
value.path === void 0 ? void 0 : Array.isArray(value.path) ? value.path.map(String).join("|") : String(value.path),
|
|
984
|
+
value.host === void 0 ? void 0 : Array.isArray(value.host) ? value.host.map(String).join("|") : String(value.host)
|
|
985
|
+
].filter(Boolean);
|
|
986
|
+
return safeDiagnosticText(parts.join(" @ "), 96);
|
|
987
|
+
});
|
|
988
|
+
}
|
|
989
|
+
function handlerDetails(rule, chainTimeout, when, includeResult, excludeResult) {
|
|
990
|
+
const include = scopeNames(rule.diagnosticRules?.include);
|
|
991
|
+
const exclude = scopeNames(rule.diagnosticRules?.exclude);
|
|
992
|
+
return {
|
|
993
|
+
...include ? { include, includeResult } : {},
|
|
994
|
+
...exclude ? { exclude, excludeResult } : {},
|
|
995
|
+
...rule.when ? { when } : {},
|
|
996
|
+
timeoutMs: rule.timeout ?? chainTimeout,
|
|
997
|
+
timeoutSource: rule.timeout === void 0 ? "chain" : "handler"
|
|
998
|
+
};
|
|
999
|
+
}
|
|
1000
|
+
function safeLogger(logger) {
|
|
1001
|
+
const wrap = (method) => (...args) => {
|
|
1002
|
+
try {
|
|
1003
|
+
const result = logger[method](...args);
|
|
1004
|
+
if (result && typeof result.then === "function") {
|
|
1005
|
+
void Promise.resolve(result).catch(() => {
|
|
1006
|
+
});
|
|
1007
|
+
}
|
|
1008
|
+
} catch {
|
|
1009
|
+
}
|
|
1010
|
+
};
|
|
1011
|
+
return {
|
|
1012
|
+
debug: wrap("debug"),
|
|
1013
|
+
info: wrap("info"),
|
|
1014
|
+
warn: wrap("warn"),
|
|
1015
|
+
error: wrap("error")
|
|
1016
|
+
};
|
|
1017
|
+
}
|
|
626
1018
|
function isNextResponse(value) {
|
|
627
1019
|
return value instanceof NextResponse2 && value.headers.get("x-middleware-next") === "1";
|
|
628
1020
|
}
|
|
629
1021
|
function stripRoutingOverrides(res) {
|
|
630
1022
|
const plain = !(res instanceof NextResponse2);
|
|
631
|
-
|
|
1023
|
+
const keys = [...res.headers.keys()];
|
|
1024
|
+
const remove = keys.filter((key) => {
|
|
632
1025
|
const lower = key.toLowerCase();
|
|
633
|
-
|
|
634
|
-
res.headers.delete(key);
|
|
635
|
-
}
|
|
636
|
-
}
|
|
637
|
-
}
|
|
638
|
-
function isPathFilter(value) {
|
|
639
|
-
if (value === null || typeof value !== "object") return false;
|
|
640
|
-
if ("nextUrl" in value) return false;
|
|
641
|
-
return "include" in value || "exclude" in value || "name" in value;
|
|
642
|
-
}
|
|
643
|
-
function defineProxy(nameOrRun, maybeRun) {
|
|
644
|
-
const defaultName = typeof nameOrRun === "string" ? nameOrRun : void 0;
|
|
645
|
-
const run = typeof nameOrRun === "function" ? nameOrRun : maybeRun;
|
|
646
|
-
const proxy = ((reqOrFilter, eventOrCtx, maybeEvent) => {
|
|
647
|
-
if (isPathFilter(reqOrFilter)) {
|
|
648
|
-
return withPaths(run, {
|
|
649
|
-
...reqOrFilter,
|
|
650
|
-
name: reqOrFilter.name ?? defaultName
|
|
651
|
-
});
|
|
652
|
-
}
|
|
653
|
-
return run(reqOrFilter, eventOrCtx, maybeEvent);
|
|
654
|
-
});
|
|
655
|
-
Object.defineProperty(proxy, "name", {
|
|
656
|
-
value: defaultName ?? "",
|
|
657
|
-
configurable: true
|
|
1026
|
+
return lower === "x-middleware-override-headers" || lower.startsWith("x-middleware-request-") || plain && (lower === "x-middleware-next" || lower === "x-middleware-rewrite");
|
|
658
1027
|
});
|
|
659
|
-
|
|
660
|
-
|
|
1028
|
+
if (!remove.length) return res;
|
|
1029
|
+
try {
|
|
1030
|
+
for (const key of remove) res.headers.delete(key);
|
|
1031
|
+
return res;
|
|
1032
|
+
} catch {
|
|
1033
|
+
const headers = new Headers(res.headers);
|
|
1034
|
+
for (const key of remove) headers.delete(key);
|
|
1035
|
+
const init = { headers, status: res.status, statusText: res.statusText };
|
|
1036
|
+
return res instanceof NextResponse2 ? new NextResponse2(res.body, init) : new Response(res.body, init);
|
|
1037
|
+
}
|
|
661
1038
|
}
|
|
662
|
-
function resolveConfig(overrides
|
|
663
|
-
const { logger, debug,
|
|
1039
|
+
function resolveConfig(overrides) {
|
|
1040
|
+
const { logger, debug, ...rest } = overrides;
|
|
664
1041
|
const config = {
|
|
665
|
-
createContext: createContext ?? fallbackCreateContext,
|
|
666
1042
|
cookieMergeStrategy: "last-write-wins",
|
|
667
1043
|
headerMergeStrategy: "last-write-wins",
|
|
668
1044
|
debug: false,
|
|
669
|
-
|
|
1045
|
+
timeout: 0,
|
|
670
1046
|
requestHeaderPolicy: {},
|
|
671
1047
|
strictOverrideCheck: false,
|
|
672
|
-
|
|
1048
|
+
tracePath: true,
|
|
673
1049
|
...rest,
|
|
674
1050
|
...debug !== void 0 ? { debug } : {},
|
|
675
|
-
logger: logger ?? createConsoleLogger(
|
|
1051
|
+
logger: safeLogger(logger ?? createConsoleLogger("info"))
|
|
676
1052
|
};
|
|
677
|
-
|
|
1053
|
+
assertValidTimeout(config.timeout);
|
|
678
1054
|
return config;
|
|
679
1055
|
}
|
|
680
|
-
function
|
|
681
|
-
const
|
|
682
|
-
const entries = (Array.isArray(optionsOrEntries) ? optionsOrEntries : maybeEntries) ?? [];
|
|
683
|
-
const fallbackCreateContext = createProxyContext;
|
|
684
|
-
const config = resolveConfig(options, fallbackCreateContext);
|
|
1056
|
+
function executeChain(options, entries) {
|
|
1057
|
+
const config = resolveConfig(options);
|
|
685
1058
|
const rules = entries.map(toRule);
|
|
686
1059
|
const {
|
|
687
1060
|
logger,
|
|
688
|
-
debug,
|
|
1061
|
+
debug: debugLevel,
|
|
689
1062
|
cookieMergeStrategy,
|
|
690
1063
|
headerMergeStrategy,
|
|
691
|
-
|
|
1064
|
+
timeout,
|
|
692
1065
|
requestHeaderPolicy,
|
|
693
|
-
strictOverrideCheck
|
|
694
|
-
hostFolderHeader
|
|
1066
|
+
strictOverrideCheck
|
|
695
1067
|
} = config;
|
|
1068
|
+
const debug = debugLevel !== false;
|
|
1069
|
+
const hasHandlerDebug = rules.some((rule) => rule.debug != null && rule.debug !== false);
|
|
1070
|
+
const hasDetailedHandlerDebug = rules.some(
|
|
1071
|
+
(rule) => rule.debug === true || rule.debug === "detailed" || rule.debug === "verbose"
|
|
1072
|
+
);
|
|
1073
|
+
const diagnosticsEnabled = debug || config.onTrace !== void 0 || hasHandlerDebug;
|
|
696
1074
|
assertOverrideMechanismSupported(strictOverrideCheck);
|
|
697
1075
|
for (let i = 0; i < rules.length; i++) {
|
|
698
1076
|
assertIncludeExcludeNoOverlap(rules[i].include, rules[i].exclude, ruleLabel(rules[i], i));
|
|
1077
|
+
assertValidTimeout(rules[i].timeout);
|
|
699
1078
|
}
|
|
700
1079
|
return async function proxy(req, event) {
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
const
|
|
709
|
-
|
|
710
|
-
|
|
1080
|
+
const startedAt = Date.now();
|
|
1081
|
+
const invocationStartedAt = monotonicNow();
|
|
1082
|
+
const requestId = `req_${globalThis.crypto.randomUUID()}`;
|
|
1083
|
+
const metadata = createRequestMetadata(req, requestId, startedAt, invocationStartedAt);
|
|
1084
|
+
const applicationState = createApplicationState();
|
|
1085
|
+
const diagnostics = diagnosticsEnabled ? [] : null;
|
|
1086
|
+
let nextHandlerIndex = 0;
|
|
1087
|
+
const finish = (response, forcedOutcome) => {
|
|
1088
|
+
if (!diagnostics) return response;
|
|
1089
|
+
for (let i = nextHandlerIndex; i < rules.length; i++) {
|
|
1090
|
+
diagnostics.push({
|
|
1091
|
+
name: safeDiagnosticText(ruleLabel(rules[i], i), 64),
|
|
1092
|
+
outcome: "not-reached"
|
|
1093
|
+
});
|
|
1094
|
+
}
|
|
1095
|
+
const trace = {
|
|
1096
|
+
requestId,
|
|
1097
|
+
startedAt,
|
|
1098
|
+
method: safeDiagnosticText(req.method, 16),
|
|
1099
|
+
pathname: config.tracePath === false ? void 0 : safeDiagnosticText(metadata.originalPathname),
|
|
1100
|
+
durationMs: monotonicNow() - invocationStartedAt,
|
|
1101
|
+
outcome: forcedOutcome ?? responseOutcome(response),
|
|
1102
|
+
handlers: diagnostics
|
|
1103
|
+
};
|
|
1104
|
+
if (config.onTrace) {
|
|
1105
|
+
try {
|
|
1106
|
+
void Promise.resolve(config.onTrace(trace)).catch(() => {
|
|
1107
|
+
});
|
|
1108
|
+
} catch {
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
const globalLevel = normalizeDebugLevel(debugLevel);
|
|
1112
|
+
if (globalLevel !== false || hasHandlerDebug) {
|
|
1113
|
+
const level = (globalLevel === "compact" || globalLevel === false) && hasDetailedHandlerDebug ? "detailed" : globalLevel === false ? "compact" : globalLevel;
|
|
1114
|
+
const visible = level === "compact" ? diagnostics : diagnostics.filter((_handler, index) => {
|
|
1115
|
+
const local = rules[index]?.debug;
|
|
1116
|
+
if (local === false) return false;
|
|
1117
|
+
if (local === "compact") return globalLevel === "compact";
|
|
1118
|
+
if (local != null) return true;
|
|
1119
|
+
return globalLevel !== false && !(globalLevel === "compact" && hasDetailedHandlerDebug);
|
|
1120
|
+
});
|
|
1121
|
+
try {
|
|
1122
|
+
config.logger.info(
|
|
1123
|
+
formatTrace(
|
|
1124
|
+
level === "compact" ? trace : { ...trace, handlers: visible },
|
|
1125
|
+
level,
|
|
1126
|
+
shouldUseColor(),
|
|
1127
|
+
supportsUnicode()
|
|
1128
|
+
)
|
|
1129
|
+
);
|
|
1130
|
+
} catch {
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
return response;
|
|
1134
|
+
};
|
|
1135
|
+
const contextFor = (signal) => createHandlerContext(metadata, applicationState, signal);
|
|
711
1136
|
let currentReq = req;
|
|
712
1137
|
let pendingRequestOverrides = null;
|
|
1138
|
+
let replaceRequestHeaders = false;
|
|
713
1139
|
let pendingRewriteUrl = null;
|
|
714
1140
|
const headerWrites = [];
|
|
715
1141
|
const cookieWrites = [];
|
|
@@ -722,119 +1148,352 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
722
1148
|
logger,
|
|
723
1149
|
debug
|
|
724
1150
|
);
|
|
1151
|
+
const requestCancelledResponse = () => finish(
|
|
1152
|
+
finalizeResponse(
|
|
1153
|
+
NextResponse2.next(),
|
|
1154
|
+
headerWrites,
|
|
1155
|
+
cookieWrites,
|
|
1156
|
+
headerMergeStrategy,
|
|
1157
|
+
cookieMergeStrategy,
|
|
1158
|
+
logger,
|
|
1159
|
+
debug
|
|
1160
|
+
),
|
|
1161
|
+
{ type: "request-cancelled" }
|
|
1162
|
+
);
|
|
725
1163
|
const materializeRequest = () => {
|
|
726
1164
|
if (!pendingRequestOverrides) return currentReq;
|
|
727
|
-
if (!headersDiffer(currentReq.headers, pendingRequestOverrides)) {
|
|
1165
|
+
if (!replaceRequestHeaders && !headersDiffer(currentReq.headers, pendingRequestOverrides)) {
|
|
728
1166
|
pendingRequestOverrides = null;
|
|
729
1167
|
return currentReq;
|
|
730
1168
|
}
|
|
731
|
-
const
|
|
1169
|
+
const nextUrl = currentReq.nextUrl.clone();
|
|
1170
|
+
const merged = new Headers();
|
|
1171
|
+
if (replaceRequestHeaders) {
|
|
1172
|
+
currentReq.headers.forEach((value, key) => {
|
|
1173
|
+
if (!isRequestHeaderAllowed(key, requestHeaderPolicy)) merged.set(key, value);
|
|
1174
|
+
});
|
|
1175
|
+
} else {
|
|
1176
|
+
currentReq.headers.forEach((value, key) => {
|
|
1177
|
+
merged.set(key, value);
|
|
1178
|
+
});
|
|
1179
|
+
}
|
|
732
1180
|
pendingRequestOverrides.forEach((v, k) => {
|
|
733
1181
|
merged.set(k, v);
|
|
734
1182
|
});
|
|
735
1183
|
pendingRequestOverrides = null;
|
|
1184
|
+
replaceRequestHeaders = false;
|
|
736
1185
|
currentReq = new NextRequest(currentReq, { headers: merged });
|
|
1186
|
+
currentReq.nextUrl.pathname = nextUrl.pathname;
|
|
1187
|
+
currentReq.nextUrl.search = nextUrl.search;
|
|
737
1188
|
return currentReq;
|
|
738
1189
|
};
|
|
739
|
-
const
|
|
740
|
-
|
|
741
|
-
|
|
1190
|
+
const queueRequestOverrides = (overrides, mode) => {
|
|
1191
|
+
if (mode === "replace") {
|
|
1192
|
+
pendingRequestOverrides = new Headers();
|
|
1193
|
+
replaceRequestHeaders = true;
|
|
1194
|
+
} else if (!pendingRequestOverrides) {
|
|
1195
|
+
pendingRequestOverrides = new Headers();
|
|
1196
|
+
}
|
|
742
1197
|
const target = pendingRequestOverrides;
|
|
743
1198
|
overrides.forEach((v, k) => {
|
|
744
1199
|
target.set(k, v);
|
|
745
|
-
appliedRequestOverrides.set(k, v);
|
|
746
1200
|
});
|
|
747
1201
|
};
|
|
748
|
-
const recoverRuleError = async (err, i, label, req2,
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
1202
|
+
const recoverRuleError = async (err, i, label, req2, durationMs, phase) => {
|
|
1203
|
+
const timeoutError = err instanceof RuleTimeoutError;
|
|
1204
|
+
const requestCancelled = err instanceof RequestCancellationError;
|
|
1205
|
+
const errorHandler = rules[i].onError ?? config.onError;
|
|
1206
|
+
const errorPolicy = rules[i].onError ? "handler" : "chain";
|
|
1207
|
+
const diagnosticPhase = phase === "before-handler" ? "handler" : phase;
|
|
1208
|
+
const details = handlerDetails(rules[i], timeout, "matched", "matched", "not-matched");
|
|
1209
|
+
const stopFailure = (policy) => {
|
|
1210
|
+
diagnostics?.push({
|
|
1211
|
+
name: safeDiagnosticText(label, 64),
|
|
1212
|
+
...requestCancelled ? {
|
|
1213
|
+
outcome: "request-cancelled",
|
|
1214
|
+
durationMs,
|
|
1215
|
+
phase: phase === "result" ? "handler" : phase,
|
|
1216
|
+
policy
|
|
1217
|
+
} : {
|
|
1218
|
+
outcome: timeoutError ? "timeout" : "failed",
|
|
1219
|
+
durationMs,
|
|
1220
|
+
phase: diagnosticPhase,
|
|
1221
|
+
policy,
|
|
1222
|
+
...timeoutError ? { timeoutMs: err.timeoutMs } : {}
|
|
1223
|
+
},
|
|
1224
|
+
details
|
|
1225
|
+
});
|
|
1226
|
+
nextHandlerIndex = i + 1;
|
|
1227
|
+
if (requestCancelled) {
|
|
1228
|
+
return {
|
|
1229
|
+
response: finish(
|
|
1230
|
+
finalizeResponse(
|
|
1231
|
+
NextResponse2.next(),
|
|
1232
|
+
headerWrites,
|
|
1233
|
+
cookieWrites,
|
|
1234
|
+
headerMergeStrategy,
|
|
1235
|
+
cookieMergeStrategy,
|
|
1236
|
+
logger,
|
|
1237
|
+
debug
|
|
1238
|
+
),
|
|
1239
|
+
{ type: "request-cancelled" }
|
|
1240
|
+
)
|
|
1241
|
+
};
|
|
1242
|
+
}
|
|
1243
|
+
if (timeoutError) {
|
|
1244
|
+
return {
|
|
1245
|
+
response: finish(failClosed(), {
|
|
1246
|
+
type: "timeout",
|
|
1247
|
+
status: 500,
|
|
1248
|
+
timeoutMs: err.timeoutMs
|
|
1249
|
+
})
|
|
1250
|
+
};
|
|
1251
|
+
}
|
|
1252
|
+
return {
|
|
1253
|
+
response: finish(failClosed(), {
|
|
1254
|
+
type: "error",
|
|
1255
|
+
status: 500,
|
|
1256
|
+
classification: "handler"
|
|
1257
|
+
})
|
|
1258
|
+
};
|
|
1259
|
+
};
|
|
1260
|
+
if (!errorHandler) {
|
|
1261
|
+
if (!diagnosticsEnabled) logger.error("handler failed");
|
|
1262
|
+
return stopFailure("none");
|
|
752
1263
|
}
|
|
753
1264
|
try {
|
|
754
|
-
const recovered = await
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
1265
|
+
const recovered = await runInRecoveryScope(
|
|
1266
|
+
req2.signal,
|
|
1267
|
+
(signal) => errorHandler(err, i, req2, contextFor(signal))
|
|
1268
|
+
);
|
|
1269
|
+
if (timeoutError || requestCancelled) {
|
|
1270
|
+
if (recovered instanceof Response && !isNextResponse(recovered)) {
|
|
1271
|
+
const response2 = stripRoutingOverrides(recovered);
|
|
1272
|
+
headerWrites.push({
|
|
1273
|
+
ruleIndex: i,
|
|
1274
|
+
ruleName: label,
|
|
1275
|
+
items: responseHeaderItems(response2.headers)
|
|
1276
|
+
});
|
|
1277
|
+
cookieWrites.push({
|
|
1278
|
+
ruleIndex: i,
|
|
1279
|
+
ruleName: label,
|
|
1280
|
+
items: cookieItemsFromHeaders(response2.headers)
|
|
1281
|
+
});
|
|
1282
|
+
diagnostics?.push({
|
|
1283
|
+
name: safeDiagnosticText(label, 64),
|
|
1284
|
+
...requestCancelled ? {
|
|
1285
|
+
outcome: "request-cancelled",
|
|
1286
|
+
durationMs,
|
|
1287
|
+
phase: phase === "result" ? "handler" : phase,
|
|
1288
|
+
policy: errorPolicy,
|
|
1289
|
+
recovery: "response"
|
|
1290
|
+
} : {
|
|
1291
|
+
outcome: "timeout",
|
|
1292
|
+
durationMs,
|
|
1293
|
+
phase: diagnosticPhase,
|
|
1294
|
+
policy: errorPolicy,
|
|
1295
|
+
recovery: "response",
|
|
1296
|
+
timeoutMs: err.timeoutMs
|
|
1297
|
+
},
|
|
1298
|
+
details
|
|
1299
|
+
});
|
|
1300
|
+
nextHandlerIndex = i + 1;
|
|
1301
|
+
return {
|
|
1302
|
+
response: finish(
|
|
1303
|
+
finalizeResponse(
|
|
1304
|
+
response2,
|
|
1305
|
+
headerWrites,
|
|
1306
|
+
cookieWrites,
|
|
1307
|
+
headerMergeStrategy,
|
|
1308
|
+
cookieMergeStrategy,
|
|
1309
|
+
logger,
|
|
1310
|
+
debug
|
|
1311
|
+
),
|
|
1312
|
+
requestCancelled ? { type: "request-cancelled" } : {
|
|
1313
|
+
type: "timeout",
|
|
1314
|
+
status: recovered.status,
|
|
1315
|
+
timeoutMs: err.timeoutMs
|
|
1316
|
+
}
|
|
1317
|
+
)
|
|
1318
|
+
};
|
|
1319
|
+
}
|
|
1320
|
+
return stopFailure(errorPolicy);
|
|
1321
|
+
}
|
|
1322
|
+
if (recovered == null) {
|
|
1323
|
+
return stopFailure(errorPolicy);
|
|
1324
|
+
}
|
|
1325
|
+
if (isNextResult(recovered) || isNextResponse(recovered)) {
|
|
1326
|
+
diagnostics?.push({
|
|
1327
|
+
name: safeDiagnosticText(label, 64),
|
|
1328
|
+
outcome: "recovered",
|
|
1329
|
+
durationMs,
|
|
1330
|
+
recovery: "continue",
|
|
1331
|
+
policy: errorPolicy,
|
|
1332
|
+
details
|
|
1333
|
+
});
|
|
1334
|
+
nextHandlerIndex = i + 1;
|
|
1335
|
+
return { raw: recovered };
|
|
1336
|
+
}
|
|
1337
|
+
if (!(recovered instanceof Response)) {
|
|
1338
|
+
diagnostics?.push({
|
|
1339
|
+
name: safeDiagnosticText(label, 64),
|
|
1340
|
+
outcome: "failed",
|
|
1341
|
+
durationMs,
|
|
1342
|
+
phase: diagnosticPhase,
|
|
1343
|
+
policy: errorPolicy,
|
|
1344
|
+
details
|
|
1345
|
+
});
|
|
1346
|
+
nextHandlerIndex = i + 1;
|
|
1347
|
+
return {
|
|
1348
|
+
response: finish(failClosed(), {
|
|
1349
|
+
type: "error",
|
|
1350
|
+
status: 500,
|
|
1351
|
+
classification: "handler"
|
|
1352
|
+
})
|
|
1353
|
+
};
|
|
1354
|
+
}
|
|
1355
|
+
const response = stripRoutingOverrides(recovered);
|
|
759
1356
|
headerWrites.push({
|
|
760
1357
|
ruleIndex: i,
|
|
761
1358
|
ruleName: label,
|
|
762
|
-
items: responseHeaderItems(
|
|
1359
|
+
items: responseHeaderItems(response.headers)
|
|
763
1360
|
});
|
|
764
1361
|
cookieWrites.push({
|
|
765
1362
|
ruleIndex: i,
|
|
766
1363
|
ruleName: label,
|
|
767
|
-
items: cookieItemsFromHeaders(
|
|
1364
|
+
items: cookieItemsFromHeaders(response.headers)
|
|
768
1365
|
});
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
duration: performance.now() - startedAt,
|
|
779
|
-
status: recovered.status
|
|
780
|
-
}
|
|
781
|
-
})
|
|
782
|
-
);
|
|
783
|
-
}
|
|
1366
|
+
diagnostics?.push({
|
|
1367
|
+
name: safeDiagnosticText(label, 64),
|
|
1368
|
+
outcome: "recovered",
|
|
1369
|
+
durationMs,
|
|
1370
|
+
recovery: responseOutcome(response).type === "redirect" ? "redirect" : responseOutcome(response).type === "rewrite" ? "rewrite" : "response",
|
|
1371
|
+
policy: errorPolicy,
|
|
1372
|
+
details
|
|
1373
|
+
});
|
|
1374
|
+
nextHandlerIndex = i + 1;
|
|
784
1375
|
return {
|
|
785
|
-
response:
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
1376
|
+
response: finish(
|
|
1377
|
+
finalizeResponse(
|
|
1378
|
+
response,
|
|
1379
|
+
headerWrites,
|
|
1380
|
+
cookieWrites,
|
|
1381
|
+
headerMergeStrategy,
|
|
1382
|
+
cookieMergeStrategy,
|
|
1383
|
+
logger,
|
|
1384
|
+
debug
|
|
1385
|
+
)
|
|
793
1386
|
)
|
|
794
1387
|
};
|
|
795
|
-
} catch
|
|
796
|
-
logger.error(
|
|
797
|
-
return
|
|
1388
|
+
} catch {
|
|
1389
|
+
if (!diagnosticsEnabled) logger.error("chain error handler failed");
|
|
1390
|
+
return stopFailure(errorPolicy);
|
|
798
1391
|
}
|
|
799
1392
|
};
|
|
800
1393
|
try {
|
|
801
1394
|
for (let i = 0; i < rules.length; i++) {
|
|
802
1395
|
const rule = rules[i];
|
|
803
1396
|
const label = ruleLabel(rule, i);
|
|
1397
|
+
nextHandlerIndex = i;
|
|
1398
|
+
if (req.signal.aborted) {
|
|
1399
|
+
const cancelled = await recoverRuleError(
|
|
1400
|
+
new RequestCancellationError(),
|
|
1401
|
+
i,
|
|
1402
|
+
label,
|
|
1403
|
+
materializeRequest(),
|
|
1404
|
+
0,
|
|
1405
|
+
"before-handler"
|
|
1406
|
+
);
|
|
1407
|
+
if ("response" in cancelled) return cancelled.response;
|
|
1408
|
+
return requestCancelledResponse();
|
|
1409
|
+
}
|
|
804
1410
|
const activeReq = materializeRequest();
|
|
805
1411
|
const reqHost = normalizeHost(
|
|
806
1412
|
activeReq.headers.get("host") ?? activeReq.headers.get("x-forwarded-host")
|
|
807
1413
|
);
|
|
808
1414
|
const matchPath = canonicalPathname(activeReq.nextUrl.pathname);
|
|
809
1415
|
if (matchPath === null) {
|
|
810
|
-
return
|
|
811
|
-
|
|
812
|
-
|
|
1416
|
+
return finish(
|
|
1417
|
+
new NextResponse2("Bad Request", {
|
|
1418
|
+
status: 400,
|
|
1419
|
+
headers: { "content-type": "text/plain; charset=utf-8" }
|
|
1420
|
+
})
|
|
1421
|
+
);
|
|
1422
|
+
}
|
|
1423
|
+
const skipReason = ruleMatchReason(matchPath, reqHost, rule);
|
|
1424
|
+
if (skipReason) {
|
|
1425
|
+
diagnostics?.push({
|
|
1426
|
+
name: safeDiagnosticText(label, 64),
|
|
1427
|
+
outcome: "skipped",
|
|
1428
|
+
reason: skipReason,
|
|
1429
|
+
details: handlerDetails(
|
|
1430
|
+
rule,
|
|
1431
|
+
timeout,
|
|
1432
|
+
"not-evaluated",
|
|
1433
|
+
skipReason === "include-mismatch" ? "mismatch" : void 0,
|
|
1434
|
+
skipReason === "exclude-match" ? "matched" : skipReason === "include-mismatch" && rule.exclude ? "not-matched" : void 0
|
|
1435
|
+
)
|
|
813
1436
|
});
|
|
1437
|
+
nextHandlerIndex = i + 1;
|
|
1438
|
+
continue;
|
|
814
1439
|
}
|
|
815
|
-
|
|
816
|
-
const
|
|
817
|
-
let
|
|
1440
|
+
const executionStartedAt = monotonicNow();
|
|
1441
|
+
const effectiveTimeout = rule.timeout ?? timeout;
|
|
1442
|
+
let phase = rule.when ? "when" : "handler";
|
|
1443
|
+
let result;
|
|
818
1444
|
try {
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
label
|
|
1445
|
+
result = await runInExecutionScope(
|
|
1446
|
+
req.signal,
|
|
1447
|
+
effectiveTimeout,
|
|
1448
|
+
label,
|
|
1449
|
+
async (signal, assertActive) => {
|
|
1450
|
+
const context = contextFor(signal);
|
|
1451
|
+
if (rule.when) {
|
|
1452
|
+
const matches = await rule.when(activeReq, event, context);
|
|
1453
|
+
assertActive();
|
|
1454
|
+
if (!matches) return { kind: "skipped" };
|
|
1455
|
+
}
|
|
1456
|
+
phase = "handler";
|
|
1457
|
+
assertActive();
|
|
1458
|
+
return {
|
|
1459
|
+
kind: "result",
|
|
1460
|
+
raw: await rule.run(activeReq, context, event)
|
|
1461
|
+
};
|
|
1462
|
+
}
|
|
823
1463
|
);
|
|
1464
|
+
if (result.kind === "skipped") {
|
|
1465
|
+
diagnostics?.push({
|
|
1466
|
+
name: safeDiagnosticText(label, 64),
|
|
1467
|
+
outcome: "skipped",
|
|
1468
|
+
reason: "when-false",
|
|
1469
|
+
details: handlerDetails(rule, timeout, "false", "matched", "not-matched")
|
|
1470
|
+
});
|
|
1471
|
+
nextHandlerIndex = i + 1;
|
|
1472
|
+
continue;
|
|
1473
|
+
}
|
|
824
1474
|
} catch (err) {
|
|
825
|
-
const recovered = await recoverRuleError(
|
|
1475
|
+
const recovered = await recoverRuleError(
|
|
1476
|
+
err,
|
|
1477
|
+
i,
|
|
1478
|
+
label,
|
|
1479
|
+
activeReq,
|
|
1480
|
+
monotonicNow() - executionStartedAt,
|
|
1481
|
+
phase
|
|
1482
|
+
);
|
|
826
1483
|
if ("response" in recovered) return recovered.response;
|
|
827
|
-
|
|
1484
|
+
result = { kind: "result", raw: recovered.raw };
|
|
828
1485
|
}
|
|
1486
|
+
let raw = result.raw;
|
|
1487
|
+
let duration2 = monotonicNow() - executionStartedAt;
|
|
829
1488
|
let outcome;
|
|
830
1489
|
try {
|
|
831
1490
|
outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
|
|
832
1491
|
} catch (err) {
|
|
833
|
-
const recovered = await recoverRuleError(err, i, label, activeReq,
|
|
1492
|
+
const recovered = await recoverRuleError(err, i, label, activeReq, duration2, "result");
|
|
834
1493
|
if ("response" in recovered) return recovered.response;
|
|
835
|
-
|
|
1494
|
+
raw = recovered.raw;
|
|
1495
|
+
outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
|
|
836
1496
|
}
|
|
837
|
-
const duration = debug ? performance.now() - startedAt : 0;
|
|
838
1497
|
if (outcome.kind === "continue") {
|
|
839
1498
|
if (outcome.rewriteUrl) {
|
|
840
1499
|
pendingRewriteUrl = outcome.rewriteUrl;
|
|
@@ -849,86 +1508,88 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
849
1508
|
currentReq.nextUrl.pathname = outcome.rewriteUrl;
|
|
850
1509
|
}
|
|
851
1510
|
}
|
|
852
|
-
if (outcome.request) queueRequestOverrides(outcome.request);
|
|
1511
|
+
if (outcome.request) queueRequestOverrides(outcome.request, outcome.requestMode);
|
|
853
1512
|
if (outcome.responseHeaders.size || outcome.cookies.size) {
|
|
854
1513
|
headerWrites.push({ ruleIndex: i, ruleName: label, items: outcome.responseHeaders });
|
|
855
1514
|
cookieWrites.push({ ruleIndex: i, ruleName: label, items: outcome.cookies });
|
|
856
1515
|
}
|
|
857
|
-
if (
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
}
|
|
1516
|
+
if (diagnostics?.at(-1)?.outcome !== "recovered") {
|
|
1517
|
+
diagnostics?.push(
|
|
1518
|
+
outcome.rewriteUrl ? {
|
|
1519
|
+
name: safeDiagnosticText(label, 64),
|
|
1520
|
+
outcome: "rewrite",
|
|
1521
|
+
durationMs: duration2,
|
|
1522
|
+
destination: safeDestination(outcome.rewriteUrl) ?? "/",
|
|
1523
|
+
final: false,
|
|
1524
|
+
details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
|
|
1525
|
+
} : {
|
|
1526
|
+
name: safeDiagnosticText(label, 64),
|
|
1527
|
+
outcome: "continue",
|
|
1528
|
+
source: isNextResult(raw) ? "next()" : raw instanceof NextResponse2 && raw.headers.get("x-middleware-next") === "1" ? "NextResponse.next()" : "undefined",
|
|
1529
|
+
durationMs: duration2,
|
|
1530
|
+
details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
|
|
1531
|
+
}
|
|
867
1532
|
);
|
|
868
1533
|
}
|
|
1534
|
+
nextHandlerIndex = i + 1;
|
|
869
1535
|
continue;
|
|
870
1536
|
}
|
|
871
|
-
stripRoutingOverrides(outcome.response);
|
|
1537
|
+
const response = stripRoutingOverrides(outcome.response);
|
|
872
1538
|
headerWrites.push({
|
|
873
1539
|
ruleIndex: i,
|
|
874
1540
|
ruleName: label,
|
|
875
|
-
items: responseHeaderItems(
|
|
1541
|
+
items: responseHeaderItems(response.headers)
|
|
876
1542
|
});
|
|
877
1543
|
cookieWrites.push({
|
|
878
1544
|
ruleIndex: i,
|
|
879
1545
|
ruleName: label,
|
|
880
|
-
items: cookieItemsFromHeaders(
|
|
1546
|
+
items: cookieItemsFromHeaders(response.headers)
|
|
881
1547
|
});
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
1548
|
+
const terminalOutcome = responseOutcome(response);
|
|
1549
|
+
diagnostics?.push(
|
|
1550
|
+
terminalOutcome.type === "redirect" ? {
|
|
1551
|
+
name: safeDiagnosticText(label, 64),
|
|
1552
|
+
outcome: "redirect",
|
|
1553
|
+
durationMs: duration2,
|
|
1554
|
+
status: terminalOutcome.status,
|
|
1555
|
+
destination: terminalOutcome.destination,
|
|
1556
|
+
details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
|
|
1557
|
+
} : terminalOutcome.type === "rewrite" ? {
|
|
1558
|
+
name: safeDiagnosticText(label, 64),
|
|
1559
|
+
outcome: "rewrite",
|
|
1560
|
+
durationMs: duration2,
|
|
1561
|
+
destination: terminalOutcome.destination,
|
|
1562
|
+
final: true,
|
|
1563
|
+
details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
|
|
1564
|
+
} : {
|
|
1565
|
+
name: safeDiagnosticText(label, 64),
|
|
1566
|
+
outcome: "response",
|
|
1567
|
+
durationMs: duration2,
|
|
1568
|
+
status: response.status,
|
|
1569
|
+
details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
|
|
1570
|
+
}
|
|
1571
|
+
);
|
|
1572
|
+
nextHandlerIndex = i + 1;
|
|
1573
|
+
const finalTerminalOutcome = responseOutcome(response);
|
|
1574
|
+
const terminalTrace = diagnostics?.at(-1);
|
|
1575
|
+
if (finalTerminalOutcome.type === "rewrite" && terminalTrace?.outcome === "rewrite") {
|
|
1576
|
+
terminalTrace.destination = finalTerminalOutcome.destination;
|
|
905
1577
|
}
|
|
906
|
-
return
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
1578
|
+
return finish(
|
|
1579
|
+
finalizeResponse(
|
|
1580
|
+
response,
|
|
1581
|
+
headerWrites,
|
|
1582
|
+
cookieWrites,
|
|
1583
|
+
headerMergeStrategy,
|
|
1584
|
+
cookieMergeStrategy,
|
|
1585
|
+
logger,
|
|
1586
|
+
debug
|
|
1587
|
+
),
|
|
1588
|
+
finalTerminalOutcome
|
|
914
1589
|
);
|
|
915
1590
|
}
|
|
916
1591
|
const finalReq = materializeRequest();
|
|
917
|
-
const
|
|
918
|
-
let finalRewriteUrl = pendingRewriteUrl;
|
|
919
|
-
if (internalHostFolder) {
|
|
920
|
-
const cleanFolder = physicalFolderPrefix(internalHostFolder);
|
|
921
|
-
if (finalRewriteUrl) {
|
|
922
|
-
finalRewriteUrl = applyFolderPrefix(finalRewriteUrl, cleanFolder, finalReq.url);
|
|
923
|
-
} else {
|
|
924
|
-
const currentPath = finalReq.nextUrl.pathname;
|
|
925
|
-
if (!isInsideFolder(currentPath, cleanFolder)) {
|
|
926
|
-
const targetUrl = finalReq.nextUrl.clone();
|
|
927
|
-
targetUrl.pathname = cleanFolder + (currentPath === "/" ? "" : currentPath);
|
|
928
|
-
finalRewriteUrl = targetUrl.toString();
|
|
929
|
-
}
|
|
930
|
-
}
|
|
931
|
-
}
|
|
1592
|
+
const finalRewriteUrl = pendingRewriteUrl;
|
|
932
1593
|
const requestInit = finalReq !== req ? { request: { headers: finalReq.headers } } : void 0;
|
|
933
1594
|
let final;
|
|
934
1595
|
if (finalRewriteUrl) {
|
|
@@ -937,7 +1598,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
937
1598
|
} else {
|
|
938
1599
|
final = NextResponse2.next(requestInit);
|
|
939
1600
|
}
|
|
940
|
-
|
|
1601
|
+
const finalResponse = finalizeResponse(
|
|
941
1602
|
final,
|
|
942
1603
|
headerWrites,
|
|
943
1604
|
cookieWrites,
|
|
@@ -946,34 +1607,51 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
946
1607
|
logger,
|
|
947
1608
|
debug
|
|
948
1609
|
);
|
|
1610
|
+
if (finalRewriteUrl) {
|
|
1611
|
+
const destination = safeDestination(finalRewriteUrl) ?? "/";
|
|
1612
|
+
const rewrite = diagnostics?.filter((handler) => handler.outcome === "rewrite").at(-1);
|
|
1613
|
+
if (rewrite?.outcome === "rewrite") {
|
|
1614
|
+
rewrite.destination = destination;
|
|
1615
|
+
rewrite.final = true;
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
return finish(finalResponse);
|
|
949
1619
|
} catch (err) {
|
|
950
|
-
logger.error(
|
|
1620
|
+
if (!diagnosticsEnabled) logger.error("proxy chain execution failed");
|
|
951
1621
|
if (config.onError) {
|
|
952
1622
|
try {
|
|
953
|
-
const recovered = await
|
|
1623
|
+
const recovered = await runInRecoveryScope(
|
|
1624
|
+
req.signal,
|
|
1625
|
+
(signal) => config.onError(err, -1, materializeRequest(), contextFor(signal))
|
|
1626
|
+
);
|
|
954
1627
|
if (recovered instanceof Response && !isNextResponse(recovered)) {
|
|
955
|
-
stripRoutingOverrides(recovered);
|
|
956
|
-
return
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
1628
|
+
const response = stripRoutingOverrides(recovered);
|
|
1629
|
+
return finish(
|
|
1630
|
+
finalizeResponse(
|
|
1631
|
+
response,
|
|
1632
|
+
headerWrites,
|
|
1633
|
+
cookieWrites,
|
|
1634
|
+
headerMergeStrategy,
|
|
1635
|
+
cookieMergeStrategy,
|
|
1636
|
+
logger,
|
|
1637
|
+
debug
|
|
1638
|
+
)
|
|
964
1639
|
);
|
|
965
1640
|
}
|
|
966
1641
|
} catch {
|
|
967
1642
|
}
|
|
968
1643
|
}
|
|
969
|
-
return
|
|
1644
|
+
return finish(
|
|
1645
|
+
failClosed(),
|
|
1646
|
+
err instanceof RuleTimeoutError ? { type: "timeout", status: 500, timeoutMs: err.timeoutMs } : { type: "error", status: 500, classification: "engine" }
|
|
1647
|
+
);
|
|
970
1648
|
}
|
|
971
1649
|
};
|
|
972
1650
|
}
|
|
973
1651
|
|
|
974
1652
|
// src/core/chain.ts
|
|
975
|
-
function
|
|
976
|
-
return typeof value === "
|
|
1653
|
+
function isDefinedHandler(value) {
|
|
1654
|
+
return typeof value === "object" && value !== null && value[DEFINED_HANDLER] === true;
|
|
977
1655
|
}
|
|
978
1656
|
function isScopeObject2(value) {
|
|
979
1657
|
return typeof value === "object" && value !== null && !(value instanceof RegExp) && !Array.isArray(value);
|
|
@@ -991,25 +1669,47 @@ function toEntry(entry) {
|
|
|
991
1669
|
if (Array.isArray(entry)) {
|
|
992
1670
|
const [target, scope] = entry;
|
|
993
1671
|
const filter = toFilter(scope);
|
|
994
|
-
if (
|
|
1672
|
+
if (isDefinedHandler(target)) return withPaths(target, filter);
|
|
995
1673
|
return withPaths(fromNative(target), filter);
|
|
996
1674
|
}
|
|
997
|
-
if (
|
|
1675
|
+
if (isDefinedHandler(entry)) return entry;
|
|
998
1676
|
if (typeof entry === "function") return fromNative(entry);
|
|
999
|
-
|
|
1677
|
+
throw new TypeError(
|
|
1678
|
+
"[proxy-chain] chain entries must be native handlers or defineHandler() results"
|
|
1679
|
+
);
|
|
1000
1680
|
}
|
|
1001
1681
|
function chain(entries, options) {
|
|
1002
1682
|
const normalized = entries.map((entry) => toEntry(entry));
|
|
1003
|
-
return
|
|
1683
|
+
return executeChain(options ?? {}, normalized);
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
// src/core/handler.ts
|
|
1687
|
+
function defineHandler(options) {
|
|
1688
|
+
assertValidTimeout(options.timeout);
|
|
1689
|
+
const include = compileScopes(options.rules?.include);
|
|
1690
|
+
const exclude = compileScopes(options.rules?.exclude);
|
|
1691
|
+
const rule = {
|
|
1692
|
+
run: (request, context, event) => options.handler(request, event, context),
|
|
1693
|
+
name: options.name,
|
|
1694
|
+
include,
|
|
1695
|
+
exclude,
|
|
1696
|
+
debug: options.debug,
|
|
1697
|
+
timeout: options.timeout,
|
|
1698
|
+
when: options.rules?.when,
|
|
1699
|
+
onError: options.onError,
|
|
1700
|
+
diagnosticRules: {
|
|
1701
|
+
include: options.rules?.include,
|
|
1702
|
+
exclude: options.rules?.exclude
|
|
1703
|
+
}
|
|
1704
|
+
};
|
|
1705
|
+
return { ...rule, [DEFINED_HANDLER]: true };
|
|
1004
1706
|
}
|
|
1005
1707
|
export {
|
|
1006
1708
|
RuleTimeoutError,
|
|
1007
1709
|
chain,
|
|
1008
|
-
|
|
1009
|
-
defineProxy,
|
|
1710
|
+
defineHandler,
|
|
1010
1711
|
host,
|
|
1011
1712
|
isNextResult,
|
|
1012
1713
|
next,
|
|
1013
|
-
path
|
|
1014
|
-
proxyChain
|
|
1714
|
+
path
|
|
1015
1715
|
};
|