@teyik0/furin 0.3.0-alpha.1 → 0.4.0-alpha.1

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.
Files changed (144) hide show
  1. package/dist/adapter/bun.d.ts +1 -1
  2. package/dist/build/client.d.ts +2 -2
  3. package/dist/build/entry-template.d.ts +4 -0
  4. package/dist/build/entry-template.ts +17 -3
  5. package/dist/build/index.d.ts +1 -1
  6. package/dist/build/index.js +8288 -6629
  7. package/dist/build/route-types.d.ts +2 -22
  8. package/dist/build/shared.d.ts +1 -1
  9. package/dist/build/ssg-cache.d.ts +1 -1
  10. package/dist/build/types.d.ts +1 -1
  11. package/dist/cli/index.js +7862 -6168
  12. package/dist/client/boundaries.d.ts +2 -0
  13. package/dist/client/define-route.d.ts +35 -0
  14. package/dist/client/document.d.ts +26 -0
  15. package/dist/client/hmr.d.ts +10 -0
  16. package/dist/client/internal/runtime-types.d.ts +3 -1
  17. package/dist/client/link.js +1177 -894
  18. package/dist/client/router/index.d.ts +1 -1
  19. package/dist/client/router/link-utils.d.ts +9 -0
  20. package/dist/client/router/search/index.d.ts +3 -7
  21. package/dist/client/router/types.d.ts +32 -24
  22. package/dist/client.d.ts +4 -159
  23. package/dist/client.js +183 -21
  24. package/dist/config.d.ts +8 -8
  25. package/dist/config.js +8 -8
  26. package/dist/define-route.d.ts +1355 -0
  27. package/dist/furin.d.ts +17 -33
  28. package/dist/furin.js +13444 -10301
  29. package/dist/plugin/index.js +953 -244
  30. package/dist/plugin/route-config-autofix.d.ts +31 -0
  31. package/dist/plugin/routes.d.ts +27 -0
  32. package/dist/routes.d.ts +6 -0
  33. package/dist/routes.js +1 -0
  34. package/dist/rsc/build/index.d.ts +1 -1
  35. package/dist/rsc.js +3 -3
  36. package/dist/server/dev-page-plugin.d.ts +7 -5
  37. package/dist/server/devtools/instrumentation.d.ts +2 -2
  38. package/dist/server/devtools/instrumentation.production.d.ts +2 -2
  39. package/dist/server/devtools/plugin.d.ts +2 -2
  40. package/dist/server/internal.d.ts +3 -0
  41. package/dist/server/logger.d.ts +4 -0
  42. package/dist/server/render/assemble.d.ts +0 -9
  43. package/dist/server/render/document.d.ts +4 -0
  44. package/dist/server/render/element.d.ts +2 -1
  45. package/dist/server/render/index.d.ts +1 -1
  46. package/dist/server/render/index.ts +0 -1
  47. package/dist/server/render/isr.d.ts +1 -1
  48. package/dist/server/render/loaders.d.ts +1 -1
  49. package/dist/server/render/not-found.d.ts +1 -1
  50. package/dist/server/render/ppr-route.d.ts +1 -1
  51. package/dist/server/render/ssg.d.ts +1 -1
  52. package/dist/server/render/ssr.d.ts +7 -6
  53. package/dist/server/render/template.d.ts +4 -0
  54. package/dist/server/router/defined-route.d.ts +24 -0
  55. package/dist/server/router/hmr.d.ts +16 -8
  56. package/dist/server/router/patterns.d.ts +6 -0
  57. package/dist/server/router/plugin.d.ts +4 -3
  58. package/dist/server/router/schema-merge.d.ts +2 -2
  59. package/dist/server/router/schemas.d.ts +5 -5
  60. package/dist/server/router/source-version.d.ts +2 -0
  61. package/dist/server/router/types.d.ts +1 -0
  62. package/dist/server/sync/index.js +961 -806
  63. package/dist/server/sync/postgres/migrate.js +3 -2
  64. package/dist/shared/await.d.ts +6 -7
  65. package/dist/shared/elysia-contract.d.ts +41 -0
  66. package/dist/shared/route-map.d.ts +5 -0
  67. package/dist/shared/utils/index.d.ts +1 -3
  68. package/package.json +44 -41
  69. package/src/adapter/bun.ts +42 -22
  70. package/src/adapter/package.ts +20 -14
  71. package/src/adapter/static.ts +4 -3
  72. package/src/build/client.ts +20 -3
  73. package/src/build/entry-template.ts +17 -3
  74. package/src/build/hydrate.ts +98 -28
  75. package/src/build/index.ts +2 -2
  76. package/src/build/route-types.ts +19 -114
  77. package/src/build/shared.ts +1 -1
  78. package/src/build/ssg-cache.ts +2 -5
  79. package/src/build/types.ts +1 -1
  80. package/src/cli/config.ts +3 -3
  81. package/src/cli/index.ts +7 -7
  82. package/src/client/boundaries.tsx +9 -1
  83. package/src/client/define-route.ts +48 -0
  84. package/src/client/document.tsx +165 -0
  85. package/src/client/hmr.ts +40 -0
  86. package/src/client/internal/runtime-types.ts +3 -1
  87. package/src/client/link.tsx +21 -6
  88. package/src/client/router/index.ts +1 -0
  89. package/src/client/router/link-utils.ts +26 -0
  90. package/src/client/router/provider.tsx +25 -2
  91. package/src/client/router/search/index.ts +4 -12
  92. package/src/client/router/types.ts +50 -24
  93. package/src/client.ts +14 -316
  94. package/src/config.ts +10 -10
  95. package/src/define-route.ts +959 -0
  96. package/src/devtools/devtools-element.js +11 -10
  97. package/src/furin.ts +303 -53
  98. package/src/plugin/route-config-autofix.ts +1140 -0
  99. package/src/plugin/routes.ts +891 -0
  100. package/src/plugin/transform-client.ts +132 -266
  101. package/src/plugin/transform-isomorphic.ts +1 -1
  102. package/src/routes.ts +6 -0
  103. package/src/rsc/build/index.ts +1 -1
  104. package/src/server/auto-invalidate/registry.ts +2 -2
  105. package/src/server/dev-page-plugin.ts +31 -12
  106. package/src/server/devtools/instrumentation.production.ts +2 -2
  107. package/src/server/devtools/instrumentation.ts +2 -2
  108. package/src/server/devtools/plugin.ts +5 -3
  109. package/src/server/instance.ts +3 -3
  110. package/src/server/internal.ts +3 -0
  111. package/src/server/logger.ts +21 -0
  112. package/src/server/render/assemble.ts +0 -41
  113. package/src/server/render/document.tsx +25 -0
  114. package/src/server/render/element.tsx +13 -1
  115. package/src/server/render/index.ts +0 -1
  116. package/src/server/render/isr.ts +31 -10
  117. package/src/server/render/loaders.ts +31 -6
  118. package/src/server/render/not-found.ts +51 -27
  119. package/src/server/render/ppr-route.ts +1 -1
  120. package/src/server/render/ssg.ts +1 -1
  121. package/src/server/render/ssr.ts +271 -113
  122. package/src/server/render/template.ts +91 -1
  123. package/src/server/router/defined-route.ts +110 -0
  124. package/src/server/router/discovery.ts +129 -29
  125. package/src/server/router/hmr.ts +111 -40
  126. package/src/server/router/patterns.ts +40 -12
  127. package/src/server/router/plugin.ts +63 -46
  128. package/src/server/router/schema-merge.ts +4 -14
  129. package/src/server/router/schemas.ts +11 -8
  130. package/src/server/router/source-version.ts +16 -0
  131. package/src/server/router/types.ts +2 -0
  132. package/src/server/sync/postgres/migrate.ts +3 -2
  133. package/src/server/sync/response.ts +14 -10
  134. package/src/shared/await.tsx +6 -7
  135. package/src/shared/elysia-contract.ts +63 -0
  136. package/src/shared/route-map.ts +37 -0
  137. package/src/shared/utils/index.ts +2 -20
  138. package/dist/build/server-routes-entry.d.ts +0 -13
  139. package/dist/build/server-routes-entry.ts +0 -30
  140. package/dist/server/router/index.d.ts +0 -7
  141. package/dist/server/router/index.js +0 -27
  142. package/dist/server/router/index.ts +0 -28
  143. package/src/build/server-routes-entry.ts +0 -30
  144. package/src/server/router/index.ts +0 -28
@@ -9,12 +9,12 @@ var _instances = new Map;
9
9
  var _defaultInstance = null;
10
10
  function createInstance(prefix, pagesDir) {
11
11
  return {
12
- prefix,
13
- pagesDir,
14
- syncStreamPath: undefined,
15
12
  buildId: "",
13
+ pagesDir,
14
+ prefix,
16
15
  registrationEpoch: 0,
17
- state: new Map
16
+ state: new Map,
17
+ syncStreamPath: undefined
18
18
  };
19
19
  }
