@teyik0/furin 0.4.0-alpha.1 → 0.5.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 (233) hide show
  1. package/dist/adapter/bun.d.ts +2 -18
  2. package/dist/adapter/package.d.ts +2 -2
  3. package/dist/adapter/runtime-build.d.ts +33 -0
  4. package/dist/adapter/vercel.d.ts +3 -0
  5. package/dist/build/client.d.ts +1 -1
  6. package/dist/build/compile-entry.d.ts +6 -4
  7. package/dist/build/compile-entry.ts +36 -77
  8. package/dist/build/elysia-aot.d.ts +9 -0
  9. package/dist/build/entry-template.d.ts +9 -3
  10. package/dist/build/entry-template.ts +55 -13
  11. package/dist/build/index.d.ts +1 -1
  12. package/dist/build/index.js +8912 -6391
  13. package/dist/build/server-app-entry.d.ts +12 -0
  14. package/dist/build/ssg-cache.d.ts +13 -0
  15. package/dist/build/types.d.ts +25 -2
  16. package/dist/build/virtual-entry.d.ts +8 -0
  17. package/dist/cache.d.ts +6 -0
  18. package/dist/cache.js +282 -0
  19. package/dist/cli/index.js +8936 -6308
  20. package/dist/cli/preview.d.ts +7 -0
  21. package/dist/client/boundaries.d.ts +1 -0
  22. package/dist/client/browser-events-runtime.d.ts +2 -0
  23. package/dist/client/browser-events.d.ts +2 -0
  24. package/dist/client/define-route.d.ts +9 -8
  25. package/dist/client/dev-error-overlay.d.ts +1 -0
  26. package/dist/client/dev-error-overlay.ts +201 -0
  27. package/dist/client/document.d.ts +1 -0
  28. package/dist/client/hmr.d.ts +4 -2
  29. package/dist/client/internal/runtime-types.d.ts +8 -1
  30. package/dist/client/link.js +465 -86
  31. package/dist/client/router/provider.d.ts +1 -1
  32. package/dist/client/router/sync-catch-up.d.ts +1 -1
  33. package/dist/client/router/types.d.ts +8 -10
  34. package/dist/client/sync.d.ts +1 -0
  35. package/dist/client.js +37 -23
  36. package/dist/config.d.ts +35 -17
  37. package/dist/config.js +10 -2
  38. package/dist/define-route.d.ts +282 -1015
  39. package/dist/devtools/protocol.d.ts +2 -2
  40. package/dist/furin.d.ts +21 -6
  41. package/dist/furin.js +12823 -8484
  42. package/dist/plugin/index.js +476 -7
  43. package/dist/plugin/routes.d.ts +10 -3
  44. package/dist/rsc/build/index.d.ts +5 -1
  45. package/dist/server/assets/production.d.ts +3 -0
  46. package/dist/server/auto-invalidate/plugin.d.ts +8 -24
  47. package/dist/server/auto-invalidate/runtime.d.ts +2 -2
  48. package/dist/server/browser-events/plugin.d.ts +11 -0
  49. package/dist/server/browser-events/types.d.ts +9 -0
  50. package/dist/server/cache/invalidation.d.ts +2 -3
  51. package/dist/server/cache/isr.d.ts +1 -0
  52. package/dist/server/cache/page-cache-state.d.ts +5 -0
  53. package/dist/server/cache/page-cache.d.ts +53 -0
  54. package/dist/server/cache/purger.d.ts +7 -0
  55. package/dist/server/cache/redis/index.d.ts +39 -0
  56. package/dist/server/cache/redis/index.js +396 -0
  57. package/dist/server/cache/redis/scripts.d.ts +6 -0
  58. package/dist/server/cache/runtime-cache.d.ts +21 -0
  59. package/dist/server/context-logger.d.ts +2 -2
  60. package/dist/server/dev/browser-events.d.ts +4 -0
  61. package/dist/server/dev/diagnostics.d.ts +39 -0
  62. package/dist/server/dev/error.d.ts +17 -0
  63. package/dist/server/dev/graph.d.ts +86 -0
  64. package/dist/server/dev/plugin.d.ts +9 -0
  65. package/dist/server/dev/request-security.d.ts +1 -0
  66. package/dist/server/dev/rewrite-module-specifiers.d.ts +7 -0
  67. package/dist/server/dev/runtime.production.d.ts +6 -0
  68. package/dist/server/dev/symbolicate.d.ts +11 -0
  69. package/dist/server/dev/transform-failure.d.ts +4 -0
  70. package/dist/server/dev-page-plugin.d.ts +7 -0
  71. package/dist/server/dev-page-plugin.production.d.ts +1 -0
  72. package/dist/server/devtools/hub.d.ts +3 -2
  73. package/dist/server/devtools/instrumentation.d.ts +1 -1
  74. package/dist/server/devtools/instrumentation.production.d.ts +1 -1
  75. package/dist/server/devtools/plugin.d.ts +1 -1
  76. package/dist/server/evlog.d.ts +14 -0
  77. package/dist/server/external-prerender.d.ts +2 -0
  78. package/dist/server/instance.d.ts +2 -2
  79. package/dist/server/internal.d.ts +20 -2
  80. package/dist/server/internal.js +2973 -1
  81. package/dist/server/render/element.d.ts +1 -0
  82. package/dist/server/render/index.d.ts +1 -1
  83. package/dist/server/render/index.ts +1 -1
  84. package/dist/server/render/not-found.d.ts +1 -1
  85. package/dist/server/render/ppr-document.d.ts +21 -0
  86. package/dist/server/render/ppr-request.d.ts +26 -0
  87. package/dist/server/render/ppr-route.d.ts +3 -1
  88. package/dist/server/render/shell.ts +0 -12
  89. package/dist/server/render/ssg.d.ts +7 -0
  90. package/dist/server/render/ssr.d.ts +17 -6
  91. package/dist/server/render/static-params.d.ts +4 -0
  92. package/dist/server/router/defined-route.d.ts +1 -1
  93. package/dist/server/router/hmr.production.d.ts +2 -0
  94. package/dist/server/router/patterns.d.ts +1 -0
  95. package/dist/server/router/plugin.d.ts +3 -1
  96. package/dist/server/router/schemas.d.ts +1 -0
  97. package/dist/server/sync/adapter.d.ts +13 -0
  98. package/dist/server/sync/config.d.ts +5 -5
  99. package/dist/server/sync/index.d.ts +6 -6
  100. package/dist/server/sync/index.js +1252 -599
  101. package/dist/server/sync/notifier.d.ts +1 -0
  102. package/dist/server/sync/plugin.d.ts +31 -158
  103. package/dist/server/sync/postgres/index.d.ts +12 -1
  104. package/dist/server/sync/postgres/index.js +101 -6
  105. package/dist/server/sync/stream.d.ts +37 -61
  106. package/dist/shared/await.d.ts +3 -3
  107. package/dist/shared/browser-events.d.ts +22 -0
  108. package/dist/shared/compact-json.d.ts +8 -0
  109. package/dist/shared/deferred-ndjson.d.ts +6 -5
  110. package/dist/shared/dev-diagnostics.d.ts +36 -0
  111. package/dist/shared/elysia-contract.d.ts +8 -14
  112. package/dist/shared/prefix.d.ts +2 -0
  113. package/package.json +26 -11
  114. package/src/adapter/README.md +53 -1
  115. package/src/adapter/bun.ts +106 -283
  116. package/src/adapter/package.ts +21 -11
  117. package/src/adapter/runtime-build.ts +382 -0
  118. package/src/adapter/static.ts +87 -8
  119. package/src/adapter/vercel.ts +876 -0
  120. package/src/build/client.ts +55 -13
  121. package/src/build/compile-entry.ts +36 -77
  122. package/src/build/elysia-aot.ts +102 -0
  123. package/src/build/entry-template.ts +55 -13
  124. package/src/build/hydrate.ts +60 -20
  125. package/src/build/index.ts +17 -8
  126. package/src/build/production-instrumentation.ts +56 -4
  127. package/src/build/server-app-entry.ts +60 -0
  128. package/src/build/shared.ts +5 -2
  129. package/src/build/ssg-cache.ts +93 -12
  130. package/src/build/types.ts +31 -2
  131. package/src/build/virtual-entry.ts +28 -0
  132. package/src/cache.ts +26 -0
  133. package/src/cli/config.ts +3 -3
  134. package/src/cli/index.ts +58 -3
  135. package/src/cli/preview.ts +90 -0
  136. package/src/client/boundaries.tsx +10 -1
  137. package/src/client/browser-events-runtime.ts +204 -0
  138. package/src/client/browser-events.ts +22 -0
  139. package/src/client/define-route.ts +7 -17
  140. package/src/client/dev-error-overlay.ts +201 -0
  141. package/src/client/document.tsx +4 -7
  142. package/src/client/hmr.ts +26 -3
  143. package/src/client/internal/runtime-types.ts +10 -1
  144. package/src/client/router/boundary-tree.tsx +4 -4
  145. package/src/client/router/provider.tsx +165 -63
  146. package/src/client/router/sync-catch-up.ts +3 -4
  147. package/src/client/router/types.ts +6 -6
  148. package/src/client/sync.ts +1 -0
  149. package/src/config.ts +28 -2
  150. package/src/define-route.ts +285 -134
  151. package/src/devtools/devtools-element.js +56 -77
  152. package/src/devtools/protocol.ts +2 -2
  153. package/src/furin.ts +272 -203
  154. package/src/plugin/route-config-autofix.ts +11 -2
  155. package/src/plugin/routes.ts +291 -65
  156. package/src/plugin/transform-client.ts +685 -3
  157. package/src/react-dom-edge.d.ts +6 -0
  158. package/src/rsc/build/index.ts +15 -3
  159. package/src/server/assets/production.ts +99 -0
  160. package/src/server/auto-invalidate/plugin.ts +4 -4
  161. package/src/server/auto-invalidate/runtime.ts +76 -41
  162. package/src/server/browser-events/plugin.ts +173 -0
  163. package/src/server/browser-events/types.ts +11 -0
  164. package/src/server/cache/dev-loader.ts +30 -29
  165. package/src/server/cache/invalidation.ts +67 -35
  166. package/src/server/cache/isr.ts +9 -0
  167. package/src/server/cache/page-cache-state.ts +22 -0
  168. package/src/server/cache/page-cache.ts +300 -0
  169. package/src/server/cache/purger.ts +41 -0
  170. package/src/server/cache/redis/index.ts +350 -0
  171. package/src/server/cache/redis/scripts.ts +160 -0
  172. package/src/server/cache/runtime-cache.ts +137 -0
  173. package/src/server/context-logger.ts +5 -5
  174. package/src/server/dev/browser-events.ts +54 -0
  175. package/src/server/dev/diagnostics.ts +297 -0
  176. package/src/server/dev/error.ts +148 -0
  177. package/src/server/dev/graph.ts +438 -0
  178. package/src/server/dev/plugin.ts +130 -0
  179. package/src/server/dev/request-security.ts +38 -0
  180. package/src/server/dev/rewrite-module-specifiers.ts +81 -0
  181. package/src/server/dev/runtime.production.ts +28 -0
  182. package/src/server/dev/symbolicate.ts +135 -0
  183. package/src/server/dev/transform-failure.ts +8 -0
  184. package/src/server/dev-page-plugin.production.ts +3 -0
  185. package/src/server/dev-page-plugin.ts +136 -53
  186. package/src/server/devtools/hub.ts +6 -5
  187. package/src/server/devtools/instrumentation.production.ts +1 -1
  188. package/src/server/devtools/instrumentation.ts +12 -6
  189. package/src/server/devtools/plugin.ts +7 -150
  190. package/src/server/evlog.ts +99 -0
  191. package/src/server/external-prerender.ts +10 -0
  192. package/src/server/instance.ts +3 -3
  193. package/src/server/internal.ts +46 -2
  194. package/src/server/render/assemble.ts +4 -4
  195. package/src/server/render/document.tsx +13 -4
  196. package/src/server/render/element.tsx +18 -14
  197. package/src/server/render/index.ts +1 -1
  198. package/src/server/render/isr.ts +509 -136
  199. package/src/server/render/loaders.ts +31 -15
  200. package/src/server/render/not-found.ts +32 -8
  201. package/src/server/render/ppr-document.ts +239 -0
  202. package/src/server/render/ppr-request.ts +104 -0
  203. package/src/server/render/ppr-route.ts +335 -28
  204. package/src/server/render/shell.ts +0 -12
  205. package/src/server/render/ssg.ts +186 -24
  206. package/src/server/render/ssr.ts +215 -89
  207. package/src/server/render/static-params.ts +174 -0
  208. package/src/server/render/template.ts +47 -11
  209. package/src/server/router/defined-route.ts +9 -40
  210. package/src/server/router/hmr.production.ts +7 -0
  211. package/src/server/router/hmr.ts +108 -67
  212. package/src/server/router/patterns.ts +5 -1
  213. package/src/server/router/plugin.ts +164 -66
  214. package/src/server/router/schema-merge.ts +1 -1
  215. package/src/server/router/schemas.ts +174 -61
  216. package/src/server/router/source-version.ts +3 -10
  217. package/src/server/sync/adapter.ts +13 -0
  218. package/src/server/sync/config.ts +12 -12
  219. package/src/server/sync/index.ts +8 -8
  220. package/src/server/sync/notifier.ts +1 -0
  221. package/src/server/sync/plugin.ts +18 -11
  222. package/src/server/sync/postgres/index.ts +111 -5
  223. package/src/server/sync/response.ts +3 -3
  224. package/src/server/sync/runtime.ts +12 -0
  225. package/src/server/sync/stream.ts +78 -113
  226. package/src/shared/await.tsx +3 -3
  227. package/src/shared/browser-events.ts +28 -0
  228. package/src/shared/compact-json.ts +77 -0
  229. package/src/shared/deferred-ndjson.ts +20 -6
  230. package/src/shared/dev-diagnostics.ts +44 -0
  231. package/src/shared/elysia-contract.ts +23 -25
  232. package/src/shared/prefix.ts +8 -0
  233. package/src/shared/route-map.ts +10 -1
