@klnap/next-proxy-chain 1.2.0 → 3.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/dist/index.cjs CHANGED
@@ -20,96 +20,103 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
- RuleTimeoutError: () => RuleTimeoutError,
24
23
  chain: () => chain,
25
- createProxyContext: () => createProxyContext,
26
- defineHandler: () => defineHandler,
27
- defineProxy: () => defineProxy,
28
- host: () => host,
29
- isNextResult: () => isNextResult,
30
- next: () => next,
31
- path: () => path,
32
- proxyChain: () => proxyChain
24
+ defineHandler: () => defineHandler
33
25
  });
34
26
  module.exports = __toCommonJS(index_exports);
35
27
 
36
- // src/core/constants.ts
37
- var NEXT = /* @__PURE__ */ Symbol.for("proxy-chain.next");
38
- var DEFAULT_BLOCKED_REQUEST_HEADERS = Object.freeze([
39
- "host",
40
- "connection",
41
- "keep-alive",
42
- "proxy-authenticate",
43
- "proxy-authorization",
44
- "te",
45
- "trailer",
46
- "transfer-encoding",
47
- "upgrade",
48
- "content-length",
49
- "cookie",
50
- "authorization",
51
- "x-forwarded-host",
52
- "x-forwarded-for",
53
- "x-forwarded-proto",
54
- "x-real-ip",
55
- "x-middleware-next",
56
- "x-middleware-override-headers"
57
- ]);
58
- var CONTEXT_RULE = /* @__PURE__ */ Symbol.for("proxy-chain.context-rule");
59
-
60
- // src/core/actions.ts
61
- function next(options = {}) {
62
- return { [NEXT]: true, ...options };
63
- }
64
- function isNextResult(value) {
65
- return typeof value === "object" && value !== null && NEXT in value;
66
- }
67
-
68
28
  // src/core/engine.ts
69
- var import_server2 = require("next/server");
29
+ var import_server2 = require("next/server.js");
70
30
 
71
31
  // src/core/context.ts
72
- function createProxyContext() {
73
- return /* @__PURE__ */ new Map();
32
+ var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
33
+ "requestId",
34
+ "startedAt",
35
+ "elapsedMs",
36
+ "originalUrl",
37
+ "originalPathname",
38
+ "originalHostname",
39
+ "signal"
40
+ ]);
41
+ function createRequestMetadata(request, requestId, startedAt, invocationStartedAt) {
42
+ const metadata = /* @__PURE__ */ Object.create(null);
43
+ Object.defineProperties(metadata, {
44
+ requestId: { value: requestId, enumerable: true },
45
+ startedAt: { value: startedAt, enumerable: true },
46
+ elapsedMs: {
47
+ get: () => performance.now() - invocationStartedAt,
48
+ enumerable: true
49
+ },
50
+ originalUrl: { value: request.url, enumerable: true },
51
+ originalPathname: { value: request.nextUrl.pathname, enumerable: true },
52
+ originalHostname: { value: request.nextUrl.hostname, enumerable: true }
53
+ });
54
+ return metadata;
55
+ }
56
+ function createApplicationState() {
57
+ return /* @__PURE__ */ Object.create(null);
58
+ }
59
+ function createHandlerContext(metadata, applicationState, signal) {
60
+ const target = /* @__PURE__ */ Object.create(null);
61
+ Object.defineProperties(target, {
62
+ requestId: { value: metadata.requestId, enumerable: true },
63
+ startedAt: { value: metadata.startedAt, enumerable: true },
64
+ elapsedMs: { get: () => metadata.elapsedMs, enumerable: true },
65
+ originalUrl: { value: metadata.originalUrl, enumerable: true },
66
+ originalPathname: { value: metadata.originalPathname, enumerable: true },
67
+ originalHostname: { value: metadata.originalHostname, enumerable: true },
68
+ signal: { value: signal, enumerable: true }
69
+ });
70
+ return new Proxy(target, {
71
+ get(view, property) {
72
+ return Reflect.has(view, property) ? Reflect.get(view, property, view) : Reflect.get(applicationState, property, applicationState);
73
+ },
74
+ set(_view, property, value) {
75
+ if (RESERVED_CONTEXT_KEYS.has(property)) return false;
76
+ return Reflect.set(applicationState, property, value, applicationState);
77
+ },
78
+ deleteProperty(_view, property) {
79
+ if (RESERVED_CONTEXT_KEYS.has(property)) return false;
80
+ return Reflect.deleteProperty(applicationState, property);
81
+ },
82
+ defineProperty(_view, property, descriptor) {
83
+ if (RESERVED_CONTEXT_KEYS.has(property)) return false;
84
+ return Reflect.defineProperty(applicationState, property, {
85
+ ...descriptor,
86
+ configurable: true
87
+ });
88
+ },
89
+ getPrototypeOf() {
90
+ return null;
91
+ },
92
+ setPrototypeOf() {
93
+ return false;
94
+ },
95
+ has(view, property) {
96
+ return Reflect.has(view, property) || Reflect.has(applicationState, property);
97
+ },
98
+ ownKeys(view) {
99
+ return [.../* @__PURE__ */ new Set([...Reflect.ownKeys(view), ...Reflect.ownKeys(applicationState)])];
100
+ },
101
+ getOwnPropertyDescriptor(view, property) {
102
+ const descriptor = Reflect.getOwnPropertyDescriptor(view, property);
103
+ if (descriptor) return descriptor;
104
+ const applicationDescriptor = Reflect.getOwnPropertyDescriptor(applicationState, property);
105
+ return applicationDescriptor ? { ...applicationDescriptor, configurable: true } : void 0;
106
+ },
107
+ preventExtensions() {
108
+ return false;
109
+ }
110
+ });
74
111
  }
75
112
 
76
113
  // src/core/headers.ts
77
- function normalizeHeaderName(name) {
78
- return name.toLowerCase();
79
- }
80
- function headersInitToHeaders(init) {
81
- return new Headers(init);
82
- }
83
114
  function headersDiffer(base, overrides) {
84
115
  for (const [key, value] of overrides.entries()) {
85
116
  if (base.get(key) !== value) return true;
86
117
  }
87
118
  return false;
88
119
  }
89
- function isRequestHeaderAllowed(name, policy = {}) {
90
- const key = normalizeHeaderName(name);
91
- const allowed = new Set((policy.allowed ?? []).map(normalizeHeaderName));
92
- if (allowed.has(key)) return true;
93
- if (key.startsWith("x-middleware-")) return false;
94
- const blocked = /* @__PURE__ */ new Set([
95
- ...DEFAULT_BLOCKED_REQUEST_HEADERS.map(normalizeHeaderName),
96
- ...(policy.blocked ?? []).map(normalizeHeaderName)
97
- ]);
98
- return !blocked.has(key);
99
- }
100
- function mergeRequestHeaderOverrides(target, overrides, policy = {}) {
101
- const dropped = [];
102
- let applied = 0;
103
- overrides.forEach((value, key) => {
104
- if (!isRequestHeaderAllowed(key, policy)) {
105
- dropped.push(key);
106
- return;
107
- }
108
- target.set(key, value);
109
- applied++;
110
- });
111
- return { applied, dropped };
112
- }
113
120
  function parseCookieName(setCookie) {
114
121
  const eq = setCookie.indexOf("=");
115
122
  return (eq === -1 ? setCookie : setCookie.slice(0, eq)).trim();
@@ -215,30 +222,6 @@ function applyMergedToResponse(res, headers, cookies, dropHeaders) {
215
222
  }
216
223
  }
217
224
 
218
- // src/core/host-folder-prefix.ts
219
- function physicalFolderPrefix(raw) {
220
- return "/" + raw.replace(/^\/+|\/+$/g, "").split("/").filter((seg) => !/^\(.*\)$/.test(seg)).join("/");
221
- }
222
- function isInsideFolder(pathname, folder) {
223
- if (folder === "/") return true;
224
- return pathname === folder || pathname.startsWith(`${folder}/`);
225
- }
226
- function applyFolderPrefix(rewriteUrl, folder, baseUrl) {
227
- try {
228
- const parsed = new URL(rewriteUrl, baseUrl);
229
- if (!isInsideFolder(parsed.pathname, folder)) {
230
- parsed.pathname = folder + (parsed.pathname === "/" ? "" : parsed.pathname);
231
- return parsed.toString();
232
- }
233
- return rewriteUrl;
234
- } catch {
235
- if (!isInsideFolder(rewriteUrl, folder)) {
236
- return folder + (rewriteUrl === "/" ? "" : rewriteUrl);
237
- }
238
- return rewriteUrl;
239
- }
240
- }
241
-
242
225
  // src/core/logger.ts