20
20
  function defaultInstance() {
@@ -183,7 +183,10 @@ import { Elysia } from "elysia";
183
183
 
184
184
  // src/server/context-logger.ts
185
185
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
186
- // ../../node_modules/.bun/evlog@2.22.3+6e5ab44a2bca2113/node_modules/evlog/dist/utils.mjs
186
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/utils.mjs
187
+ function elapsedMs(startTime) {
188
+ return Math.max(0, Date.now() - startTime);
189
+ }
187
190
  function formatDuration(ms) {
188
191
  if (ms < 1000)
189
192
  return `${Math.round(ms)}ms`;
@@ -299,795 +302,954 @@ function globToRegExp(pattern, separator = "/") {
299
302
  function matchesPattern(path, pattern) {
300
303
  return globToRegExp(pattern, "/").test(path);
301
304
  }
302
-
303
- // ../../node_modules/.bun/evlog@2.22.3+6e5ab44a2bca2113/node_modules/evlog/dist/pretty-error-DTIHxnBN.mjs
304
- var snippetReader = null;
305
- var PRETTY_ERROR_TREE_SPACER = "__EVLOG_TREE_SPACER__";
306
- function pushTreeSpacer(children) {
307
- children.push(PRETTY_ERROR_TREE_SPACER);
308
- }
309
- var SKIP_PATH_RE = /(?:^|[/\\])(?:node_modules|\.nuxt|\.next|\.output)(?:[/\\]|$)/;
310
- var SKIP_FRAME_PATH_RE = /(?:^|[/\\])(?:packages[/\\]evlog|evlog[/\\](?:dist|src))(?:[/\\]|$)/;
311
- var SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
312
- function isPlainObject(val) {
313
- return val !== null && typeof val === "object" && !Array.isArray(val);
314
- }
315
- function pickString(obj, key) {
316
- const val = obj[key];
317
- return typeof val === "string" && val.length > 0 ? val : undefined;
305
+ var _isoDate = /* @__PURE__ */ new Date;
306
+ var _isoCachedSecond = -1;
307
+ var _isoCachedPrefix = "";
308
+ function isoNow() {
309
+ const now = Date.now();
310
+ const sec = Math.floor(now / 1000);
311
+ if (sec !== _isoCachedSecond) {
312
+ _isoCachedSecond = sec;
313
+ _isoDate.setTime(now);
314
+ _isoCachedPrefix = _isoDate.toISOString().slice(0, 19);
315
+ }
316
+ return `${_isoCachedPrefix}.${String(now % 1000).padStart(3, "0")}Z`;
318
317
  }
319
- function pickNumber(obj, key) {
320
- const val = obj[key];
321
- return typeof val === "number" ? val : undefined;
318
+
319
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/redact-C7FmdhwI.mjs
320
+ var DEFAULT_REPLACEMENT = "[REDACTED]";
321
+ function normalizeRedactPathPattern(pattern) {
322
+ if (!pattern.includes("*") && !pattern.includes("."))
323
+ return `**.${pattern}`;
324
+ return pattern;
322
325
  }
323
- function extractGuidance(data) {
326
+ function compileRedactPathMatchers(patterns) {
327
+ if (!patterns?.length)
328
+ return;
329
+ const exactPaths = /* @__PURE__ */ new Set;
330
+ const pathGlobs = [];
331
+ const keyGlobs = [];
332
+ const caseInsensitiveLeaves = /* @__PURE__ */ new Set;
333
+ for (const raw of patterns) {
334
+ if (!raw.includes("*")) {
335
+ if (raw.includes("."))
336
+ exactPaths.add(raw);
337
+ else
338
+ addPathGlobPattern(normalizeRedactPathPattern(raw), exactPaths, pathGlobs, caseInsensitiveLeaves);
339
+ continue;
340
+ }
341
+ if (!raw.includes("."))
342
+ keyGlobs.push(globToRegExp(raw, "."));
343
+ else
344
+ addPathGlobPattern(raw, exactPaths, pathGlobs, caseInsensitiveLeaves);
345
+ }
346
+ if (exactPaths.size === 0 && pathGlobs.length === 0 && keyGlobs.length === 0 && caseInsensitiveLeaves.size === 0)
347
+ return;
324
348
  return {
325
- code: pickString(data, "code"),
326
- why: pickString(data, "why"),
327
- fix: pickString(data, "fix"),
328
- link: pickString(data, "link")
349
+ exactPaths,
350
+ pathGlobs,
351
+ keyGlobs,
352
+ caseInsensitiveLeaves
329
353
  };
330
354
  }
331
- function normalizeErrorContext(error) {
332
- if (error === null || error === undefined)
333
- return null;
334
- if (typeof error === "string")
335
- return { message: error };
336
- if (!isPlainObject(error))
337
- return { message: String(error) };
338
- const result = {
339
- message: pickString(error, "message") ?? pickString(error, "statusText") ?? pickString(error, "statusMessage") ?? "Unknown error",
340
- name: pickString(error, "name"),
341
- code: pickString(error, "code"),
342
- why: pickString(error, "why"),
343
- fix: pickString(error, "fix"),
344
- link: pickString(error, "link"),
345
- status: pickNumber(error, "status") ?? pickNumber(error, "statusCode"),
346
- stack: pickString(error, "stack")
347
- };
348
- const { data, cause } = error;
349
- if (isPlainObject(data)) {
350
- const guidance = extractGuidance(data);
351
- if (!result.code)
352
- result.code = guidance.code;
353
- if (!result.why)
354
- result.why = guidance.why;
355
- if (!result.fix)
356
- result.fix = guidance.fix;
357
- if (!result.link)
358
- result.link = guidance.link;
355
+ function addPathGlobPattern(pattern, exactPaths, pathGlobs, caseInsensitiveLeaves) {
356
+ pathGlobs.push(globToRegExp(pattern, "."));
357
+ const leaf = pattern.match(/^\*\*\.([^.?*]+)$/);
358
+ if (leaf) {
359
+ exactPaths.add(leaf[1]);
360
+ caseInsensitiveLeaves.add(leaf[1].toLowerCase());
359
361
  }
360
- if (cause instanceof Error)
361
- result.cause = cause.message;
362
- else if (isPlainObject(cause) && pickString(cause, "message"))
363
- result.cause = pickString(cause, "message");
364
- return result;
365
- }
366
- function decodeFileUrl(file) {
367
- if (file.startsWith("file://"))
368
- try {
369
- return decodeURIComponent(new URL(file).pathname);
370
- } catch {
371
- return file.slice(7);
372
- }
373
- return file;
374
362
  }
375
- function isAppPath(file) {
376
- const normalized = decodeFileUrl(file).replace(/\\/g, "/");
377
- if (normalized.startsWith("node:"))
378
- return false;
379
- if (SKIP_PATH_RE.test(normalized))
380
- return false;
381
- if (normalized.includes("/node_modules/"))
382
- return false;
383
- if (isFrameworkRuntimePath(normalized))
384
- return false;
385
- return true;
363
+ function matchesRedactPath(fullPath, leafKey, matchers) {
364
+ if (matchers.exactPaths.has(fullPath))
365
+ return true;
366
+ if (matchers.caseInsensitiveLeaves.has(leafKey.toLowerCase()))
367
+ return true;
368
+ for (const glob of matchers.pathGlobs) {
369
+ glob.lastIndex = 0;
370
+ if (glob.test(fullPath))
371
+ return true;
372
+ }
373
+ for (const glob of matchers.keyGlobs) {
374
+ glob.lastIndex = 0;
375
+ if (glob.test(leafKey))
376
+ return true;
377
+ }
378
+ return false;
386
379
  }
387
- function formatDisplayPath(file, cwd) {
388
- const decoded = decodeFileUrl(file).replace(/\\/g, "/");
389
- const cwdNorm = cwd.replace(/\\/g, "/").replace(/\/$/, "");
390
- if (cwdNorm && decoded.startsWith(`${cwdNorm}/`)) {
391
- const rel = decoded.slice(cwdNorm.length + 1);
392
- return rel.startsWith("./") ? rel.slice(2) : rel;
380
+ function resolveReplacement(replacement, matched, ctx) {
381
+ if (typeof replacement === "string")
382
+ return replacement;
383
+ try {
384
+ const result = replacement(matched, ctx);
385
+ if (typeof result !== "string") {
386
+ console.error(`[evlog] redact replacement returned ${typeof result} for "${ctx.path}", expected string \u2014 using ${DEFAULT_REPLACEMENT}`);
387
+ return DEFAULT_REPLACEMENT;
388
+ }
389
+ return result;
390
+ } catch (err) {
391
+ console.error(`[evlog] redact replacement failed for "${ctx.path}":`, err);
392
+ return DEFAULT_REPLACEMENT;
393
393
  }
394
- const serverIdx = decoded.indexOf("/server/");
395
- if (serverIdx >= 0)
396
- return decoded.slice(serverIdx + 1);
397
- const srcIdx = decoded.indexOf("/src/");
398
- if (srcIdx >= 0)
399
- return decoded.slice(srcIdx + 1);
400
- return decoded;
401
394
  }
402
- function compactStackForStorage(stack, maxFrames = 5) {
403
- if (!stack)
395
+ function redactPathsInTree(obj, matchers, replacement, prefix = "") {
396
+ if (obj === null || obj === undefined)
404
397
  return;
405
- const head = stack.split(`
406
- `)[0] ?? "";
407
- const useful = parseStackFrames(stack).filter((f) => f.file && f.line && f.isApp && !isInternalErrorFrame(f)).slice(0, maxFrames);
408
- if (useful.length === 0)
409
- return stack;
410
- return [head, ...useful.map((f) => f.raw)].join(`
411
- `);
412
- }
413
- function parseStackFrames(stack) {
414
- if (!stack)
415
- return [];
416
- const lines = stack.split(`
417
- `);
418
- const frames = [];
419
- for (const line of lines) {
420
- const trimmed = line.trim();
421
- if (!trimmed.startsWith("at "))
422
- continue;
423
- const withFn = trimmed.match(/^at (.+?) \((.+):(\d+):(\d+)\)$/);
424
- if (withFn) {
425
- const [, fn, file, lineStr, colStr] = withFn;
426
- frames.push({
427
- raw: trimmed,
428
- fn,
429
- file,
430
- line: Number(lineStr),
431
- column: Number(colStr),
432
- isApp: isAppPath(file)
433
- });
434
- continue;
435
- }
436
- const withoutFn = trimmed.match(/^at (.+):(\d+):(\d+)$/);
437
- if (withoutFn) {
438
- const [, file, lineStr, colStr] = withoutFn;
439
- frames.push({
440
- raw: trimmed,
441
- file,
442
- line: Number(lineStr),
443
- column: Number(colStr),
444
- isApp: isAppPath(file)
445
- });
446
- continue;
398
+ if (Array.isArray(obj)) {
399
+ for (let i = 0;i < obj.length; i++) {
400
+ const segment = String(i);
401
+ const fullPath = prefix ? `${prefix}.${segment}` : segment;
402
+ redactPathsInTree(obj[i], matchers, replacement, fullPath);
447
403
  }
448
- const asyncFn = trimmed.match(/^at async (.+?) \((.+):(\d+):(\d+)\)$/);
449
- if (asyncFn) {
450
- const [, fn, file, lineStr, colStr] = asyncFn;
451
- frames.push({
452
- raw: trimmed,
453
- fn: `async ${fn}`,
454
- file,
455
- line: Number(lineStr),
456
- column: Number(colStr),
457
- isApp: isAppPath(file)
458
- });
404
+ return;
405
+ }
406
+ if (typeof obj === "object") {
407
+ const record = obj;
408
+ for (const key of redactableKeys(record)) {
409
+ const fullPath = prefix ? `${prefix}.${key}` : key;
410
+ if (matchesRedactPath(fullPath, key, matchers))
411
+ setRedacted(record, key, resolveReplacement(replacement, record[key], {
412
+ path: fullPath,
413
+ key
414
+ }), fullPath);
415
+ else
416
+ redactPathsInTree(record[key], matchers, replacement, fullPath);
459
417
  }
460
418
  }
461
- return frames;
462
- }
463
- function isFrameworkRuntimePath(path) {
464
- const normalized = path.replace(/\\/g, "/");
465
- return normalized.includes("route-modules/") || normalized.includes("webpack://next/") || normalized.includes("/next/dist/") || normalized.includes("/compiled/next-server/");
466
419
  }
467
- function isFrameworkRuntimeFrame(frame) {
468
- if (!frame.file)
469
- return false;
470
- return isFrameworkRuntimePath(decodeFileUrl(frame.file));
420
+ function redactableKeys(record) {
421
+ return Object.keys(record);
471
422
  }
472
- function isInternalErrorFrame(frame) {
473
- if (isFrameworkRuntimeFrame(frame))
474
- return true;
475
- if (frame.fn) {
476
- const fn = frame.fn.replace(/^async /, "");
477
- if (SKIP_FRAME_FN_RE.test(fn))
478
- return true;
423
+ function setRedacted(record, key, value, path) {
424
+ if (Reflect.set(record, key, value))
425
+ return;
426
+ const desc = Object.getOwnPropertyDescriptor(record, key);
427
+ if (desc && "value" in desc && desc.configurable) {
428
+ Object.defineProperty(record, key, {
429
+ ...desc,
430
+ value
431
+ });
432
+ return;
479
433
  }
480
- if (!frame.file)
481
- return true;
482
- const path = decodeFileUrl(frame.file).replace(/\\/g, "/");
483
- if (SKIP_FRAME_PATH_RE.test(path))
484
- return true;
485
- if (path.includes(".nuxt/"))
486
- return true;
487
- if (path.includes(".next/"))
488
- return true;
489
- return false;
490
- }
491
- function pickPrimaryFrame(frames) {
492
- for (const frame of frames)
493
- if (frame.isApp && frame.file && frame.line && !isInternalErrorFrame(frame))
494
- return frame;
434
+ console.warn(`[evlog] redact could not rewrite read-only field "${path}" \u2014 value left as-is`);
495
435
  }
496
- function readCodeSnippet(file, line, contextLines = 2) {
497
- if (!isDev() || isBrowser() || !snippetReader)
498
- return null;
499
- const path = decodeFileUrl(file).replace(/\\/g, "/");
500
- if (path.includes(".next/") || path.includes(".nuxt/") || path.includes(".output/"))
501
- return null;
502
- return snippetReader(file, line, contextLines);
436
+ var builtinPatterns = {
437
+ creditCard: {
438
+ pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
439
+ mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
440
+ },
441
+ email: {
442
+ pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g,
443
+ mask: (m) => {
444
+ if (m.indexOf("@") < 1)
445
+ return "***@***";
446
+ const tld = m.slice(m.lastIndexOf("."));
447
+ return `${m[0]}***@***${tld}`;
448
+ }
449
+ },
450
+ ipv4: {
451
+ pattern: /\b(?!0\.0\.0\.0\b)(?!127\.0\.0\.1\b)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
452
+ mask: (m) => `***.***.***.${m.split(".").pop()}`
453
+ },
454
+ phone: {
455
+ pattern: /(?:\+\d{1,3}[\s.-]?\(?\d{1,4}\)?|\(\d{1,4}\))(?:[\s.-]?\d{2,4}){2,4}\b/g,
456
+ mask: (m) => {
457
+ const digits = m.replace(/[^\d]/g, "");
458
+ if (m.startsWith("+") && digits.length > 4) {
459
+ const ccMatch = m.match(/^\+\d{1,3}/);
460
+ return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
461
+ }
462
+ if (digits.length > 2)
463
+ return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
464
+ return "***";
465
+ }
466
+ },
467
+ jwt: {
468
+ pattern: /\beyJ[\w-]*\.[\w-]*\.[\w-]*\b/g,
469
+ mask: () => "eyJ***.***"
470
+ },
471
+ bearer: {
472
+ pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
473
+ mask: () => "Bearer ***"
474
+ },
475
+ iban: {
476
+ pattern: /\b[A-Z]{2}\d{2}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}\b/g,
477
+ mask: (m) => {
478
+ const clean = m.replace(/[\s-]/g, "");
479
+ return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
480
+ }
481
+ }
482
+ };
483
+ function resolveRedactConfig(input) {
484
+ if (input === undefined || input === false)
485
+ return;
486
+ if (input === true)
487
+ return { _maskers: allBuiltinMaskers() };
488
+ if (input.builtins === false)
489
+ return {
490
+ ...input,
491
+ _pathMatchers: compileRedactPathMatchers(input.paths)
492
+ };
493
+ const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
494
+ return {
495
+ ...input,
496
+ _maskers: maskers,
497
+ _pathMatchers: compileRedactPathMatchers(input.paths)
498
+ };
503
499
  }
504
- function formatSnippetLines(snippet) {
505
- const width = String(snippet[snippet.length - 1]?.line ?? 0).length;
506
- return snippet.map(({ line, content, isErrorLine }) => {
507
- const marker = isErrorLine ? `${colors.red}\u276F${colors.reset}` : `${colors.dim} ${colors.reset}`;
508
- const numColor = isErrorLine ? colors.red : colors.gray;
509
- const trimmed = content.length > 120 ? `${content.slice(0, 117)}\u2026` : content;
510
- return `${marker} ${numColor}${String(line).padStart(width, " ")}${colors.reset} ${colors.dim}\u2503${colors.reset} ${colors.dim}${trimmed}${colors.reset}`;
511
- });
500
+ function allBuiltinMaskers() {
501
+ return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
512
502
  }
513
- function formatFrameLocation(frame, cwd) {
514
- const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
515
- const loc = frame.line ? `${file}:${frame.line}` : file;
516
- const fn = frame.fn && frame.fn !== "<unknown>" ? frame.fn : undefined;
517
- return fn ? `at ${fn} (${loc})` : `at ${loc}`;
503
+ function cloneRegex(re) {
504
+ return new RegExp(re.source, re.flags);
518
505
  }
519
- function formatCollapsedFrame(frame, cwd) {
520
- const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
521
- const loc = frame.line ? `${file}:${frame.line}` : file;
522
- const prefix = frame.fn?.startsWith("async") ? "at async " : "at ";
523
- const fn = frame.fn?.replace(/^async /, "");
524
- if (fn && fn !== "<unknown>" && fn !== loc)
525
- return `${prefix}${fn} (${loc})`;
526
- return `${prefix}${loc}`;
506
+ var globallyRedacted = Symbol.for("evlog.globallyRedacted");
507
+ function markGloballyRedacted(event) {
508
+ Object.defineProperty(event, globallyRedacted, {
509
+ value: true,
510
+ enumerable: false,
511
+ configurable: true
512
+ });
527
513
  }
528
- var GUIDANCE_WRAP_WIDTH = 76;
529
- var GUIDANCE_CONTINUATION = " ";
530
- function formatGuidanceLine(label, text, labelColor) {
531
- const prefix = `${labelColor}${label}:${colors.reset} `;
532
- const lines = [];
533
- let remaining = text.trim();
534
- let first = true;
535
- while (remaining.length > 0) {
536
- const budget = first ? Math.max(24, GUIDANCE_WRAP_WIDTH - prefix.length) : Math.max(24, GUIDANCE_WRAP_WIDTH - 5);
537
- if (remaining.length <= budget) {
538
- lines.push(first ? `${prefix}${remaining}` : `${GUIDANCE_CONTINUATION}${remaining}`);
539
- break;
514
+ function cloneForRedaction(event) {
515
+ try {
516
+ return structuredClone(event);
517
+ } catch {
518
+ try {
519
+ return JSON.parse(JSON.stringify(event));
520
+ } catch {
521
+ console.warn("[cloneForRedaction] Shallow clone used \u2014 nested objects may be mutated by redactPath, redactPatterns, and applyMaskersToTree");
522
+ return { ...event };
540
523
  }
541
- let split = remaining.lastIndexOf(" ", budget);
542
- if (split <= 0)
543
- split = budget;
544
- const chunk = remaining.slice(0, split).trimEnd();
545
- lines.push(first ? `${prefix}${chunk}` : `${GUIDANCE_CONTINUATION}${chunk}`);
546
- remaining = remaining.slice(split).trimStart();
547
- first = false;
548
524
  }
549
- return lines;
550
525
  }
551
- function buildErrorEntries(error, options = {}) {
552
- const normalized = normalizeErrorContext(error);
553
- if (!normalized)
554
- return [];
555
- const cwd = options.cwd ?? (typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd() : ".");
556
- const compact = options.compact ?? isDev();
557
- const guidanceOnly = (options.detail ?? "full") === "guidance";
558
- const showFrames = !guidanceOnly && !isBrowser() && (options.snippet ?? isDev());
559
- const stackDepth = guidanceOnly ? 0 : options.stackDepth ?? (compact ? 2 : 3);
560
- const snippetContextLines = compact ? 1 : 2;
561
- const children = [];
562
- const frames = guidanceOnly ? [] : parseStackFrames(normalized.stack);
563
- const primary = guidanceOnly ? undefined : pickPrimaryFrame(frames);
564
- if (!guidanceOnly && primary?.file && primary.line) {
565
- pushTreeSpacer(children);
566
- if (showFrames) {
567
- const snippet = readCodeSnippet(primary.file, primary.line, snippetContextLines);
568
- children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
569
- if (snippet)
570
- children.push(...formatSnippetLines(snippet));
571
- } else
572
- children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
526
+ function redactEvent(event, config) {
527
+ const clone = cloneForRedaction(event);
528
+ const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
529
+ if (config.transform)
530
+ try {
531
+ config.transform(clone);
532
+ } catch (err) {
533
+ console.error("[evlog] redact transform failed:", err);
534
+ }
535
+ const pathMatchers = config._pathMatchers ?? compileRedactPathMatchers(config.paths);
536
+ if (pathMatchers)
537
+ redactPathsInTree(clone, pathMatchers, replacement);
538
+ if (config._maskers?.length)
539
+ applyMaskersToTree(clone, config._maskers);
540
+ if (config.patterns?.length)
541
+ redactPatterns(clone, config.patterns, replacement);
542
+ return clone;
543
+ }
544
+ function redactPatterns(obj, patterns, replacement, prefix = "") {
545
+ if (obj === null || obj === undefined)
546
+ return;
547
+ if (Array.isArray(obj)) {
548
+ for (let i = 0;i < obj.length; i++) {
549
+ const key = String(i);
550
+ const fullPath = prefix ? `${prefix}.${key}` : key;
551
+ if (typeof obj[i] === "string")
552
+ obj[i] = applyPatterns(obj[i], patterns, replacement, fullPath, key);
553
+ else if (typeof obj[i] === "object")
554
+ redactPatterns(obj[i], patterns, replacement, fullPath);
555
+ }
556
+ return;
573
557
  }
574
- if (normalized.code)
575
- children.push(`${colors.dim}Code:${colors.reset} ${normalized.code}`);
576
- if (Boolean(normalized.why || normalized.fix || normalized.link))
577
- pushTreeSpacer(children);
578
- if (normalized.why)
579
- children.push(...formatGuidanceLine("Why", normalized.why, colors.yellow));
580
- if (normalized.fix)
581
- children.push(...formatGuidanceLine("Fix", normalized.fix, colors.cyan));
582
- if (normalized.link)
583
- children.push(`${colors.dim}More:${colors.reset} ${normalized.link}`);
584
- if (normalized.cause && normalized.cause !== normalized.message)
585
- children.push(`${colors.dim}Caused by:${colors.reset} ${normalized.cause}`);
586
- const hiddenCount = guidanceOnly ? 0 : frames.filter((f) => !f.isApp || isInternalErrorFrame(f)).length;
587
- const tailFrames = stackDepth > 0 ? frames.filter((f) => f !== primary && !isInternalErrorFrame(f)).slice(0, stackDepth) : [];
588
- if (!guidanceOnly && (hiddenCount > 0 || tailFrames.length > 0)) {
589
- pushTreeSpacer(children);
590
- if (hiddenCount > 0)
591
- children.push(`${colors.gray}stack (${hiddenCount} frame${hiddenCount === 1 ? "" : "s"} hidden in node_modules)${colors.reset}`);
592
- else
593
- children.push(`${colors.gray}stack${colors.reset}`);
594
- for (const frame of tailFrames)
595
- children.push(`${colors.gray} ${formatCollapsedFrame(frame, cwd)}${colors.reset}`);
558
+ if (typeof obj === "object") {
559
+ const record = obj;
560
+ for (const key of redactableKeys(record)) {
561
+ const val = record[key];
562
+ const fullPath = prefix ? `${prefix}.${key}` : key;
563
+ if (typeof val === "string")
564
+ setRedacted(record, key, applyPatterns(val, patterns, replacement, fullPath, key), fullPath);
565
+ else if (typeof val === "object")
566
+ redactPatterns(val, patterns, replacement, fullPath);
567
+ }
596
568
  }
597
- return [{
598
- key: "error",
599
- value: `${colors.red}${colors.bold}${normalized.message}${colors.reset}`,
600
- children: children.length > 0 ? children : undefined
601
- }];
602
569
  }
603
-
604
- // ../../node_modules/.bun/evlog@2.22.3+6e5ab44a2bca2113/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
605
- var DEV_PRESETS = {
606
- evlog: {
607
- frameworkOverlay: false,
608
- detail: "full"
609
- },
610
- nitro: {
611
- frameworkOverlay: true,
612
- detail: "guidance"
613
- },
614
- both: {
615
- frameworkOverlay: true,
616
- detail: "full"
570
+ function applyPatterns(value, patterns, replacement, path, key) {
571
+ let result = value;
572
+ for (const pattern of patterns) {
573
+ if (typeof replacement === "string") {
574
+ result = result.replace(pattern, replacement);
575
+ continue;
576
+ }
577
+ result = result.replace(pattern, (...args) => {
578
+ const match = args[0];
579
+ return resolveReplacement(replacement, match, {
580
+ path,
581
+ key,
582
+ groups: captureGroups(args)
583
+ });
584
+ });
617
585
  }
618
- };
619
- function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
620
- const compact = partial.compact ?? (inDev && pretty);
621
- const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
622
- const stackDepth = detail === "guidance" ? 0 : partial.stackDepth ?? (compact ? 2 : 3);
623
- return {
624
- snippet: partial.snippet ?? (detail === "full" && pretty && inDev),
625
- stackDepth,
626
- compact,
627
- detail
628
- };
586
+ return result;
629
587
  }
630
- function resolveDevTerminal(input = {}) {
631
- const pretty = input.pretty ?? isDev();
632
- const inDev = isDev();
633
- let frameworkOverlay;
634
- let prettyError = {};
635
- if (typeof input.dev === "string" && input.dev in DEV_PRESETS) {
636
- const { frameworkOverlay: presetOverlay, detail } = DEV_PRESETS[input.dev];
637
- frameworkOverlay = presetOverlay;
638
- prettyError = { detail };
639
- } else if (input.dev && typeof input.dev === "object") {
640
- const { frameworkOverlay: devOverlay, prettyError: devPrettyError } = input.dev;
641
- frameworkOverlay = devOverlay;
642
- if (devPrettyError)
643
- prettyError = devPrettyError;
644
- }
645
- if (frameworkOverlay === undefined)
646
- frameworkOverlay = !(pretty && inDev);
588
+ function captureGroups(args) {
589
+ const last = args.at(-1);
590
+ const trailing = typeof last === "object" && last !== null ? 3 : 2;
591
+ return args.slice(1, Math.max(1, args.length - trailing));
592
+ }
593
+ function applyMaskersToTree(obj, maskers) {
594
+ if (obj === null || obj === undefined)
595
+ return;
596
+ if (Array.isArray(obj)) {
597
+ for (let i = 0;i < obj.length; i++)
598
+ if (typeof obj[i] === "string")
599
+ obj[i] = applyMaskers(obj[i], maskers);
600
+ else if (typeof obj[i] === "object")
601
+ applyMaskersToTree(obj[i], maskers);
602
+ return;
603
+ }
604
+ if (typeof obj === "object") {
605
+ const record = obj;
606
+ for (const key of redactableKeys(record)) {
607
+ const val = record[key];
608
+ if (typeof val === "string")
609
+ setRedacted(record, key, applyMaskers(val, maskers), key);
610
+ else if (typeof val === "object")
611
+ applyMaskersToTree(val, maskers);
612
+ }
613
+ }
614
+ }
615
+ function applyMaskers(value, maskers) {
616
+ let result = value;
617
+ for (const [pattern, mask] of maskers)
618
+ result = result.replace(pattern, mask);
619
+ return result;
620
+ }
621
+
622
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
623
+ function logPluginError(name, hook, err) {
624
+ console.error(`[evlog/${name}] ${hook} failed:`, err);
625
+ }
626
+ function createPluginRunner(plugins = []) {
627
+ const byName = /* @__PURE__ */ new Map;
628
+ for (const plugin of plugins)
629
+ byName.set(plugin.name, plugin);
630
+ const list = Array.from(byName.values());
647
631
  return {
648
- frameworkOverlay,
649
- prettyError: finalizePrettyError(prettyError, frameworkOverlay, pretty, inDev)
632
+ plugins: list,
633
+ hasEnrich: list.some((p) => typeof p.enrich === "function"),
634
+ hasDrain: list.some((p) => typeof p.drain === "function"),
635
+ hasKeep: list.some((p) => typeof p.keep === "function"),
636
+ hasRequestLifecycle: list.some((p) => typeof p.onRequestStart === "function" || typeof p.onRequestFinish === "function"),
637
+ hasClientLog: list.some((p) => typeof p.onClientLog === "function"),
638
+ hasExtendLogger: list.some((p) => typeof p.extendLogger === "function"),
639
+ applyExtendLogger(logger) {
640
+ for (const plugin of list) {
641
+ if (!plugin.extendLogger)
642
+ continue;
643
+ try {
644
+ plugin.extendLogger(logger);
645
+ } catch (err) {
646
+ logPluginError(plugin.name, "extendLogger", err);
647
+ }
648
+ }
649
+ },
650
+ runOnRequestStart(ctx) {
651
+ for (const plugin of list) {
652
+ if (!plugin.onRequestStart)
653
+ continue;
654
+ try {
655
+ plugin.onRequestStart(ctx);
656
+ } catch (err) {
657
+ logPluginError(plugin.name, "onRequestStart", err);
658
+ }
659
+ }
660
+ },
661
+ runOnRequestFinish(ctx) {
662
+ for (const plugin of list) {
663
+ if (!plugin.onRequestFinish)
664
+ continue;
665
+ try {
666
+ plugin.onRequestFinish(ctx);
667
+ } catch (err) {
668
+ logPluginError(plugin.name, "onRequestFinish", err);
669
+ }
670
+ }
671
+ },
672
+ async runEnrich(ctx) {
673
+ for (const plugin of list) {
674
+ if (!plugin.enrich)
675
+ continue;
676
+ try {
677
+ await plugin.enrich(ctx);
678
+ } catch (err) {
679
+ logPluginError(plugin.name, "enrich", err);
680
+ }
681
+ }
682
+ },
683
+ async runDrain(ctx) {
684
+ const drains = list.filter((p) => typeof p.drain === "function");
685
+ if (drains.length === 0)
686
+ return;
687
+ await Promise.allSettled(drains.map(async (plugin) => {
688
+ try {
689
+ await plugin.drain(ctx);
690
+ } catch (err) {
691
+ logPluginError(plugin.name, "drain", err);
692
+ }
693
+ }));
694
+ },
695
+ async runKeep(ctx) {
696
+ for (const plugin of list) {
697
+ if (!plugin.keep)
698
+ continue;
699
+ try {
700
+ await plugin.keep(ctx);
701
+ } catch (err) {
702
+ logPluginError(plugin.name, "keep", err);
703
+ }
704
+ }
705
+ },
706
+ runOnClientLog(ctx) {
707
+ for (const plugin of list) {
708
+ if (!plugin.onClientLog)
709
+ continue;
710
+ try {
711
+ plugin.onClientLog(ctx);
712
+ } catch (err) {
713
+ logPluginError(plugin.name, "onClientLog", err);
714
+ }
715
+ }
716
+ },
717
+ async runSetup(ctx) {
718
+ for (const plugin of list) {
719
+ if (!plugin.setup)
720
+ continue;
721
+ try {
722
+ await plugin.setup(ctx);
723
+ } catch (err) {
724
+ logPluginError(plugin.name, "setup", err);
725
+ }
726
+ }
727
+ }
650
728
  };
651
729
  }
730
+ var emptyRunner = createPluginRunner([]);
731
+ function getEmptyPluginRunner() {
732
+ return emptyRunner;
733
+ }
734
+ var EVLOG_MAJOR = 2;
735
+ var REGISTRY_KEY = Symbol.for(`evlog.registry.v${EVLOG_MAJOR}`);
736
+ var MAJORS_KEY = Symbol.for("evlog.majors");
737
+ function createConfig() {
738
+ return {
739
+ env: {
740
+ service: "app",
741
+ environment: "development"
742
+ },
743
+ pretty: isDev(),
744
+ prettyError: {
745
+ snippet: isDev(),
746
+ stackDepth: 2,
747
+ compact: isDev(),
748
+ detail: "full"
749
+ },
750
+ sampling: {},
751
+ stringify: true,
752
+ drain: undefined,
753
+ redact: undefined,
754
+ enabled: true,
755
+ silent: false,
756
+ minLevel: "debug",
757
+ locked: false,
758
+ initialized: false,
759
+ pluginRunner: getEmptyPluginRunner()
760
+ };
761
+ }
762
+ function warnOnMultiMajor(host) {
763
+ const majors = host[MAJORS_KEY] ??= /* @__PURE__ */ new Set;
764
+ if (majors.has(EVLOG_MAJOR))
765
+ return;
766
+ majors.add(EVLOG_MAJOR);
767
+ if (majors.size > 1)
768
+ console.warn(`[evlog] Multiple major versions of evlog are loaded in this process (${[...majors].map((m) => `${m}.x`).join(", ")}). They cannot share request scope or logger configuration: events emitted through the other copy will be undrained and unredacted, and useLogger() may throw. Deduplicate evlog to a single major.`);
769
+ }
770
+ function getRegistry() {
771
+ const host = globalThis;
772
+ warnOnMultiMajor(host);
773
+ return host[REGISTRY_KEY] ??= {
774
+ config: createConfig(),
775
+ storages: /* @__PURE__ */ new Map
776
+ };
777
+ }
778
+ var globalConfig = getRegistry().config;
652
779
 
653
- // ../../node_modules/.bun/evlog@2.22.3+6e5ab44a2bca2113/node_modules/evlog/dist/error.mjs
654
- var evlogErrorInternalKey = Symbol.for("evlog.error.internal");
655
- var EvlogError = class EvlogError2 extends Error {
656
- code;
657
- status;
658
- why;
659
- fix;
660
- link;
661
- get internal() {
662
- return this[evlogErrorInternalKey];
663
- }
664
- constructor(options) {
665
- const opts = typeof options === "string" ? { message: options } : options;
666
- super(opts.message, { cause: opts.cause });
667
- this.name = "EvlogError";
668
- this.code = opts.code;
669
- this.status = opts.status ?? 500;
670
- this.why = opts.why;
671
- this.fix = opts.fix;
672
- this.link = opts.link;
673
- if (opts.internal !== undefined)
674
- Object.defineProperty(this, evlogErrorInternalKey, {
675
- value: opts.internal,
676
- enumerable: false,
677
- writable: false,
678
- configurable: true
679
- });
680
- if (Error.captureStackTrace)
681
- Error.captureStackTrace(this, EvlogError2);
682
- }
683
- get statusText() {
684
- return this.message;
685
- }
686
- get statusCode() {
687
- return this.status;
688
- }
689
- get statusMessage() {
690
- return this.message;
691
- }
692
- get data() {
693
- if (this.code || this.why || this.fix || this.link)
694
- return {
695
- code: this.code,
696
- why: this.why,
697
- fix: this.fix,
698
- link: this.link
699
- };
700
- }
701
- toString() {
702
- const useColors = isServer();
703
- const red = useColors ? colors.red : "";
704
- const yellow = useColors ? colors.yellow : "";
705
- const cyan = useColors ? colors.cyan : "";
706
- const dim = useColors ? colors.dim : "";
707
- const reset = useColors ? colors.reset : "";
708
- const bold = useColors ? colors.bold : "";
709
- const lines = [];
710
- lines.push(`${red}${bold}Error:${reset} ${this.message}`);
711
- if (this.code)
712
- lines.push(`${dim}Code:${reset} ${this.code}`);
713
- if (this.why)
714
- lines.push(`${yellow}Why:${reset} ${this.why}`);
715
- if (this.fix)
716
- lines.push(`${cyan}Fix:${reset} ${this.fix}`);
717
- if (this.link)
718
- lines.push(`${dim}More info:${reset} ${this.link}`);
719
- if (this.cause)
720
- lines.push(`${dim}Caused by:${reset} ${this.cause.message}`);
721
- return lines.join(`
722
- `);
780
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/pretty-error-DTIHxnBN.mjs
781
+ var snippetReader = null;
782
+ var PRETTY_ERROR_TREE_SPACER = "__EVLOG_TREE_SPACER__";
783
+ function pushTreeSpacer(children) {
784
+ children.push(PRETTY_ERROR_TREE_SPACER);
785
+ }
786
+ var SKIP_PATH_RE = /(?:^|[/\\])(?:node_modules|\.nuxt|\.next|\.output)(?:[/\\]|$)/;
787
+ var SKIP_FRAME_PATH_RE = /(?:^|[/\\])(?:packages[/\\]evlog|evlog[/\\](?:dist|src))(?:[/\\]|$)/;
788
+ var SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
789
+ function isPlainObject(val) {
790
+ return val !== null && typeof val === "object" && !Array.isArray(val);
791
+ }
792
+ function pickString(obj, key) {
793
+ const val = obj[key];
794
+ return typeof val === "string" && val.length > 0 ? val : undefined;
795
+ }
796
+ function pickNumber(obj, key) {
797
+ const val = obj[key];
798
+ return typeof val === "number" ? val : undefined;
799
+ }
800
+ function extractGuidance(data) {
801
+ return {
802
+ code: pickString(data, "code"),
803
+ why: pickString(data, "why"),
804
+ fix: pickString(data, "fix"),
805
+ link: pickString(data, "link")
806
+ };
807
+ }
808
+ function normalizeErrorContext(error) {
809
+ if (error === null || error === undefined)
810
+ return null;
811
+ if (typeof error === "string")
812
+ return { message: error };
813
+ if (!isPlainObject(error))
814
+ return { message: String(error) };
815
+ const result = {
816
+ message: pickString(error, "message") ?? pickString(error, "statusText") ?? pickString(error, "statusMessage") ?? "Unknown error",
817
+ name: pickString(error, "name"),
818
+ code: pickString(error, "code"),
819
+ why: pickString(error, "why"),
820
+ fix: pickString(error, "fix"),
821
+ link: pickString(error, "link"),
822
+ status: pickNumber(error, "status") ?? pickNumber(error, "statusCode"),
823
+ stack: pickString(error, "stack")
824
+ };
825
+ const { data, cause } = error;
826
+ if (isPlainObject(data)) {
827
+ const guidance = extractGuidance(data);
828
+ if (!result.code)
829
+ result.code = guidance.code;
830
+ if (!result.why)
831
+ result.why = guidance.why;
832
+ if (!result.fix)
833
+ result.fix = guidance.fix;
834
+ if (!result.link)
835
+ result.link = guidance.link;
723
836
  }
724
- toJSON() {
725
- const { data } = this;
726
- return {
727
- name: this.name,
728
- message: this.message,
729
- status: this.status,
730
- ...data && { data },
731
- ...this.cause instanceof Error && { cause: {
732
- name: this.cause.name,
733
- message: this.cause.message
734
- } }
735
- };
837
+ if (cause instanceof Error)
838
+ result.cause = cause.message;
839
+ else if (isPlainObject(cause) && pickString(cause, "message"))
840
+ result.cause = pickString(cause, "message");
841
+ return result;
842
+ }
843
+ function decodeFileUrl(file) {
844
+ if (file.startsWith("file://"))
845
+ try {
846
+ return decodeURIComponent(new URL(file).pathname);
847
+ } catch {
848
+ return file.slice(7);
849
+ }
850
+ return file;
851
+ }
852
+ function isAppPath(file) {
853
+ const normalized = decodeFileUrl(file).replace(/\\/g, "/");
854
+ if (normalized.startsWith("node:"))
855
+ return false;
856
+ if (SKIP_PATH_RE.test(normalized))
857
+ return false;
858
+ if (normalized.includes("/node_modules/"))
859
+ return false;
860
+ if (isFrameworkRuntimePath(normalized))
861
+ return false;
862
+ return true;
863
+ }
864
+ function formatDisplayPath(file, cwd) {
865
+ const decoded = decodeFileUrl(file).replace(/\\/g, "/");
866
+ const cwdNorm = cwd.replace(/\\/g, "/").replace(/\/$/, "");
867
+ if (cwdNorm && decoded.startsWith(`${cwdNorm}/`)) {
868
+ const rel = decoded.slice(cwdNorm.length + 1);
869
+ return rel.startsWith("./") ? rel.slice(2) : rel;
736
870
  }
737
- };
738
-
739
- // ../../node_modules/.bun/evlog@2.22.3+6e5ab44a2bca2113/node_modules/evlog/dist/audit-CPODPtOL.mjs
740
- var DEFAULT_REPLACEMENT = "[REDACTED]";
741
- function normalizeRedactPathPattern(pattern) {
742
- if (!pattern.includes("*") && !pattern.includes("."))
743
- return `**.${pattern}`;
744
- return pattern;
871
+ const serverIdx = decoded.indexOf("/server/");
872
+ if (serverIdx >= 0)
873
+ return decoded.slice(serverIdx + 1);
874
+ const srcIdx = decoded.indexOf("/src/");
875
+ if (srcIdx >= 0)
876
+ return decoded.slice(srcIdx + 1);
877
+ return decoded;
745
878
  }
746
- function compileRedactPathMatchers(patterns) {
747
- if (!patterns?.length)
879
+ function compactStackForStorage(stack, maxFrames = 5) {
880
+ if (!stack)
748
881
  return;
749
- const exactPaths = /* @__PURE__ */ new Set;
750
- const pathGlobs = [];
751
- const keyGlobs = [];
752
- const caseInsensitiveLeaves = /* @__PURE__ */ new Set;
753
- for (const raw of patterns) {
754
- if (!raw.includes("*")) {
755
- if (raw.includes("."))
756
- exactPaths.add(raw);
757
- else
758
- addPathGlobPattern(normalizeRedactPathPattern(raw), exactPaths, pathGlobs, caseInsensitiveLeaves);
882
+ const head = stack.split(`
883
+ `)[0] ?? "";
884
+ const useful = parseStackFrames(stack).filter((f) => f.file && f.line && f.isApp && !isInternalErrorFrame(f)).slice(0, maxFrames);
885
+ if (useful.length === 0)
886
+ return stack;
887
+ return [head, ...useful.map((f) => f.raw)].join(`
888
+ `);
889
+ }
890
+ function parseStackFrames(stack) {
891
+ if (!stack)
892
+ return [];
893
+ const lines = stack.split(`
894
+ `);
895
+ const frames = [];
896
+ for (const line of lines) {
897
+ const trimmed = line.trim();
898
+ if (!trimmed.startsWith("at "))
899
+ continue;
900
+ const withFn = trimmed.match(/^at (.+?) \((.+):(\d+):(\d+)\)$/);
901
+ if (withFn) {
902
+ const [, fn, file, lineStr, colStr] = withFn;
903
+ frames.push({
904
+ raw: trimmed,
905
+ fn,
906
+ file,
907
+ line: Number(lineStr),
908
+ column: Number(colStr),
909
+ isApp: isAppPath(file)
910
+ });
759
911
  continue;
760
912
  }
761
- if (!raw.includes("."))
762
- keyGlobs.push(globToRegExp(raw, "."));
763
- else
764
- addPathGlobPattern(raw, exactPaths, pathGlobs, caseInsensitiveLeaves);
913
+ const withoutFn = trimmed.match(/^at (.+):(\d+):(\d+)$/);
914
+ if (withoutFn) {
915
+ const [, file, lineStr, colStr] = withoutFn;
916
+ frames.push({
917
+ raw: trimmed,
918
+ file,
919
+ line: Number(lineStr),
920
+ column: Number(colStr),
921
+ isApp: isAppPath(file)
922
+ });
923
+ continue;
924
+ }
925
+ const asyncFn = trimmed.match(/^at async (.+?) \((.+):(\d+):(\d+)\)$/);
926
+ if (asyncFn) {
927
+ const [, fn, file, lineStr, colStr] = asyncFn;
928
+ frames.push({
929
+ raw: trimmed,
930
+ fn: `async ${fn}`,
931
+ file,
932
+ line: Number(lineStr),
933
+ column: Number(colStr),
934
+ isApp: isAppPath(file)
935
+ });
936
+ }
765
937
  }
766
- if (exactPaths.size === 0 && pathGlobs.length === 0 && keyGlobs.length === 0 && caseInsensitiveLeaves.size === 0)
767
- return;
768
- return {
769
- exactPaths,
770
- pathGlobs,
771
- keyGlobs,
772
- caseInsensitiveLeaves
773
- };
938
+ return frames;
774
939
  }
775
- function addPathGlobPattern(pattern, exactPaths, pathGlobs, caseInsensitiveLeaves) {
776
- pathGlobs.push(globToRegExp(pattern, "."));
777
- const leaf = pattern.match(/^\*\*\.([^.?*]+)$/);
778
- if (leaf) {
779
- exactPaths.add(leaf[1]);
780
- caseInsensitiveLeaves.add(leaf[1].toLowerCase());
781
- }
940
+ function isFrameworkRuntimePath(path) {
941
+ const normalized = path.replace(/\\/g, "/");
942
+ return normalized.includes("route-modules/") || normalized.includes("webpack://next/") || normalized.includes("/next/dist/") || normalized.includes("/compiled/next-server/");
782
943
  }
783
- function matchesRedactPath(fullPath, leafKey, matchers) {
784
- if (matchers.exactPaths.has(fullPath))
785
- return true;
786
- if (matchers.caseInsensitiveLeaves.has(leafKey.toLowerCase()))
944
+ function isFrameworkRuntimeFrame(frame) {
945
+ if (!frame.file)
946
+ return false;
947
+ return isFrameworkRuntimePath(decodeFileUrl(frame.file));
948
+ }
949
+ function isInternalErrorFrame(frame) {
950
+ if (isFrameworkRuntimeFrame(frame))
787
951
  return true;
788
- for (const glob of matchers.pathGlobs) {
789
- glob.lastIndex = 0;
790
- if (glob.test(fullPath))
791
- return true;
792
- }
793
- for (const glob of matchers.keyGlobs) {
794
- glob.lastIndex = 0;
795
- if (glob.test(leafKey))
952
+ if (frame.fn) {
953
+ const fn = frame.fn.replace(/^async /, "");
954
+ if (SKIP_FRAME_FN_RE.test(fn))
796
955
  return true;
797
956
  }
957
+ if (!frame.file)
958
+ return true;
959
+ const path = decodeFileUrl(frame.file).replace(/\\/g, "/");
960
+ if (SKIP_FRAME_PATH_RE.test(path))
961
+ return true;
962
+ if (path.includes(".nuxt/"))
963
+ return true;
964
+ if (path.includes(".next/"))
965
+ return true;
798
966
  return false;
799
967
  }
800
- function redactPathsInTree(obj, matchers, replacement, prefix = "") {
801
- if (obj === null || obj === undefined)
802
- return;
803
- if (Array.isArray(obj)) {
804
- for (let i = 0;i < obj.length; i++) {
805
- const segment = String(i);
806
- const fullPath = prefix ? `${prefix}.${segment}` : segment;
807
- redactPathsInTree(obj[i], matchers, replacement, fullPath);
968
+ function pickPrimaryFrame(frames) {
969
+ for (const frame of frames)
970
+ if (frame.isApp && frame.file && frame.line && !isInternalErrorFrame(frame))
971
+ return frame;
972
+ }
973
+ function readCodeSnippet(file, line, contextLines = 2) {
974
+ if (!isDev() || isBrowser() || !snippetReader)
975
+ return null;
976
+ const path = decodeFileUrl(file).replace(/\\/g, "/");
977
+ if (path.includes(".next/") || path.includes(".nuxt/") || path.includes(".output/"))
978
+ return null;
979
+ return snippetReader(file, line, contextLines);
980
+ }
981
+ function formatSnippetLines(snippet) {
982
+ const width = String(snippet[snippet.length - 1]?.line ?? 0).length;
983
+ return snippet.map(({ line, content, isErrorLine }) => {
984
+ const marker = isErrorLine ? `${colors.red}\u276F${colors.reset}` : `${colors.dim} ${colors.reset}`;
985
+ const numColor = isErrorLine ? colors.red : colors.gray;
986
+ const trimmed = content.length > 120 ? `${content.slice(0, 117)}\u2026` : content;
987
+ return `${marker} ${numColor}${String(line).padStart(width, " ")}${colors.reset} ${colors.dim}\u2503${colors.reset} ${colors.dim}${trimmed}${colors.reset}`;
988
+ });
989
+ }
990
+ function formatFrameLocation(frame, cwd) {
991
+ const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
992
+ const loc = frame.line ? `${file}:${frame.line}` : file;
993
+ const fn = frame.fn && frame.fn !== "<unknown>" ? frame.fn : undefined;
994
+ return fn ? `at ${fn} (${loc})` : `at ${loc}`;
995
+ }
996
+ function formatCollapsedFrame(frame, cwd) {
997
+ const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
998
+ const loc = frame.line ? `${file}:${frame.line}` : file;
999
+ const prefix = frame.fn?.startsWith("async") ? "at async " : "at ";
1000
+ const fn = frame.fn?.replace(/^async /, "");
1001
+ if (fn && fn !== "<unknown>" && fn !== loc)
1002
+ return `${prefix}${fn} (${loc})`;
1003
+ return `${prefix}${loc}`;
1004
+ }
1005
+ var GUIDANCE_WRAP_WIDTH = 76;
1006
+ var GUIDANCE_CONTINUATION = " ";
1007
+ function formatGuidanceLine(label, text, labelColor) {
1008
+ const prefix = `${labelColor}${label}:${colors.reset} `;
1009
+ const lines = [];
1010
+ let remaining = text.trim();
1011
+ let first = true;
1012
+ while (remaining.length > 0) {
1013
+ const budget = first ? Math.max(24, GUIDANCE_WRAP_WIDTH - prefix.length) : Math.max(24, GUIDANCE_WRAP_WIDTH - 5);
1014
+ if (remaining.length <= budget) {
1015
+ lines.push(first ? `${prefix}${remaining}` : `${GUIDANCE_CONTINUATION}${remaining}`);
1016
+ break;
808
1017
  }
809
- return;
1018
+ let split = remaining.lastIndexOf(" ", budget);
1019
+ if (split <= 0)
1020
+ split = budget;
1021
+ const chunk = remaining.slice(0, split).trimEnd();
1022
+ lines.push(first ? `${prefix}${chunk}` : `${GUIDANCE_CONTINUATION}${chunk}`);
1023
+ remaining = remaining.slice(split).trimStart();
1024
+ first = false;
810
1025
  }
811
- if (typeof obj === "object") {
812
- const record = obj;
813
- for (const key in record) {
814
- const fullPath = prefix ? `${prefix}.${key}` : key;
815
- if (matchesRedactPath(fullPath, key, matchers))
816
- record[key] = replacement;
817
- else
818
- redactPathsInTree(record[key], matchers, replacement, fullPath);
819
- }
1026
+ return lines;
1027
+ }
1028
+ function buildErrorEntries(error, options = {}) {
1029
+ const normalized = normalizeErrorContext(error);
1030
+ if (!normalized)
1031
+ return [];
1032
+ const cwd = options.cwd ?? (typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd() : ".");
1033
+ const compact = options.compact ?? isDev();
1034
+ const guidanceOnly = (options.detail ?? "full") === "guidance";
1035
+ const showFrames = !guidanceOnly && !isBrowser() && (options.snippet ?? isDev());
1036
+ const stackDepth = guidanceOnly ? 0 : options.stackDepth ?? (compact ? 2 : 3);
1037
+ const snippetContextLines = compact ? 1 : 2;
1038
+ const children = [];
1039
+ const frames = guidanceOnly ? [] : parseStackFrames(normalized.stack);
1040
+ const primary = guidanceOnly ? undefined : pickPrimaryFrame(frames);
1041
+ if (!guidanceOnly && primary?.file && primary.line) {
1042
+ pushTreeSpacer(children);
1043
+ if (showFrames) {
1044
+ const snippet = readCodeSnippet(primary.file, primary.line, snippetContextLines);
1045
+ children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
1046
+ if (snippet)
1047
+ children.push(...formatSnippetLines(snippet));
1048
+ } else
1049
+ children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
1050
+ }
1051
+ if (normalized.code)
1052
+ children.push(`${colors.dim}Code:${colors.reset} ${normalized.code}`);
1053
+ if (Boolean(normalized.why || normalized.fix || normalized.link))
1054
+ pushTreeSpacer(children);
1055
+ if (normalized.why)
1056
+ children.push(...formatGuidanceLine("Why", normalized.why, colors.yellow));
1057
+ if (normalized.fix)
1058
+ children.push(...formatGuidanceLine("Fix", normalized.fix, colors.cyan));
1059
+ if (normalized.link)
1060
+ children.push(`${colors.dim}More:${colors.reset} ${normalized.link}`);
1061
+ if (normalized.cause && normalized.cause !== normalized.message)
1062
+ children.push(`${colors.dim}Caused by:${colors.reset} ${normalized.cause}`);
1063
+ const hiddenCount = guidanceOnly ? 0 : frames.filter((f) => !f.isApp || isInternalErrorFrame(f)).length;
1064
+ const tailFrames = stackDepth > 0 ? frames.filter((f) => f !== primary && !isInternalErrorFrame(f)).slice(0, stackDepth) : [];
1065
+ if (!guidanceOnly && (hiddenCount > 0 || tailFrames.length > 0)) {
1066
+ pushTreeSpacer(children);
1067
+ if (hiddenCount > 0)
1068
+ children.push(`${colors.gray}stack (${hiddenCount} frame${hiddenCount === 1 ? "" : "s"} hidden in node_modules)${colors.reset}`);
1069
+ else
1070
+ children.push(`${colors.gray}stack${colors.reset}`);
1071
+ for (const frame of tailFrames)
1072
+ children.push(`${colors.gray} ${formatCollapsedFrame(frame, cwd)}${colors.reset}`);
820
1073
  }
1074
+ return [{
1075
+ key: "error",
1076
+ value: `${colors.red}${colors.bold}${normalized.message}${colors.reset}`,
1077
+ children: children.length > 0 ? children : undefined
1078
+ }];
821
1079
  }
822
- var builtinPatterns = {
823
- creditCard: {
824
- pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
825
- mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
826
- },
827
- email: {
828
- pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g,
829
- mask: (m) => {
830
- if (m.indexOf("@") < 1)
831
- return "***@***";
832
- const tld = m.slice(m.lastIndexOf("."));
833
- return `${m[0]}***@***${tld}`;
834
- }
835
- },
836
- ipv4: {
837
- pattern: /\b(?!0\.0\.0\.0\b)(?!127\.0\.0\.1\b)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
838
- mask: (m) => `***.***.***.${m.split(".").pop()}`
839
- },
840
- phone: {
841
- pattern: /(?:\+\d{1,3}[\s.-]?\(?\d{1,4}\)?|\(\d{1,4}\))(?:[\s.-]?\d{2,4}){2,4}\b/g,
842
- mask: (m) => {
843
- const digits = m.replace(/[^\d]/g, "");
844
- if (m.startsWith("+") && digits.length > 4) {
845
- const ccMatch = m.match(/^\+\d{1,3}/);
846
- return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
847
- }
848
- if (digits.length > 2)
849
- return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
850
- return "***";
851
- }
852
- },
853
- jwt: {
854
- pattern: /\beyJ[\w-]*\.[\w-]*\.[\w-]*\b/g,
855
- mask: () => "eyJ***.***"
1080
+
1081
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
1082
+ var DEV_PRESETS = {
1083
+ evlog: {
1084
+ frameworkOverlay: false,
1085
+ detail: "full"
856
1086
  },
857
- bearer: {
858
- pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
859
- mask: () => "Bearer ***"
1087
+ nitro: {
1088
+ frameworkOverlay: true,
1089
+ detail: "guidance"
860
1090
  },
861
- iban: {
862
- pattern: /\b[A-Z]{2}\d{2}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}\b/g,
863
- mask: (m) => {
864
- const clean = m.replace(/[\s-]/g, "");
865
- return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
866
- }
1091
+ both: {
1092
+ frameworkOverlay: true,
1093
+ detail: "full"
867
1094
  }
868
1095
  };
869
- function resolveRedactConfig(input) {
870
- if (input === undefined || input === false)
871
- return;
872
- if (input === true)
873
- return { _maskers: allBuiltinMaskers() };
874
- if (input.builtins === false)
875
- return {
876
- ...input,
877
- _pathMatchers: compileRedactPathMatchers(input.paths)
878
- };
879
- const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
1096
+ function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
1097
+ const compact = partial.compact ?? (inDev && pretty);
1098
+ const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
1099
+ const stackDepth = detail === "guidance" ? 0 : partial.stackDepth ?? (compact ? 2 : 3);
880
1100
  return {
881
- ...input,
882
- _maskers: maskers,
883
- _pathMatchers: compileRedactPathMatchers(input.paths)
1101
+ snippet: partial.snippet ?? (detail === "full" && pretty && inDev),
1102
+ stackDepth,
1103
+ compact,
1104
+ detail
884
1105
  };
885
1106
  }
886
- function allBuiltinMaskers() {
887
- return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
888
- }
889
- function cloneRegex(re) {
890
- return new RegExp(re.source, re.flags);
891
- }
892
- var globallyRedacted = Symbol.for("evlog.globallyRedacted");
893
- function markGloballyRedacted(event) {
894
- Object.defineProperty(event, globallyRedacted, {
895
- value: true,
896
- enumerable: false,
897
- configurable: true
898
- });
899
- }
900
- function cloneForRedaction(event) {
901
- try {
902
- return structuredClone(event);
903
- } catch {
904
- try {
905
- return JSON.parse(JSON.stringify(event));
906
- } catch {
907
- console.warn("[cloneForRedaction] Shallow clone used \u2014 nested objects may be mutated by redactPath, redactPatterns, and applyMaskersToTree");
908
- return { ...event };
909
- }
910
- }
911
- }
912
- function redactEvent(event, config) {
913
- const clone = cloneForRedaction(event);
914
- const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
915
- const pathMatchers = config._pathMatchers ?? compileRedactPathMatchers(config.paths);
916
- if (pathMatchers)
917
- redactPathsInTree(clone, pathMatchers, replacement);
918
- if (config._maskers?.length)
919
- applyMaskersToTree(clone, config._maskers);
920
- if (config.patterns?.length)
921
- redactPatterns(clone, config.patterns, replacement);
922
- return clone;
1107
+ function resolveDevTerminal(input = {}) {
1108
+ const pretty = input.pretty ?? isDev();
1109
+ const inDev = isDev();
1110
+ let frameworkOverlay;
1111
+ let prettyError = {};
1112
+ if (typeof input.dev === "string" && input.dev in DEV_PRESETS) {
1113
+ const { frameworkOverlay: presetOverlay, detail } = DEV_PRESETS[input.dev];
1114
+ frameworkOverlay = presetOverlay;
1115
+ prettyError = { detail };
1116
+ } else if (input.dev && typeof input.dev === "object") {
1117
+ const { frameworkOverlay: devOverlay, prettyError: devPrettyError } = input.dev;
1118
+ frameworkOverlay = devOverlay;
1119
+ if (devPrettyError)
1120
+ prettyError = devPrettyError;
1121
+ }
1122
+ if (frameworkOverlay === undefined)
1123
+ frameworkOverlay = !(pretty && inDev);
1124
+ return {
1125
+ frameworkOverlay,
1126
+ prettyError: finalizePrettyError(prettyError, frameworkOverlay, pretty, inDev)
1127
+ };
923
1128
  }
924
- function redactPatterns(obj, patterns, replacement) {
925
- if (obj === null || obj === undefined)
926
- return;
927
- if (Array.isArray(obj)) {
928
- for (let i = 0;i < obj.length; i++)
929
- if (typeof obj[i] === "string")
930
- obj[i] = applyPatterns(obj[i], patterns, replacement);
931
- else if (typeof obj[i] === "object")
932
- redactPatterns(obj[i], patterns, replacement);
1129
+
1130
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
1131
+ var publisher = null;
1132
+ function publishWideEvent(event) {
1133
+ if (!publisher)
933
1134
  return;
934
- }
935
- if (typeof obj === "object") {
936
- const record = obj;
937
- for (const key in record) {
938
- const val = record[key];
939
- if (typeof val === "string")
940
- record[key] = applyPatterns(val, patterns, replacement);
941
- else if (typeof val === "object")
942
- redactPatterns(val, patterns, replacement);
943
- }
1135
+ try {
1136
+ publisher(event);
1137
+ } catch (err) {
1138
+ console.error("[evlog] diagnostics channel publish failed:", err);
944
1139
  }
945
1140
  }
946
- function applyPatterns(value, patterns, replacement) {
947
- let result = value;
948
- for (const pattern of patterns)
949
- result = result.replace(pattern, replacement);
950
- return result;
1141
+
1142
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
1143
+ var evlogErrorBrand = Symbol.for("evlog.error.brand");
1144
+ function isEvlogError(error) {
1145
+ return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
951
1146
  }
952
- function applyMaskersToTree(obj, maskers) {
953
- if (obj === null || obj === undefined)
954
- return;
955
- if (Array.isArray(obj)) {
956
- for (let i = 0;i < obj.length; i++)
957
- if (typeof obj[i] === "string")
958
- obj[i] = applyMaskers(obj[i], maskers);
959
- else if (typeof obj[i] === "object")
960
- applyMaskersToTree(obj[i], maskers);
961
- return;
1147
+
1148
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/error.mjs
1149
+ var evlogErrorInternalKey = Symbol.for("evlog.error.internal");
1150
+ var evlogErrorDataKey = Symbol.for("evlog.error.data");
1151
+ var EvlogError = class EvlogError extends Error {
1152
+ static isEvlogError(error) {
1153
+ return isEvlogError(error);
962
1154
  }
963
- if (typeof obj === "object") {
964
- const record = obj;
965
- for (const key in record) {
966
- const val = record[key];
967
- if (typeof val === "string")
968
- record[key] = applyMaskers(val, maskers);
969
- else if (typeof val === "object")
970
- applyMaskersToTree(val, maskers);
971
- }
1155
+ code;
1156
+ status;
1157
+ why;
1158
+ fix;
1159
+ link;
1160
+ get internal() {
1161
+ return this[evlogErrorInternalKey];
972
1162
  }
973
- }
974
- function applyMaskers(value, maskers) {
975
- let result = value;
976
- for (const [pattern, mask] of maskers)
977
- result = result.replace(pattern, mask);
978
- return result;
979
- }
980
- function logPluginError(name, hook, err) {
981
- console.error(`[evlog/${name}] ${hook} failed:`, err);
982
- }
983
- function createPluginRunner(plugins = []) {
984
- const byName = /* @__PURE__ */ new Map;
985
- for (const plugin of plugins)
986
- byName.set(plugin.name, plugin);
987
- const list = Array.from(byName.values());
988
- return {
989
- plugins: list,
990
- hasEnrich: list.some((p) => typeof p.enrich === "function"),
991
- hasDrain: list.some((p) => typeof p.drain === "function"),
992
- hasKeep: list.some((p) => typeof p.keep === "function"),
993
- hasRequestLifecycle: list.some((p) => typeof p.onRequestStart === "function" || typeof p.onRequestFinish === "function"),
994
- hasClientLog: list.some((p) => typeof p.onClientLog === "function"),
995
- hasExtendLogger: list.some((p) => typeof p.extendLogger === "function"),
996
- applyExtendLogger(logger) {
997
- for (const plugin of list) {
998
- if (!plugin.extendLogger)
999
- continue;
1000
- try {
1001
- plugin.extendLogger(logger);
1002
- } catch (err) {
1003
- logPluginError(plugin.name, "extendLogger", err);
1004
- }
1005
- }
1006
- },
1007
- runOnRequestStart(ctx) {
1008
- for (const plugin of list) {
1009
- if (!plugin.onRequestStart)
1010
- continue;
1011
- try {
1012
- plugin.onRequestStart(ctx);
1013
- } catch (err) {
1014
- logPluginError(plugin.name, "onRequestStart", err);
1015
- }
1016
- }
1017
- },
1018
- runOnRequestFinish(ctx) {
1019
- for (const plugin of list) {
1020
- if (!plugin.onRequestFinish)
1021
- continue;
1022
- try {
1023
- plugin.onRequestFinish(ctx);
1024
- } catch (err) {
1025
- logPluginError(plugin.name, "onRequestFinish", err);
1026
- }
1027
- }
1028
- },
1029
- async runEnrich(ctx) {
1030
- for (const plugin of list) {
1031
- if (!plugin.enrich)
1032
- continue;
1033
- try {
1034
- await plugin.enrich(ctx);
1035
- } catch (err) {
1036
- logPluginError(plugin.name, "enrich", err);
1037
- }
1038
- }
1039
- },
1040
- async runDrain(ctx) {
1041
- const drains = list.filter((p) => typeof p.drain === "function");
1042
- if (drains.length === 0)
1043
- return;
1044
- await Promise.allSettled(drains.map(async (plugin) => {
1045
- try {
1046
- await plugin.drain(ctx);
1047
- } catch (err) {
1048
- logPluginError(plugin.name, "drain", err);
1049
- }
1050
- }));
1051
- },
1052
- async runKeep(ctx) {
1053
- for (const plugin of list) {
1054
- if (!plugin.keep)
1055
- continue;
1056
- try {
1057
- await plugin.keep(ctx);
1058
- } catch (err) {
1059
- logPluginError(plugin.name, "keep", err);
1060
- }
1061
- }
1062
- },
1063
- runOnClientLog(ctx) {
1064
- for (const plugin of list) {
1065
- if (!plugin.onClientLog)
1066
- continue;
1067
- try {
1068
- plugin.onClientLog(ctx);
1069
- } catch (err) {
1070
- logPluginError(plugin.name, "onClientLog", err);
1071
- }
1072
- }
1073
- },
1074
- async runSetup(ctx) {
1075
- for (const plugin of list) {
1076
- if (!plugin.setup)
1077
- continue;
1078
- try {
1079
- await plugin.setup(ctx);
1080
- } catch (err) {
1081
- logPluginError(plugin.name, "setup", err);
1082
- }
1083
- }
1084
- }
1085
- };
1086
- }
1087
- var emptyRunner = createPluginRunner([]);
1088
- function getEmptyPluginRunner() {
1089
- return emptyRunner;
1090
- }
1163
+ constructor(options) {
1164
+ const opts = typeof options === "string" ? { message: options } : options;
1165
+ super(opts.message, { cause: opts.cause });
1166
+ this.name = "EvlogError";
1167
+ this.code = opts.code;
1168
+ this.status = opts.status ?? 500;
1169
+ this.why = opts.why;
1170
+ this.fix = opts.fix;
1171
+ this.link = opts.link;
1172
+ if (opts.internal !== undefined)
1173
+ Object.defineProperty(this, evlogErrorInternalKey, {
1174
+ value: opts.internal,
1175
+ enumerable: false,
1176
+ writable: false,
1177
+ configurable: true
1178
+ });
1179
+ if (opts.data !== undefined)
1180
+ Object.defineProperty(this, evlogErrorDataKey, {
1181
+ value: opts.data,
1182
+ enumerable: false,
1183
+ writable: false,
1184
+ configurable: true
1185
+ });
1186
+ if (Error.captureStackTrace)
1187
+ Error.captureStackTrace(this, EvlogError);
1188
+ }
1189
+ get statusText() {
1190
+ return this.message;
1191
+ }
1192
+ get statusCode() {
1193
+ return this.status;
1194
+ }
1195
+ get statusMessage() {
1196
+ return this.message;
1197
+ }
1198
+ get data() {
1199
+ const extra = this[evlogErrorDataKey];
1200
+ if (!extra && !this.code && !this.why && !this.fix && !this.link)
1201
+ return;
1202
+ return {
1203
+ ...extra,
1204
+ ...this.code !== undefined && { code: this.code },
1205
+ ...this.why !== undefined && { why: this.why },
1206
+ ...this.fix !== undefined && { fix: this.fix },
1207
+ ...this.link !== undefined && { link: this.link }
1208
+ };
1209
+ }
1210
+ toString() {
1211
+ const useColors = isServer();
1212
+ const red = useColors ? colors.red : "";
1213
+ const yellow = useColors ? colors.yellow : "";
1214
+ const cyan = useColors ? colors.cyan : "";
1215
+ const dim = useColors ? colors.dim : "";
1216
+ const reset = useColors ? colors.reset : "";
1217
+ const bold = useColors ? colors.bold : "";
1218
+ const lines = [];
1219
+ lines.push(`${red}${bold}Error:${reset} ${this.message}`);
1220
+ if (this.code)
1221
+ lines.push(`${dim}Code:${reset} ${this.code}`);
1222
+ if (this.why)
1223
+ lines.push(`${yellow}Why:${reset} ${this.why}`);
1224
+ if (this.fix)
1225
+ lines.push(`${cyan}Fix:${reset} ${this.fix}`);
1226
+ if (this.link)
1227
+ lines.push(`${dim}More info:${reset} ${this.link}`);
1228
+ if (this.cause)
1229
+ lines.push(`${dim}Caused by:${reset} ${this.cause.message}`);
1230
+ return lines.join(`
1231
+ `);
1232
+ }
1233
+ toJSON() {
1234
+ const { data } = this;
1235
+ return {
1236
+ name: this.name,
1237
+ message: this.message,
1238
+ status: this.status,
1239
+ ...data && { data },
1240
+ ...this.cause instanceof Error && { cause: {
1241
+ name: this.cause.name,
1242
+ message: this.cause.message
1243
+ } }
1244
+ };
1245
+ }
1246
+ };
1247
+ Object.defineProperty(EvlogError.prototype, evlogErrorBrand, {
1248
+ value: true,
1249
+ enumerable: false
1250
+ });
1251
+
1252
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/audit-CW8wdQDm.mjs
1091
1253
  var nativeStdoutWrite = typeof process !== "undefined" && typeof process.stdout?.write === "function" ? process.stdout.write.bind(process.stdout) : undefined;
1092
1254
  function writePrettyStdout(text) {
1093
1255
  (globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
@@ -1095,11 +1257,6 @@ function writePrettyStdout(text) {
1095
1257
  function isPlainObject$1(val) {
1096
1258
  return val !== null && typeof val === "object" && !Array.isArray(val);
1097
1259
  }
1098
- var _tsDate = /* @__PURE__ */ new Date;
1099
- function isoNow() {
1100
- _tsDate.setTime(Date.now());
1101
- return _tsDate.toISOString();
1102
- }
1103
1260
  var POST_EMIT_FORK_HINT = "For intentional background work tied to this request, use log.fork('label', fn) when your integration supports it (see https://evlog.dev).";
1104
1261
  function warnPostEmit(method, detail) {
1105
1262
  console.warn(`[evlog] ${method} called after the wide event was emitted \u2014 ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}`);
@@ -1110,12 +1267,14 @@ function mergeInto(target, source) {
1110
1267
  if (sourceVal === undefined || sourceVal === null)
1111
1268
  continue;
1112
1269
  const targetVal = target[key];
1270
+ if (sourceVal === targetVal)
1271
+ continue;
1113
1272
  if (isPlainObject$1(sourceVal) && isPlainObject$1(targetVal))
1114
1273
  mergeInto(targetVal, sourceVal);
1115
1274
  else if (Array.isArray(targetVal) && Array.isArray(sourceVal))
1116
1275
  target[key] = [...targetVal, ...sourceVal];
1117
1276
  else
1118
- target[key] = sourceVal;
1277
+ Reflect.set(target, key, sourceVal);
1119
1278
  }
1120
1279
  }
1121
1280
  var pendingDrainState = /* @__PURE__ */ new WeakMap;
@@ -1123,54 +1282,35 @@ function isAiOnlyFieldUpdate(data) {
1123
1282
  const keys = Object.keys(data);
1124
1283
  return keys.length === 1 && keys[0] === "ai";
1125
1284
  }
1126
- var globalEnv = {
1127
- service: "app",
1128
- environment: "development"
1129
- };
1130
- var globalPretty = isDev();
1131
- var globalPrettyError = {
1132
- snippet: isDev(),
1133
- stackDepth: 2,
1134
- compact: isDev(),
1135
- detail: "full"
1136
- };
1137
- var globalSampling = {};
1138
- var globalStringify = true;
1139
- var globalDrain;
1140
- var globalRedact;
1141
- var globalEnabled = true;
1142
- var globalSilent = false;
1143
- var globalMinLevel = "debug";
1144
- var _loggerInitialized = false;
1145
- var globalPluginRunner = getEmptyPluginRunner();
1285
+ var state = globalConfig;
1146
1286
  function initLogger(config = {}) {
1147
- globalEnabled = config.enabled ?? true;
1287
+ state.enabled = config.enabled ?? true;
1148
1288
  const detected = detectEnvironment();
1149
- globalEnv = {
1289
+ state.env = {
1150
1290
  service: config.env?.service ?? detected.service ?? "app",
1151
1291
  environment: config.env?.environment ?? detected.environment ?? "development",
1152
1292
  version: config.env?.version ?? detected.version,
1153
1293
  commitHash: config.env?.commitHash ?? detected.commitHash,
1154
1294
  region: config.env?.region ?? detected.region
1155
1295
  };
1156
- globalPretty = config.pretty ?? isDev();
1157
- globalPrettyError = resolveDevTerminal(config).prettyError;
1158
- globalSampling = config.sampling ?? {};
1159
- globalStringify = config.stringify ?? true;
1160
- globalDrain = config.drain;
1161
- globalRedact = resolveRedactConfig(config.redact ?? !isDev());
1162
- globalSilent = config.silent ?? false;
1163
- globalMinLevel = config.minLevel ?? "debug";
1164
- globalPluginRunner = config.plugins?.length ? createPluginRunner(config.plugins) : getEmptyPluginRunner();
1165
- if (globalPluginRunner.plugins.length > 0)
1166
- globalPluginRunner.runSetup({ env: { ...globalEnv } });
1167
- const hasAnyDrain = !!globalDrain || globalPluginRunner.hasDrain;
1168
- if (globalSilent && !hasAnyDrain && !config._suppressDrainWarning)
1296
+ state.pretty = config.pretty ?? isDev();
1297
+ state.prettyError = resolveDevTerminal(config).prettyError;
1298
+ state.sampling = config.sampling ?? {};
1299
+ state.stringify = config.stringify ?? true;
1300
+ state.drain = config.drain;
1301
+ state.redact = resolveRedactConfig(config.redact ?? !isDev());
1302
+ state.silent = config.silent ?? false;
1303
+ state.minLevel = config.minLevel ?? "debug";
1304
+ state.pluginRunner = config.plugins?.length ? createPluginRunner(config.plugins) : getEmptyPluginRunner();
1305
+ if (state.pluginRunner.plugins.length > 0)
1306
+ state.pluginRunner.runSetup({ env: { ...state.env } });
1307
+ const hasAnyDrain = !!state.drain || state.pluginRunner.hasDrain;
1308
+ if (state.silent && !hasAnyDrain && !config._suppressDrainWarning)
1169
1309
  console.warn("[evlog] silent mode is enabled but no drain is configured. Events will be built and sampled but not output anywhere. Set a drain via initLogger({ drain }) or a framework hook (evlog:drain).");
1170
- _loggerInitialized = true;
1310
+ state.initialized = true;
1171
1311
  }
1172
1312
  function shouldSample(level) {
1173
- const { rates } = globalSampling;
1313
+ const { rates } = state.sampling;
1174
1314
  if (!rates)
1175
1315
  return true;
1176
1316
  const percentage = level === "error" && rates.error === undefined ? 100 : rates[level] ?? 100;
@@ -1181,7 +1321,7 @@ function shouldSample(level) {
1181
1321
  return Math.random() * 100 < percentage;
1182
1322
  }
1183
1323
  function shouldKeep(ctx) {
1184
- const { keep } = globalSampling;
1324
+ const { keep } = state.sampling;
1185
1325
  if (!keep?.length)
1186
1326
  return false;
1187
1327
  return keep.some((condition) => {
@@ -1196,10 +1336,10 @@ function shouldKeep(ctx) {
1196
1336
  }
1197
1337
  function emitWideEvent(level, event, options = {}) {
1198
1338
  const { deferDrain = false, ownsEvent = false, waitUntil } = options;
1199
- if (!globalEnabled)
1339
+ if (!state.enabled)
1200
1340
  return null;
1201
1341
  if (!ownsEvent) {
1202
- if (!isLevelEnabled(level, globalMinLevel))
1342
+ if (!isLevelEnabled(level, state.minLevel))
1203
1343
  return null;
1204
1344
  if (!shouldSample(level))
1205
1345
  return null;
@@ -1209,57 +1349,58 @@ function emitWideEvent(level, event, options = {}) {
1209
1349
  event.timestamp = isoNow();
1210
1350
  event.level = level;
1211
1351
  if (event.service === undefined)
1212
- event.service = globalEnv.service;
1352
+ event.service = state.env.service;
1213
1353
  if (event.environment === undefined)
1214
- event.environment = globalEnv.environment;
1215
- if (globalEnv.version !== undefined && event.version === undefined)
1216
- event.version = globalEnv.version;
1217
- if (globalEnv.commitHash !== undefined && event.commitHash === undefined)
1218
- event.commitHash = globalEnv.commitHash;
1219
- if (globalEnv.region !== undefined && event.region === undefined)
1220
- event.region = globalEnv.region;
1354
+ event.environment = state.env.environment;
1355
+ if (state.env.version !== undefined && event.version === undefined)
1356
+ event.version = state.env.version;
1357
+ if (state.env.commitHash !== undefined && event.commitHash === undefined)
1358
+ event.commitHash = state.env.commitHash;
1359
+ if (state.env.region !== undefined && event.region === undefined)
1360
+ event.region = state.env.region;
1221
1361
  formatted = event;
1222
1362
  } else
1223
1363
  formatted = {
1224
1364
  timestamp: isoNow(),
1225
1365
  level,
1226
- ...globalEnv,
1366
+ ...state.env,
1227
1367
  ...event
1228
1368
  };
1229
1369
  finalizeAudit(formatted);
1230
- if (globalRedact) {
1231
- formatted = redactEvent(formatted, globalRedact);
1370
+ if (state.redact) {
1371
+ formatted = redactEvent(formatted, state.redact);
1232
1372
  markGloballyRedacted(formatted);
1233
1373
  }
1234
- if (!globalSilent)
1235
- if (globalPretty)
1374
+ if (!state.silent)
1375
+ if (state.pretty)
1236
1376
  prettyPrintWideEvent(formatted);
1237
- else if (globalStringify)
1377
+ else if (state.stringify)
1238
1378
  console[getConsoleMethod(level)](JSON.stringify(formatted));
1239
1379
  else
1240
1380
  console[getConsoleMethod(level)](formatted);
1241
1381
  if (!deferDrain) {
1382
+ publishWideEvent(formatted);
1242
1383
  const drainPromises = [];
1243
- if (globalDrain)
1384
+ if (state.drain)
1244
1385
  drainPromises.push((async () => {
1245
1386
  try {
1246
- await globalDrain({ event: formatted });
1387
+ await state.drain({ event: formatted });
1247
1388
  } catch (err) {
1248
1389
  console.error("[evlog] drain failed:", err);
1249
1390
  }
1250
1391
  })());
1251
- if (globalPluginRunner.hasDrain)
1252
- drainPromises.push(globalPluginRunner.runDrain({ event: formatted }));
1392
+ if (state.pluginRunner.hasDrain)
1393
+ drainPromises.push(state.pluginRunner.runDrain({ event: formatted }));
1253
1394
  if (drainPromises.length > 0 && waitUntil)
1254
1395
  waitUntil(Promise.all(drainPromises));
1255
1396
  }
1256
1397
  return formatted;
1257
1398
  }
1258
1399
  function emitTaggedLog(level, tag, message) {
1259
- if (!globalEnabled)
1400
+ if (!state.enabled)
1260
1401
  return;
1261
- if (globalPretty && !globalSilent) {
1262
- if (!isLevelEnabled(level, globalMinLevel))
1402
+ if (state.pretty && !state.silent) {
1403
+ if (!isLevelEnabled(level, state.minLevel))
1263
1404
  return;
1264
1405
  if (!shouldSample(level))
1265
1406
  return;
@@ -1574,6 +1715,7 @@ function prettyPrintWideEvent(event) {
1574
1715
  parts.push(` ${colors.dim}in ${rest.duration}${colors.reset}`);
1575
1716
  delete rest.duration;
1576
1717
  }
1718
+ delete rest.durationMs;
1577
1719
  writeLine(parts.join(""), ...styles);
1578
1720
  const aiData = isPlainObject$1(rest.ai) ? rest.ai : undefined;
1579
1721
  if (aiData)
@@ -1583,7 +1725,7 @@ function prettyPrintWideEvent(event) {
1583
1725
  delete rest.error;
1584
1726
  const restEntries = Object.entries(rest).filter(([_, v]) => v !== undefined);
1585
1727
  const aiEntries = aiData ? buildAIEntries(aiData) : [];
1586
- const errorEntries = errorData !== undefined ? buildErrorEntries(errorData, globalPrettyError) : [];
1728
+ const errorEntries = errorData !== undefined ? buildErrorEntries(errorData, state.prettyError) : [];
1587
1729
  const contextEntries = [...restEntries.map(([key, value]) => ({
1588
1730
  key,
1589
1731
  value: formatValue(value)
@@ -1661,7 +1803,7 @@ var noopLogger = {
1661
1803
  audit: Object.assign(() => {}, { deny: () => {} })
1662
1804
  };
1663
1805
  function createLogger(initialContext = {}, internalOptions) {
1664
- if (!globalEnabled)
1806
+ if (!state.enabled)
1665
1807
  return noopLogger;
1666
1808
  const deferDrain = internalOptions?._deferDrain ?? false;
1667
1809
  const waitUntil = internalOptions?.waitUntil;
@@ -1750,7 +1892,7 @@ function createLogger(initialContext = {}, internalOptions) {
1750
1892
  ])
1751
1893
  if (k in err)
1752
1894
  errorObj[k] = errRecord[k];
1753
- if (err instanceof EvlogError) {
1895
+ if (EvlogError.isEvlogError(err)) {
1754
1896
  if (err.code)
1755
1897
  errorObj.code = err.code;
1756
1898
  if (err.why)
@@ -1795,7 +1937,7 @@ function createLogger(initialContext = {}, internalOptions) {
1795
1937
  warnPostEmit("log.emit()", "Ignoring duplicate emit.");
1796
1938
  return null;
1797
1939
  }
1798
- const durationMs = Date.now() - startTime;
1940
+ const durationMs = elapsedMs(startTime);
1799
1941
  const level = manualLevel ?? (hasError ? "error" : hasWarn ? "warn" : "info");
1800
1942
  let forceKeep = false;
1801
1943
  const auditForceKeep = consumeAuditForceKeep(context);
@@ -1803,7 +1945,7 @@ function createLogger(initialContext = {}, internalOptions) {
1803
1945
  forceKeep = true;
1804
1946
  else if (auditForceKeep)
1805
1947
  forceKeep = true;
1806
- else if (globalSampling.keep?.length)
1948
+ else if (state.sampling.keep?.length)
1807
1949
  forceKeep = shouldKeep({
1808
1950
  status: overrides?.status ?? context.status,
1809
1951
  duration: durationMs,
@@ -1822,6 +1964,7 @@ function createLogger(initialContext = {}, internalOptions) {
1822
1964
  if (key !== "_forceKeep")
1823
1965
  context[key] = obj[key];
1824
1966
  }
1967
+ context.durationMs = durationMs;
1825
1968
  context.duration = formatDuration(durationMs);
1826
1969
  const wide = emitWideEvent(level, context, {
1827
1970
  deferDrain,
@@ -2415,7 +2558,13 @@ function unreplayable() {
2415
2558
  };
2416
2559
  }
2417
2560
  function mergeStoredResponseHeaders(storedResponse, headers) {
2418
- const merged = new Headers(storedResponse.headers.filter(([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase())).map(([name, value]) => [name, value]));
2561
+ const headerEntries = [];
2562
+ for (const [name, value] of storedResponse.headers) {
2563
+ if (!NON_REPLAYABLE_HEADERS.has(name.toLowerCase())) {
2564
+ headerEntries.push([name, value]);
2565
+ }
2566
+ }
2567
+ const merged = new Headers(headerEntries);
2419
2568
  for (const [name, value] of Object.entries(headers)) {
2420
2569
  if (value !== undefined && !NON_REPLAYABLE_HEADERS.has(name.toLowerCase())) {
2421
2570
  merged.delete(name);
@@ -2432,12 +2581,12 @@ function mergeStoredResponseHeaders(storedResponse, headers) {
2432
2581
  async function storeResponse(responseValue, set) {
2433
2582
  if (responseValue instanceof Response) {
2434
2583
  const clone = responseValue.clone();
2435
- const body2 = await readBoundedResponseBody(clone);
2436
- if (body2 === undefined) {
2584
+ const body = await readBoundedResponseBody(clone);
2585
+ if (body === undefined) {
2437
2586
  return unreplayable();
2438
2587
  }
2439
- const headers2 = new Headers([...clone.headers.entries()].filter(([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase())));
2440
- return storedResponseResult(headers2, body2, clone.status);
2588
+ const headers = new Headers([...clone.headers.entries()].filter(([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase())));
2589
+ return storedResponseResult(headers, body, clone.status);
2441
2590
  }
2442
2591
  const headers = responseHeaders(set.headers);
2443
2592
  const statusResponse = unwrapStatusResponse(responseValue);
@@ -2457,8 +2606,14 @@ async function storeResponse(responseValue, set) {
2457
2606
  }
2458
2607
  function replayResponse(stored) {
2459
2608
  const body = stored.status === 204 || stored.status === 205 || stored.status === 304 ? null : stored.body.slice();
2609
+ const headerEntries = [];
2610
+ for (const [name, value] of stored.headers) {
2611
+ if (!NON_REPLAYABLE_HEADERS.has(name.toLowerCase())) {
2612
+ headerEntries.push([name, value]);
2613
+ }
2614
+ }
2460
2615
  return new Response(body, {
2461
- headers: new Headers(stored.headers.filter(([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase())).map(([name, value]) => [name, value])),
2616
+ headers: new Headers(headerEntries),
2462
2617
  status: stored.status
2463
2618
  });
2464
2619
  }