@@ -1,12 +1,18 @@
1
1
  // @bun
2
- // src/server/sync/config.ts
3
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
2
+ var __esm = (fn, res, err) => () => {
3
+ if (fn)
4
+ try {
5
+ res = fn(fn = 0);
6
+ } catch (e) {
7
+ err = [e];
8
+ }
9
+ if (err)
10
+ throw err[0];
11
+ return res;
12
+ };
4
13
 
5
14
  // src/server/instance.ts
6
15
  import { AsyncLocalStorage } from "async_hooks";
7
- var _requestScope = new AsyncLocalStorage;
8
- var _instances = new Map;
9
- var _defaultInstance = null;
10
16
  function createInstance(prefix, pagesDir) {
11
17
  return {
12
18
  buildId: "",
@@ -14,7 +20,7 @@ function createInstance(prefix, pagesDir) {
14
20
  prefix,
15
21
  registrationEpoch: 0,
16
22
  state: new Map,
17
- syncStreamPath: undefined
23
+ syncPath: undefined
18
24
  };
19
25
  }
20
26
  function defaultInstance() {
@@ -63,32 +69,42 @@ function instanceSlot(init) {
63
69
  return value;
64
70
  };
65
71
  }
72
+ var _requestScope, _instances, _defaultInstance = null;
73
+ var init_instance = __esm(() => {
74
+ _requestScope = new AsyncLocalStorage;
75
+ _instances = new Map;
76
+ });
66
77
 
67
78
  // src/server/sync/config.ts
68
- var SYNC_STREAM_DEFAULT_PATH = "/_furin/sync";
69
- var requestSyncStreamPath = new AsyncLocalStorage2;
70
- function resolveSyncStreamPath(sync) {
79
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
80
+ function resolveSyncPath(sync) {
71
81
  if (!sync) {
72
82
  return;
73
83
  }
74
- return sync.streamPath ?? SYNC_STREAM_DEFAULT_PATH;
84
+ return sync.path ?? SYNC_DEFAULT_PATH;
75
85
  }
76
- function getSyncStreamPath() {
77
- const override = requestSyncStreamPath.getStore();
86
+ function getSyncPath() {
87
+ const override = requestSyncPath.getStore();
78
88
  if (override !== undefined) {
79
89
  return override;
80
90
  }
81
- return currentInstance().syncStreamPath;
91
+ return currentInstance().syncPath;
82
92
  }
83
- function runWithSyncStreamPath(path, fn) {
84
- return requestSyncStreamPath.run(path, fn);
93
+ function runWithSyncPath(path, fn) {
94
+ return requestSyncPath.run(path, fn);
85
95
  }
86
96
  function syncRuntimeOptions(sync) {
87
97
  return { adapter: sync.adapter, notifier: sync.notifier, principal: sync.principal };
88
98
  }
99
+ var SYNC_DEFAULT_PATH = "/_furin/sync", requestSyncPath;
100
+ var init_config = __esm(() => {
101
+ init_instance();
102
+ requestSyncPath = new AsyncLocalStorage2;
103
+ });
89
104
 
90
105
  // src/server/sync/notifier.ts
91
106
  class PollingSyncNotifier {
107
+ recovery = "self";
92
108
  adapter;
93
109
  intervalMs;
94
110
  listeners = new Set;
@@ -178,12 +194,7 @@ class PollingSyncNotifier {
178
194
  }
179
195
  }
180
196
 
181
- // src/server/sync/plugin.ts
182
- import { Elysia } from "elysia";
183
-
184
- // src/server/context-logger.ts
185
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
186
- // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/utils.mjs
197
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/utils.mjs
187
198
  function elapsedMs(startTime) {
188
199
  return Math.max(0, Date.now() - startTime);
189
200
  }
@@ -222,71 +233,28 @@ function detectEnvironment() {
222
233
  region: env.VERCEL_REGION || env.AWS_REGION || env.FLY_REGION || env.CF_REGION
223
234
  };
224
235
  }
225
- var LEVEL_ORDER = {
226
- debug: 0,
227
- info: 1,
228
- warn: 2,
229
- error: 3
230
- };
231
236
  function isLevelEnabled(level, minLevel) {
232
237
  return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];
233
238
  }
234
239
  function getConsoleMethod(level) {
235
240
  return level;
236
241
  }
237
- var colors = {
238
- reset: "\x1B[0m",
239
- bold: "\x1B[1m",
240
- dim: "\x1B[2m",
241
- red: "\x1B[31m",
242
- green: "\x1B[32m",
243
- yellow: "\x1B[33m",
244
- blue: "\x1B[34m",
245
- magenta: "\x1B[35m",
246
- cyan: "\x1B[36m",
247
- white: "\x1B[37m",
248
- gray: "\x1B[90m"
249
- };
250
- var levelColorMap = {
251
- error: colors.red,
252
- warn: colors.yellow,
253
- info: colors.cyan,
254
- debug: colors.gray
255
- };
256
242
  function getLevelColor(level) {
257
243
  return levelColorMap[level] ?? colors.white;
258
244
  }
259
- var cssColors = {
260
- dim: "color: #6b7280",
261
- red: "color: #ef4444; font-weight: bold",
262
- green: "color: #22c55e",
263
- yellow: "color: #f59e0b; font-weight: bold",
264
- cyan: "color: #06b6d4; font-weight: bold",
265
- gray: "color: #6b7280; font-weight: bold",
266
- reset: "color: inherit; font-weight: normal"
267
- };
268
- var cssLevelColorMap = {
269
- error: cssColors.red,
270
- warn: cssColors.yellow,
271
- info: cssColors.cyan,
272
- debug: cssColors.gray
273
- };
274
245
  function getCssLevelColor(level) {
275
246
  return cssLevelColorMap[level] ?? cssColors.reset;
276
247
  }
277
248
  function escapeFormatString(str) {
278
249
  return str.replace(/%/g, "%%");
279
250
  }
280
- var SENSITIVE_HEADERS = [
281
- "authorization",
282
- "cookie",
283
- "set-cookie",
284
- "x-api-key",
285
- "x-auth-token",
286
- "proxy-authorization"
287
- ];
288
- var SENSITIVE_HEADER_SET = new Set(SENSITIVE_HEADERS);
289
- var patternCache = /* @__PURE__ */ new Map;
251
+ function filterSafeHeaders(headers) {
252
+ const safeHeaders = {};
253
+ for (const [key, value] of Object.entries(headers))
254
+ if (value !== undefined && !SENSITIVE_HEADER_SET.has(key.toLowerCase()))
255
+ safeHeaders[key] = value;
256
+ return safeHeaders;
257
+ }
290
258
  function globToRegExp(pattern, separator = "/") {
291
259
  const cacheKey = `${separator}:${pattern}`;
292
260
  let regex = patternCache.get(cacheKey);
@@ -302,9 +270,6 @@ function globToRegExp(pattern, separator = "/") {
302
270
  function matchesPattern(path, pattern) {
303
271
  return globToRegExp(pattern, "/").test(path);
304
272
  }
305
- var _isoDate = /* @__PURE__ */ new Date;
306
- var _isoCachedSecond = -1;
307
- var _isoCachedPrefix = "";
308
273
  function isoNow() {
309
274
  const now = Date.now();
310
275
  const sec = Math.floor(now / 1000);
@@ -315,9 +280,62 @@ function isoNow() {
315
280
  }
316
281
  return `${_isoCachedPrefix}.${String(now % 1000).padStart(3, "0")}Z`;
317
282
  }
283
+ var LEVEL_ORDER, colors, levelColorMap, cssColors, cssLevelColorMap, SENSITIVE_HEADERS, SENSITIVE_HEADER_SET, patternCache, _isoDate, _isoCachedSecond = -1, _isoCachedPrefix = "";
284
+ var init_utils = __esm(() => {
285
+ LEVEL_ORDER = {
286
+ debug: 0,
287
+ info: 1,
288
+ warn: 2,
289
+ error: 3
290
+ };
291
+ colors = {
292
+ reset: "\x1B[0m",
293
+ bold: "\x1B[1m",
294
+ dim: "\x1B[2m",
295
+ red: "\x1B[31m",
296
+ green: "\x1B[32m",
297
+ yellow: "\x1B[33m",
298
+ blue: "\x1B[34m",
299
+ magenta: "\x1B[35m",
300
+ cyan: "\x1B[36m",
301
+ white: "\x1B[37m",
302
+ gray: "\x1B[90m"
303
+ };
304
+ levelColorMap = {
305
+ error: colors.red,
306
+ warn: colors.yellow,
307
+ info: colors.cyan,
308
+ debug: colors.gray
309
+ };
310
+ cssColors = {
311
+ dim: "color: #6b7280",
312
+ red: "color: #ef4444; font-weight: bold",
313
+ green: "color: #22c55e",
314
+ yellow: "color: #f59e0b; font-weight: bold",
315
+ cyan: "color: #06b6d4; font-weight: bold",
316
+ gray: "color: #6b7280; font-weight: bold",
317
+ reset: "color: inherit; font-weight: normal"
318
+ };
319
+ cssLevelColorMap = {
320
+ error: cssColors.red,
321
+ warn: cssColors.yellow,
322
+ info: cssColors.cyan,
323
+ debug: cssColors.gray
324
+ };
325
+ SENSITIVE_HEADERS = [
326
+ "authorization",
327
+ "cookie",
328
+ "set-cookie",
329
+ "x-api-key",
330
+ "x-auth-token",
331
+ "proxy-authorization"
332
+ ];
333
+ SENSITIVE_HEADER_SET = new Set(SENSITIVE_HEADERS);
334
+ patternCache = /* @__PURE__ */ new Map;
335
+ _isoDate = /* @__PURE__ */ new Date;
336
+ });
318
337
 
319
- // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/redact-C7FmdhwI.mjs
320
- var DEFAULT_REPLACEMENT = "[REDACTED]";
338
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/redact-C7FmdhwI.mjs
321
339
  function normalizeRedactPathPattern(pattern) {
322
340
  if (!pattern.includes("*") && !pattern.includes("."))
323
341
  return `**.${pattern}`;
@@ -433,53 +451,6 @@ function setRedacted(record, key, value, path) {
433
451
  }
434
452
  console.warn(`[evlog] redact could not rewrite read-only field "${path}" \u2014 value left as-is`);
435
453
  }
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
454
  function resolveRedactConfig(input) {
484
455
  if (input === undefined || input === false)
485
456
  return;
@@ -503,7 +474,6 @@ function allBuiltinMaskers() {
503
474
  function cloneRegex(re) {
504
475
  return new RegExp(re.source, re.flags);
505
476
  }
506
- var globallyRedacted = Symbol.for("evlog.globallyRedacted");
507
477
  function markGloballyRedacted(event) {
508
478
  Object.defineProperty(event, globallyRedacted, {
509
479
  value: true,
@@ -511,6 +481,9 @@ function markGloballyRedacted(event) {
511
481
  configurable: true
512
482
  });
513
483
  }
484
+ function isGloballyRedacted(event) {
485
+ return Reflect.has(event, globallyRedacted);
486
+ }
514
487
  function cloneForRedaction(event) {
515
488
  try {
516
489
  return structuredClone(event);
@@ -618,8 +591,60 @@ function applyMaskers(value, maskers) {
618
591
  result = result.replace(pattern, mask);
619
592
  return result;
620
593
  }
594
+ var DEFAULT_REPLACEMENT = "[REDACTED]", builtinPatterns, globallyRedacted;
595
+ var init_redact_C7FmdhwI = __esm(() => {
596
+ init_utils();
597
+ builtinPatterns = {
598
+ creditCard: {
599
+ pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
600
+ mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
601
+ },
602
+ email: {
603
+ pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g,
604
+ mask: (m) => {
605
+ if (m.indexOf("@") < 1)
606
+ return "***@***";
607
+ const tld = m.slice(m.lastIndexOf("."));
608
+ return `${m[0]}***@***${tld}`;
609
+ }
610
+ },
611
+ ipv4: {
612
+ 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,
613
+ mask: (m) => `***.***.***.${m.split(".").pop()}`
614
+ },
615
+ phone: {
616
+ pattern: /(?:\+\d{1,3}[\s.-]?\(?\d{1,4}\)?|\(\d{1,4}\))(?:[\s.-]?\d{2,4}){2,4}\b/g,
617
+ mask: (m) => {
618
+ const digits = m.replace(/[^\d]/g, "");
619
+ if (m.startsWith("+") && digits.length > 4) {
620
+ const ccMatch = m.match(/^\+\d{1,3}/);
621
+ return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
622
+ }
623
+ if (digits.length > 2)
624
+ return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
625
+ return "***";
626
+ }
627
+ },
628
+ jwt: {
629
+ pattern: /\beyJ[\w-]*\.[\w-]*\.[\w-]*\b/g,
630
+ mask: () => "eyJ***.***"
631
+ },
632
+ bearer: {
633
+ pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
634
+ mask: () => "Bearer ***"
635
+ },
636
+ iban: {
637
+ 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,
638
+ mask: (m) => {
639
+ const clean = m.replace(/[\s-]/g, "");
640
+ return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
641
+ }
642
+ }
643
+ };
644
+ globallyRedacted = Symbol.for("evlog.globallyRedacted");
645
+ });
621
646
 
622
- // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
647
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
623
648
  function logPluginError(name, hook, err) {
624
649
  console.error(`[evlog/${name}] ${hook} failed:`, err);
625
650
  }
@@ -727,13 +752,9 @@ function createPluginRunner(plugins = []) {
727
752
  }
728
753
  };
729
754
  }
730
- var emptyRunner = createPluginRunner([]);
731
755
  function getEmptyPluginRunner() {
732
756
  return emptyRunner;
733
757
  }
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
758
  function createConfig() {
738
759
  return {
739
760
  env: {
@@ -775,17 +796,28 @@ function getRegistry() {
775
796
  storages: /* @__PURE__ */ new Map
776
797
  };
777
798
  }
778
- var globalConfig = getRegistry().config;
799
+ function getSharedStorage(id, create) {
800
+ const { storages } = getRegistry();
801
+ let storage = storages.get(id);
802
+ if (!storage) {
803
+ storage = create();
804
+ storages.set(id, storage);
805
+ }
806
+ return storage;
807
+ }
808
+ var emptyRunner, EVLOG_MAJOR = 2, REGISTRY_KEY, MAJORS_KEY, globalConfig;
809
+ var init_globalRegistry_Bh3bIGwA = __esm(() => {
810
+ init_utils();
811
+ emptyRunner = createPluginRunner([]);
812
+ REGISTRY_KEY = Symbol.for(`evlog.registry.v${EVLOG_MAJOR}`);
813
+ MAJORS_KEY = Symbol.for("evlog.majors");
814
+ globalConfig = getRegistry().config;
815
+ });
779
816
 
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__";
817
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
783
818
  function pushTreeSpacer(children) {
784
819
  children.push(PRETTY_ERROR_TREE_SPACER);
785
820
  }
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
821
  function isPlainObject(val) {
790
822
  return val !== null && typeof val === "object" && !Array.isArray(val);
791
823
  }
@@ -1002,15 +1034,13 @@ function formatCollapsedFrame(frame, cwd) {
1002
1034
  return `${prefix}${fn} (${loc})`;
1003
1035
  return `${prefix}${loc}`;
1004
1036
  }
1005
- var GUIDANCE_WRAP_WIDTH = 76;
1006
- var GUIDANCE_CONTINUATION = " ";
1007
1037
  function formatGuidanceLine(label, text, labelColor) {
1008
1038
  const prefix = `${labelColor}${label}:${colors.reset} `;
1009
1039
  const lines = [];
1010
1040
  let remaining = text.trim();
1011
1041
  let first = true;
1012
1042
  while (remaining.length > 0) {
1013
- const budget = first ? Math.max(24, GUIDANCE_WRAP_WIDTH - prefix.length) : Math.max(24, GUIDANCE_WRAP_WIDTH - 5);
1043
+ const budget = first ? Math.max(24, GUIDANCE_WRAP_WIDTH - prefix.length) : Math.max(24, 71);
1014
1044
  if (remaining.length <= budget) {
1015
1045
  lines.push(first ? `${prefix}${remaining}` : `${GUIDANCE_CONTINUATION}${remaining}`);
1016
1046
  break;
@@ -1077,22 +1107,15 @@ function buildErrorEntries(error, options = {}) {
1077
1107
  children: children.length > 0 ? children : undefined
1078
1108
  }];
1079
1109
  }
1110
+ var snippetReader = null, PRETTY_ERROR_TREE_SPACER = "__EVLOG_TREE_SPACER__", SKIP_PATH_RE, SKIP_FRAME_PATH_RE, SKIP_FRAME_FN_RE, GUIDANCE_WRAP_WIDTH = 76, GUIDANCE_CONTINUATION = " ";
1111
+ var init_pretty_error_D8rlWNL1 = __esm(() => {
1112
+ init_utils();
1113
+ SKIP_PATH_RE = /(?:^|[/\\])(?:node_modules|\.nuxt|\.next|\.output)(?:[/\\]|$)/;
1114
+ SKIP_FRAME_PATH_RE = /(?:^|[/\\])(?:packages[/\\]evlog|evlog[/\\](?:dist|src))(?:[/\\]|$)/;
1115
+ SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
1116
+ });
1080
1117
 
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"
1086
- },
1087
- nitro: {
1088
- frameworkOverlay: true,
1089
- detail: "guidance"
1090
- },
1091
- both: {
1092
- frameworkOverlay: true,
1093
- detail: "full"
1094
- }
1095
- };
1118
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
1096
1119
  function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
1097
1120
  const compact = partial.compact ?? (inDev && pretty);
1098
1121
  const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
@@ -1126,9 +1149,29 @@ function resolveDevTerminal(input = {}) {
1126
1149
  prettyError: finalizePrettyError(prettyError, frameworkOverlay, pretty, inDev)
1127
1150
  };
1128
1151
  }
1152
+ var DEV_PRESETS;
1153
+ var init_dev_terminal_Brarc6vc = __esm(() => {
1154
+ init_utils();
1155
+ DEV_PRESETS = {
1156
+ evlog: {
1157
+ frameworkOverlay: false,
1158
+ detail: "full"
1159
+ },
1160
+ nitro: {
1161
+ frameworkOverlay: true,
1162
+ detail: "guidance"
1163
+ },
1164
+ both: {
1165
+ frameworkOverlay: true,
1166
+ detail: "full"
1167
+ }
1168
+ };
1169
+ });
1129
1170
 
1130
- // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
1131
- var publisher = null;
1171
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
1172
+ function hasWideEventPublisher() {
1173
+ return publisher !== null;
1174
+ }
1132
1175
  function publishWideEvent(event) {
1133
1176
  if (!publisher)
1134
1177
  return;
@@ -1138,126 +1181,155 @@ function publishWideEvent(event) {
1138
1181
  console.error("[evlog] diagnostics channel publish failed:", err);
1139
1182
  }
1140
1183
  }
1184
+ var publisher = null;
1185
+ var init_wideEventChannel_BUDW48oP = () => {};
1141
1186
 
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");
1187
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
1144
1188
  function isEvlogError(error) {
1145
1189
  return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
1146
1190
  }
1191
+ var evlogErrorBrand;
1192
+ var init_error_brand_D0_DCPvr = __esm(() => {
1193
+ evlogErrorBrand = Symbol.for("evlog.error.brand");
1194
+ });
1147
1195
 
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);
1154
- }
1155
- code;
1156
- status;
1157
- why;
1158
- fix;
1159
- link;
1160
- get internal() {
1161
- return this[evlogErrorInternalKey];
1162
- }
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(`
1196
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/error.mjs
1197
+ var evlogErrorInternalKey, evlogErrorDataKey, EvlogError;
1198
+ var init_error = __esm(() => {
1199
+ init_utils();
1200
+ init_error_brand_D0_DCPvr();
1201
+ evlogErrorInternalKey = Symbol.for("evlog.error.internal");
1202
+ evlogErrorDataKey = Symbol.for("evlog.error.data");
1203
+ EvlogError = class EvlogError extends Error {
1204
+ static isEvlogError(error) {
1205
+ return isEvlogError(error);
1206
+ }
1207
+ code;
1208
+ status;
1209
+ why;
1210
+ fix;
1211
+ link;
1212
+ get internal() {
1213
+ return this[evlogErrorInternalKey];
1214
+ }
1215
+ constructor(options) {
1216
+ const opts = typeof options === "string" ? { message: options } : options;
1217
+ super(opts.message, { cause: opts.cause });
1218
+ this.name = "EvlogError";
1219
+ this.code = opts.code;
1220
+ this.status = opts.status ?? 500;
1221
+ this.why = opts.why;
1222
+ this.fix = opts.fix;
1223
+ this.link = opts.link;
1224
+ if (opts.internal !== undefined)
1225
+ Object.defineProperty(this, evlogErrorInternalKey, {
1226
+ value: opts.internal,
1227
+ enumerable: false,
1228
+ writable: false,
1229
+ configurable: true
1230
+ });
1231
+ if (opts.data !== undefined)
1232
+ Object.defineProperty(this, evlogErrorDataKey, {
1233
+ value: opts.data,
1234
+ enumerable: false,
1235
+ writable: false,
1236
+ configurable: true
1237
+ });
1238
+ if (Error.captureStackTrace)
1239
+ Error.captureStackTrace(this, EvlogError);
1240
+ }
1241
+ get statusText() {
1242
+ return this.message;
1243
+ }
1244
+ get statusCode() {
1245
+ return this.status;
1246
+ }
1247
+ get statusMessage() {
1248
+ return this.message;
1249
+ }
1250
+ get data() {
1251
+ const extra = this[evlogErrorDataKey];
1252
+ if (!extra && !this.code && !this.why && !this.fix && !this.link)
1253
+ return;
1254
+ return {
1255
+ ...extra,
1256
+ ...this.code !== undefined && { code: this.code },
1257
+ ...this.why !== undefined && { why: this.why },
1258
+ ...this.fix !== undefined && { fix: this.fix },
1259
+ ...this.link !== undefined && { link: this.link }
1260
+ };
1261
+ }
1262
+ toString() {
1263
+ const useColors = isServer();
1264
+ const red = useColors ? colors.red : "";
1265
+ const yellow = useColors ? colors.yellow : "";
1266
+ const cyan = useColors ? colors.cyan : "";
1267
+ const dim = useColors ? colors.dim : "";
1268
+ const reset = useColors ? colors.reset : "";
1269
+ const bold = useColors ? colors.bold : "";
1270
+ const lines = [];
1271
+ lines.push(`${red}${bold}Error:${reset} ${this.message}`);
1272
+ if (this.code)
1273
+ lines.push(`${dim}Code:${reset} ${this.code}`);
1274
+ if (this.why)
1275
+ lines.push(`${yellow}Why:${reset} ${this.why}`);
1276
+ if (this.fix)
1277
+ lines.push(`${cyan}Fix:${reset} ${this.fix}`);
1278
+ if (this.link)
1279
+ lines.push(`${dim}More info:${reset} ${this.link}`);
1280
+ if (this.cause)
1281
+ lines.push(`${dim}Caused by:${reset} ${this.cause.message}`);
1282
+ return lines.join(`
1231
1283
  `);
1284
+ }
1285
+ toJSON() {
1286
+ const { data } = this;
1287
+ return {
1288
+ name: this.name,
1289
+ message: this.message,
1290
+ status: this.status,
1291
+ ...data && { data },
1292
+ ...this.cause instanceof Error && { cause: {
1293
+ name: this.cause.name,
1294
+ message: this.cause.message
1295
+ } }
1296
+ };
1297
+ }
1298
+ };
1299
+ Object.defineProperty(EvlogError.prototype, evlogErrorBrand, {
1300
+ value: true,
1301
+ enumerable: false
1302
+ });
1303
+ });
1304
+
1305
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
1306
+ function extractSafeHeaders(headers) {
1307
+ const raw = {};
1308
+ headers.forEach((value, key) => {
1309
+ raw[key] = value;
1310
+ });
1311
+ return filterSafeHeaders(raw);
1312
+ }
1313
+ function extractSafeNodeHeaders(headers) {
1314
+ const raw = {};
1315
+ for (const [key, value] of Object.entries(headers)) {
1316
+ if (value === undefined)
1317
+ continue;
1318
+ raw[key] = Array.isArray(value) ? value.join(", ") : value;
1232
1319
  }
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
1320
+ return filterSafeHeaders(raw);
1321
+ }
1322
+ var init_headers_Bx1ieR_m = __esm(() => {
1323
+ init_utils();
1250
1324
  });
1251
1325
 
1252
- // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/audit-CW8wdQDm.mjs
1253
- var nativeStdoutWrite = typeof process !== "undefined" && typeof process.stdout?.write === "function" ? process.stdout.write.bind(process.stdout) : undefined;
1326
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/audit-C8euLMvu.mjs
1254
1327
  function writePrettyStdout(text) {
1255
1328
  (globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
1256
1329
  }
1257
1330
  function isPlainObject$1(val) {
1258
1331
  return val !== null && typeof val === "object" && !Array.isArray(val);
1259
1332
  }
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).";
1261
1333
  function warnPostEmit(method, detail) {
1262
1334
  console.warn(`[evlog] ${method} called after the wide event was emitted \u2014 ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}`);
1263
1335
  }
@@ -1277,12 +1349,17 @@ function mergeInto(target, source) {
1277
1349
  Reflect.set(target, key, sourceVal);
1278
1350
  }
1279
1351
  }
1280
- var pendingDrainState = /* @__PURE__ */ new WeakMap;
1281
1352
  function isAiOnlyFieldUpdate(data) {
1282
1353
  const keys = Object.keys(data);
1283
1354
  return keys.length === 1 && keys[0] === "ai";
1284
1355
  }
1285
- var state = globalConfig;
1356
+ function markWideEventDrainStarted(event) {
1357
+ if (!event)
1358
+ return;
1359
+ const state = pendingDrainState.get(event);
1360
+ if (state)
1361
+ state.drainStarted = true;
1362
+ }
1286
1363
  function initLogger(config = {}) {
1287
1364
  state.enabled = config.enabled ?? true;
1288
1365
  const detected = detectEnvironment();
@@ -1309,6 +1386,15 @@ function initLogger(config = {}) {
1309
1386
  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).");
1310
1387
  state.initialized = true;
1311
1388
  }
1389
+ function getGlobalPluginRunner() {
1390
+ return state.pluginRunner;
1391
+ }
1392
+ function isEnabled() {
1393
+ return state.enabled;
1394
+ }
1395
+ function getGlobalDrain() {
1396
+ return state.drain;
1397
+ }
1312
1398
  function shouldSample(level) {
1313
1399
  const { rates } = state.sampling;
1314
1400
  if (!rates)
@@ -1371,13 +1457,14 @@ function emitWideEvent(level, event, options = {}) {
1371
1457
  formatted = redactEvent(formatted, state.redact);
1372
1458
  markGloballyRedacted(formatted);
1373
1459
  }
1374
- if (!state.silent)
1460
+ if (!state.silent) {
1375
1461
  if (state.pretty)
1376
1462
  prettyPrintWideEvent(formatted);
1377
1463
  else if (state.stringify)
1378
1464
  console[getConsoleMethod(level)](JSON.stringify(formatted));
1379
1465
  else
1380
1466
  console[getConsoleMethod(level)](formatted);
1467
+ }
1381
1468
  if (!deferDrain) {
1382
1469
  publishWideEvent(formatted);
1383
1470
  const drainPromises = [];
@@ -1428,11 +1515,12 @@ function formatValue(value) {
1428
1515
  if (isPlainObject$1(value)) {
1429
1516
  const pairs = [];
1430
1517
  for (const [k, v] of Object.entries(value))
1431
- if (v !== undefined && v !== null)
1518
+ if (v !== undefined && v !== null) {
1432
1519
  if (typeof v === "object")
1433
1520
  pairs.push(`${k}=${JSON.stringify(v)}`);
1434
1521
  else
1435
1522
  pairs.push(`${k}=${v}`);
1523
+ }
1436
1524
  return pairs.join(" ");
1437
1525
  }
1438
1526
  return String(value);
@@ -1487,6 +1575,20 @@ function asToolCallArray(value) {
1487
1575
  return;
1488
1576
  return value.every(isToolCallEntry) ? value : undefined;
1489
1577
  }
1578
+ function asCapturedLines(value) {
1579
+ if (typeof value !== "string" || value.length === 0)
1580
+ return;
1581
+ const lines = value.split(`
1582
+ `).map((line) => {
1583
+ return line.length > CAPTURED_LINE_MAX_LENGTH ? `${line.slice(0, CAPTURED_LINE_MAX_LENGTH)}\u2026` : line;
1584
+ });
1585
+ if (lines.length > CAPTURED_MAX_LINES) {
1586
+ lines.length = CAPTURED_MAX_LINES;
1587
+ lines.push(`+${value.split(`
1588
+ `).length - CAPTURED_MAX_LINES} more lines (full text in the event)`);
1589
+ }
1590
+ return lines;
1591
+ }
1490
1592
  function buildAIEntries(ai) {
1491
1593
  const entries = [];
1492
1594
  const headerParts = [];
@@ -1581,7 +1683,7 @@ function buildAIEntries(ai) {
1581
1683
  value: "",
1582
1684
  children
1583
1685
  });
1584
- } else if (toolCalls?.length)
1686
+ } else if (toolCalls?.length) {
1585
1687
  if (toolCallEntries?.length) {
1586
1688
  const children = toolCallEntries.map((tc) => {
1587
1689
  const inputStr = serializeToolInput(tc.input);
@@ -1601,6 +1703,7 @@ function buildAIEntries(ai) {
1601
1703
  value: names.join(", ")
1602
1704
  });
1603
1705
  }
1706
+ }
1604
1707
  const stepsUsage = Array.isArray(ai.stepsUsage) ? ai.stepsUsage.filter(isPlainObject$1) : undefined;
1605
1708
  if (stepsUsage?.length) {
1606
1709
  const firstModel = stepsUsage[0]?.model;
@@ -1622,6 +1725,20 @@ function buildAIEntries(ai) {
1622
1725
  key: "ai.steps",
1623
1726
  value: String(steps)
1624
1727
  });
1728
+ const promptLines = asCapturedLines(ai.prompt);
1729
+ if (promptLines)
1730
+ entries.push({
1731
+ key: "ai.prompt",
1732
+ value: "",
1733
+ children: promptLines
1734
+ });
1735
+ const outputLines = asCapturedLines(ai.output);
1736
+ if (outputLines)
1737
+ entries.push({
1738
+ key: "ai.output",
1739
+ value: "",
1740
+ children: outputLines
1741
+ });
1625
1742
  const embedding = isPlainObject$1(ai.embedding) ? ai.embedding : undefined;
1626
1743
  if (embedding) {
1627
1744
  const parts = [];
@@ -1772,36 +1889,69 @@ function prettyPrintWideEvent(event) {
1772
1889
  if (!browser && lines.length > 0)
1773
1890
  flushPrettyLines(lines);
1774
1891
  }
1892
+ function removeErrorCycles(value, ancestors) {
1893
+ if (value === null || typeof value !== "object")
1894
+ return value;
1895
+ if (ancestors.has(value))
1896
+ return "[Circular]";
1897
+ ancestors.add(value);
1898
+ let changed = false;
1899
+ const visit = (item) => {
1900
+ const result = removeErrorCycles(item, ancestors);
1901
+ if (!Object.is(result, item))
1902
+ changed = true;
1903
+ return result;
1904
+ };
1905
+ const copy = Array.isArray(value) ? value.map(visit) : Object.fromEntries(Object.entries(value).map(([key, item]) => [key, visit(item)]));
1906
+ ancestors.delete(value);
1907
+ return changed ? copy : value;
1908
+ }
1909
+ function serializeError(err) {
1910
+ const errorObj = {
1911
+ name: err.name,
1912
+ message: err.message,
1913
+ stack: isDev() ? compactStackForStorage(err.stack) : err.stack
1914
+ };
1915
+ const errRecord = err;
1916
+ const ancestors = new WeakSet([err]);
1917
+ for (const k of [
1918
+ "code",
1919
+ "status",
1920
+ "statusText",
1921
+ "statusCode",
1922
+ "statusMessage",
1923
+ "data",
1924
+ "cause",
1925
+ "internal"
1926
+ ])
1927
+ if (k in err)
1928
+ errorObj[k] = removeErrorCycles(errRecord[k], ancestors);
1929
+ if (EvlogError.isEvlogError(err)) {
1930
+ if (err.code)
1931
+ errorObj.code = err.code;
1932
+ if (err.why)
1933
+ errorObj.why = err.why;
1934
+ if (err.fix)
1935
+ errorObj.fix = err.fix;
1936
+ if (err.link)
1937
+ errorObj.link = err.link;
1938
+ if (err.status)
1939
+ errorObj.status = err.status;
1940
+ }
1941
+ return errorObj;
1942
+ }
1775
1943
  function createLogMethod(level) {
1776
1944
  return function logMethod(tagOrEvent, message) {
1777
1945
  if (typeof tagOrEvent === "string" && message !== undefined)
1778
1946
  emitTaggedLog(level, tagOrEvent, message);
1947
+ else if (tagOrEvent instanceof Error)
1948
+ emitWideEvent(level, { error: serializeError(tagOrEvent) });
1779
1949
  else if (typeof tagOrEvent === "object")
1780
1950
  emitWideEvent(level, tagOrEvent);
1781
1951
  else
1782
1952
  emitTaggedLog(level, "log", String(tagOrEvent));
1783
1953
  };
1784
1954
  }
1785
- var _log = {
1786
- info: createLogMethod("info"),
1787
- error: createLogMethod("error"),
1788
- warn: createLogMethod("warn"),
1789
- debug: createLogMethod("debug")
1790
- };
1791
- var noopLogger = {
1792
- set() {},
1793
- setLevel() {},
1794
- error() {},
1795
- info() {},
1796
- warn() {},
1797
- emit() {
1798
- return null;
1799
- },
1800
- getContext() {
1801
- return {};
1802
- },
1803
- audit: Object.assign(() => {}, { deny: () => {} })
1804
- };
1805
1955
  function createLogger(initialContext = {}, internalOptions) {
1806
1956
  if (!state.enabled)
1807
1957
  return noopLogger;
@@ -1874,36 +2024,7 @@ function createLogger(initialContext = {}, internalOptions) {
1874
2024
  const err = typeof error === "string" ? new Error(error) : error;
1875
2025
  if (errorContext)
1876
2026
  mergeInto(context, errorContext);
1877
- const errorObj = {
1878
- name: err.name,
1879
- message: err.message,
1880
- stack: isDev() ? compactStackForStorage(err.stack) : err.stack
1881
- };
1882
- const errRecord = err;
1883
- for (const k of [
1884
- "code",
1885
- "status",
1886
- "statusText",
1887
- "statusCode",
1888
- "statusMessage",
1889
- "data",
1890
- "cause",
1891
- "internal"
1892
- ])
1893
- if (k in err)
1894
- errorObj[k] = errRecord[k];
1895
- if (EvlogError.isEvlogError(err)) {
1896
- if (err.code)
1897
- errorObj.code = err.code;
1898
- if (err.why)
1899
- errorObj.why = err.why;
1900
- if (err.fix)
1901
- errorObj.fix = err.fix;
1902
- if (err.link)
1903
- errorObj.link = err.link;
1904
- if (err.status)
1905
- errorObj.status = err.status;
1906
- }
2027
+ const errorObj = serializeError(err);
1907
2028
  if (isPlainObject$1(context.error))
1908
2029
  mergeInto(context.error, errorObj);
1909
2030
  else
@@ -1982,8 +2103,20 @@ function createLogger(initialContext = {}, internalOptions) {
1982
2103
  }
1983
2104
  };
1984
2105
  }
1985
- if (typeof __EVLOG_CONFIG__ !== "undefined")
1986
- initLogger(__EVLOG_CONFIG__);
2106
+ function createRequestLogger(options = {}, internalOptions) {
2107
+ const { method, path, requestId, waitUntil: optionsWaitUntil } = options;
2108
+ const initial = {};
2109
+ if (method !== undefined)
2110
+ initial.method = method;
2111
+ if (path !== undefined)
2112
+ initial.path = path;
2113
+ if (requestId !== undefined)
2114
+ initial.requestId = requestId;
2115
+ return createLogger(initial, {
2116
+ ...internalOptions,
2117
+ waitUntil: internalOptions?.waitUntil ?? optionsWaitUntil
2118
+ });
2119
+ }
1987
2120
  function isPlainObject2(value) {
1988
2121
  if (typeof value !== "object" || value === null || Array.isArray(value))
1989
2122
  return false;
@@ -2045,7 +2178,6 @@ function buildAuditFields(input) {
2045
2178
  version: input.version ?? 1
2046
2179
  };
2047
2180
  }
2048
- var _testCollector = null;
2049
2181
  function decorateAudit(audit, timestamp) {
2050
2182
  if (audit.idempotencyKey)
2051
2183
  return audit;
@@ -2077,13 +2209,645 @@ function finalizeAudit(event) {
2077
2209
  event.audit = decorated;
2078
2210
  _testCollector?.(decorated, event);
2079
2211
  }
2212
+ var nativeStdoutWrite, 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).", pendingDrainState, state, CAPTURED_LINE_MAX_LENGTH = 160, CAPTURED_MAX_LINES = 8, _log, noopLogger, _testCollector = null;
2213
+ var init_audit_C8euLMvu = __esm(() => {
2214
+ init_utils();
2215
+ init_redact_C7FmdhwI();
2216
+ init_globalRegistry_Bh3bIGwA();
2217
+ init_pretty_error_D8rlWNL1();
2218
+ init_dev_terminal_Brarc6vc();
2219
+ init_wideEventChannel_BUDW48oP();
2220
+ init_error();
2221
+ nativeStdoutWrite = typeof process !== "undefined" && typeof process.stdout?.write === "function" ? process.stdout.write.bind(process.stdout) : undefined;
2222
+ pendingDrainState = /* @__PURE__ */ new WeakMap;
2223
+ state = globalConfig;
2224
+ _log = {
2225
+ info: createLogMethod("info"),
2226
+ error: createLogMethod("error"),
2227
+ warn: createLogMethod("warn"),
2228
+ debug: createLogMethod("debug")
2229
+ };
2230
+ noopLogger = {
2231
+ set() {},
2232
+ setLevel() {},
2233
+ error() {},
2234
+ info() {},
2235
+ warn() {},
2236
+ emit() {
2237
+ return null;
2238
+ },
2239
+ getContext() {
2240
+ return {};
2241
+ },
2242
+ audit: Object.assign(() => {}, { deny: () => {} })
2243
+ };
2244
+ if (typeof __EVLOG_CONFIG__ !== "undefined")
2245
+ initLogger(__EVLOG_CONFIG__);
2246
+ });
2247
+
2248
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/index.mjs
2249
+ var init_dist = __esm(() => {
2250
+ init_audit_C8euLMvu();
2251
+ });
2252
+
2253
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
2254
+ function shouldDeferEmitForResponse(response) {
2255
+ if (!response.body)
2256
+ return false;
2257
+ const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
2258
+ if (contentType.includes("text/event-stream"))
2259
+ return true;
2260
+ if (contentType.includes("application/x-ndjson"))
2261
+ return true;
2262
+ if (response.headers.has("x-vercel-ai-ui-message-stream"))
2263
+ return true;
2264
+ if (response.headers.get("transfer-encoding")?.toLowerCase().includes("chunked"))
2265
+ return true;
2266
+ return false;
2267
+ }
2268
+ function toError(value) {
2269
+ return value instanceof Error ? value : new Error(String(value));
2270
+ }
2271
+ function createObservedBody(body, onDone, onError) {
2272
+ if (body.locked) {
2273
+ Promise.resolve(onError(/* @__PURE__ */ new TypeError("stream is already locked"))).catch((err) => {
2274
+ console.error("[evlog] stream error handling failed:", err);
2275
+ });
2276
+ return null;
2277
+ }
2278
+ const reader = body.getReader();
2279
+ let settled = false;
2280
+ const settle = (fn) => {
2281
+ if (settled)
2282
+ return;
2283
+ settled = true;
2284
+ Promise.resolve(fn()).catch((err) => {
2285
+ console.error("[evlog] stream completion handling failed:", err);
2286
+ });
2287
+ };
2288
+ return new ReadableStream({
2289
+ async pull(controller) {
2290
+ try {
2291
+ const { done, value } = await reader.read();
2292
+ if (done) {
2293
+ settle(onDone);
2294
+ controller.close();
2295
+ return;
2296
+ }
2297
+ controller.enqueue(value);
2298
+ } catch (err) {
2299
+ settle(() => onError(err));
2300
+ controller.error(err);
2301
+ }
2302
+ },
2303
+ async cancel(reason) {
2304
+ try {
2305
+ await reader.cancel(reason);
2306
+ } finally {
2307
+ settle(onDone);
2308
+ }
2309
+ }
2310
+ });
2311
+ }
2312
+ function bindStreamingResponseLifecycle(response, onComplete) {
2313
+ if (!response.body) {
2314
+ Promise.resolve(onComplete({ status: response.status })).catch((err) => {
2315
+ console.error("[evlog] stream completion handling failed:", err);
2316
+ });
2317
+ return response;
2318
+ }
2319
+ const body = createObservedBody(response.body, () => onComplete({ status: response.status }), (err) => onComplete({
2320
+ status: response.status,
2321
+ error: toError(err)
2322
+ }));
2323
+ if (!body)
2324
+ return response;
2325
+ return new Response(body, {
2326
+ status: response.status,
2327
+ statusText: response.statusText,
2328
+ headers: response.headers
2329
+ });
2330
+ }
2331
+ var init_streamResponse_OlirMA5P = () => {};
2332
+
2333
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/errors-CL8dDgIi.mjs
2334
+ function extractErrorStatus(error) {
2335
+ if (error === null || typeof error !== "object")
2336
+ return 500;
2337
+ const raw = error.status ?? error.statusCode;
2338
+ const status = Number(raw);
2339
+ return Number.isFinite(status) ? status : 500;
2340
+ }
2341
+ var init_errors_CL8dDgIi = () => {};
2342
+
2343
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
2344
+ function shouldLog(path, include, exclude) {
2345
+ if (exclude && exclude.length > 0) {
2346
+ if (exclude.some((pattern) => matchesPattern(path, pattern)))
2347
+ return false;
2348
+ }
2349
+ if (!include || include.length === 0)
2350
+ return true;
2351
+ return include.some((pattern) => matchesPattern(path, pattern));
2352
+ }
2353
+ function getServiceForPath(path, routes) {
2354
+ if (!routes)
2355
+ return;
2356
+ for (const [pattern, config] of Object.entries(routes))
2357
+ if (matchesPattern(path, pattern))
2358
+ return config.service;
2359
+ }
2360
+ function extendDeferredDrain(drainPromise, waitUntil) {
2361
+ drainPromise.catch((err) => {
2362
+ console.error("[evlog] background drain failed:", err);
2363
+ });
2364
+ if (typeof waitUntil === "function")
2365
+ waitUntil(drainPromise);
2366
+ }
2367
+ var init_deferred_drain_CfRYimo5 = __esm(() => {
2368
+ init_utils();
2369
+ });
2370
+
2371
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/middleware-fam3VyaL.mjs
2372
+ function resolveMiddlewarePluginRunner(options) {
2373
+ const global = getGlobalPluginRunner();
2374
+ const local = options.plugins;
2375
+ if (!local || local.length === 0)
2376
+ return global;
2377
+ const cached = runnerCache.get(local);
2378
+ if (cached && cached.global === global)
2379
+ return cached.merged;
2380
+ const merged = /* @__PURE__ */ new Map;
2381
+ for (const plugin of global.plugins)
2382
+ merged.set(plugin.name, plugin);
2383
+ for (const plugin of local)
2384
+ merged.set(plugin.name, plugin);
2385
+ if (merged.size === 0)
2386
+ return getEmptyPluginRunner();
2387
+ const runner = createPluginRunner(Array.from(merged.values()));
2388
+ runnerCache.set(local, {
2389
+ global,
2390
+ merged: runner
2391
+ });
2392
+ return runner;
2393
+ }
2394
+ function assignRedactedEvent(target, redacted) {
2395
+ for (const key of Object.keys(target))
2396
+ if (!(key in redacted))
2397
+ delete target[key];
2398
+ Object.assign(target, redacted);
2399
+ }
2400
+ async function runEnrichAndDrain(emittedEvent, options, requestInfo, responseStatus, plugins) {
2401
+ const runner = plugins ?? resolveMiddlewarePluginRunner(options);
2402
+ const resolvedRedact = resolveRedactConfig(options.redact);
2403
+ if (resolvedRedact && !isGloballyRedacted(emittedEvent))
2404
+ assignRedactedEvent(emittedEvent, redactEvent(emittedEvent, resolvedRedact));
2405
+ if (options.enrich || runner.hasEnrich) {
2406
+ const enrichCtx = {
2407
+ event: emittedEvent,
2408
+ request: requestInfo,
2409
+ headers: options.headers,
2410
+ response: { status: responseStatus }
2411
+ };
2412
+ if (options.enrich)
2413
+ try {
2414
+ await options.enrich(enrichCtx);
2415
+ } catch (err) {
2416
+ console.error("[evlog] enrich failed:", err);
2417
+ }
2418
+ if (runner.hasEnrich)
2419
+ await runner.runEnrich(enrichCtx);
2420
+ }
2421
+ publishWideEvent(emittedEvent);
2422
+ markWideEventDrainStarted(emittedEvent);
2423
+ const drain = options.drain ?? getGlobalDrain();
2424
+ const hasUserDrain = !!drain;
2425
+ const hasPluginDrain = runner.hasDrain;
2426
+ if (hasUserDrain || hasPluginDrain) {
2427
+ const drainCtx = {
2428
+ event: emittedEvent,
2429
+ request: requestInfo,
2430
+ headers: options.headers
2431
+ };
2432
+ const tasks = [];
2433
+ if (hasUserDrain)
2434
+ tasks.push((async () => {
2435
+ try {
2436
+ await drain(drainCtx);
2437
+ } catch (err) {
2438
+ console.error("[evlog] drain failed:", err);
2439
+ }
2440
+ })());
2441
+ if (hasPluginDrain)
2442
+ tasks.push(runner.runDrain(drainCtx));
2443
+ const drainPromise = Promise.all(tasks);
2444
+ if (options.waitUntil) {
2445
+ extendDeferredDrain(drainPromise, options.waitUntil);
2446
+ if (hasUserDrain) {
2447
+ const { settled } = drain;
2448
+ if (typeof settled === "function")
2449
+ extendDeferredDrain(settled(), options.waitUntil);
2450
+ }
2451
+ return;
2452
+ }
2453
+ await drainPromise;
2454
+ }
2455
+ }
2456
+ function createMiddlewareLogger(options) {
2457
+ if (!isEnabled())
2458
+ return noopResult;
2459
+ const { method, path, requestId, include, exclude, routes, keep } = options;
2460
+ if (!shouldLog(path, include, exclude))
2461
+ return noopResult;
2462
+ const resolvedRequestId = requestId || crypto.randomUUID();
2463
+ const logger = createRequestLogger({
2464
+ method,
2465
+ path,
2466
+ requestId: resolvedRequestId
2467
+ }, { _deferDrain: true });
2468
+ const routeService = getServiceForPath(path, routes);
2469
+ if (routeService)
2470
+ logger.set({ service: routeService });
2471
+ const pluginRunner = resolveMiddlewarePluginRunner(options);
2472
+ if (pluginRunner.hasExtendLogger)
2473
+ pluginRunner.applyExtendLogger(logger);
2474
+ const startTime = Date.now();
2475
+ const requestInfo = {
2476
+ method,
2477
+ path,
2478
+ requestId: resolvedRequestId
2479
+ };
2480
+ if (pluginRunner.hasRequestLifecycle)
2481
+ pluginRunner.runOnRequestStart({
2482
+ logger,
2483
+ request: requestInfo,
2484
+ headers: options.headers
2485
+ });
2486
+ const finish = (opts) => {
2487
+ return performFinish(logger, opts);
2488
+ };
2489
+ const finishResponse = async (response, opts) => {
2490
+ const status = opts?.status ?? response.status;
2491
+ if (!shouldDeferEmitForResponse(response)) {
2492
+ await performFinish(logger, { status });
2493
+ return response;
2494
+ }
2495
+ return bindStreamingResponseLifecycle(response, async (meta) => {
2496
+ await performFinish(logger, {
2497
+ status: meta.status ?? status,
2498
+ error: meta.error
2499
+ });
2500
+ });
2501
+ };
2502
+ async function performFinish(requestLogger, opts) {
2503
+ const { status, error } = opts ?? {};
2504
+ if (error) {
2505
+ requestLogger.error(error);
2506
+ const errorStatus = extractErrorStatus(error);
2507
+ requestLogger.set({ status: errorStatus });
2508
+ } else if (status !== undefined)
2509
+ requestLogger.set({ status });
2510
+ const durationMs = elapsedMs(startTime);
2511
+ const resolvedStatus = error ? extractErrorStatus(error) : status ?? requestLogger.getContext().status;
2512
+ const tailCtx = {
2513
+ status: resolvedStatus,
2514
+ duration: durationMs,
2515
+ path,
2516
+ method,
2517
+ context: requestLogger.getContext(),
2518
+ shouldKeep: false
2519
+ };
2520
+ if (keep)
2521
+ await keep(tailCtx);
2522
+ if (pluginRunner.hasKeep)
2523
+ await pluginRunner.runKeep(tailCtx);
2524
+ const forceKeep = tailCtx.shouldKeep || shouldKeep(tailCtx);
2525
+ const emittedEvent = requestLogger.emit({ _forceKeep: forceKeep });
2526
+ if (emittedEvent && (options.enrich || options.drain || pluginRunner.hasEnrich || pluginRunner.hasDrain || getGlobalDrain() || hasWideEventPublisher()))
2527
+ await runEnrichAndDrain(emittedEvent, options, requestInfo, resolvedStatus, pluginRunner);
2528
+ if (pluginRunner.hasRequestLifecycle)
2529
+ pluginRunner.runOnRequestFinish({
2530
+ logger: requestLogger,
2531
+ request: requestInfo,
2532
+ headers: options.headers,
2533
+ event: emittedEvent,
2534
+ status: resolvedStatus,
2535
+ durationMs,
2536
+ error
2537
+ });
2538
+ return emittedEvent;
2539
+ }
2540
+ return {
2541
+ logger,
2542
+ finish,
2543
+ finishResponse,
2544
+ skipped: false
2545
+ };
2546
+ }
2547
+ var noopResult, runnerCache;
2548
+ var init_middleware_fam3VyaL = __esm(() => {
2549
+ init_utils();
2550
+ init_redact_C7FmdhwI();
2551
+ init_globalRegistry_Bh3bIGwA();
2552
+ init_wideEventChannel_BUDW48oP();
2553
+ init_audit_C8euLMvu();
2554
+ init_errors_CL8dDgIi();
2555
+ init_deferred_drain_CfRYimo5();
2556
+ init_streamResponse_OlirMA5P();
2557
+ noopResult = {
2558
+ logger: noopLogger,
2559
+ finish: () => Promise.resolve(null),
2560
+ finishResponse: (response) => Promise.resolve(response),
2561
+ skipped: true
2562
+ };
2563
+ runnerCache = /* @__PURE__ */ new WeakMap;
2564
+ });
2565
+
2566
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/integration-CGD18W8r.mjs
2567
+ function attachForkToLogger(storage, parent, middlewareOptions, lifecycle) {
2568
+ const log = parent;
2569
+ log.fork = (label, fn) => {
2570
+ forkBackgroundLogger({
2571
+ storage,
2572
+ parent,
2573
+ middlewareOptions,
2574
+ label,
2575
+ fn,
2576
+ lifecycle
2577
+ });
2578
+ };
2579
+ }
2580
+ function forkBackgroundLogger(options) {
2581
+ const { storage, parent, middlewareOptions, label, fn, lifecycle } = options;
2582
+ const parentCtx = parent.getContext();
2583
+ const parentRequestId = parentCtx.requestId;
2584
+ if (typeof parentRequestId !== "string" || parentRequestId.length === 0)
2585
+ throw new Error("[evlog] log.fork() requires the parent logger to have a requestId. Ensure the request was created by evlog middleware.");
2586
+ const method = String(parentCtx.method ?? middlewareOptions.method);
2587
+ const path = String(parentCtx.path ?? middlewareOptions.path);
2588
+ const child = createRequestLogger({
2589
+ method,
2590
+ path,
2591
+ requestId: crypto.randomUUID()
2592
+ }, { _deferDrain: true });
2593
+ child.set({
2594
+ operation: label,
2595
+ _parentRequestId: parentRequestId
2596
+ });
2597
+ const childRequestInfo = {
2598
+ method,
2599
+ path,
2600
+ requestId: child.getContext().requestId
2601
+ };
2602
+ storage.run(child, () => {
2603
+ lifecycle?.onChildEnter?.(child);
2604
+ Promise.resolve().then(() => fn()).then(async () => {
2605
+ const emittedEvent = child.emit();
2606
+ const ctxStatus = child.getContext().status;
2607
+ const status = emittedEvent?.status ?? (typeof ctxStatus === "number" ? ctxStatus : undefined);
2608
+ if (emittedEvent && (middlewareOptions.enrich || middlewareOptions.drain || getGlobalDrain()))
2609
+ await runEnrichAndDrain(emittedEvent, middlewareOptions, childRequestInfo, status);
2610
+ }).catch(async (err) => {
2611
+ const error = err instanceof Error ? err : new Error(String(err));
2612
+ child.error(error);
2613
+ child.set({ status: extractErrorStatus(error) });
2614
+ const emittedEvent = child.emit();
2615
+ const status = extractErrorStatus(error);
2616
+ if (emittedEvent && (middlewareOptions.enrich || middlewareOptions.drain || getGlobalDrain()))
2617
+ await runEnrichAndDrain(emittedEvent, middlewareOptions, childRequestInfo, status);
2618
+ }).finally(() => {
2619
+ lifecycle?.onChildExit?.(child);
2620
+ });
2621
+ });
2622
+ }
2623
+ function normalizeHeaders(headers) {
2624
+ if (!headers)
2625
+ return;
2626
+ if (typeof headers.forEach === "function" && typeof headers.get === "function")
2627
+ return extractSafeHeaders(headers);
2628
+ return extractSafeNodeHeaders(headers);
2629
+ }
2630
+ function defineFrameworkIntegration(spec) {
2631
+ return { start(ctx, options = {}) {
2632
+ const extracted = spec.extractRequest(ctx);
2633
+ const headers = normalizeHeaders(extracted.headers);
2634
+ const waitUntil = options.waitUntil ?? spec.extractWaitUntil?.(ctx);
2635
+ const middlewareOptions = {
2636
+ method: extracted.method,
2637
+ path: extracted.path,
2638
+ requestId: extracted.requestId || crypto.randomUUID(),
2639
+ headers,
2640
+ ...options,
2641
+ waitUntil
2642
+ };
2643
+ const result = createMiddlewareLogger(middlewareOptions);
2644
+ if (!result.skipped) {
2645
+ if (spec.storage)
2646
+ attachForkToLogger(spec.storage, result.logger, middlewareOptions, spec.forkLifecycle);
2647
+ spec.attachLogger(ctx, result.logger);
2648
+ }
2649
+ const { storage } = spec;
2650
+ const runWith = async (fn) => {
2651
+ if (!storage || result.skipped)
2652
+ return await fn();
2653
+ return await storage.run(result.logger, fn);
2654
+ };
2655
+ return {
2656
+ ...result,
2657
+ middlewareOptions,
2658
+ runWith
2659
+ };
2660
+ } };
2661
+ }
2662
+ var init_integration_CGD18W8r = __esm(() => {
2663
+ init_audit_C8euLMvu();
2664
+ init_headers_Bx1ieR_m();
2665
+ init_errors_CL8dDgIi();
2666
+ init_middleware_fam3VyaL();
2667
+ });
2668
+
2669
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/toolkit/storage.mjs
2670
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
2671
+ function createLoggerStorage(contextHint, id = contextHint) {
2672
+ const storage = getSharedStorage(id, () => new AsyncLocalStorage4);
2673
+ function useLogger() {
2674
+ const logger = storage.getStore();
2675
+ if (!logger)
2676
+ throw new Error(`[evlog] useLogger() was called outside of an evlog ${contextHint}`);
2677
+ return logger;
2678
+ }
2679
+ return {
2680
+ storage,
2681
+ useLogger
2682
+ };
2683
+ }
2684
+ var init_storage = __esm(() => {
2685
+ init_globalRegistry_Bh3bIGwA();
2686
+ });
2687
+
2688
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/toolkit.mjs
2689
+ var init_toolkit = __esm(() => {
2690
+ init_integration_CGD18W8r();
2691
+ init_storage();
2692
+ });
2693
+
2694
+ // src/server/evlog.ts
2695
+ import { Elysia } from "elysia";
2696
+ var loggerStorage, integration, getRequestLogger;
2697
+ var init_evlog = __esm(() => {
2698
+ init_toolkit();
2699
+ loggerStorage = createLoggerStorage("Furin request context. Make sure the Furin plugin is registered before your routes.", "@teyik0/furin:evlog");
2700
+ integration = defineFrameworkIntegration({
2701
+ attachLogger: () => {
2702
+ return;
2703
+ },
2704
+ extractRequest: ({ request }) => {
2705
+ const url = new URL(request.url);
2706
+ return {
2707
+ headers: request.headers,
2708
+ method: request.method,
2709
+ path: url.pathname,
2710
+ requestId: request.headers.get("x-request-id") ?? undefined
2711
+ };
2712
+ },
2713
+ name: "furin",
2714
+ storage: loggerStorage.storage
2715
+ });
2716
+ getRequestLogger = loggerStorage.useLogger;
2717
+ });
2718
+
2080
2719
  // src/server/context-logger.ts
2081
- var syntheticRenderStorage = new AsyncLocalStorage3;
2720
+ import { AsyncLocalStorage as AsyncLocalStorage5 } from "async_hooks";
2721
+ function getLogger() {
2722
+ try {
2723
+ return getRequestLogger();
2724
+ } catch {
2725
+ return syntheticRenderStorage.getStore() ?? noopLogger2;
2726
+ }
2727
+ }
2728
+ var noopLogger2, syntheticRenderStorage;
2729
+ var init_context_logger = __esm(() => {
2730
+ init_dist();
2731
+ init_evlog();
2732
+ noopLogger2 = {
2733
+ emit: () => null,
2734
+ error: () => {},
2735
+ fork: (_label, fn) => fn(),
2736
+ getContext: () => ({}),
2737
+ info: () => {},
2738
+ set: () => {},
2739
+ setLevel: () => {},
2740
+ warn: () => {}
2741
+ };
2742
+ syntheticRenderStorage = new AsyncLocalStorage5;
2743
+ });
2744
+
2745
+ // src/server/runtime-env.ts
2746
+ var IS_DEV = true;
2747
+
2748
+ // src/server/sync/runtime.ts
2749
+ function resolveSyncRuntime(options) {
2750
+ if (!IS_DEV && options.adapter.scope === "process-local") {
2751
+ throw new Error("[furin] Production sync cannot use a process-local SyncAdapter.");
2752
+ }
2753
+ if (options.notifier) {
2754
+ if (options.adapter.notificationChannel !== undefined && options.notifier.notificationChannel !== undefined && options.adapter.notificationChannel !== options.notifier.notificationChannel) {
2755
+ throw new Error("[furin] SyncAdapter and SyncNotifier notification channels do not match.");
2756
+ }
2757
+ return { adapter: options.adapter, notifier: options.notifier };
2758
+ }
2759
+ if (!IS_DEV && options.adapter.scope === "distributed") {
2760
+ throw new Error("[furin] Distributed production sync requires an explicit SyncNotifier. Configure the adapter notifier or pass PollingSyncNotifier as a compatibility fallback.");
2761
+ }
2762
+ const existing = pollingNotifiers.get(options.adapter);
2763
+ if (existing) {
2764
+ return { adapter: options.adapter, notifier: existing };
2765
+ }
2766
+ const notifier = new PollingSyncNotifier(options.adapter, POLL_INTERVAL_MS);
2767
+ pollingNotifiers.set(options.adapter, notifier);
2768
+ return { adapter: options.adapter, notifier };
2769
+ }
2770
+ var POLL_INTERVAL_MS = 250, pollingNotifiers;
2771
+ var init_runtime = __esm(() => {
2772
+ pollingNotifiers = new WeakMap;
2773
+ });
2774
+
2775
+ // src/server/sync/stream.ts
2776
+ import { Elysia as Elysia2 } from "elysia";
2777
+ function parseChangeQuery(request) {
2778
+ const url = new URL(request.url);
2779
+ const after = url.searchParams.get("after") ?? undefined;
2780
+ if (after !== undefined && (after.length === 0 || after.length > MAX_CURSOR_LENGTH)) {
2781
+ return { error: Response.json({ code: "FURIN_INVALID_SYNC_CURSOR" }, { status: 400 }) };
2782
+ }
2783
+ const limitValue = url.searchParams.get("limit");
2784
+ if (limitValue !== null && !UNSIGNED_INTEGER_PATTERN.test(limitValue)) {
2785
+ return { error: Response.json({ code: "FURIN_INVALID_SYNC_LIMIT" }, { status: 400 }) };
2786
+ }
2787
+ const limit = limitValue === null ? DEFAULT_CHANGE_LIMIT : Number.parseInt(limitValue, 10);
2788
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_CHANGE_LIMIT) {
2789
+ return { error: Response.json({ code: "FURIN_INVALID_SYNC_LIMIT" }, { status: 400 }) };
2790
+ }
2791
+ return { after, limit };
2792
+ }
2793
+ function clientInvalidations(change) {
2794
+ const entries = new Set;
2795
+ for (const invalidation of change.invalidations) {
2796
+ if (invalidation.kind === "tags") {
2797
+ entries.add("/:layout");
2798
+ } else {
2799
+ entries.add(invalidation.type === "layout" ? `${invalidation.path}:layout` : invalidation.path);
2800
+ }
2801
+ }
2802
+ return [...entries];
2803
+ }
2804
+ function createSyncChangesPlugin(options) {
2805
+ const syncPath = options.path ?? defaultSyncPath;
2806
+ const runtime = resolveSyncRuntime(syncRuntimeOptions(options));
2807
+ return new Elysia2({ name: `furin-sync-changes-${syncPath}` }).get(`${syncPath}/changes`, async ({ request, set }) => {
2808
+ set.headers["cache-control"] = "no-store";
2809
+ const query = parseChangeQuery(request);
2810
+ if ("error" in query) {
2811
+ return query.error;
2812
+ }
2813
+ const page = await runtime.adapter.readChanges(query);
2814
+ return {
2815
+ ...page,
2816
+ changes: page.changes.map((change) => ({
2817
+ cursor: change.cursor,
2818
+ invalidations: clientInvalidations(change)
2819
+ }))
2820
+ };
2821
+ });
2822
+ }
2823
+ var DEFAULT_CHANGE_LIMIT = 100, MAX_CHANGE_LIMIT = 500, MAX_CURSOR_LENGTH = 128, UNSIGNED_INTEGER_PATTERN, defaultSyncPath = "/_furin/sync", cursorStates, resolvedStates;
2824
+ var init_stream = __esm(() => {
2825
+ init_config();
2826
+ init_runtime();
2827
+ UNSIGNED_INTEGER_PATTERN = /^\d+$/;
2828
+ cursorStates = new Map;
2829
+ resolvedStates = new Set;
2830
+ });
2831
+
2832
+ // src/server/sync/index.ts
2833
+ init_config();
2834
+
2835
+ // src/server/sync/plugin.ts
2836
+ import { Elysia as Elysia3 } from "elysia";
2837
+
2838
+ // src/shared/prefix.ts
2839
+ function physicalPath(prefix, path) {
2840
+ if (prefix === "") {
2841
+ return path;
2842
+ }
2843
+ return path === "/" ? prefix : `${prefix}${path}`;
2844
+ }
2082
2845
 
2083
2846
  // src/devtools/protocol.ts
2084
- var DEVTOOLS_PROTOCOL_VERSION = 1;
2847
+ var DEVTOOLS_PROTOCOL_VERSION = 2;
2085
2848
 
2086
2849
  // src/server/devtools/hub.ts
2850
+ init_instance();
2087
2851
  var EVENT_LIMIT = 1000;
2088
2852
  var instanceDevtoolsHub = instanceSlot(() => ({ events: [], listeners: new Set, sequence: 0 }));
2089
2853
  function devtoolsInstanceId() {
@@ -2110,6 +2874,8 @@ function appendDevtoolsEvent(event) {
2110
2874
  }
2111
2875
 
2112
2876
  // src/server/auto-invalidate/registry.ts
2877
+ init_instance();
2878
+
2113
2879
  class AutoInvalidateRegistry {
2114
2880
  pathToTags = new Map;
2115
2881
  tagToPaths = new Map;
@@ -2167,6 +2933,7 @@ function getAutoInvalidateRegistry(instance) {
2167
2933
  }
2168
2934
 
2169
2935
  // src/server/cache/registry.ts
2936
+ init_instance();
2170
2937
  var instanceInvalidators = instanceSlot(() => new Map);
2171
2938
  function getCacheInvalidators(instance) {
2172
2939
  return instanceInvalidators(instance).values();
@@ -2182,8 +2949,8 @@ function pathWithoutSearch(path) {
2182
2949
  }
2183
2950
 
2184
2951
  // src/server/devtools/request-context.ts
2185
- import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
2186
- var requestContext = new AsyncLocalStorage4;
2952
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
2953
+ var requestContext = new AsyncLocalStorage3;
2187
2954
  function currentDevtoolsRequest() {
2188
2955
  return requestContext.getStore();
2189
2956
  }
@@ -2196,8 +2963,38 @@ function currentInstrumentationRequest() {
2196
2963
  return currentDevtoolsRequest();
2197
2964
  }
2198
2965
 
2199
- // src/server/runtime-env.ts
2200
- var IS_DEV = true;
2966
+ // src/server/cache/invalidation.ts
2967
+ init_instance();
2968
+
2969
+ // src/server/cache/page-cache-state.ts
2970
+ init_instance();
2971
+ var instancePageCacheAdapter = instanceSlot(() => ({
2972
+ adapter: undefined
2973
+ }));
2974
+ function getPageCacheAdapter(instance) {
2975
+ return instancePageCacheAdapter(instance).adapter;
2976
+ }
2977
+ // src/server/cache/purger.ts
2978
+ var pathPurger;
2979
+ var tagPurger;
2980
+ function callCachePurger(paths) {
2981
+ dispatch(pathPurger, paths);
2982
+ }
2983
+ function callCacheTagPurger(tags) {
2984
+ dispatch(tagPurger, tags);
2985
+ }
2986
+ function dispatch(purger, keys) {
2987
+ if (!purger || keys.length === 0) {
2988
+ return;
2989
+ }
2990
+ Promise.resolve().then(() => purger(keys)).catch(async (error) => {
2991
+ await Promise.resolve().then(() => init_context_logger());
2992
+ const logger = createLogger({});
2993
+ logger.set({ furin: { action: "cdn_purge_failed", keys } });
2994
+ logger.error(error instanceof Error ? error : new Error(String(error)));
2995
+ logger.emit();
2996
+ });
2997
+ }
2201
2998
 
2202
2999
  // src/server/cache/invalidation.ts
2203
3000
  var _globalPendingInvalidations = new Set;
@@ -2216,35 +3013,58 @@ function consumePendingInvalidations() {
2216
3013
  function peekPendingInvalidations() {
2217
3014
  return [..._activeInvalidationSet()];
2218
3015
  }
2219
- var _cachePurger = null;
2220
- function callCachePurger(paths) {
2221
- if (!_cachePurger || paths.length === 0) {
3016
+ function callCachePurger2(paths) {
3017
+ callCachePurger(paths);
3018
+ }
3019
+ function emitPathInvalidation(instance, path, deleted, purgedPaths) {
3020
+ if (!IS_DEV) {
2222
3021
  return;
2223
3022
  }
2224
- _cachePurger(paths).catch((err) => {
2225
- const logger = createLogger({});
2226
- logger.set({
2227
- furin: {
2228
- action: "cdn_purge_failed",
2229
- paths
2230
- }
3023
+ withInstance(instance, () => {
3024
+ const request = currentInstrumentationRequest();
3025
+ emitCacheInvalidated({
3026
+ deleted,
3027
+ operationId: request?.operationId ?? null,
3028
+ purgedPaths: new Set(purgedPaths).size,
3029
+ reason: "path",
3030
+ requestId: request?.requestId ?? null,
3031
+ target: path
2231
3032
  });
2232
- logger.error(err instanceof Error ? err : new Error(String(err)));
2233
- logger.emit();
2234
3033
  });
2235
3034
  }
2236
- function revalidatePath(path, type) {
3035
+ async function invalidateInstancePath(instance, path, type) {
3036
+ const result = revalidatePathForInstance(instance, path, type, false);
3037
+ const purgedPaths = [physicalPath(instance.prefix, path)];
3038
+ for (const purged of result.purgedPaths) {
3039
+ purgedPaths.push(physicalPath(instance.prefix, purged));
3040
+ }
3041
+ const pageCache = getPageCacheAdapter(instance);
3042
+ if (pageCache === undefined) {
3043
+ emitPathInvalidation(instance, path, result.deleted, purgedPaths);
3044
+ return { deleted: result.deleted, purgedPaths };
3045
+ }
3046
+ const sharedResult = await pageCache.invalidate({
3047
+ kind: "path",
3048
+ path,
3049
+ scope: instance.prefix,
3050
+ type
3051
+ });
3052
+ for (const purged of sharedResult.paths) {
3053
+ purgedPaths.push(physicalPath(instance.prefix, purged));
3054
+ }
3055
+ const deleted = result.deleted || sharedResult.invalidated;
3056
+ emitPathInvalidation(instance, path, deleted, purgedPaths);
3057
+ return { deleted, purgedPaths };
3058
+ }
3059
+ async function revalidatePath(path, type) {
2237
3060
  let deleted = false;
2238
3061
  const purgedPaths = [];
2239
- for (const instance of allInstances()) {
2240
- const result = revalidatePathForInstance(instance, path, type);
3062
+ const results = await Promise.all(allInstances().map((instance) => invalidateInstancePath(instance, path, type)));
3063
+ for (const result of results) {
2241
3064
  deleted = result.deleted || deleted;
2242
- purgedPaths.push(`${instance.prefix}${path}`);
2243
- for (const purged of result.purgedPaths) {
2244
- purgedPaths.push(`${instance.prefix}${purged}`);
2245
- }
3065
+ purgedPaths.push(...result.purgedPaths);
2246
3066
  }
2247
- callCachePurger(dedupePaths(purgedPaths));
3067
+ callCachePurger2(dedupePaths(purgedPaths));
2248
3068
  return deleted;
2249
3069
  }
2250
3070
  function revalidatePathForInstance(instance, path, type, emitPathEvent) {
@@ -2258,17 +3078,7 @@ function revalidatePathForInstance(instance, path, type, emitPathEvent) {
2258
3078
  purgedPaths.push(...result.purgedPaths);
2259
3079
  }
2260
3080
  if (IS_DEV && emitPathEvent !== false) {
2261
- const request = currentInstrumentationRequest();
2262
- const operationId = request === undefined ? null : request.operationId;
2263
- const requestId = request === undefined ? null : request.requestId;
2264
- emitCacheInvalidated({
2265
- deleted,
2266
- operationId,
2267
- purgedPaths: new Set(purgedPaths).size,
2268
- reason: "path",
2269
- requestId,
2270
- target: path
2271
- });
3081
+ emitPathInvalidation(instance, path, deleted, purgedPaths);
2272
3082
  }
2273
3083
  });
2274
3084
  return { deleted, purgedPaths };
@@ -2278,6 +3088,7 @@ function dedupePaths(paths) {
2278
3088
  }
2279
3089
 
2280
3090
  // src/server/auto-invalidate/runtime.ts
3091
+ init_instance();
2281
3092
  function toRules(input) {
2282
3093
  return Array.isArray(input) ? input : [input];
2283
3094
  }
@@ -2365,57 +3176,83 @@ function appendPendingInvalidationHeader(set) {
2365
3176
  set.headers[headerName] = typeof existing === "string" && existing.length > 0 ? `${existing},${pending.join(",")}` : pending.join(",");
2366
3177
  return pending;
2367
3178
  }
2368
- function revalidateTag(tags) {
2369
- const tagList = typeof tags === "string" ? [tags] : [...tags];
3179
+ async function invalidateTagsForInstance(instance, tagList) {
2370
3180
  let deleted = false;
2371
3181
  const purgedPaths = new Set;
2372
- for (const instance of allInstances()) {
2373
- let instanceDeleted = false;
2374
- const instancePurgedPaths = new Set;
2375
- for (const path of getAutoInvalidateRegistry(instance).pathsForTags(tagList)) {
2376
- const logicalPath = pathWithoutSearch(path);
2377
- const result = revalidatePathForInstance(instance, logicalPath, "page", false);
2378
- deleted = result.deleted || deleted;
2379
- instanceDeleted = result.deleted || instanceDeleted;
2380
- purgedPaths.add(`${instance.prefix}${logicalPath}`);
2381
- instancePurgedPaths.add(logicalPath);
2382
- for (const purged of result.purgedPaths) {
2383
- purgedPaths.add(`${instance.prefix}${purged}`);
2384
- instancePurgedPaths.add(purged);
2385
- }
3182
+ const logicalPurgedPaths = new Set;
3183
+ const pageCache = getPageCacheAdapter(instance);
3184
+ const sharedResult = pageCache === undefined ? undefined : await pageCache.invalidate({
3185
+ kind: "tags",
3186
+ scope: instance.prefix,
3187
+ tags: tagList
3188
+ });
3189
+ if (sharedResult !== undefined) {
3190
+ deleted = sharedResult.invalidated;
3191
+ }
3192
+ const taggedPaths = new Set([
3193
+ ...getAutoInvalidateRegistry(instance).pathsForTags(tagList),
3194
+ ...sharedResult?.paths ?? []
3195
+ ]);
3196
+ for (const path of taggedPaths) {
3197
+ const logicalPath = pathWithoutSearch(path);
3198
+ const result = revalidatePathForInstance(instance, logicalPath, "page", false);
3199
+ deleted = result.deleted || deleted;
3200
+ purgedPaths.add(physicalPath(instance.prefix, logicalPath));
3201
+ logicalPurgedPaths.add(logicalPath);
3202
+ for (const purged of result.purgedPaths) {
3203
+ purgedPaths.add(physicalPath(instance.prefix, purged));
3204
+ logicalPurgedPaths.add(purged);
2386
3205
  }
2387
- if (IS_DEV) {
2388
- withInstance(instance, () => {
2389
- const request = currentInstrumentationRequest();
2390
- const operationId = request === undefined ? null : request.operationId;
2391
- const requestId = request === undefined ? null : request.requestId;
2392
- emitCacheInvalidated({
2393
- deleted: instanceDeleted,
2394
- operationId,
2395
- purgedPaths: instancePurgedPaths.size,
2396
- reason: "tag",
2397
- requestId,
2398
- target: tagList.join(",")
2399
- });
3206
+ }
3207
+ if (IS_DEV) {
3208
+ withInstance(instance, () => {
3209
+ const request = currentInstrumentationRequest();
3210
+ const operationId = request === undefined ? null : request.operationId;
3211
+ const requestId = request === undefined ? null : request.requestId;
3212
+ emitCacheInvalidated({
3213
+ deleted,
3214
+ operationId,
3215
+ purgedPaths: logicalPurgedPaths.size,
3216
+ reason: "tag",
3217
+ requestId,
3218
+ target: tagList.join(",")
2400
3219
  });
3220
+ });
3221
+ }
3222
+ return { deleted, purgedPaths: [...purgedPaths] };
3223
+ }
3224
+ async function revalidateTag(tags) {
3225
+ const tagList = typeof tags === "string" ? [tags] : [...tags];
3226
+ callCacheTagPurger(tagList);
3227
+ const results = await Promise.all(allInstances().map((instance) => invalidateTagsForInstance(instance, tagList)));
3228
+ const purgedPaths = new Set;
3229
+ let deleted = false;
3230
+ for (const result of results) {
3231
+ deleted = result.deleted || deleted;
3232
+ for (const path of result.purgedPaths) {
3233
+ purgedPaths.add(path);
2401
3234
  }
2402
3235
  }
2403
- callCachePurger([...purgedPaths]);
3236
+ callCachePurger2([...purgedPaths]);
2404
3237
  return deleted;
2405
3238
  }
2406
- function runInvalidationRules(input) {
2407
- let deleted = false;
2408
- for (const rule of toRules(input)) {
3239
+ async function runInvalidationRules(input) {
3240
+ const operations = toRules(input).flatMap((rule) => {
3241
+ const pending = [];
2409
3242
  if ("path" in rule && rule.path) {
2410
- deleted = revalidatePath(rule.path, rule.type) || deleted;
3243
+ pending.push(revalidatePath(rule.path, rule.type));
2411
3244
  }
2412
3245
  if (rule.tags && rule.tags.length > 0) {
2413
- deleted = revalidateTag(rule.tags) || deleted;
3246
+ pending.push(revalidateTag(rule.tags));
2414
3247
  }
2415
- }
2416
- return deleted;
3248
+ return pending;
3249
+ });
3250
+ return (await Promise.all(operations)).some(Boolean);
2417
3251
  }
2418
3252
 
3253
+ // src/server/sync/plugin.ts
3254
+ init_context_logger();
3255
+
2419
3256
  // src/server/sync/fingerprint.ts
2420
3257
  function compareCodePoints(left, right) {
2421
3258
  if (left === right) {
@@ -2451,7 +3288,7 @@ function createMutationFingerprint(input) {
2451
3288
  }
2452
3289
 
2453
3290
  // src/server/sync/response.ts
2454
- import { ElysiaCustomStatusResponse, StatusMap } from "elysia";
3291
+ import { ElysiaStatus, StatusMap } from "elysia";
2455
3292
  var NON_REPLAYABLE_HEADERS = new Set([
2456
3293
  "authorization",
2457
3294
  "connection",
@@ -2475,10 +3312,10 @@ function statusCode(status) {
2475
3312
  return status === undefined ? 200 : StatusMap[status];
2476
3313
  }
2477
3314
  function unwrapStatusResponse(value) {
2478
- if (!(value instanceof ElysiaCustomStatusResponse)) {
3315
+ if (!(value instanceof ElysiaStatus)) {
2479
3316
  return;
2480
3317
  }
2481
- return { status: value.code, value: value.response };
3318
+ return { status: value.status, value: value.response };
2482
3319
  }
2483
3320
  function responseHeaders(headers) {
2484
3321
  const result = new Headers;
@@ -2618,26 +3455,8 @@ function replayResponse(stored) {
2618
3455
  });
2619
3456
  }
2620
3457
 
2621
- // src/server/sync/runtime.ts
2622
- var POLL_INTERVAL_MS = 250;
2623
- var pollingNotifiers = new WeakMap;
2624
- function resolveSyncRuntime(options) {
2625
- if (!IS_DEV && options.adapter.scope === "process-local") {
2626
- throw new Error("[furin] Production sync cannot use a process-local SyncAdapter.");
2627
- }
2628
- if (options.notifier) {
2629
- return { adapter: options.adapter, notifier: options.notifier };
2630
- }
2631
- const existing = pollingNotifiers.get(options.adapter);
2632
- if (existing) {
2633
- return { adapter: options.adapter, notifier: existing };
2634
- }
2635
- const notifier = new PollingSyncNotifier(options.adapter, POLL_INTERVAL_MS);
2636
- pollingNotifiers.set(options.adapter, notifier);
2637
- return { adapter: options.adapter, notifier };
2638
- }
2639
-
2640
3458
  // src/server/sync/plugin.ts
3459
+ init_runtime();
2641
3460
  var routeMetadata = new WeakMap;
2642
3461
  var activeMutations = new WeakMap;
2643
3462
  function hideTransportResponse(hook) {
@@ -2764,8 +3583,13 @@ function furinSync(options) {
2764
3583
  const result = await storeResponse(ctx.responseValue, ctx.set);
2765
3584
  const manualPending = peekPendingInvalidations();
2766
3585
  const invalidate = routeMetadata.get(ctx.request)?.invalidate;
3586
+ const logger = getLogger();
2767
3587
  if (invalidate) {
2768
- runInvalidationRules(invalidate);
3588
+ try {
3589
+ await runInvalidationRules(invalidate);
3590
+ } catch {
3591
+ logger.warn("Sync cache invalidation failed after mutation; preserving the idempotent result");
3592
+ }
2769
3593
  }
2770
3594
  const pending = appendPendingInvalidationHeader(ctx.set);
2771
3595
  if (pending.length > 0) {
@@ -2788,7 +3612,8 @@ function furinSync(options) {
2788
3612
  if (completion.kind === "lost") {
2789
3613
  return leaseLostResponse();
2790
3614
  }
2791
- if (completion.cursor !== undefined) {
3615
+ const notificationAlreadyPublished = runtime.adapter.notificationChannel !== undefined && runtime.adapter.notificationChannel === runtime.notifier.notificationChannel;
3616
+ if (completion.cursor !== undefined && !notificationAlreadyPublished) {
2792
3617
  runtime.notifier.publish(completion.cursor).catch(() => {
2793
3618
  return;
2794
3619
  });
@@ -2822,7 +3647,7 @@ function furinSync(options) {
2822
3647
  }
2823
3648
  const beginMutationHook = hideTransportResponse(beginMutation);
2824
3649
  const finishMutationHook = hideTransportResponse(finishMutation);
2825
- return new Elysia({ name: "furin-sync" }).macro({
3650
+ return new Elysia3({ name: "furin-sync" }).beforeHandle("global", beginMutationHook).afterHandle("global", finishMutationHook).error("global", ({ request }) => abortMutation(request)).macro({
2826
3651
  sync(input) {
2827
3652
  return {
2828
3653
  transform({ request }) {
@@ -2830,194 +3655,22 @@ function furinSync(options) {
2830
3655
  }
2831
3656
  };
2832
3657
  }
2833
- }).onBeforeHandle({ as: "global" }, beginMutationHook).onAfterHandle({ as: "global" }, finishMutationHook).onError({ as: "global" }, ({ request }) => abortMutation(request));
2834
- }
2835
-
2836
- // src/server/sync/stream.ts
2837
- import { Elysia as Elysia2 } from "elysia";
2838
- var DEFAULT_CHANGE_LIMIT = 100;
2839
- var MAX_CHANGE_LIMIT = 500;
2840
- var MAX_STREAM_CLIENTS = 100;
2841
- var MAX_CURSOR_LENGTH = 128;
2842
- var SAFETY_POLL_INTERVAL_MS = IS_DEV ? 250 : 15000;
2843
- var UNSIGNED_INTEGER_PATTERN = /^\d+$/;
2844
- var defaultStreamPath = "/_furin/sync";
2845
- var encoder = new TextEncoder;
2846
- var noOpSubscription = {
2847
- unsubscribe: () => Promise.resolve()
2848
- };
2849
- var streams = new Map;
2850
- var resolvedStates = new Set;
2851
- function encodeSseCursor(cursor) {
2852
- return encoder.encode(`id: ${cursor}
2853
- event: furin.sync
2854
- retry: 3000
2855
- data: ${JSON.stringify({ cursor })}
2856
-
2857
- `);
2858
- }
2859
- function closeClient(state, client) {
2860
- const heartbeat = state.clients.get(client);
2861
- state.clients.delete(client);
2862
- if (heartbeat) {
2863
- clearInterval(heartbeat);
2864
- }
2865
- try {
2866
- client.close();
2867
- } catch {}
2868
- }
2869
- function notifyState(state, cursor) {
2870
- if (state.cursor === cursor) {
2871
- return;
2872
- }
2873
- state.cursor = cursor;
2874
- const chunk = encodeSseCursor(cursor);
2875
- for (const client of state.clients.keys()) {
2876
- if (client.desiredSize === null || client.desiredSize <= 0) {
2877
- closeClient(state, client);
2878
- continue;
2879
- }
2880
- try {
2881
- client.enqueue(chunk);
2882
- } catch {
2883
- closeClient(state, client);
2884
- }
2885
- }
2886
- }
2887
- async function createStreamState(runtime) {
2888
- const state = {};
2889
- state.clients = new Map;
2890
- state.cursor = await runtime.adapter.currentCursor();
2891
- state.safetyPoll = setInterval(() => {
2892
- runtime.adapter.currentCursor().then((cursor) => notifyState(state, cursor)).catch(() => {
2893
- return;
2894
- });
2895
- }, SAFETY_POLL_INTERVAL_MS);
2896
- state.safetyPoll.unref?.();
2897
- state.subscription = await runtime.notifier.subscribe((cursor) => notifyState(state, cursor)).catch(() => noOpSubscription);
2898
- resolvedStates.add(state);
2899
- return state;
2900
- }
2901
- function getStreamState(runtime) {
2902
- const existing = streams.get(runtime.adapter);
2903
- if (existing) {
2904
- return existing;
2905
- }
2906
- const state = createStreamState(runtime);
2907
- streams.set(runtime.adapter, state);
2908
- state.catch(() => {
2909
- if (streams.get(runtime.adapter) === state) {
2910
- streams.delete(runtime.adapter);
2911
- }
2912
- });
2913
- return state;
2914
- }
2915
- function parseChangeQuery(request) {
2916
- const url = new URL(request.url);
2917
- const after = url.searchParams.get("after") ?? undefined;
2918
- if (after !== undefined && (after.length === 0 || after.length > MAX_CURSOR_LENGTH)) {
2919
- return { error: Response.json({ code: "FURIN_INVALID_SYNC_CURSOR" }, { status: 400 }) };
2920
- }
2921
- const limitValue = url.searchParams.get("limit");
2922
- if (limitValue !== null && !UNSIGNED_INTEGER_PATTERN.test(limitValue)) {
2923
- return { error: Response.json({ code: "FURIN_INVALID_SYNC_LIMIT" }, { status: 400 }) };
2924
- }
2925
- const limit = limitValue === null ? DEFAULT_CHANGE_LIMIT : Number.parseInt(limitValue, 10);
2926
- if (!Number.isInteger(limit) || limit < 1 || limit > MAX_CHANGE_LIMIT) {
2927
- return { error: Response.json({ code: "FURIN_INVALID_SYNC_LIMIT" }, { status: 400 }) };
2928
- }
2929
- return { after, limit };
2930
- }
2931
- function clientInvalidations(change) {
2932
- const entries = new Set;
2933
- for (const invalidation of change.invalidations) {
2934
- if (invalidation.kind === "tags") {
2935
- entries.add("/:layout");
2936
- } else {
2937
- entries.add(invalidation.type === "layout" ? `${invalidation.path}:layout` : invalidation.path);
2938
- }
2939
- }
2940
- return [...entries];
2941
- }
2942
- function createSyncStreamPlugin(options) {
2943
- const streamPath = options.streamPath ?? defaultStreamPath;
2944
- const runtime = resolveSyncRuntime(syncRuntimeOptions(options));
2945
- return new Elysia2({ name: `furin-sync-stream-${streamPath}` }).get(`${streamPath}/changes`, async ({ request, set }) => {
2946
- set.headers["cache-control"] = "no-store";
2947
- const query = parseChangeQuery(request);
2948
- if ("error" in query) {
2949
- return query.error;
2950
- }
2951
- const page = await runtime.adapter.readChanges(query);
2952
- return {
2953
- ...page,
2954
- changes: page.changes.map((change) => ({
2955
- cursor: change.cursor,
2956
- invalidations: clientInvalidations(change)
2957
- }))
2958
- };
2959
- }).get(streamPath, async () => {
2960
- const state = await getStreamState(runtime);
2961
- if (state.clients.size >= MAX_STREAM_CLIENTS) {
2962
- return Response.json({ code: "FURIN_SYNC_STREAM_CAPACITY" }, { status: 503 });
2963
- }
2964
- let controllerRef;
2965
- let heartbeat;
2966
- const stream = new ReadableStream({
2967
- cancel() {
2968
- if (controllerRef) {
2969
- closeClient(state, controllerRef);
2970
- }
2971
- if (heartbeat) {
2972
- clearInterval(heartbeat);
2973
- }
2974
- },
2975
- start(controller) {
2976
- controllerRef = controller;
2977
- controller.enqueue(encoder.encode(`: connected
2978
- retry: 3000
2979
-
2980
- `));
2981
- state.clients.set(controller, undefined);
2982
- heartbeat = setInterval(() => {
2983
- if (controller.desiredSize === null || controller.desiredSize <= 0) {
2984
- closeClient(state, controller);
2985
- return;
2986
- }
2987
- try {
2988
- controller.enqueue(encoder.encode(`: heartbeat
2989
-
2990
- `));
2991
- } catch {
2992
- closeClient(state, controller);
2993
- }
2994
- }, 15000);
2995
- heartbeat.unref?.();
2996
- state.clients.set(controller, heartbeat);
2997
- }
2998
- });
2999
- return new Response(stream, {
3000
- headers: {
3001
- "cache-control": "no-cache, no-transform",
3002
- connection: "keep-alive",
3003
- "content-type": "text/event-stream; charset=utf-8"
3004
- }
3005
- });
3006
3658
  });
3007
3659
  }
3008
3660
 
3009
3661
  // src/server/sync/index.ts
3010
- var createSyncStreamPlugin2 = createSyncStreamPlugin;
3662
+ init_stream();
3663
+ var createSyncChangesPlugin2 = createSyncChangesPlugin;
3011
3664
  var furinSync2 = furinSync;
3012
- var getSyncStreamPath2 = getSyncStreamPath;
3665
+ var getSyncPath2 = getSyncPath;
3013
3666
  var PollingSyncNotifier2 = PollingSyncNotifier;
3014
- var resolveSyncStreamPath2 = resolveSyncStreamPath;
3015
- var runWithSyncStreamPath2 = runWithSyncStreamPath;
3667
+ var resolveSyncPath2 = resolveSyncPath;
3668
+ var runWithSyncPath2 = runWithSyncPath;
3016
3669
  export {
3017
3670
  PollingSyncNotifier2 as PollingSyncNotifier,
3018
- createSyncStreamPlugin2 as createSyncStreamPlugin,
3671
+ createSyncChangesPlugin2 as createSyncChangesPlugin,
3019
3672
  furinSync2 as furinSync,
3020
- getSyncStreamPath2 as getSyncStreamPath,
3021
- resolveSyncStreamPath2 as resolveSyncStreamPath,
3022
- runWithSyncStreamPath2 as runWithSyncStreamPath
3673
+ getSyncPath2 as getSyncPath,
3674
+ resolveSyncPath2 as resolveSyncPath,
3675
+ runWithSyncPath2 as runWithSyncPath
3023
3676
  };