@klnap/next-proxy-chain 1.1.1 → 1.2.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
@@ -23,6 +23,7 @@ __export(index_exports, {
23
23
  RuleTimeoutError: () => RuleTimeoutError,
24
24
  chain: () => chain,
25
25
  createProxyContext: () => createProxyContext,
26
+ defineHandler: () => defineHandler,
26
27
  defineProxy: () => defineProxy,
27
28
  host: () => host,
28
29
  isNextResult: () => isNextResult,
@@ -264,22 +265,206 @@ function createConsoleLogger(minLevel = "info") {
264
265
  error: write("error")
265
266
  };
266
267
  }
267
- function formatDuration(ms) {
268
+
269
+ // src/core/diagnostics/sanitize.ts
270
+ var MAX_TEXT_LENGTH = 160;
271
+ function safeDiagnosticText(value, limit = MAX_TEXT_LENGTH) {
272
+ let output = "";
273
+ for (const char of value) {
274
+ const code = char.codePointAt(0);
275
+ 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) {
276
+ output += "\uFFFD";
277
+ } else {
278
+ output += char;
279
+ }
280
+ if (output.length >= limit) return `${output.slice(0, limit)}\u2026`;
281
+ }
282
+ return output;
283
+ }
284
+ function safeDestination(value) {
285
+ if (!value) return void 0;
286
+ try {
287
+ const url = new URL(value, "http://proxy-chain.invalid");
288
+ return safeDiagnosticText(`${url.pathname}${url.search ? "?[query]" : ""}`);
289
+ } catch {
290
+ return safeDiagnosticText(value.split(/[?#]/, 1)[0] ?? "");
291
+ }
292
+ }
293
+
294
+ // src/core/diagnostics/formatter.ts
295
+ function runtime() {
296
+ return globalThis.process;
297
+ }
298
+ function shouldUseColor() {
299
+ const process = runtime();
300
+ const env = process?.env;
301
+ if (env?.NO_COLOR) return false;
302
+ if (env?.FORCE_COLOR) return env.FORCE_COLOR !== "0";
303
+ if (env?.CI || env?.TERM === "dumb" || !process?.stdout?.isTTY) return false;
304
+ try {
305
+ return process.stdout.getColorDepth?.() !== 1;
306
+ } catch {
307
+ return false;
308
+ }
309
+ }
310
+ function supportsUnicode() {
311
+ const process = runtime();
312
+ if (!process?.env) return false;
313
+ const env = process.env;
314
+ const locale = (env.LC_ALL || env.LC_CTYPE || env.LANG || "").toLowerCase();
315
+ return !/(^|\s)(c|posix)(\.|$|\s)/.test(locale) && !locale.includes("ascii");
316
+ }
317
+ function paint(text, code, enabled) {
318
+ return enabled ? `\x1B[${code}m${text}\x1B[0m` : text;
319
+ }
320
+ function duration(ms) {
268
321
  return `${ms.toFixed(2)}ms`;
269
322
  }
270
- function formatPipelineLine(input) {
271
- const trace = input.traceId ? ` [${input.traceId.slice(0, 8)}]` : "";
272
- const req = `${input.method} ${input.path}${trace}`;
273
- const { name, outcome } = input;
274
- switch (outcome.kind) {
275
- case "passed":
276
- return `[proxy-chain] \xB7 ${req} | ${name} (${formatDuration(outcome.duration)}) -> passed`;
323
+ function handlerLabel(handler) {
324
+ switch (handler.outcome) {
325
+ case "continue":
326
+ return { symbol: "\u2713", text: "continue", color: 32 };
327
+ case "rewrite":
328
+ return { symbol: "\u21AA", text: "rewrite", color: 36 };
329
+ case "redirect":
330
+ return { symbol: "\u2197", text: "redirect", color: 33 };
331
+ case "response":
332
+ return { symbol: "\u2713", text: `response ${handler.status}`, color: 32 };
333
+ case "skipped":
334
+ return { symbol: "\u25CB", text: "skipped", color: 2 };
335
+ case "not-reached":
336
+ return { symbol: "\u2013", text: "not reached", color: 2 };
337
+ case "recovered":
338
+ return { symbol: "!", text: "recovered", color: 33 };
339
+ case "timeout":
340
+ return { symbol: "\xD7", text: "timeout", color: 31 };
341
+ case "failed":
342
+ return { symbol: "\xD7", text: "failed", color: 31 };
343
+ }
344
+ }
345
+ function outcomeText(outcome) {
346
+ switch (outcome.type) {
347
+ case "next":
348
+ return "NEXT";
349
+ case "rewrite":
350
+ return `REWRITE ${outcome.destination}`;
351
+ case "redirect":
352
+ return `REDIRECT ${outcome.status}${outcome.destination ? ` ${outcome.destination}` : ""}`;
353
+ case "response":
354
+ return `RESPONSE ${outcome.status}`;
355
+ case "error":
356
+ return `ERROR ${outcome.status}`;
357
+ case "timeout":
358
+ return `ERROR ${outcome.status} \xB7 timeout ${outcome.timeoutMs}ms`;
359
+ }
360
+ }
361
+ function outcomeColor(outcome) {
362
+ switch (outcome.type) {
277
363
  case "next":
278
- return `[proxy-chain] ~ ${req} | ${name} (${formatDuration(outcome.duration)}) -> headers mutated (${outcome.headers})`;
279
- case "stop":
280
- return `[proxy-chain] \xD7 ${req} | ${name} (${formatDuration(outcome.duration)}) -> stop ${outcome.status}`;
364
+ return 32;
365
+ case "rewrite":
366
+ return 36;
367
+ case "redirect":
368
+ return 33;
369
+ case "error":
370
+ case "timeout":
371
+ return 31;
372
+ case "response":
373
+ return outcome.status >= 500 ? 31 : 32;
281
374
  }
282
375
  }
376
+ function formatTrace(trace, level, color = shouldUseColor(), unicode = true) {
377
+ const path2 = trace.pathname ? ` ${safeDiagnosticText(trace.pathname)}` : "";
378
+ const header = `proxy-chain ${safeDiagnosticText(trace.method)}${path2}`;
379
+ const rows = [];
380
+ const handlers = trace.handlers;
381
+ 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)}`;
387
+ }
388
+ rows.push(`${header.padEnd(52)} ${duration(trace.durationMs)}`);
389
+ const shown = handlers;
390
+ const symbols = unicode ? {
391
+ pass: "\u2502",
392
+ last: "\u2514",
393
+ continue: "\u2713",
394
+ rewrite: "\u21AA",
395
+ redirect: "\u2197",
396
+ skip: "\u25CB",
397
+ missing: "\u2013",
398
+ error: "\xD7",
399
+ recovered: "!"
400
+ } : {
401
+ pass: "|",
402
+ last: "`-",
403
+ continue: "+",
404
+ rewrite: "->",
405
+ redirect: "->",
406
+ skip: "o",
407
+ missing: "-",
408
+ error: "x",
409
+ recovered: "!"
410
+ };
411
+ for (let index = 0; index < shown.length; index++) {
412
+ const handler = shown[index];
413
+ 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;
415
+ const prefix = symbols.pass;
416
+ const name = safeDiagnosticText(handler.name, 32);
417
+ const time = "durationMs" in handler ? paint(duration(handler.durationMs), 2, color) : "";
418
+ rows.push(
419
+ `${prefix} ${paint(symbol, label.color, color)} ${name.padEnd(16)} ${label.text.padEnd(14)} ${time}`.trimEnd()
420
+ );
421
+ if (level === "verbose") {
422
+ if (handler.details?.timeoutMs !== void 0) {
423
+ rows.push(
424
+ `${symbols.pass} timeout: ${handler.details.timeoutMs}ms (${handler.details.timeoutSource ?? "chain"})`
425
+ );
426
+ }
427
+ if (handler.details?.include) {
428
+ rows.push(
429
+ `${symbols.pass} include: ${handler.details.include.join(", ")}${handler.details.includeResult ? ` (${handler.details.includeResult})` : ""}`
430
+ );
431
+ }
432
+ if (handler.details?.exclude) {
433
+ rows.push(
434
+ `${symbols.pass} exclude: ${handler.details.exclude.join(", ")}${handler.details.excludeResult ? ` (${handler.details.excludeResult})` : ""}`
435
+ );
436
+ }
437
+ if (handler.details?.when) {
438
+ rows.push(
439
+ `${symbols.pass} when: ${handler.details.when === "matched" ? "true" : handler.details.when === "false" ? "false" : "not evaluated"}`
440
+ );
441
+ }
442
+ if (handler.outcome === "continue") rows.push(`${symbols.pass} source: ${handler.source}`);
443
+ if (handler.outcome === "skipped") rows.push(`${symbols.pass} reason: ${handler.reason}`);
444
+ if (handler.outcome === "rewrite") {
445
+ rows.push(`${symbols.pass} destination: ${handler.destination}`);
446
+ }
447
+ if (handler.outcome === "redirect" && handler.destination) {
448
+ rows.push(`${symbols.pass} destination: ${handler.destination}`);
449
+ }
450
+ }
451
+ if (handler.outcome === "recovered" || handler.outcome === "failed" || handler.outcome === "timeout") {
452
+ const policy = handler.policy === "none" ? "chain default" : handler.policy;
453
+ rows.push(`${symbols.pass} error policy: ${policy}`);
454
+ }
455
+ if (handler.outcome === "timeout" && handler.details?.timeoutMs !== void 0) {
456
+ rows.push(`${symbols.pass} deadline: ${handler.details.timeoutMs}ms`);
457
+ }
458
+ }
459
+ rows.push(
460
+ `${symbols.last} ${paint(outcomeText(trace.outcome), outcomeColor(trace.outcome), color)}`
461
+ );
462
+ const output = rows.join("\n");
463
+ if (output.length <= 16384) return output;
464
+ const safeBoundary = output.lastIndexOf("\n", 16384);
465
+ return `${output.slice(0, safeBoundary < 0 ? 16384 : safeBoundary)}
466
+ ${unicode ? "\u2026" : "..."} diagnostics truncated`;
467
+ }
283
468
 
284
469
  // src/core/matching.ts
285
470
  var RESERVED_FN_NAMES = /* @__PURE__ */ new Set(["", "proxy", "anonymous", "run", "next"]);
@@ -435,14 +620,25 @@ function withPaths(entry, filter) {
435
620
  const exclude = compileScopes(filter.exclude);
436
621
  const name = filter.name ?? base.name;
437
622
  assertIncludeExcludeNoOverlap(include, exclude, name ?? "proxy");
438
- return { run: base.run, include, exclude, name };
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
+ };
439
633
  }
440
- function ruleMatches(pathname, hostname, rule) {
441
- if (rule.exclude?.some((scope) => scopeMatches(pathname, hostname, scope))) return false;
634
+ function ruleMatchReason(pathname, hostname, rule) {
635
+ if (rule.exclude?.some((scope) => scopeMatches(pathname, hostname, scope))) {
636
+ return "exclude-match";
637
+ }
442
638
  if (rule.include && !rule.include.some((scope) => scopeMatches(pathname, hostname, scope))) {
443
- return false;
639
+ return "include-mismatch";
444
640
  }
445
- return true;
641
+ return void 0;
446
642
  }
447
643
  function normalizeHost(raw) {
448
644
  if (!raw) return null;
@@ -657,6 +853,78 @@ async function withRuleTimeout(promise, timeoutMs, ruleName) {
657
853
  }
658
854
 
659
855
  // src/core/engine.ts
856
+ function monotonicNow() {
857
+ try {
858
+ if (typeof globalThis.performance?.now === "function") return globalThis.performance.now();
859
+ } catch {
860
+ }
861
+ return Date.now();
862
+ }
863
+ function normalizeDebugLevel(level) {
864
+ return level === true ? "detailed" : level;
865
+ }
866
+ function responseOutcome(response) {
867
+ const rewrite = response.headers.get("x-middleware-rewrite");
868
+ if (rewrite) {
869
+ return { type: "rewrite", destination: safeDestination(rewrite) ?? "/" };
870
+ }
871
+ const location = response.headers.get("location");
872
+ if (location && response.status >= 300 && response.status < 400) {
873
+ return {
874
+ type: "redirect",
875
+ status: response.status,
876
+ destination: safeDestination(location)
877
+ };
878
+ }
879
+ if (response instanceof import_server2.NextResponse && response.headers.get("x-middleware-next") === "1") {
880
+ return { type: "next" };
881
+ }
882
+ return { type: "response", status: response.status };
883
+ }
884
+ function scopeNames(scopeList) {
885
+ if (scopeList === void 0) return void 0;
886
+ const scopes = Array.isArray(scopeList) ? scopeList : [scopeList];
887
+ return scopes.map((scope) => {
888
+ if (typeof scope === "string") return safeDiagnosticText(scope, 96);
889
+ if (scope instanceof RegExp) return safeDiagnosticText(scope.toString(), 96);
890
+ if (typeof scope !== "object" || scope === null) return "";
891
+ const value = scope;
892
+ const parts = [
893
+ value.path === void 0 ? void 0 : Array.isArray(value.path) ? value.path.map(String).join("|") : String(value.path),
894
+ value.host === void 0 ? void 0 : Array.isArray(value.host) ? value.host.map(String).join("|") : String(value.host)
895
+ ].filter(Boolean);
896
+ return safeDiagnosticText(parts.join(" @ "), 96);
897
+ });
898
+ }
899
+ function handlerDetails(rule, chainTimeout, when, includeResult, excludeResult) {
900
+ const include = scopeNames(rule.diagnosticRules?.include);
901
+ const exclude = scopeNames(rule.diagnosticRules?.exclude);
902
+ return {
903
+ ...include ? { include, includeResult } : {},
904
+ ...exclude ? { exclude, excludeResult } : {},
905
+ ...rule.when ? { when } : {},
906
+ timeoutMs: rule.timeout ?? chainTimeout,
907
+ timeoutSource: rule.timeout === void 0 ? "chain" : "handler"
908
+ };
909
+ }
910
+ function safeLogger(logger) {
911
+ const wrap = (method) => (...args) => {
912
+ try {
913
+ const result = logger[method](...args);
914
+ if (result && typeof result.then === "function") {
915
+ void Promise.resolve(result).catch(() => {
916
+ });
917
+ }
918
+ } catch {
919
+ }
920
+ };
921
+ return {
922
+ debug: wrap("debug"),
923
+ info: wrap("info"),
924
+ warn: wrap("warn"),
925
+ error: wrap("error")
926
+ };
927
+ }
660
928
  function isNextResponse(value) {
661
929
  return value instanceof import_server2.NextResponse && value.headers.get("x-middleware-next") === "1";
662
930
  }
@@ -704,9 +972,10 @@ function resolveConfig(overrides, fallbackCreateContext) {
704
972
  requestHeaderPolicy: {},
705
973
  strictOverrideCheck: false,
706
974
  hostFolderHeader: void 0,
975
+ tracePath: true,
707
976
  ...rest,
708
977
  ...debug !== void 0 ? { debug } : {},
709
- logger: logger ?? createConsoleLogger(debug ? "debug" : "info")
978
+ logger: safeLogger(logger ?? createConsoleLogger("info"))
710
979
  };
711
980
  assertFiniteRuleTimeoutMs(config.ruleTimeoutMs);
712
981
  return config;
@@ -719,7 +988,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
719
988
  const rules = entries.map(toRule);
720
989
  const {
721
990
  logger,
722
- debug,
991
+ debug: debugLevel,
723
992
  cookieMergeStrategy,
724
993
  headerMergeStrategy,
725
994
  ruleTimeoutMs,
@@ -727,21 +996,74 @@ function proxyChain(optionsOrEntries, maybeEntries) {
727
996
  strictOverrideCheck,
728
997
  hostFolderHeader
729
998
  } = config;
999
+ const debug = debugLevel !== false;
1000
+ const hasHandlerDebug = rules.some((rule) => rule.debug != null && rule.debug !== false);
1001
+ const hasDetailedHandlerDebug = rules.some(
1002
+ (rule) => rule.debug === true || rule.debug === "detailed" || rule.debug === "verbose"
1003
+ );
1004
+ const diagnosticsEnabled = debug || config.onTrace !== void 0 || hasHandlerDebug;
730
1005
  assertOverrideMechanismSupported(strictOverrideCheck);
731
1006
  for (let i = 0; i < rules.length; i++) {
732
1007
  assertIncludeExcludeNoOverlap(rules[i].include, rules[i].exclude, ruleLabel(rules[i], i));
1008
+ assertFiniteRuleTimeoutMs(rules[i].timeout);
733
1009
  }
734
1010
  return async function proxy(req, event) {
1011
+ const startedAt = diagnosticsEnabled ? monotonicNow() : 0;
1012
+ const diagnostics = diagnosticsEnabled ? [] : null;
1013
+ let nextHandlerIndex = 0;
1014
+ const finish = (response, forcedOutcome) => {
1015
+ if (!diagnostics) return response;
1016
+ for (let i = nextHandlerIndex; i < rules.length; i++) {
1017
+ diagnostics.push({
1018
+ name: safeDiagnosticText(ruleLabel(rules[i], i), 64),
1019
+ outcome: "not-reached"
1020
+ });
1021
+ }
1022
+ const trace = {
1023
+ method: safeDiagnosticText(req.method, 16),
1024
+ pathname: config.tracePath === false ? void 0 : safeDiagnosticText(req.nextUrl.pathname),
1025
+ durationMs: monotonicNow() - startedAt,
1026
+ outcome: forcedOutcome ?? responseOutcome(response),
1027
+ handlers: diagnostics
1028
+ };
1029
+ if (config.onTrace) {
1030
+ try {
1031
+ void Promise.resolve(config.onTrace(trace)).catch(() => {
1032
+ });
1033
+ } catch {
1034
+ }
1035
+ }
1036
+ const globalLevel = normalizeDebugLevel(debugLevel);
1037
+ if (globalLevel !== false || hasHandlerDebug) {
1038
+ const visible = diagnostics.filter((_handler, index) => {
1039
+ const local = rules[index]?.debug;
1040
+ if (local === false) return false;
1041
+ if (local === "compact") return globalLevel === "compact";
1042
+ if (local != null) return true;
1043
+ return globalLevel !== false && !(globalLevel === "compact" && hasDetailedHandlerDebug);
1044
+ });
1045
+ const level = (globalLevel === "compact" || globalLevel === false) && hasDetailedHandlerDebug ? "detailed" : globalLevel === false ? "compact" : globalLevel;
1046
+ try {
1047
+ config.logger.info(
1048
+ formatTrace(
1049
+ level === "compact" ? trace : { ...trace, handlers: visible },
1050
+ level,
1051
+ shouldUseColor(),
1052
+ supportsUnicode()
1053
+ )
1054
+ );
1055
+ } catch {
1056
+ }
1057
+ }
1058
+ return response;
1059
+ };
735
1060
  let ctx;
736
1061
  try {
737
1062
  ctx = config.createContext(req, event);
738
- } catch (err) {
739
- logger.error({ err }, "createContext threw");
740
- return safeInternalError();
1063
+ } catch {
1064
+ if (!diagnosticsEnabled) logger.error("request context creation failed");
1065
+ return finish(safeInternalError(), { type: "error", status: 500, classification: "engine" });
741
1066
  }
742
- const method = req.method;
743
- const pathname = req.nextUrl.pathname;
744
- const traceId = req.headers.get("x-request-id") ?? req.headers.get("traceparent") ?? req.headers.get("x-b3-traceid") ?? void 0;
745
1067
  let currentReq = req;
746
1068
  let pendingRequestOverrides = null;
747
1069
  let pendingRewriteUrl = null;
@@ -779,16 +1101,83 @@ function proxyChain(optionsOrEntries, maybeEntries) {
779
1101
  appliedRequestOverrides.set(k, v);
780
1102
  });
781
1103
  };
782
- const recoverRuleError = async (err, i, label, req2, startedAt) => {
783
- if (!config.onError) {
784
- logger.error({ rule: label, err }, "rule threw");
785
- return { response: failClosed() };
1104
+ const recoverRuleError = async (err, i, label, req2, startedAt2) => {
1105
+ const timeoutError = err instanceof RuleTimeoutError;
1106
+ const durationMs = () => diagnosticsEnabled ? monotonicNow() - startedAt2 : 0;
1107
+ const errorHandler = rules[i].onError ?? config.onError;
1108
+ const errorPolicy = rules[i].onError ? "handler" : "chain";
1109
+ if (!errorHandler) {
1110
+ if (!diagnosticsEnabled) logger.error("handler failed");
1111
+ diagnostics?.push({
1112
+ 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")
1117
+ });
1118
+ nextHandlerIndex = i + 1;
1119
+ return {
1120
+ response: finish(
1121
+ failClosed(),
1122
+ timeoutError ? {
1123
+ type: "timeout",
1124
+ status: 500,
1125
+ timeoutMs: err instanceof RuleTimeoutError ? err.timeoutMs : ruleTimeoutMs
1126
+ } : { type: "error", status: 500, classification: "handler" }
1127
+ )
1128
+ };
786
1129
  }
787
1130
  try {
788
- const recovered = await config.onError(err, i, req2, ctx);
789
- if (recovered == null) return { response: failClosed() };
790
- if (isNextResult(recovered) || isNextResponse(recovered)) return { raw: recovered };
791
- if (!(recovered instanceof Response)) return { response: failClosed() };
1131
+ const recovered = await errorHandler(err, i, req2, ctx);
1132
+ 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
+ };
1151
+ }
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 };
1163
+ }
1164
+ if (!(recovered instanceof Response)) {
1165
+ diagnostics?.push({
1166
+ name: safeDiagnosticText(label, 64),
1167
+ outcome: timeoutError ? "timeout" : "failed",
1168
+ durationMs: durationMs(),
1169
+ policy: errorPolicy,
1170
+ details: handlerDetails(rules[i], ruleTimeoutMs, "matched", "matched", "not-matched")
1171
+ });
1172
+ nextHandlerIndex = i + 1;
1173
+ return {
1174
+ response: finish(failClosed(), {
1175
+ type: "error",
1176
+ status: 500,
1177
+ classification: "handler"
1178
+ })
1179
+ };
1180
+ }
792
1181
  stripRoutingOverrides(recovered);
793
1182
  headerWrites.push({
794
1183
  ruleIndex: i,
@@ -800,35 +1189,45 @@ function proxyChain(optionsOrEntries, maybeEntries) {
800
1189
  ruleName: label,
801
1190
  items: cookieItemsFromHeaders(recovered.headers)
802
1191
  });
803
- if (debug) {
804
- logger.debug(
805
- formatPipelineLine({
806
- method,
807
- path: pathname,
808
- name: label,
809
- traceId,
810
- outcome: {
811
- kind: "stop",
812
- duration: performance.now() - startedAt,
813
- status: recovered.status
814
- }
815
- })
816
- );
817
- }
1192
+ diagnostics?.push({
1193
+ name: safeDiagnosticText(label, 64),
1194
+ outcome: "recovered",
1195
+ durationMs: durationMs(),
1196
+ recovery: responseOutcome(recovered).type === "redirect" ? "redirect" : responseOutcome(recovered).type === "rewrite" ? "rewrite" : "response",
1197
+ policy: errorPolicy,
1198
+ details: handlerDetails(rules[i], ruleTimeoutMs, "matched", "matched", "not-matched")
1199
+ });
1200
+ nextHandlerIndex = i + 1;
818
1201
  return {
819
- response: finalizeResponse(
820
- recovered,
821
- headerWrites,
822
- cookieWrites,
823
- headerMergeStrategy,
824
- cookieMergeStrategy,
825
- logger,
826
- debug
1202
+ response: finish(
1203
+ finalizeResponse(
1204
+ recovered,
1205
+ headerWrites,
1206
+ cookieWrites,
1207
+ headerMergeStrategy,
1208
+ cookieMergeStrategy,
1209
+ logger,
1210
+ debug
1211
+ )
827
1212
  )
828
1213
  };
829
- } catch (onErrorErr) {
830
- logger.error({ rule: label, err: onErrorErr }, "onError handler threw");
831
- return { response: failClosed() };
1214
+ } catch {
1215
+ 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
+ };
832
1231
  }
833
1232
  };
834
1233
  try {
@@ -841,22 +1240,57 @@ function proxyChain(optionsOrEntries, maybeEntries) {
841
1240
  );
842
1241
  const matchPath = canonicalPathname(activeReq.nextUrl.pathname);
843
1242
  if (matchPath === null) {
844
- return new import_server2.NextResponse("Bad Request", {
845
- status: 400,
846
- headers: { "content-type": "text/plain; charset=utf-8" }
1243
+ return finish(
1244
+ new import_server2.NextResponse("Bad Request", {
1245
+ status: 400,
1246
+ headers: { "content-type": "text/plain; charset=utf-8" }
1247
+ })
1248
+ );
1249
+ }
1250
+ nextHandlerIndex = i;
1251
+ const skipReason = ruleMatchReason(matchPath, reqHost, rule);
1252
+ if (skipReason) {
1253
+ diagnostics?.push({
1254
+ name: safeDiagnosticText(label, 64),
1255
+ outcome: "skipped",
1256
+ reason: skipReason,
1257
+ details: handlerDetails(
1258
+ rule,
1259
+ ruleTimeoutMs,
1260
+ "not-evaluated",
1261
+ skipReason === "include-mismatch" ? "mismatch" : void 0,
1262
+ skipReason === "exclude-match" ? "matched" : skipReason === "include-mismatch" && rule.exclude ? "not-matched" : void 0
1263
+ )
847
1264
  });
1265
+ nextHandlerIndex = i + 1;
1266
+ continue;
848
1267
  }
849
- if (!ruleMatches(matchPath, reqHost, rule)) continue;
850
- const startedAt = debug ? performance.now() : 0;
1268
+ const startedAt2 = diagnosticsEnabled ? monotonicNow() : 0;
851
1269
  let raw;
852
1270
  try {
853
- raw = await withRuleTimeout(
854
- Promise.resolve(rule.run(activeReq, ctx, event)),
855
- ruleTimeoutMs,
1271
+ const result = await withRuleTimeout(
1272
+ (async () => {
1273
+ if (rule.when && !await rule.when(activeReq, event, ctx)) {
1274
+ return { kind: "skipped" };
1275
+ }
1276
+ return { kind: "result", raw: await rule.run(activeReq, ctx, event) };
1277
+ })(),
1278
+ rule.timeout ?? ruleTimeoutMs,
856
1279
  label
857
1280
  );
1281
+ if (result.kind === "skipped") {
1282
+ diagnostics?.push({
1283
+ name: safeDiagnosticText(label, 64),
1284
+ outcome: "skipped",
1285
+ reason: "when-false",
1286
+ details: handlerDetails(rule, ruleTimeoutMs, "false", "matched", "not-matched")
1287
+ });
1288
+ nextHandlerIndex = i + 1;
1289
+ continue;
1290
+ }
1291
+ raw = result.raw;
858
1292
  } catch (err) {
859
- const recovered = await recoverRuleError(err, i, label, activeReq, startedAt);
1293
+ const recovered = await recoverRuleError(err, i, label, activeReq, startedAt2);
860
1294
  if ("response" in recovered) return recovered.response;
861
1295
  raw = recovered.raw;
862
1296
  }
@@ -864,11 +1298,11 @@ function proxyChain(optionsOrEntries, maybeEntries) {
864
1298
  try {
865
1299
  outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
866
1300
  } catch (err) {
867
- const recovered = await recoverRuleError(err, i, label, activeReq, startedAt);
1301
+ const recovered = await recoverRuleError(err, i, label, activeReq, startedAt2);
868
1302
  if ("response" in recovered) return recovered.response;
869
1303
  outcome = resolveRuleResult(recovered.raw, requestHeaderPolicy, logger, debug);
870
1304
  }
871
- const duration = debug ? performance.now() - startedAt : 0;
1305
+ const duration2 = diagnosticsEnabled ? monotonicNow() - startedAt2 : 0;
872
1306
  if (outcome.kind === "continue") {
873
1307
  if (outcome.rewriteUrl) {
874
1308
  pendingRewriteUrl = outcome.rewriteUrl;
@@ -888,18 +1322,37 @@ function proxyChain(optionsOrEntries, maybeEntries) {
888
1322
  headerWrites.push({ ruleIndex: i, ruleName: label, items: outcome.responseHeaders });
889
1323
  cookieWrites.push({ ruleIndex: i, ruleName: label, items: outcome.cookies });
890
1324
  }
891
- if (debug) {
892
- const mutated = outcome.responseHeaders.size + outcome.cookies.size + (outcome.request ? 1 : 0) + (outcome.rewriteUrl ? 1 : 0);
893
- logger.debug(
894
- formatPipelineLine({
895
- method,
896
- path: pathname,
897
- name: label,
898
- traceId,
899
- outcome: mutated === 0 ? { kind: "passed", duration } : { kind: "next", duration, headers: outcome.responseHeaders.size }
900
- })
1325
+ if (diagnostics?.at(-1)?.outcome !== "recovered") {
1326
+ diagnostics?.push(
1327
+ outcome.rewriteUrl ? {
1328
+ name: safeDiagnosticText(label, 64),
1329
+ outcome: "rewrite",
1330
+ durationMs: duration2,
1331
+ destination: safeDestination(outcome.rewriteUrl) ?? "/",
1332
+ final: false,
1333
+ details: handlerDetails(
1334
+ rule,
1335
+ ruleTimeoutMs,
1336
+ "matched",
1337
+ "matched",
1338
+ "not-matched"
1339
+ )
1340
+ } : {
1341
+ name: safeDiagnosticText(label, 64),
1342
+ outcome: "continue",
1343
+ source: isNextResult(raw) ? "next()" : raw instanceof import_server2.NextResponse && raw.headers.get("x-middleware-next") === "1" ? "NextResponse.next()" : "undefined",
1344
+ durationMs: duration2,
1345
+ details: handlerDetails(
1346
+ rule,
1347
+ ruleTimeoutMs,
1348
+ "matched",
1349
+ "matched",
1350
+ "not-matched"
1351
+ )
1352
+ }
901
1353
  );
902
1354
  }
1355
+ nextHandlerIndex = i + 1;
903
1356
  continue;
904
1357
  }
905
1358
  stripRoutingOverrides(outcome.response);
@@ -913,21 +1366,31 @@ function proxyChain(optionsOrEntries, maybeEntries) {
913
1366
  ruleName: label,
914
1367
  items: cookieItemsFromHeaders(outcome.response.headers)
915
1368
  });
916
- if (debug) {
917
- logger.debug(
918
- formatPipelineLine({
919
- method,
920
- path: pathname,
921
- name: label,
922
- traceId,
923
- outcome: {
924
- kind: "stop",
925
- duration,
926
- status: outcome.response.status
927
- }
928
- })
929
- );
930
- }
1369
+ const terminalOutcome = responseOutcome(outcome.response);
1370
+ diagnostics?.push(
1371
+ terminalOutcome.type === "redirect" ? {
1372
+ name: safeDiagnosticText(label, 64),
1373
+ outcome: "redirect",
1374
+ durationMs: duration2,
1375
+ status: terminalOutcome.status,
1376
+ destination: terminalOutcome.destination,
1377
+ details: handlerDetails(rule, ruleTimeoutMs, "matched", "matched", "not-matched")
1378
+ } : terminalOutcome.type === "rewrite" ? {
1379
+ name: safeDiagnosticText(label, 64),
1380
+ outcome: "rewrite",
1381
+ durationMs: duration2,
1382
+ destination: terminalOutcome.destination,
1383
+ final: true,
1384
+ details: handlerDetails(rule, ruleTimeoutMs, "matched", "matched", "not-matched")
1385
+ } : {
1386
+ name: safeDiagnosticText(label, 64),
1387
+ outcome: "response",
1388
+ durationMs: duration2,
1389
+ status: outcome.response.status,
1390
+ details: handlerDetails(rule, ruleTimeoutMs, "matched", "matched", "not-matched")
1391
+ }
1392
+ );
1393
+ nextHandlerIndex = i + 1;
931
1394
  const internalFolder = hostFolderHeader ? appliedRequestOverrides.get(hostFolderHeader) : null;
932
1395
  if (internalFolder && outcome.response.headers.has("x-middleware-rewrite")) {
933
1396
  const rawRewrite = outcome.response.headers.get("x-middleware-rewrite");
@@ -937,14 +1400,22 @@ function proxyChain(optionsOrEntries, maybeEntries) {
937
1400
  applyFolderPrefix(rawRewrite, cleanFolder, currentReq.url)
938
1401
  );
939
1402
  }
940
- return finalizeResponse(
941
- outcome.response,
942
- headerWrites,
943
- cookieWrites,
944
- headerMergeStrategy,
945
- cookieMergeStrategy,
946
- logger,
947
- debug
1403
+ const finalTerminalOutcome = responseOutcome(outcome.response);
1404
+ const terminalTrace = diagnostics?.at(-1);
1405
+ if (finalTerminalOutcome.type === "rewrite" && terminalTrace?.outcome === "rewrite") {
1406
+ terminalTrace.destination = finalTerminalOutcome.destination;
1407
+ }
1408
+ return finish(
1409
+ finalizeResponse(
1410
+ outcome.response,
1411
+ headerWrites,
1412
+ cookieWrites,
1413
+ headerMergeStrategy,
1414
+ cookieMergeStrategy,
1415
+ logger,
1416
+ debug
1417
+ ),
1418
+ finalTerminalOutcome
948
1419
  );
949
1420
  }
950
1421
  const finalReq = materializeRequest();
@@ -971,7 +1442,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
971
1442
  } else {
972
1443
  final = import_server2.NextResponse.next(requestInit);
973
1444
  }
974
- return finalizeResponse(
1445
+ const finalResponse = finalizeResponse(
975
1446
  final,
976
1447
  headerWrites,
977
1448
  cookieWrites,
@@ -980,27 +1451,41 @@ function proxyChain(optionsOrEntries, maybeEntries) {
980
1451
  logger,
981
1452
  debug
982
1453
  );
1454
+ if (finalRewriteUrl) {
1455
+ const destination = safeDestination(finalRewriteUrl) ?? "/";
1456
+ const rewrite = diagnostics?.filter((handler) => handler.outcome === "rewrite").at(-1);
1457
+ if (rewrite?.outcome === "rewrite") {
1458
+ rewrite.destination = destination;
1459
+ rewrite.final = true;
1460
+ }
1461
+ }
1462
+ return finish(finalResponse);
983
1463
  } catch (err) {
984
- logger.error({ err }, "proxy chain failed");
1464
+ if (!diagnosticsEnabled) logger.error("proxy chain execution failed");
985
1465
  if (config.onError) {
986
1466
  try {
987
1467
  const recovered = await config.onError(err, -1, materializeRequest(), ctx);
988
1468
  if (recovered instanceof Response && !isNextResponse(recovered)) {
989
1469
  stripRoutingOverrides(recovered);
990
- return finalizeResponse(
991
- recovered,
992
- headerWrites,
993
- cookieWrites,
994
- headerMergeStrategy,
995
- cookieMergeStrategy,
996
- logger,
997
- debug
1470
+ return finish(
1471
+ finalizeResponse(
1472
+ recovered,
1473
+ headerWrites,
1474
+ cookieWrites,
1475
+ headerMergeStrategy,
1476
+ cookieMergeStrategy,
1477
+ logger,
1478
+ debug
1479
+ )
998
1480
  );
999
1481
  }
1000
1482
  } catch {
1001
1483
  }
1002
1484
  }
1003
- return failClosed();
1485
+ return finish(
1486
+ failClosed(),
1487
+ err instanceof RuleTimeoutError ? { type: "timeout", status: 500, timeoutMs: err.timeoutMs } : { type: "error", status: 500, classification: "engine" }
1488
+ );
1004
1489
  }
1005
1490
  };
1006
1491
  }
@@ -1036,11 +1521,33 @@ function chain(entries, options) {
1036
1521
  const normalized = entries.map((entry) => toEntry(entry));
1037
1522
  return proxyChain(options ?? {}, normalized);
1038
1523
  }
1524
+
1525
+ // src/core/handler.ts
1526
+ function defineHandler(options) {
1527
+ const include = compileScopes(options.rules?.include);
1528
+ const exclude = compileScopes(options.rules?.exclude);
1529
+ const rule = {
1530
+ run: (request, context, event) => options.handler(request, event, context),
1531
+ name: options.name,
1532
+ include,
1533
+ exclude,
1534
+ debug: options.debug,
1535
+ timeout: options.timeout,
1536
+ when: options.rules?.when,
1537
+ onError: options.onError,
1538
+ diagnosticRules: {
1539
+ include: options.rules?.include,
1540
+ exclude: options.rules?.exclude
1541
+ }
1542
+ };
1543
+ return rule;
1544
+ }
1039
1545
  // Annotate the CommonJS export names for ESM import in node:
1040
1546
  0 && (module.exports = {
1041
1547
  RuleTimeoutError,
1042
1548
  chain,
1043
1549
  createProxyContext,
1550
+ defineHandler,
1044
1551
  defineProxy,
1045
1552
  host,
1046
1553
  isNextResult,