243
226
  var LEVEL_RANK = {
244
227
  debug: 10,
@@ -338,6 +321,8 @@ function handlerLabel(handler) {
338
321
  return { symbol: "!", text: "recovered", color: 33 };
339
322
  case "timeout":
340
323
  return { symbol: "\xD7", text: "timeout", color: 31 };
324
+ case "request-cancelled":
325
+ return { symbol: "\u2298", text: "request cancelled", color: 33 };
341
326
  case "failed":
342
327
  return { symbol: "\xD7", text: "failed", color: 31 };
343
328
  }
@@ -356,6 +341,8 @@ function outcomeText(outcome) {
356
341
  return `ERROR ${outcome.status}`;
357
342
  case "timeout":
358
343
  return `ERROR ${outcome.status} \xB7 timeout ${outcome.timeoutMs}ms`;
344
+ case "request-cancelled":
345
+ return "REQUEST CANCELLED";
359
346
  }
360
347
  }
361
348
  function outcomeColor(outcome) {
@@ -369,23 +356,23 @@ function outcomeColor(outcome) {
369
356
  case "error":
370
357
  case "timeout":
371
358
  return 31;
359
+ case "request-cancelled":
360
+ return 33;
372
361
  case "response":
373
362
  return outcome.status >= 500 ? 31 : 32;
374
363
  }
375
364
  }
376
365
  function formatTrace(trace, level, color = shouldUseColor(), unicode = true) {
377
366
  const path2 = trace.pathname ? ` ${safeDiagnosticText(trace.pathname)}` : "";
378
- const header = `proxy-chain ${safeDiagnosticText(trace.method)}${path2}`;
367
+ const header = `[proxy-chain] ${safeDiagnosticText(trace.method)}${path2}`;
379
368
  const rows = [];
380
369
  const handlers = trace.handlers;
381
370
  if (level === "compact") {
382
- const executed = handlers.filter(
383
- (handler) => handler.outcome !== "skipped" && handler.outcome !== "not-reached"
384
- ).length;
385
- const skipped = handlers.filter((handler) => handler.outcome === "skipped").length;
386
- return `${header} ${unicode ? "\u2192" : "->"} ${paint(outcomeText(trace.outcome), outcomeColor(trace.outcome), color)} \xB7 ${executed} executed \xB7 ${skipped} skipped \xB7 ${paint(duration(trace.durationMs), 2, color)}`;
371
+ const reached = handlers.filter((handler) => handler.outcome !== "not-reached").length;
372
+ 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`;
387
373
  }
388
- rows.push(`${header.padEnd(52)} ${duration(trace.durationMs)}`);
374
+ rows.push(header);
375
+ rows.push(` Request: ${safeDiagnosticText(trace.requestId, 64)}`);
389
376
  const shown = handlers;
390
377
  const symbols = unicode ? {
391
378
  pass: "\u2502",
@@ -396,6 +383,7 @@ function formatTrace(trace, level, color = shouldUseColor(), unicode = true) {
396
383
  skip: "\u25CB",
397
384
  missing: "\u2013",
398
385
  error: "\xD7",
386
+ cancelled: "\u2298",
399
387
  recovered: "!"
400
388
  } : {
401
389
  pass: "|",
@@ -406,12 +394,13 @@ function formatTrace(trace, level, color = shouldUseColor(), unicode = true) {
406
394
  skip: "o",
407
395
  missing: "-",
408
396
  error: "x",
397
+ cancelled: "!",
409
398
  recovered: "!"
410
399
  };
411
400
  for (let index = 0; index < shown.length; index++) {
412
401
  const handler = shown[index];
413
402
  const label = handlerLabel(handler);
414
- 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 : symbols.error;
403
+ 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;
415
404
  const prefix = symbols.pass;
416
405
  const name = safeDiagnosticText(handler.name, 32);
417
406
  const time = "durationMs" in handler ? paint(duration(handler.durationMs), 2, color) : "";
@@ -448,17 +437,20 @@ function formatTrace(trace, level, color = shouldUseColor(), unicode = true) {
448
437
  rows.push(`${symbols.pass} destination: ${handler.destination}`);
449
438
  }
450
439
  }
451
- if (handler.outcome === "recovered" || handler.outcome === "failed" || handler.outcome === "timeout") {
440
+ if (handler.outcome === "recovered" || handler.outcome === "failed" || handler.outcome === "timeout" || handler.outcome === "request-cancelled") {
452
441
  const policy = handler.policy === "none" ? "chain default" : handler.policy;
453
- rows.push(`${symbols.pass} error policy: ${policy}`);
442
+ rows.push(
443
+ `${symbols.pass} ${handler.outcome === "request-cancelled" ? "cancellation policy" : "error policy"}: ${policy}`
444
+ );
454
445
  }
455
- if (handler.outcome === "timeout" && handler.details?.timeoutMs !== void 0) {
456
- rows.push(`${symbols.pass} deadline: ${handler.details.timeoutMs}ms`);
446
+ if (handler.outcome === "timeout" && handler.timeoutMs !== void 0) {
447
+ rows.push(`${symbols.pass} deadline: ${handler.timeoutMs}ms`);
457
448
  }
458
449
  }
459
450
  rows.push(
460
451
  `${symbols.last} ${paint(outcomeText(trace.outcome), outcomeColor(trace.outcome), color)}`
461
452
  );
453
+ rows.push(` Total: ${paint(duration(trace.durationMs), 2, color)}`);
462
454
  const output = rows.join("\n");
463
455
  if (output.length <= 16384) return output;
464
456
  const safeBoundary = output.lastIndexOf("\n", 16384);
@@ -545,16 +537,14 @@ function path(pattern) {
545
537
  if (pattern instanceof RegExp) return compileRegexPath(pattern);
546
538
  return compileStringPath(pattern);
547
539
  }
548
- function toPathRegex(matcher) {
540
+ function toPathRegexes(matcher) {
549
541
  const list = Array.isArray(matcher) ? matcher : [matcher];
550
- const regexes = list.map((m) => path(m));
551
- if (regexes.length === 1) return toStatelessRegExp(regexes[0]);
552
- return toStatelessRegExp(new RegExp(`(?:${regexes.map((r) => `(?:${r.source})`).join("|")})`));
542
+ return list.map((m) => toStatelessRegExp(path(m)));
553
543
  }
554
544
  function compileScopes(input) {
555
545
  if (input == null) return void 0;
556
546
  const list = Array.isArray(input) ? input : [input];
557
- const compilePath = (matcher) => toPathRegex(matcher);
547
+ const compilePath = (matcher) => toPathRegexes(matcher);
558
548
  const compiled = [];
559
549
  for (const item of list) {
560
550
  if (typeof item === "string" || item instanceof RegExp) {
@@ -580,7 +570,7 @@ function scopeMatches(pathname, hostname, scope) {
580
570
  if (!hostname || !scope.host.test(hostname)) return false;
581
571
  }
582
572
  if (scope.path) {
583
- if (!scope.path.test(pathname)) return false;
573
+ if (!scope.path.some((alternative) => alternative.test(pathname))) return false;
584
574
  }
585
575
  return true;
586
576
  }
@@ -595,12 +585,12 @@ function toRule(entry) {
595
585
  const harden = (scopes) => scopes?.map((s) => {
596
586
  if (!s.host && !s.path) {
597
587
  throw new Error(
598
- "[proxy-chain] include/exclude scope needs `host` or `path`. Build scopes with path() or host()."
588
+ "[proxy-chain] include/exclude scope needs a path, host, or host/path object."
599
589
  );
600
590
  }
601
591
  return {
602
592
  host: s.host ? toStatelessRegExp(s.host) : void 0,
603
- path: s.path ? toStatelessRegExp(s.path) : void 0
593
+ path: s.path?.map(toStatelessRegExp)
604
594
  };
605
595
  });
606
596
  return {
@@ -614,23 +604,6 @@ function ruleLabel(rule, index) {
614
604
  const runName = typeof rule.run === "function" ? extractMeaningfulName(rule.run.name) : void 0;
615
605
  return extractMeaningfulName(rule.name) ?? runName ?? `rule#${index}`;
616
606
  }
617
- function withPaths(entry, filter) {
618
- const base = toRule(entry);
619
- const include = compileScopes(filter.include);
620
- const exclude = compileScopes(filter.exclude);
621
- const name = filter.name ?? base.name;
622
- assertIncludeExcludeNoOverlap(include, exclude, name ?? "proxy");
623
- return {
624
- run: base.run,
625
- include,
626
- exclude,
627
- name,
628
- debug: base.debug,
629
- timeout: base.timeout,
630
- when: base.when,
631
- diagnosticRules: { include: filter.include, exclude: filter.exclude }
632
- };
633
- }
634
607
  function ruleMatchReason(pathname, hostname, rule) {
635
608
  if (rule.exclude?.some((scope) => scopeMatches(pathname, hostname, scope))) {
636
609
  return "exclude-match";
@@ -661,7 +634,8 @@ function canonicalPathname(pathname) {
661
634
  return decoded.length > 1 ? decoded.replace(/\/+$/, "") || "/" : decoded;
662
635
  }
663
636
  function scopeKey(scope) {
664
- return `${scope.host?.source ?? "*"}::${scope.host?.flags ?? ""}|${scope.path?.source ?? "*"}::${scope.path?.flags ?? ""}`;
637
+ const path2 = scope.path?.map((alternative) => `${alternative.source}::${alternative.flags}`).join("&");
638
+ return `${scope.host?.source ?? "*"}::${scope.host?.flags ?? ""}|${path2 ?? "*"}`;
665
639
  }
666
640
  function assertIncludeExcludeNoOverlap(include, exclude, label) {
667
641
  if (!include?.length || !exclude?.length) return;
@@ -676,7 +650,7 @@ function assertIncludeExcludeNoOverlap(include, exclude, label) {
676
650
  }
677
651
 
678
652
  // src/core/pipeline.ts
679
- var import_server = require("next/server");
653
+ var import_server = require("next/server.js");
680
654
  function safeInternalError() {
681
655
  return new import_server.NextResponse("Internal Server Error", {
682
656
  status: 500,
@@ -723,48 +697,26 @@ function assertOverrideMechanismSupported(strict = false) {
723
697
  return false;
724
698
  }
725
699
  }
726
- function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
727
- if (res == null) {
700
+ function resolveRuleResult(res) {
701
+ if (res === void 0) {
728
702
  return { kind: "continue", responseHeaders: /* @__PURE__ */ new Map(), cookies: /* @__PURE__ */ new Map() };
729
703
  }
730
- if (!isNextResult(res) && !(res instanceof Response)) {
704
+ if (!(res instanceof Response)) {
731
705
  throw new TypeError(
732
- `[proxy-chain] rule must return next(), a Response, or undefined. Got ${typeof res}.`
706
+ `[proxy-chain] rule must return a Response or undefined. Got ${typeof res}.`
733
707
  );
734
708
  }
735
- if (isNextResult(res)) {
736
- let request;
737
- if (res.request) {
738
- const filtered = new Headers();
739
- const { dropped } = mergeRequestHeaderOverrides(
740
- filtered,
741
- headersInitToHeaders(res.request),
742
- requestHeaderPolicy
743
- );
744
- if (debug && dropped.length) {
745
- logger.warn({ dropped }, "blocked request header mutation");
746
- }
747
- if ([...filtered.keys()].length) request = filtered;
748
- }
749
- const headerInit = res.headers ? headersInitToHeaders(res.headers) : void 0;
750
- return {
751
- kind: "continue",
752
- request,
753
- responseHeaders: headerInit ? responseHeaderItems(headerInit) : /* @__PURE__ */ new Map(),
754
- cookies: headerInit ? cookieItemsFromHeaders(headerInit) : /* @__PURE__ */ new Map()
755
- };
756
- }
757
709
  if (res instanceof import_server.NextResponse && res.headers.get("x-middleware-next") === "1") {
758
710
  let request;
759
711
  const decoded = decodeOverriddenRequestHeaders(res.headers);
760
- if ([...decoded.keys()].length > 0) {
761
- const target = new Headers();
762
- mergeRequestHeaderOverrides(target, decoded, requestHeaderPolicy);
763
- if ([...target.keys()].length) request = target;
712
+ const hasRequestOverride = res.headers.has("x-middleware-override-headers");
713
+ if (hasRequestOverride) {
714
+ request = decoded;
764
715
  }
765
716
  return {
766
717
  kind: "continue",
767
718
  request,
719
+ ...hasRequestOverride ? { requestMode: "replace" } : {},
768
720
  responseHeaders: responseHeaderItems(res.headers),
769
721
  cookies: cookieItemsFromHeaders(res.headers)
770
722
  };
@@ -773,14 +725,14 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
773
725
  if (rewriteHeader && (res.status === 200 || !res.status)) {
774
726
  let request;
775
727
  const decoded = decodeOverriddenRequestHeaders(res.headers);
776
- if ([...decoded.keys()].length > 0) {
777
- const target = new Headers();
778
- mergeRequestHeaderOverrides(target, decoded, requestHeaderPolicy);
779
- if ([...target.keys()].length) request = target;
728
+ const hasRequestOverride = res.headers.has("x-middleware-override-headers");
729
+ if (hasRequestOverride) {
730
+ request = decoded;
780
731
  }
781
732
  return {
782
733
  kind: "continue",
783
734
  request,
735
+ ...hasRequestOverride ? { requestMode: "replace" } : {},
784
736
  responseHeaders: responseHeaderItems(res.headers),
785
737
  cookies: cookieItemsFromHeaders(res.headers),
786
738
  rewriteUrl: rewriteHeader
@@ -819,6 +771,7 @@ function finalizeResponse(res, headerWrites, cookieWrites, headerStrategy, cooki
819
771
  }
820
772
 
821
773
  // src/core/timeout.ts
774
+ var MAX_TIMEOUT_MS = 2147483647;
822
775
  var RuleTimeoutError = class extends Error {
823
776
  ruleName;
824
777
  timeoutMs;
@@ -829,36 +782,94 @@ var RuleTimeoutError = class extends Error {
829
782
  this.timeoutMs = timeoutMs;
830
783
  }
831
784
  };
832
- function assertFiniteRuleTimeoutMs(ruleTimeoutMs) {
833
- if (ruleTimeoutMs != null && (!Number.isFinite(ruleTimeoutMs) || ruleTimeoutMs < 0)) {
785
+ var RequestCancellationError = class extends Error {
786
+ constructor() {
787
+ super("[proxy-chain] incoming request was cancelled");
788
+ this.name = "AbortError";
789
+ }
790
+ };
791
+ function assertValidTimeout(timeoutMs) {
792
+ if (timeoutMs !== void 0 && (typeof timeoutMs !== "number" || !Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > MAX_TIMEOUT_MS)) {
834
793
  throw new RangeError(
835
- `[proxy-chain] ruleTimeoutMs must be a finite number >= 0 (0 disables), got ${ruleTimeoutMs}`
794
+ `[proxy-chain] timeout must be an integer from 0 through ${MAX_TIMEOUT_MS} milliseconds`
836
795
  );
837
796
  }
838
797
  }
839
- async function withRuleTimeout(promise, timeoutMs, ruleName) {
840
- assertFiniteRuleTimeoutMs(timeoutMs);
841
- if (timeoutMs == null || timeoutMs <= 0) return promise;
798
+ async function runInExecutionScope(requestSignal, timeoutMs, ruleName, run) {
799
+ assertValidTimeout(timeoutMs);
800
+ const controller = new AbortController();
801
+ if (requestSignal.aborted) {
802
+ controller.abort();
803
+ throw new RequestCancellationError();
804
+ }
805
+ const scopeStartedAt = performance.now();
806
+ const timeoutError = timeoutMs > 0 ? new RuleTimeoutError(ruleName, timeoutMs) : void 0;
807
+ let failure;
808
+ let rejectCancelled;
809
+ const cancelled = new Promise((_resolve, reject) => {
810
+ rejectCancelled = reject;
811
+ });
812
+ const cancel = (error) => {
813
+ if (failure) return;
814
+ failure = error;
815
+ controller.abort();
816
+ rejectCancelled(error);
817
+ };
818
+ const assertActive = () => {
819
+ if (requestSignal.aborted) cancel(new RequestCancellationError());
820
+ else if (timeoutError && !failure && performance.now() - scopeStartedAt >= timeoutMs) {
821
+ cancel(timeoutError);
822
+ }
823
+ if (failure) throw failure;
824
+ };
825
+ const onRequestAbort = () => cancel(new RequestCancellationError());
826
+ requestSignal.addEventListener("abort", onRequestAbort, { once: true });
842
827
  let timer;
843
- const timeout = new Promise((_, reject) => {
844
- timer = setTimeout(() => reject(new RuleTimeoutError(ruleName, timeoutMs)), timeoutMs);
828
+ if (timeoutError) {
829
+ timer = setTimeout(() => cancel(timeoutError), timeoutMs);
830
+ }
831
+ const work = Promise.resolve().then(async () => {
832
+ if (controller.signal.aborted) throw failure ?? new RequestCancellationError();
833
+ try {
834
+ const result = await run(controller.signal, assertActive);
835
+ if (timeoutError && !failure && performance.now() - scopeStartedAt >= timeoutMs) {
836
+ cancel(timeoutError);
837
+ }
838
+ if (failure) throw failure;
839
+ return result;
840
+ } catch (error) {
841
+ if (timeoutError && !failure && performance.now() - scopeStartedAt >= timeoutMs) {
842
+ cancel(timeoutError);
843
+ }
844
+ throw failure ?? error;
845
+ }
845
846
  });
846
847
  try {
847
- return await Promise.race([promise, timeout]);
848
+ return await Promise.race([work, cancelled]);
849
+ } catch (error) {
850
+ throw failure ?? error;
848
851
  } finally {
849
852
  if (timer !== void 0) clearTimeout(timer);
850
- void promise.catch(() => {
853
+ requestSignal.removeEventListener("abort", onRequestAbort);
854
+ void work.catch(() => {
851
855
  });
852
856
  }
853
857
  }
858
+ async function runInRecoveryScope(requestSignal, run) {
859
+ const controller = new AbortController();
860
+ const abort = () => controller.abort();
861
+ if (requestSignal.aborted) controller.abort();
862
+ else requestSignal.addEventListener("abort", abort, { once: true });
863
+ try {
864
+ return await run(controller.signal);
865
+ } finally {
866
+ requestSignal.removeEventListener("abort", abort);
867
+ }
868
+ }
854
869
 
855
870
  // src/core/engine.ts
856
871
  function monotonicNow() {
857
- try {
858
- if (typeof globalThis.performance?.now === "function") return globalThis.performance.now();
859
- } catch {
860
- }
861
- return Date.now();
872
+ return performance.now();
862
873
  }
863
874
  function normalizeDebugLevel(level) {
864
875
  return level === true ? "detailed" : level;
@@ -925,76 +936,56 @@ function safeLogger(logger) {
925
936
  error: wrap("error")
926
937
  };
927
938
  }
928
- function isNextResponse(value) {
929
- return value instanceof import_server2.NextResponse && value.headers.get("x-middleware-next") === "1";
939
+ function isTerminalRecovery(value) {
940
+ return value instanceof Response && resolveRuleResult(value).kind === "stop";
941
+ }
942
+ function isContinuingRecovery(value) {
943
+ return value instanceof Response && resolveRuleResult(value).kind === "continue";
930
944
  }
931
945
  function stripRoutingOverrides(res) {
932
946
  const plain = !(res instanceof import_server2.NextResponse);
933
- for (const key of [...res.headers.keys()]) {
947
+ const keys = [...res.headers.keys()];
948
+ const remove = keys.filter((key) => {
934
949
  const lower = key.toLowerCase();
935
- if (lower === "x-middleware-override-headers" || lower.startsWith("x-middleware-request-") || plain && (lower === "x-middleware-next" || lower === "x-middleware-rewrite")) {
936
- res.headers.delete(key);
937
- }
938
- }
939
- }
940
- function isPathFilter(value) {
941
- if (value === null || typeof value !== "object") return false;
942
- if ("nextUrl" in value) return false;
943
- return "include" in value || "exclude" in value || "name" in value;
944
- }
945
- function defineProxy(nameOrRun, maybeRun) {
946
- const defaultName = typeof nameOrRun === "string" ? nameOrRun : void 0;
947
- const run = typeof nameOrRun === "function" ? nameOrRun : maybeRun;
948
- const proxy = ((reqOrFilter, eventOrCtx, maybeEvent) => {
949
- if (isPathFilter(reqOrFilter)) {
950
- return withPaths(run, {
951
- ...reqOrFilter,
952
- name: reqOrFilter.name ?? defaultName
953
- });
954
- }
955
- return run(reqOrFilter, eventOrCtx, maybeEvent);
956
- });
957
- Object.defineProperty(proxy, "name", {
958
- value: defaultName ?? "",
959
- configurable: true
950
+ return lower === "x-middleware-override-headers" || lower.startsWith("x-middleware-request-") || plain && (lower === "x-middleware-next" || lower === "x-middleware-rewrite");
960
951
  });
961
- Object.defineProperty(proxy, CONTEXT_RULE, { value: true });
962
- return proxy;
952
+ if (!remove.length) return res;
953
+ try {
954
+ for (const key of remove) res.headers.delete(key);
955
+ return res;
956
+ } catch {
957
+ const headers = new Headers(res.headers);
958
+ for (const key of remove) headers.delete(key);
959
+ const init = { headers, status: res.status, statusText: res.statusText };
960
+ return res instanceof import_server2.NextResponse ? new import_server2.NextResponse(res.body, init) : new Response(res.body, init);
961
+ }
963
962
  }
964
- function resolveConfig(overrides, fallbackCreateContext) {
965
- const { logger, debug, createContext, ...rest } = overrides;
963
+ function resolveConfig(overrides) {
964
+ const { logger, debug, ...rest } = overrides;
966
965
  const config = {
967
- createContext: createContext ?? fallbackCreateContext,
968
966
  cookieMergeStrategy: "last-write-wins",
969
967
  headerMergeStrategy: "last-write-wins",
970
968
  debug: false,
971
- ruleTimeoutMs: 0,
972
- requestHeaderPolicy: {},
969
+ timeout: 0,
973
970
  strictOverrideCheck: false,
974
- hostFolderHeader: void 0,
975
971
  tracePath: true,
976
972
  ...rest,
977
973
  ...debug !== void 0 ? { debug } : {},
978
974
  logger: safeLogger(logger ?? createConsoleLogger("info"))
979
975
  };
980
- assertFiniteRuleTimeoutMs(config.ruleTimeoutMs);
976
+ assertValidTimeout(config.timeout);
981
977
  return config;
982
978
  }
983
- function proxyChain(optionsOrEntries, maybeEntries) {
984
- const options = Array.isArray(optionsOrEntries) ? {} : optionsOrEntries;
985
- const entries = (Array.isArray(optionsOrEntries) ? optionsOrEntries : maybeEntries) ?? [];
986
- const fallbackCreateContext = createProxyContext;
987
- const config = resolveConfig(options, fallbackCreateContext);
979
+ function executeChain(options, entries) {
980
+ const config = resolveConfig(options);
988
981
  const rules = entries.map(toRule);
989
982
  const {
990
983
  logger,
991
984
  debug: debugLevel,
992
985
  cookieMergeStrategy,
993
986
  headerMergeStrategy,
994
- ruleTimeoutMs,
995
- requestHeaderPolicy,
996
- strictOverrideCheck,
997
- hostFolderHeader
987
+ timeout,
988
+ strictOverrideCheck
998
989
  } = config;
999
990
  const debug = debugLevel !== false;
1000
991
  const hasHandlerDebug = rules.some((rule) => rule.debug != null && rule.debug !== false);
@@ -1005,10 +996,14 @@ function proxyChain(optionsOrEntries, maybeEntries) {
1005
996
  assertOverrideMechanismSupported(strictOverrideCheck);
1006
997
  for (let i = 0; i < rules.length; i++) {
1007
998
  assertIncludeExcludeNoOverlap(rules[i].include, rules[i].exclude, ruleLabel(rules[i], i));
1008
- assertFiniteRuleTimeoutMs(rules[i].timeout);
999
+ assertValidTimeout(rules[i].timeout);
1009
1000
  }
1010
1001
  return async function proxy(req, event) {
1011
- const startedAt = diagnosticsEnabled ? monotonicNow() : 0;
1002
+ const startedAt = Date.now();
1003
+ const invocationStartedAt = monotonicNow();
1004
+ const requestId = `req_${globalThis.crypto.randomUUID()}`;
1005
+ const metadata = createRequestMetadata(req, requestId, startedAt, invocationStartedAt);
1006
+ const applicationState = createApplicationState();
1012
1007
  const diagnostics = diagnosticsEnabled ? [] : null;
1013
1008
  let nextHandlerIndex = 0;
1014
1009
  const finish = (response, forcedOutcome) => {
@@ -1020,9 +1015,11 @@ function proxyChain(optionsOrEntries, maybeEntries) {
1020
1015
  });
1021
1016
  }
1022
1017
  const trace = {
1018
+ requestId,
1019
+ startedAt,
1023
1020
  method: safeDiagnosticText(req.method, 16),
1024
- pathname: config.tracePath === false ? void 0 : safeDiagnosticText(req.nextUrl.pathname),
1025
- durationMs: monotonicNow() - startedAt,
1021
+ pathname: config.tracePath === false ? void 0 : safeDiagnosticText(metadata.originalPathname),
1022
+ durationMs: monotonicNow() - invocationStartedAt,
1026
1023
  outcome: forcedOutcome ?? responseOutcome(response),
1027
1024
  handlers: diagnostics
1028
1025
  };
@@ -1035,14 +1032,14 @@ function proxyChain(optionsOrEntries, maybeEntries) {
1035
1032
  }
1036
1033
  const globalLevel = normalizeDebugLevel(debugLevel);
1037
1034
  if (globalLevel !== false || hasHandlerDebug) {
1038
- const visible = diagnostics.filter((_handler, index) => {
1035
+ const level = (globalLevel === "compact" || globalLevel === false) && hasDetailedHandlerDebug ? "detailed" : globalLevel === false ? "compact" : globalLevel;
1036
+ const visible = level === "compact" ? diagnostics : diagnostics.filter((_handler, index) => {
1039
1037
  const local = rules[index]?.debug;
1040
1038
  if (local === false) return false;
1041
1039
  if (local === "compact") return globalLevel === "compact";
1042
1040
  if (local != null) return true;
1043
1041
  return globalLevel !== false && !(globalLevel === "compact" && hasDetailedHandlerDebug);
1044
1042
  });
1045
- const level = (globalLevel === "compact" || globalLevel === false) && hasDetailedHandlerDebug ? "detailed" : globalLevel === false ? "compact" : globalLevel;
1046
1043
  try {
1047
1044
  config.logger.info(
1048
1045
  formatTrace(
@@ -1057,15 +1054,10 @@ function proxyChain(optionsOrEntries, maybeEntries) {
1057
1054
  }
1058
1055
  return response;
1059
1056
  };
1060
- let ctx;
1061
- try {
1062
- ctx = config.createContext(req, event);
1063
- } catch {
1064
- if (!diagnosticsEnabled) logger.error("request context creation failed");
1065
- return finish(safeInternalError(), { type: "error", status: 500, classification: "engine" });
1066
- }
1057
+ const contextFor = (signal) => createHandlerContext(metadata, applicationState, signal);
1067
1058
  let currentReq = req;
1068
1059
  let pendingRequestOverrides = null;
1060
+ let replaceRequestHeaders = false;
1069
1061
  let pendingRewriteUrl = null;
1070
1062
  const headerWrites = [];
1071
1063
  const cookieWrites = [];
@@ -1078,96 +1070,182 @@ function proxyChain(optionsOrEntries, maybeEntries) {
1078
1070
  logger,
1079
1071
  debug
1080
1072
  );
1073
+ const requestCancelledResponse = () => finish(
1074
+ finalizeResponse(
1075
+ import_server2.NextResponse.next(),
1076
+ headerWrites,
1077
+ cookieWrites,
1078
+ headerMergeStrategy,
1079
+ cookieMergeStrategy,
1080
+ logger,
1081
+ debug
1082
+ ),
1083
+ { type: "request-cancelled" }
1084
+ );
1081
1085
  const materializeRequest = () => {
1082
1086
  if (!pendingRequestOverrides) return currentReq;
1083
- if (!headersDiffer(currentReq.headers, pendingRequestOverrides)) {
1087
+ if (!replaceRequestHeaders && !headersDiffer(currentReq.headers, pendingRequestOverrides)) {
1084
1088
  pendingRequestOverrides = null;
1085
1089
  return currentReq;
1086
1090
  }
1087
- const merged = new Headers(currentReq.headers);
1091
+ const nextUrl = currentReq.nextUrl.clone();
1092
+ const merged = replaceRequestHeaders ? new Headers() : new Headers(currentReq.headers);
1088
1093
  pendingRequestOverrides.forEach((v, k) => {
1089
1094
  merged.set(k, v);
1090
1095
  });
1091
1096
  pendingRequestOverrides = null;
1097
+ replaceRequestHeaders = false;
1092
1098
  currentReq = new import_server2.NextRequest(currentReq, { headers: merged });
1099
+ currentReq.nextUrl.pathname = nextUrl.pathname;
1100
+ currentReq.nextUrl.search = nextUrl.search;
1093
1101
  return currentReq;
1094
1102
  };
1095
- const appliedRequestOverrides = new Headers();
1096
- const queueRequestOverrides = (overrides) => {
1097
- if (!pendingRequestOverrides) pendingRequestOverrides = new Headers();
1103
+ const queueRequestOverrides = (overrides, mode) => {
1104
+ if (mode === "replace") {
1105
+ pendingRequestOverrides = new Headers();
1106
+ replaceRequestHeaders = true;
1107
+ } else if (!pendingRequestOverrides) {
1108
+ pendingRequestOverrides = new Headers();
1109
+ }
1098
1110
  const target = pendingRequestOverrides;
1099
1111
  overrides.forEach((v, k) => {
1100
1112
  target.set(k, v);
1101
- appliedRequestOverrides.set(k, v);
1102
1113
  });
1103
1114
  };
1104
- const recoverRuleError = async (err, i, label, req2, startedAt2) => {
1115
+ const recoverRuleError = async (err, i, label, req2, durationMs, phase) => {
1105
1116
  const timeoutError = err instanceof RuleTimeoutError;
1106
- const durationMs = () => diagnosticsEnabled ? monotonicNow() - startedAt2 : 0;
1117
+ const requestCancelled = err instanceof RequestCancellationError;
1107
1118
  const errorHandler = rules[i].onError ?? config.onError;
1108
1119
  const errorPolicy = rules[i].onError ? "handler" : "chain";
1109
- if (!errorHandler) {
1110
- if (!diagnosticsEnabled) logger.error("handler failed");
1120
+ const diagnosticPhase = phase === "before-handler" ? "handler" : phase;
1121
+ const details = handlerDetails(rules[i], timeout, "matched", "matched", "not-matched");
1122
+ const stopFailure = (policy) => {
1111
1123
  diagnostics?.push({
1112
1124
  name: safeDiagnosticText(label, 64),
1113
- outcome: timeoutError ? "timeout" : "failed",
1114
- durationMs: durationMs(),
1115
- policy: "none",
1116
- details: handlerDetails(rules[i], ruleTimeoutMs, "matched", "matched", "not-matched")
1125
+ ...requestCancelled ? {
1126
+ outcome: "request-cancelled",
1127
+ durationMs,
1128
+ phase: phase === "result" ? "handler" : phase,
1129
+ policy
1130
+ } : {
1131
+ outcome: timeoutError ? "timeout" : "failed",
1132
+ durationMs,
1133
+ phase: diagnosticPhase,
1134
+ policy,
1135
+ ...timeoutError ? { timeoutMs: err.timeoutMs } : {}
1136
+ },
1137
+ details
1117
1138
  });
1118
1139
  nextHandlerIndex = i + 1;
1119
- return {
1120
- response: finish(
1121
- failClosed(),
1122
- timeoutError ? {
1140
+ if (requestCancelled) {
1141
+ return {
1142
+ response: finish(
1143
+ finalizeResponse(
1144
+ import_server2.NextResponse.next(),
1145
+ headerWrites,
1146
+ cookieWrites,
1147
+ headerMergeStrategy,
1148
+ cookieMergeStrategy,
1149
+ logger,
1150
+ debug
1151
+ ),
1152
+ { type: "request-cancelled" }
1153
+ )
1154
+ };
1155
+ }
1156
+ if (timeoutError) {
1157
+ return {
1158
+ response: finish(failClosed(), {
1123
1159
  type: "timeout",
1124
1160
  status: 500,
1125
- timeoutMs: err instanceof RuleTimeoutError ? err.timeoutMs : ruleTimeoutMs
1126
- } : { type: "error", status: 500, classification: "handler" }
1127
- )
1161
+ timeoutMs: err.timeoutMs
1162
+ })
1163
+ };
1164
+ }
1165
+ return {
1166
+ response: finish(failClosed(), {
1167
+ type: "error",
1168
+ status: 500,
1169
+ classification: "handler"
1170
+ })
1128
1171
  };
1172
+ };
1173
+ if (!errorHandler) {
1174
+ if (!diagnosticsEnabled) logger.error("handler failed");
1175
+ return stopFailure("none");
1129
1176
  }
1130
1177
  try {
1131
- const recovered = await errorHandler(err, i, req2, ctx);
1178
+ const recovered = await runInRecoveryScope(
1179
+ req2.signal,
1180
+ (signal) => errorHandler(err, i, req2, contextFor(signal))
1181
+ );
1182
+ if (timeoutError || requestCancelled) {
1183
+ if (isTerminalRecovery(recovered)) {
1184
+ const response2 = stripRoutingOverrides(recovered);
1185
+ headerWrites.push({
1186
+ ruleIndex: i,
1187
+ ruleName: label,
1188
+ items: responseHeaderItems(response2.headers)
1189
+ });
1190
+ cookieWrites.push({
1191
+ ruleIndex: i,
1192
+ ruleName: label,
1193
+ items: cookieItemsFromHeaders(response2.headers)
1194
+ });
1195
+ diagnostics?.push({
1196
+ name: safeDiagnosticText(label, 64),
1197
+ ...requestCancelled ? {
1198
+ outcome: "request-cancelled",
1199
+ durationMs,
1200
+ phase: phase === "result" ? "handler" : phase,
1201
+ policy: errorPolicy,
1202
+ recovery: "response"
1203
+ } : {
1204
+ outcome: "timeout",
1205
+ durationMs,
1206
+ phase: diagnosticPhase,
1207
+ policy: errorPolicy,
1208
+ recovery: "response",
1209
+ timeoutMs: err.timeoutMs
1210
+ },
1211
+ details
1212
+ });
1213
+ nextHandlerIndex = i + 1;
1214
+ return {
1215
+ response: finish(
1216
+ finalizeResponse(
1217
+ response2,
1218
+ headerWrites,
1219
+ cookieWrites,
1220
+ headerMergeStrategy,
1221
+ cookieMergeStrategy,
1222
+ logger,
1223
+ debug
1224
+ ),
1225
+ requestCancelled ? { type: "request-cancelled" } : {
1226
+ type: "timeout",
1227
+ status: recovered.status,
1228
+ timeoutMs: err.timeoutMs
1229
+ }
1230
+ )
1231
+ };
1232
+ }
1233
+ return stopFailure(errorPolicy);
1234
+ }
1132
1235
  if (recovered == null) {
1133
- diagnostics?.push({
1134
- name: safeDiagnosticText(label, 64),
1135
- outcome: timeoutError ? "timeout" : "failed",
1136
- durationMs: durationMs(),
1137
- policy: errorPolicy,
1138
- details: handlerDetails(rules[i], ruleTimeoutMs, "matched", "matched", "not-matched")
1139
- });
1140
- nextHandlerIndex = i + 1;
1141
- return {
1142
- response: finish(
1143
- failClosed(),
1144
- timeoutError ? {
1145
- type: "timeout",
1146
- status: 500,
1147
- timeoutMs: err instanceof RuleTimeoutError ? err.timeoutMs : ruleTimeoutMs
1148
- } : { type: "error", status: 500, classification: "handler" }
1149
- )
1150
- };
1236
+ return stopFailure(errorPolicy);
1151
1237
  }
1152
- if (isNextResult(recovered) || isNextResponse(recovered)) {
1153
- diagnostics?.push({
1154
- name: safeDiagnosticText(label, 64),
1155
- outcome: "recovered",
1156
- durationMs: durationMs(),
1157
- recovery: "continue",
1158
- policy: errorPolicy,
1159
- details: handlerDetails(rules[i], ruleTimeoutMs, "matched", "matched", "not-matched")
1160
- });
1161
- nextHandlerIndex = i + 1;
1162
- return { raw: recovered };
1238
+ if (isContinuingRecovery(recovered)) {
1239
+ return { raw: recovered, recovered: { durationMs, policy: errorPolicy, details } };
1163
1240
  }
1164
1241
  if (!(recovered instanceof Response)) {
1165
1242
  diagnostics?.push({
1166
1243
  name: safeDiagnosticText(label, 64),
1167
- outcome: timeoutError ? "timeout" : "failed",
1168
- durationMs: durationMs(),
1244
+ outcome: "failed",
1245
+ durationMs,
1246
+ phase: diagnosticPhase,
1169
1247
  policy: errorPolicy,
1170
- details: handlerDetails(rules[i], ruleTimeoutMs, "matched", "matched", "not-matched")
1248
+ details
1171
1249
  });
1172
1250
  nextHandlerIndex = i + 1;
1173
1251
  return {
@@ -1178,30 +1256,30 @@ function proxyChain(optionsOrEntries, maybeEntries) {
1178
1256
  })
1179
1257
  };
1180
1258
  }
1181
- stripRoutingOverrides(recovered);
1259
+ const response = stripRoutingOverrides(recovered);
1182
1260
  headerWrites.push({
1183
1261
  ruleIndex: i,
1184
1262
  ruleName: label,
1185
- items: responseHeaderItems(recovered.headers)
1263
+ items: responseHeaderItems(response.headers)
1186
1264
  });
1187
1265
  cookieWrites.push({
1188
1266
  ruleIndex: i,
1189
1267
  ruleName: label,
1190
- items: cookieItemsFromHeaders(recovered.headers)
1268
+ items: cookieItemsFromHeaders(response.headers)
1191
1269
  });
1192
1270
  diagnostics?.push({
1193
1271
  name: safeDiagnosticText(label, 64),
1194
1272
  outcome: "recovered",
1195
- durationMs: durationMs(),
1196
- recovery: responseOutcome(recovered).type === "redirect" ? "redirect" : responseOutcome(recovered).type === "rewrite" ? "rewrite" : "response",
1273
+ durationMs,
1274
+ recovery: responseOutcome(response).type === "redirect" ? "redirect" : responseOutcome(response).type === "rewrite" ? "rewrite" : "response",
1197
1275
  policy: errorPolicy,
1198
- details: handlerDetails(rules[i], ruleTimeoutMs, "matched", "matched", "not-matched")
1276
+ details
1199
1277
  });
1200
1278
  nextHandlerIndex = i + 1;
1201
1279
  return {
1202
1280
  response: finish(
1203
1281
  finalizeResponse(
1204
- recovered,
1282
+ response,
1205
1283
  headerWrites,
1206
1284
  cookieWrites,
1207
1285
  headerMergeStrategy,
@@ -1213,27 +1291,26 @@ function proxyChain(optionsOrEntries, maybeEntries) {
1213
1291
  };
1214
1292
  } catch {
1215
1293
  if (!diagnosticsEnabled) logger.error("chain error handler failed");
1216
- diagnostics?.push({
1217
- name: safeDiagnosticText(label, 64),
1218
- outcome: timeoutError ? "timeout" : "failed",
1219
- durationMs: durationMs(),
1220
- policy: errorPolicy,
1221
- details: handlerDetails(rules[i], ruleTimeoutMs, "matched", "matched", "not-matched")
1222
- });
1223
- nextHandlerIndex = i + 1;
1224
- return {
1225
- response: finish(failClosed(), {
1226
- type: "error",
1227
- status: 500,
1228
- classification: "handler"
1229
- })
1230
- };
1294
+ return stopFailure(errorPolicy);
1231
1295
  }
1232
1296
  };
1233
1297
  try {
1234
1298
  for (let i = 0; i < rules.length; i++) {
1235
1299
  const rule = rules[i];
1236
1300
  const label = ruleLabel(rule, i);
1301
+ nextHandlerIndex = i;
1302
+ if (req.signal.aborted) {
1303
+ const cancelled = await recoverRuleError(
1304
+ new RequestCancellationError(),
1305
+ i,
1306
+ label,
1307
+ materializeRequest(),
1308
+ 0,
1309
+ "before-handler"
1310
+ );
1311
+ if ("response" in cancelled) return cancelled.response;
1312
+ return requestCancelledResponse();
1313
+ }
1237
1314
  const activeReq = materializeRequest();
1238
1315
  const reqHost = normalizeHost(
1239
1316
  activeReq.headers.get("host") ?? activeReq.headers.get("x-forwarded-host")
@@ -1247,7 +1324,6 @@ function proxyChain(optionsOrEntries, maybeEntries) {
1247
1324
  })
1248
1325
  );
1249
1326
  }
1250
- nextHandlerIndex = i;
1251
1327
  const skipReason = ruleMatchReason(matchPath, reqHost, rule);
1252
1328
  if (skipReason) {
1253
1329
  diagnostics?.push({
@@ -1256,7 +1332,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
1256
1332
  reason: skipReason,
1257
1333
  details: handlerDetails(
1258
1334
  rule,
1259
- ruleTimeoutMs,
1335
+ timeout,
1260
1336
  "not-evaluated",
1261
1337
  skipReason === "include-mismatch" ? "mismatch" : void 0,
1262
1338
  skipReason === "exclude-match" ? "matched" : skipReason === "include-mismatch" && rule.exclude ? "not-matched" : void 0
@@ -1265,44 +1341,66 @@ function proxyChain(optionsOrEntries, maybeEntries) {
1265
1341
  nextHandlerIndex = i + 1;
1266
1342
  continue;
1267
1343
  }
1268
- const startedAt2 = diagnosticsEnabled ? monotonicNow() : 0;
1269
- let raw;
1344
+ const executionStartedAt = monotonicNow();
1345
+ const effectiveTimeout = rule.timeout ?? timeout;
1346
+ let phase = rule.when ? "when" : "handler";
1347
+ let result;
1348
+ let recoveredRule;
1270
1349
  try {
1271
- const result = await withRuleTimeout(
1272
- (async () => {
1273
- if (rule.when && !await rule.when(activeReq, event, ctx)) {
1274
- return { kind: "skipped" };
1350
+ result = await runInExecutionScope(
1351
+ req.signal,
1352
+ effectiveTimeout,
1353
+ label,
1354
+ async (signal, assertActive) => {
1355
+ const context = contextFor(signal);
1356
+ if (rule.when) {
1357
+ const matches = await rule.when(activeReq, event, context);
1358
+ assertActive();
1359
+ if (!matches) return { kind: "skipped" };
1275
1360
  }
1276
- return { kind: "result", raw: await rule.run(activeReq, ctx, event) };
1277
- })(),
1278
- rule.timeout ?? ruleTimeoutMs,
1279
- label
1361
+ phase = "handler";
1362
+ assertActive();
1363
+ return {
1364
+ kind: "result",
1365
+ raw: await rule.run(activeReq, context, event)
1366
+ };
1367
+ }
1280
1368
  );
1281
1369
  if (result.kind === "skipped") {
1282
1370
  diagnostics?.push({
1283
1371
  name: safeDiagnosticText(label, 64),
1284
1372
  outcome: "skipped",
1285
1373
  reason: "when-false",
1286
- details: handlerDetails(rule, ruleTimeoutMs, "false", "matched", "not-matched")
1374
+ details: handlerDetails(rule, timeout, "false", "matched", "not-matched")
1287
1375
  });
1288
1376
  nextHandlerIndex = i + 1;
1289
1377
  continue;
1290
1378
  }
1291
- raw = result.raw;
1292
1379
  } catch (err) {
1293
- const recovered = await recoverRuleError(err, i, label, activeReq, startedAt2);
1380
+ const recovered = await recoverRuleError(
1381
+ err,
1382
+ i,
1383
+ label,
1384
+ activeReq,
1385
+ monotonicNow() - executionStartedAt,
1386
+ phase
1387
+ );
1294
1388
  if ("response" in recovered) return recovered.response;
1295
- raw = recovered.raw;
1389
+ result = { kind: "result", raw: recovered.raw };
1390
+ recoveredRule = recovered.recovered;
1296
1391
  }
1392
+ let raw = result.raw;
1393
+ let duration2 = monotonicNow() - executionStartedAt;
1297
1394
  let outcome;
1298
1395
  try {
1299
- outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
1396
+ outcome = resolveRuleResult(raw);
1300
1397
  } catch (err) {
1301
- const recovered = await recoverRuleError(err, i, label, activeReq, startedAt2);
1398
+ const recovered = await recoverRuleError(err, i, label, activeReq, duration2, "result");
1302
1399
  if ("response" in recovered) return recovered.response;
1303
- outcome = resolveRuleResult(recovered.raw, requestHeaderPolicy, logger, debug);
1400
+ raw = recovered.raw;
1401
+ recoveredRule = recovered.recovered;
1402
+ outcome = resolveRuleResult(raw);
1304
1403
  }
1305
- const duration2 = diagnosticsEnabled ? monotonicNow() - startedAt2 : 0;
1306
1404
  if (outcome.kind === "continue") {
1307
1405
  if (outcome.rewriteUrl) {
1308
1406
  pendingRewriteUrl = outcome.rewriteUrl;
@@ -1317,12 +1415,21 @@ function proxyChain(optionsOrEntries, maybeEntries) {
1317
1415
  currentReq.nextUrl.pathname = outcome.rewriteUrl;
1318
1416
  }
1319
1417
  }
1320
- if (outcome.request) queueRequestOverrides(outcome.request);
1418
+ if (outcome.request) queueRequestOverrides(outcome.request, outcome.requestMode);
1321
1419
  if (outcome.responseHeaders.size || outcome.cookies.size) {
1322
1420
  headerWrites.push({ ruleIndex: i, ruleName: label, items: outcome.responseHeaders });
1323
1421
  cookieWrites.push({ ruleIndex: i, ruleName: label, items: outcome.cookies });
1324
1422
  }
1325
- if (diagnostics?.at(-1)?.outcome !== "recovered") {
1423
+ if (recoveredRule) {
1424
+ diagnostics?.push({
1425
+ name: safeDiagnosticText(label, 64),
1426
+ outcome: "recovered",
1427
+ durationMs: recoveredRule.durationMs,
1428
+ recovery: outcome.rewriteUrl ? "rewrite" : "continue",
1429
+ policy: recoveredRule.policy,
1430
+ details: recoveredRule.details
1431
+ });
1432
+ } else {
1326
1433
  diagnostics?.push(
1327
1434
  outcome.rewriteUrl ? {
1328
1435
  name: safeDiagnosticText(label, 64),
@@ -1330,43 +1437,31 @@ function proxyChain(optionsOrEntries, maybeEntries) {
1330
1437
  durationMs: duration2,
1331
1438
  destination: safeDestination(outcome.rewriteUrl) ?? "/",
1332
1439
  final: false,
1333
- details: handlerDetails(
1334
- rule,
1335
- ruleTimeoutMs,
1336
- "matched",
1337
- "matched",
1338
- "not-matched"
1339
- )
1440
+ details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
1340
1441
  } : {
1341
1442
  name: safeDiagnosticText(label, 64),
1342
1443
  outcome: "continue",
1343
- source: isNextResult(raw) ? "next()" : raw instanceof import_server2.NextResponse && raw.headers.get("x-middleware-next") === "1" ? "NextResponse.next()" : "undefined",
1444
+ source: raw instanceof import_server2.NextResponse && raw.headers.get("x-middleware-next") === "1" ? "NextResponse.next()" : "undefined",
1344
1445
  durationMs: duration2,
1345
- details: handlerDetails(
1346
- rule,
1347
- ruleTimeoutMs,
1348
- "matched",
1349
- "matched",
1350
- "not-matched"
1351
- )
1446
+ details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
1352
1447
  }
1353
1448
  );
1354
1449
  }
1355
1450
  nextHandlerIndex = i + 1;
1356
1451
  continue;
1357
1452
  }
1358
- stripRoutingOverrides(outcome.response);
1453
+ const response = stripRoutingOverrides(outcome.response);
1359
1454
  headerWrites.push({
1360
1455
  ruleIndex: i,
1361
1456
  ruleName: label,
1362
- items: responseHeaderItems(outcome.response.headers)
1457
+ items: responseHeaderItems(response.headers)
1363
1458
  });
1364
1459
  cookieWrites.push({
1365
1460
  ruleIndex: i,
1366
1461
  ruleName: label,
1367
- items: cookieItemsFromHeaders(outcome.response.headers)
1462
+ items: cookieItemsFromHeaders(response.headers)
1368
1463
  });
1369
- const terminalOutcome = responseOutcome(outcome.response);
1464
+ const terminalOutcome = responseOutcome(response);
1370
1465
  diagnostics?.push(
1371
1466
  terminalOutcome.type === "redirect" ? {
1372
1467
  name: safeDiagnosticText(label, 64),
@@ -1374,40 +1469,31 @@ function proxyChain(optionsOrEntries, maybeEntries) {
1374
1469
  durationMs: duration2,
1375
1470
  status: terminalOutcome.status,
1376
1471
  destination: terminalOutcome.destination,
1377
- details: handlerDetails(rule, ruleTimeoutMs, "matched", "matched", "not-matched")
1472
+ details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
1378
1473
  } : terminalOutcome.type === "rewrite" ? {
1379
1474
  name: safeDiagnosticText(label, 64),
1380
1475
  outcome: "rewrite",
1381
1476
  durationMs: duration2,
1382
1477
  destination: terminalOutcome.destination,
1383
1478
  final: true,
1384
- details: handlerDetails(rule, ruleTimeoutMs, "matched", "matched", "not-matched")
1479
+ details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
1385
1480
  } : {
1386
1481
  name: safeDiagnosticText(label, 64),
1387
1482
  outcome: "response",
1388
1483
  durationMs: duration2,
1389
- status: outcome.response.status,
1390
- details: handlerDetails(rule, ruleTimeoutMs, "matched", "matched", "not-matched")
1484
+ status: response.status,
1485
+ details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
1391
1486
  }
1392
1487
  );
1393
1488
  nextHandlerIndex = i + 1;
1394
- const internalFolder = hostFolderHeader ? appliedRequestOverrides.get(hostFolderHeader) : null;
1395
- if (internalFolder && outcome.response.headers.has("x-middleware-rewrite")) {
1396
- const rawRewrite = outcome.response.headers.get("x-middleware-rewrite");
1397
- const cleanFolder = physicalFolderPrefix(internalFolder);
1398
- outcome.response.headers.set(
1399
- "x-middleware-rewrite",
1400
- applyFolderPrefix(rawRewrite, cleanFolder, currentReq.url)
1401
- );
1402
- }
1403
- const finalTerminalOutcome = responseOutcome(outcome.response);
1489
+ const finalTerminalOutcome = responseOutcome(response);
1404
1490
  const terminalTrace = diagnostics?.at(-1);
1405
1491
  if (finalTerminalOutcome.type === "rewrite" && terminalTrace?.outcome === "rewrite") {
1406
1492
  terminalTrace.destination = finalTerminalOutcome.destination;
1407
1493
  }
1408
1494
  return finish(
1409
1495
  finalizeResponse(
1410
- outcome.response,
1496
+ response,
1411
1497
  headerWrites,
1412
1498
  cookieWrites,
1413
1499
  headerMergeStrategy,
@@ -1419,21 +1505,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
1419
1505
  );
1420
1506
  }
1421
1507
  const finalReq = materializeRequest();
1422
- const internalHostFolder = hostFolderHeader ? appliedRequestOverrides.get(hostFolderHeader) : null;
1423
- let finalRewriteUrl = pendingRewriteUrl;
1424
- if (internalHostFolder) {
1425
- const cleanFolder = physicalFolderPrefix(internalHostFolder);
1426
- if (finalRewriteUrl) {
1427
- finalRewriteUrl = applyFolderPrefix(finalRewriteUrl, cleanFolder, finalReq.url);
1428
- } else {
1429
- const currentPath = finalReq.nextUrl.pathname;
1430
- if (!isInsideFolder(currentPath, cleanFolder)) {
1431
- const targetUrl = finalReq.nextUrl.clone();
1432
- targetUrl.pathname = cleanFolder + (currentPath === "/" ? "" : currentPath);
1433
- finalRewriteUrl = targetUrl.toString();
1434
- }
1435
- }
1436
- }
1508
+ const finalRewriteUrl = pendingRewriteUrl;
1437
1509
  const requestInit = finalReq !== req ? { request: { headers: finalReq.headers } } : void 0;
1438
1510
  let final;
1439
1511
  if (finalRewriteUrl) {
@@ -1464,12 +1536,15 @@ function proxyChain(optionsOrEntries, maybeEntries) {
1464
1536
  if (!diagnosticsEnabled) logger.error("proxy chain execution failed");
1465
1537
  if (config.onError) {
1466
1538
  try {
1467
- const recovered = await config.onError(err, -1, materializeRequest(), ctx);
1468
- if (recovered instanceof Response && !isNextResponse(recovered)) {
1469
- stripRoutingOverrides(recovered);
1539
+ const recovered = await runInRecoveryScope(
1540
+ req.signal,
1541
+ (signal) => config.onError(err, -1, materializeRequest(), contextFor(signal))
1542
+ );
1543
+ if (isTerminalRecovery(recovered)) {
1544
+ const response = stripRoutingOverrides(recovered);
1470
1545
  return finish(
1471
1546
  finalizeResponse(
1472
- recovered,
1547
+ response,
1473
1548
  headerWrites,
1474
1549
  cookieWrites,
1475
1550
  headerMergeStrategy,
@@ -1490,44 +1565,28 @@ function proxyChain(optionsOrEntries, maybeEntries) {
1490
1565
  };
1491
1566
  }
1492
1567
 
1493
- // src/core/chain.ts
1494
- function isContextRule(value) {
1495
- return typeof value === "function" && value[CONTEXT_RULE] === true;
1496
- }
1497
- function isScopeObject2(value) {
1498
- return typeof value === "object" && value !== null && !(value instanceof RegExp) && !Array.isArray(value);
1499
- }
1500
- function toFilter(scope) {
1501
- if (isScopeObject2(scope)) return { include: scope.include, exclude: scope.exclude };
1502
- return { include: scope };
1503
- }
1504
- function fromNative(handler) {
1505
- const run = (req, ctx, event) => handler(req, event, ctx);
1506
- const name = handler.name && handler.name !== "proxy" ? handler.name : void 0;
1507
- return { run, name };
1508
- }
1509
- function toEntry(entry) {
1510
- if (Array.isArray(entry)) {
1511
- const [target, scope] = entry;
1512
- const filter = toFilter(scope);
1513
- if (isContextRule(target)) return target(filter);
1514
- return withPaths(fromNative(target), filter);
1568
+ // src/core/handler.ts
1569
+ function assertHandlerConfig(options) {
1570
+ if (!options || typeof options !== "object" || typeof options.name !== "string" || options.name.trim() === "" || typeof options.handle !== "function") {
1571
+ throw new TypeError("[proxy-chain] configured handlers require a non-empty name and handle");
1515
1572
  }
1516
- if (isContextRule(entry)) return entry;
1517
- if (typeof entry === "function") return fromNative(entry);
1518
- return entry;
1519
- }
1520
- function chain(entries, options) {
1521
- const normalized = entries.map((entry) => toEntry(entry));
1522
- return proxyChain(options ?? {}, normalized);
1573
+ if ("handler" in options) {
1574
+ throw new TypeError(
1575
+ "[proxy-chain] configured handler property 'handler' is unsupported; use 'handle'"
1576
+ );
1577
+ }
1578
+ if ("config" in options || "options" in options) {
1579
+ throw new TypeError("[proxy-chain] handler configuration must use top-level options");
1580
+ }
1581
+ assertValidTimeout(options.timeout);
1523
1582
  }
1524
-
1525
- // src/core/handler.ts
1526
- function defineHandler(options) {
1583
+ function toHandlerRule(options) {
1584
+ assertHandlerConfig(options);
1585
+ const { handle } = options;
1527
1586
  const include = compileScopes(options.rules?.include);
1528
1587
  const exclude = compileScopes(options.rules?.exclude);
1529
- const rule = {
1530
- run: (request, context, event) => options.handler(request, event, context),
1588
+ return {
1589
+ run: (request, context, event) => handle(request, event, context),
1531
1590
  name: options.name,
1532
1591
  include,
1533
1592
  exclude,
@@ -1540,18 +1599,32 @@ function defineHandler(options) {
1540
1599
  exclude: options.rules?.exclude
1541
1600
  }
1542
1601
  };
1543
- return rule;
1602
+ }
1603
+ function defineHandler(options) {
1604
+ assertHandlerConfig(options);
1605
+ return options;
1606
+ }
1607
+
1608
+ // src/core/chain.ts
1609
+ function fromNative(handle) {
1610
+ const run = (req, ctx, event) => handle(req, event, ctx);
1611
+ const name = handle.name && handle.name !== "proxy" ? handle.name : void 0;
1612
+ return { run, name };
1613
+ }
1614
+ function toEntry(entry) {
1615
+ if (typeof entry === "function") return fromNative(entry);
1616
+ if (Array.isArray(entry)) {
1617
+ throw new TypeError("[proxy-chain] tuple entries are not supported; use a configured handler");
1618
+ }
1619
+ if (entry && typeof entry === "object") return toHandlerRule(entry);
1620
+ throw new TypeError("[proxy-chain] chain entries must be native handlers or configured handlers");
1621
+ }
1622
+ function chain(entries, options) {
1623
+ const normalized = entries.map((entry) => toEntry(entry));
1624
+ return executeChain(options ?? {}, normalized);
1544
1625
  }
1545
1626
  // Annotate the CommonJS export names for ESM import in node:
1546
1627
  0 && (module.exports = {
1547
- RuleTimeoutError,
1548
1628
  chain,
1549
- createProxyContext,
1550
- defineHandler,
1551
- defineProxy,
1552
- host,
1553
- isNextResult,
1554
- next,
1555
- path,
1556
- proxyChain
1629
+ defineHandler
1557
1630
  });