@teyik0/furin 0.4.0-alpha.2 → 0.5.0-alpha.2

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 (129) hide show
  1. package/dist/build/compile-entry.d.ts +2 -1
  2. package/dist/build/compile-entry.ts +17 -13
  3. package/dist/build/elysia-aot.d.ts +9 -0
  4. package/dist/build/entry-template.d.ts +5 -1
  5. package/dist/build/entry-template.ts +27 -6
  6. package/dist/build/index.js +969 -528
  7. package/dist/build/private-server-sourcemaps.d.ts +2 -0
  8. package/dist/build/server-app-entry.d.ts +12 -0
  9. package/dist/build/types.d.ts +2 -0
  10. package/dist/cache.d.ts +1 -0
  11. package/dist/cache.js +185 -0
  12. package/dist/cli/index.js +983 -541
  13. package/dist/client/document.d.ts +2 -0
  14. package/dist/client/internal/runtime-types.d.ts +8 -1
  15. package/dist/client/link.js +232 -11
  16. package/dist/client/sync.d.ts +1 -0
  17. package/dist/client.js +11 -0
  18. package/dist/config.d.ts +28 -22
  19. package/dist/config.js +25 -2
  20. package/dist/define-route.d.ts +273 -1009
  21. package/dist/furin.d.ts +20 -5
  22. package/dist/furin.js +6431 -5457
  23. package/dist/plugin/routes.d.ts +6 -0
  24. package/dist/rsc-client.js +9 -1
  25. package/dist/rsc.js +19 -7
  26. package/dist/server/assets/production.d.ts +3 -0
  27. package/dist/server/auto-invalidate/plugin.d.ts +8 -24
  28. package/dist/server/auto-invalidate/runtime.d.ts +2 -2
  29. package/dist/server/browser-events/shutdown.d.ts +3 -0
  30. package/dist/server/cache/invalidation.d.ts +1 -1
  31. package/dist/server/cache/page-cache-state.d.ts +5 -0
  32. package/dist/server/cache/page-cache.d.ts +53 -0
  33. package/dist/server/cache/redis/index.d.ts +41 -0
  34. package/dist/server/cache/redis/index.js +451 -0
  35. package/dist/server/cache/redis/scripts.d.ts +6 -0
  36. package/dist/server/context-logger.d.ts +2 -2
  37. package/dist/server/dev/plugin.d.ts +1 -0
  38. package/dist/server/dev/runtime.production.d.ts +1 -0
  39. package/dist/server/dev-page-plugin.d.ts +7 -0
  40. package/dist/server/evlog.d.ts +14 -0
  41. package/dist/server/internal.d.ts +6 -0
  42. package/dist/server/internal.js +2539 -0
  43. package/dist/server/production-server.d.ts +13 -0
  44. package/dist/server/production-server.js +2906 -0
  45. package/dist/server/render/not-found.d.ts +1 -1
  46. package/dist/server/render/ssg.d.ts +5 -0
  47. package/dist/server/render/static-params.d.ts +4 -0
  48. package/dist/server/router/defined-route.d.ts +1 -1
  49. package/dist/server/router/hmr.d.ts +6 -0
  50. package/dist/server/router/hmr.production.d.ts +5 -0
  51. package/dist/server/router/plugin.d.ts +5 -1
  52. package/dist/server/router/schemas.d.ts +1 -0
  53. package/dist/server/sync/index.js +798 -117
  54. package/dist/server/sync/plugin.d.ts +31 -158
  55. package/dist/server/sync/stream.d.ts +38 -49
  56. package/dist/shared/elysia-contract.d.ts +8 -14
  57. package/dist/shared/production-build.d.ts +2 -0
  58. package/package.json +19 -8
  59. package/src/adapter/README.md +9 -2
  60. package/src/adapter/bun.ts +146 -41
  61. package/src/adapter/package.ts +6 -2
  62. package/src/adapter/runtime-build.ts +11 -4
  63. package/src/adapter/static.ts +8 -6
  64. package/src/adapter/vercel.ts +64 -31
  65. package/src/build/client.ts +18 -1
  66. package/src/build/compile-entry.ts +17 -13
  67. package/src/build/elysia-aot.ts +102 -0
  68. package/src/build/entry-template.ts +27 -6
  69. package/src/build/hydrate.ts +5 -1
  70. package/src/build/index.ts +5 -5
  71. package/src/build/private-server-sourcemaps.ts +20 -0
  72. package/src/build/production-instrumentation.ts +2 -2
  73. package/src/build/server-app-entry.ts +61 -0
  74. package/src/build/shared.ts +3 -1
  75. package/src/build/ssg-cache.ts +5 -10
  76. package/src/build/types.ts +2 -0
  77. package/src/build/virtual-entry.ts +5 -4
  78. package/src/cache.ts +12 -0
  79. package/src/cli/config.ts +3 -3
  80. package/src/cli/index.ts +6 -2
  81. package/src/client/document.tsx +19 -0
  82. package/src/client/internal/runtime-types.ts +10 -1
  83. package/src/client/sync.ts +1 -0
  84. package/src/config.ts +33 -4
  85. package/src/define-route.ts +266 -128
  86. package/src/furin.ts +168 -154
  87. package/src/plugin/route-config-autofix.ts +11 -2
  88. package/src/plugin/routes.ts +85 -29
  89. package/src/rsc/codec.ts +11 -6
  90. package/src/rsc/render-error.ts +3 -1
  91. package/src/server/assets/production.ts +99 -0
  92. package/src/server/auto-invalidate/plugin.ts +4 -4
  93. package/src/server/auto-invalidate/runtime.ts +74 -42
  94. package/src/server/browser-events/plugin.ts +13 -1
  95. package/src/server/browser-events/shutdown.ts +32 -0
  96. package/src/server/cache/invalidation.ts +61 -20
  97. package/src/server/cache/page-cache-state.ts +22 -0
  98. package/src/server/cache/page-cache.ts +300 -0
  99. package/src/server/cache/redis/index.ts +367 -0
  100. package/src/server/cache/redis/scripts.ts +200 -0
  101. package/src/server/context-logger.ts +5 -5
  102. package/src/server/dev/plugin.ts +10 -1
  103. package/src/server/dev/runtime.production.ts +4 -0
  104. package/src/server/dev-page-plugin.ts +54 -10
  105. package/src/server/evlog.ts +106 -0
  106. package/src/server/internal.ts +7 -0
  107. package/src/server/production-server.ts +135 -0
  108. package/src/server/render/document.tsx +7 -1
  109. package/src/server/render/isr.ts +480 -132
  110. package/src/server/render/loaders.ts +18 -12
  111. package/src/server/render/not-found.ts +4 -4
  112. package/src/server/render/ppr-document.ts +2 -2
  113. package/src/server/render/ppr-route.ts +193 -7
  114. package/src/server/render/ssg.ts +148 -4
  115. package/src/server/render/ssr.ts +6 -7
  116. package/src/server/render/static-params.ts +174 -0
  117. package/src/server/render/template.ts +5 -1
  118. package/src/server/router/defined-route.ts +2 -1
  119. package/src/server/router/discovery.ts +3 -1
  120. package/src/server/router/hmr.production.ts +11 -0
  121. package/src/server/router/hmr.ts +85 -76
  122. package/src/server/router/plugin.ts +118 -50
  123. package/src/server/router/schema-merge.ts +10 -3
  124. package/src/server/router/schemas.ts +174 -61
  125. package/src/server/sync/plugin.ts +14 -10
  126. package/src/server/sync/response.ts +3 -3
  127. package/src/server/sync/stream.ts +43 -2
  128. package/src/shared/elysia-contract.ts +23 -25
  129. package/src/shared/production-build.ts +20 -0
@@ -0,0 +1,2906 @@
1
+ // @bun
2
+ // src/server/browser-events/shutdown.ts
3
+ var closeConnections = new WeakMap;
4
+ function closeBrowserEventConnections(server) {
5
+ const connections = closeConnections.get(server);
6
+ if (!connections) {
7
+ return;
8
+ }
9
+ closeConnections.delete(server);
10
+ for (const close of connections) {
11
+ close();
12
+ }
13
+ connections.clear();
14
+ }
15
+
16
+ // src/server/instance.ts
17
+ import { AsyncLocalStorage } from "async_hooks";
18
+ var _requestScope = new AsyncLocalStorage;
19
+ var _instances = new Map;
20
+ var _defaultInstance = null;
21
+ function createInstance(prefix, pagesDir) {
22
+ return {
23
+ buildId: "",
24
+ pagesDir,
25
+ prefix,
26
+ registrationEpoch: 0,
27
+ state: new Map,
28
+ syncPath: undefined
29
+ };
30
+ }
31
+ function defaultInstance() {
32
+ if (!_defaultInstance) {
33
+ _defaultInstance = createInstance("", "");
34
+ }
35
+ return _defaultInstance;
36
+ }
37
+ function currentInstance() {
38
+ const scope = _requestScope.getStore();
39
+ if (scope) {
40
+ return scope.instance;
41
+ }
42
+ if (_instances.size === 1) {
43
+ const only = _instances.values().next().value;
44
+ if (only) {
45
+ return only;
46
+ }
47
+ }
48
+ return defaultInstance();
49
+ }
50
+ function allStateBuckets() {
51
+ const buckets = [..._instances.values()];
52
+ const fallback = defaultInstance();
53
+ if (!buckets.includes(fallback)) {
54
+ buckets.push(fallback);
55
+ }
56
+ return buckets;
57
+ }
58
+ function instanceSlot(init) {
59
+ const key = Symbol("furin-instance-slot");
60
+ return (instance) => {
61
+ const target = instance ?? currentInstance();
62
+ if (target.state.has(key)) {
63
+ return target.state.get(key);
64
+ }
65
+ const value = init(target);
66
+ target.state.set(key, value);
67
+ return value;
68
+ };
69
+ }
70
+
71
+ // src/server/auto-invalidate/registry.ts
72
+ class AutoInvalidateRegistry {
73
+ pathToTags = new Map;
74
+ tagToPaths = new Map;
75
+ registerLoaderTags(urlPath, tags) {
76
+ if (!tags || tags.length === 0) {
77
+ this.unregisterPath(urlPath);
78
+ return;
79
+ }
80
+ this.unregisterPath(urlPath);
81
+ const uniqueTags = new Set(tags);
82
+ this.pathToTags.set(urlPath, uniqueTags);
83
+ for (const tag of uniqueTags) {
84
+ let paths = this.tagToPaths.get(tag);
85
+ if (!paths) {
86
+ paths = new Set;
87
+ this.tagToPaths.set(tag, paths);
88
+ }
89
+ paths.add(urlPath);
90
+ }
91
+ }
92
+ pathsForTags(tags) {
93
+ const paths = new Set;
94
+ for (const tag of tags) {
95
+ for (const path of this.tagToPaths.get(tag) ?? []) {
96
+ paths.add(path);
97
+ }
98
+ }
99
+ return [...paths];
100
+ }
101
+ unregisterPath(urlPath) {
102
+ const tags = this.pathToTags.get(urlPath);
103
+ if (!tags) {
104
+ return;
105
+ }
106
+ for (const tag of tags) {
107
+ const paths = this.tagToPaths.get(tag);
108
+ if (!paths) {
109
+ continue;
110
+ }
111
+ paths.delete(urlPath);
112
+ if (paths.size === 0) {
113
+ this.tagToPaths.delete(tag);
114
+ }
115
+ }
116
+ this.pathToTags.delete(urlPath);
117
+ }
118
+ reset() {
119
+ this.pathToTags.clear();
120
+ this.tagToPaths.clear();
121
+ }
122
+ }
123
+ var instanceAutoInvalidateRegistry = instanceSlot(() => new AutoInvalidateRegistry);
124
+ var autoInvalidateRegistry = {
125
+ pathsForTags: (tags) => instanceAutoInvalidateRegistry().pathsForTags(tags),
126
+ registerLoaderTags: (urlPath, tags) => instanceAutoInvalidateRegistry().registerLoaderTags(urlPath, tags),
127
+ reset: () => instanceAutoInvalidateRegistry().reset(),
128
+ unregisterPath: (urlPath) => instanceAutoInvalidateRegistry().unregisterPath(urlPath)
129
+ };
130
+
131
+ // src/server/cache/route-cache.ts
132
+ function defaultPathFromKey(key) {
133
+ return key;
134
+ }
135
+ function pathWithoutSearch(path) {
136
+ const searchStart = path.indexOf("?");
137
+ if (searchStart === -1) {
138
+ return path;
139
+ }
140
+ return path.slice(0, searchStart);
141
+ }
142
+ function matchesPath(urlPath, path, type) {
143
+ if (type === "page") {
144
+ return urlPath === path;
145
+ }
146
+ const prefix = path === "/" || path.endsWith("/") ? path : `${path}/`;
147
+ return urlPath === path || urlPath.startsWith(prefix);
148
+ }
149
+ function createRouteCache(options) {
150
+ const store = new Map;
151
+ const pathFromKey = options.pathFromKey ?? defaultPathFromKey;
152
+ const evictOldest = () => {
153
+ if (options.maxSize === undefined || store.size <= options.maxSize) {
154
+ return;
155
+ }
156
+ const oldest = store.keys().next().value;
157
+ if (oldest !== undefined) {
158
+ deleteEntry(oldest);
159
+ }
160
+ };
161
+ const deleteEntry = (key) => {
162
+ const entry = store.get(key);
163
+ if (entry === undefined) {
164
+ return false;
165
+ }
166
+ store.delete(key);
167
+ options.onDelete?.(key, entry);
168
+ return true;
169
+ };
170
+ return {
171
+ clear() {
172
+ for (const key of [...store.keys()]) {
173
+ deleteEntry(key);
174
+ }
175
+ store.clear();
176
+ },
177
+ delete(key) {
178
+ return deleteEntry(key);
179
+ },
180
+ entries() {
181
+ return store.entries();
182
+ },
183
+ get(key) {
184
+ const entry = store.get(key);
185
+ if (entry !== undefined && options.maxSize !== undefined) {
186
+ store.delete(key);
187
+ store.set(key, entry);
188
+ }
189
+ return entry;
190
+ },
191
+ has(key) {
192
+ return store.has(key);
193
+ },
194
+ invalidatePath(path, type) {
195
+ let deleted = false;
196
+ const purgedPaths = [];
197
+ for (const key of [...store.keys()]) {
198
+ const urlPath = pathFromKey(key);
199
+ if (urlPath === null || !matchesPath(urlPath, path, type)) {
200
+ continue;
201
+ }
202
+ deleteEntry(key);
203
+ deleted = true;
204
+ purgedPaths.push(urlPath);
205
+ }
206
+ return { deleted, purgedPaths: [...new Set(purgedPaths)] };
207
+ },
208
+ keys() {
209
+ return store.keys();
210
+ },
211
+ name: options.name,
212
+ set(key, entry) {
213
+ const previous = store.get(key);
214
+ if (previous !== undefined) {
215
+ store.delete(key);
216
+ }
217
+ store.set(key, entry);
218
+ options.onSet?.(key, entry, previous);
219
+ evictOldest();
220
+ },
221
+ get size() {
222
+ return store.size;
223
+ },
224
+ store
225
+ };
226
+ }
227
+
228
+ // src/server/cache/isr-ssg.ts
229
+ var MAX_HTML_CACHE_SIZE = 1000;
230
+ function createHtmlRouteCache(mode, options) {
231
+ return createRouteCache({
232
+ maxSize: MAX_HTML_CACHE_SIZE,
233
+ name: `render:${mode}-html`,
234
+ onDelete: (key, entry) => {
235
+ autoInvalidateRegistry.unregisterPath(key);
236
+ options?.onDelete?.(key, entry);
237
+ },
238
+ pathFromKey: pathWithoutSearch
239
+ });
240
+ }
241
+
242
+ // src/server/cache/registry.ts
243
+ var instanceInvalidators = instanceSlot(() => new Map);
244
+ function registerCacheInvalidator(invalidator, instance) {
245
+ const invalidators = instanceInvalidators(instance);
246
+ const existing = invalidators.get(invalidator.name);
247
+ if (existing !== undefined && existing !== invalidator) {
248
+ throw new Error(`Cache invalidator "${invalidator.name}" is already registered for this furin instance with a different invalidator object.`);
249
+ }
250
+ invalidators.set(invalidator.name, invalidator);
251
+ return () => {
252
+ if (invalidators.get(invalidator.name) === invalidator) {
253
+ invalidators.delete(invalidator.name);
254
+ }
255
+ };
256
+ }
257
+
258
+ // src/server/cache/store-view.ts
259
+ function createStoreView(resolve) {
260
+ return {
261
+ clear: () => resolve().clear(),
262
+ delete: (key) => resolve().delete(key),
263
+ entries: () => resolve().entries(),
264
+ get: (key) => resolve().get(key),
265
+ has: (key) => resolve().has(key),
266
+ keys: () => resolve().keys(),
267
+ set: (key, entry) => {
268
+ resolve().set(key, entry);
269
+ },
270
+ get size() {
271
+ return resolve().size;
272
+ }
273
+ };
274
+ }
275
+
276
+ // src/server/cache/isr.ts
277
+ var instanceIsrCache = instanceSlot((instance) => {
278
+ const generations = new Map;
279
+ const pendingRevalidations = new Map;
280
+ const cache = createHtmlRouteCache("isr", {
281
+ onDelete: (key) => {
282
+ const pending = generations.get(key);
283
+ if (pending === undefined) {
284
+ return;
285
+ }
286
+ for (const generation of pending) {
287
+ generation.valid = false;
288
+ }
289
+ generations.delete(key);
290
+ }
291
+ });
292
+ registerCacheInvalidator(cache, instance);
293
+ return { cache, generations, pendingRevalidations };
294
+ });
295
+ var isrCache = createStoreView(() => instanceIsrCache().cache.store);
296
+ async function waitForPendingISRRevalidations() {
297
+ const pending = allStateBuckets().flatMap((instance) => [
298
+ ...instanceIsrCache(instance).pendingRevalidations.values()
299
+ ]);
300
+ if (pending.length === 0) {
301
+ return;
302
+ }
303
+ await Promise.allSettled(pending);
304
+ await Bun.sleep(1);
305
+ }
306
+
307
+ // src/server/evlog.ts
308
+ import { Elysia } from "elysia";
309
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
310
+ function shouldDeferEmitForResponse(response) {
311
+ if (!response.body)
312
+ return false;
313
+ const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
314
+ if (contentType.includes("text/event-stream"))
315
+ return true;
316
+ if (contentType.includes("application/x-ndjson"))
317
+ return true;
318
+ if (response.headers.has("x-vercel-ai-ui-message-stream"))
319
+ return true;
320
+ if (response.headers.get("transfer-encoding")?.toLowerCase().includes("chunked"))
321
+ return true;
322
+ return false;
323
+ }
324
+ function toError(value) {
325
+ return value instanceof Error ? value : new Error(String(value));
326
+ }
327
+ function createObservedBody(body, onDone, onError) {
328
+ if (body.locked) {
329
+ Promise.resolve(onError(/* @__PURE__ */ new TypeError("stream is already locked"))).catch((err) => {
330
+ console.error("[evlog] stream error handling failed:", err);
331
+ });
332
+ return null;
333
+ }
334
+ const reader = body.getReader();
335
+ let settled = false;
336
+ const settle = (fn) => {
337
+ if (settled)
338
+ return;
339
+ settled = true;
340
+ Promise.resolve(fn()).catch((err) => {
341
+ console.error("[evlog] stream completion handling failed:", err);
342
+ });
343
+ };
344
+ return new ReadableStream({
345
+ async pull(controller) {
346
+ try {
347
+ const { done, value } = await reader.read();
348
+ if (done) {
349
+ settle(onDone);
350
+ controller.close();
351
+ return;
352
+ }
353
+ controller.enqueue(value);
354
+ } catch (err) {
355
+ settle(() => onError(err));
356
+ controller.error(err);
357
+ }
358
+ },
359
+ async cancel(reason) {
360
+ try {
361
+ await reader.cancel(reason);
362
+ } finally {
363
+ settle(onDone);
364
+ }
365
+ }
366
+ });
367
+ }
368
+ function bindStreamingResponseLifecycle(response, onComplete) {
369
+ if (!response.body) {
370
+ Promise.resolve(onComplete({ status: response.status })).catch((err) => {
371
+ console.error("[evlog] stream completion handling failed:", err);
372
+ });
373
+ return response;
374
+ }
375
+ const body = createObservedBody(response.body, () => onComplete({ status: response.status }), (err) => onComplete({
376
+ status: response.status,
377
+ error: toError(err)
378
+ }));
379
+ if (!body)
380
+ return response;
381
+ return new Response(body, {
382
+ status: response.status,
383
+ statusText: response.statusText,
384
+ headers: response.headers
385
+ });
386
+ }
387
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/utils.mjs
388
+ function elapsedMs(startTime) {
389
+ return Math.max(0, Date.now() - startTime);
390
+ }
391
+ function formatDuration(ms) {
392
+ if (ms < 1000)
393
+ return `${Math.round(ms)}ms`;
394
+ return `${(ms / 1000).toFixed(2)}s`;
395
+ }
396
+ function isServer() {
397
+ return typeof window === "undefined";
398
+ }
399
+ function isBrowser() {
400
+ if (typeof window === "undefined")
401
+ return false;
402
+ if (typeof document === "undefined")
403
+ return false;
404
+ if (typeof navigator !== "undefined" && navigator.product === "ReactNative")
405
+ return false;
406
+ return true;
407
+ }
408
+ function isDev() {
409
+ if (typeof process !== "undefined")
410
+ return true;
411
+ if (typeof window !== "undefined")
412
+ return true;
413
+ return false;
414
+ }
415
+ function detectEnvironment() {
416
+ const env = typeof process !== "undefined" ? process.env : {};
417
+ const defaultEnvironment = isDev() ? "development" : "production";
418
+ return {
419
+ environment: env.NODE_ENV || defaultEnvironment,
420
+ service: env.SERVICE_NAME || "app",
421
+ version: env.APP_VERSION,
422
+ commitHash: env.COMMIT_SHA || env.GITHUB_SHA || env.VERCEL_GIT_COMMIT_SHA || env.CF_PAGES_COMMIT_SHA,
423
+ region: env.VERCEL_REGION || env.AWS_REGION || env.FLY_REGION || env.CF_REGION
424
+ };
425
+ }
426
+ var LEVEL_ORDER = {
427
+ debug: 0,
428
+ info: 1,
429
+ warn: 2,
430
+ error: 3
431
+ };
432
+ function isLevelEnabled(level, minLevel) {
433
+ return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];
434
+ }
435
+ function getConsoleMethod(level) {
436
+ return level;
437
+ }
438
+ var colors = {
439
+ reset: "\x1B[0m",
440
+ bold: "\x1B[1m",
441
+ dim: "\x1B[2m",
442
+ red: "\x1B[31m",
443
+ green: "\x1B[32m",
444
+ yellow: "\x1B[33m",
445
+ blue: "\x1B[34m",
446
+ magenta: "\x1B[35m",
447
+ cyan: "\x1B[36m",
448
+ white: "\x1B[37m",
449
+ gray: "\x1B[90m"
450
+ };
451
+ var levelColorMap = {
452
+ error: colors.red,
453
+ warn: colors.yellow,
454
+ info: colors.cyan,
455
+ debug: colors.gray
456
+ };
457
+ function getLevelColor(level) {
458
+ return levelColorMap[level] ?? colors.white;
459
+ }
460
+ var cssColors = {
461
+ dim: "color: #6b7280",
462
+ red: "color: #ef4444; font-weight: bold",
463
+ green: "color: #22c55e",
464
+ yellow: "color: #f59e0b; font-weight: bold",
465
+ cyan: "color: #06b6d4; font-weight: bold",
466
+ gray: "color: #6b7280; font-weight: bold",
467
+ reset: "color: inherit; font-weight: normal"
468
+ };
469
+ var cssLevelColorMap = {
470
+ error: cssColors.red,
471
+ warn: cssColors.yellow,
472
+ info: cssColors.cyan,
473
+ debug: cssColors.gray
474
+ };
475
+ function getCssLevelColor(level) {
476
+ return cssLevelColorMap[level] ?? cssColors.reset;
477
+ }
478
+ function escapeFormatString(str) {
479
+ return str.replace(/%/g, "%%");
480
+ }
481
+ var SENSITIVE_HEADERS = [
482
+ "authorization",
483
+ "cookie",
484
+ "set-cookie",
485
+ "x-api-key",
486
+ "x-auth-token",
487
+ "proxy-authorization"
488
+ ];
489
+ var SENSITIVE_HEADER_SET = new Set(SENSITIVE_HEADERS);
490
+ function filterSafeHeaders(headers) {
491
+ const safeHeaders = {};
492
+ for (const [key, value] of Object.entries(headers))
493
+ if (value !== undefined && !SENSITIVE_HEADER_SET.has(key.toLowerCase()))
494
+ safeHeaders[key] = value;
495
+ return safeHeaders;
496
+ }
497
+ var patternCache = /* @__PURE__ */ new Map;
498
+ function globToRegExp(pattern, separator = "/") {
499
+ const cacheKey = `${separator}:${pattern}`;
500
+ let regex = patternCache.get(cacheKey);
501
+ if (!regex) {
502
+ const segment = separator === "/" ? "[^/]*" : "[^.]*";
503
+ const char = separator === "/" ? "[^/]" : "[^.]";
504
+ const regexPattern = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, segment).replace(/{{GLOBSTAR}}/g, ".*").replace(/\?/g, char);
505
+ regex = new RegExp(`^${regexPattern}$`);
506
+ patternCache.set(cacheKey, regex);
507
+ }
508
+ return regex;
509
+ }
510
+ function matchesPattern(path, pattern) {
511
+ return globToRegExp(pattern, "/").test(path);
512
+ }
513
+ var _isoDate = /* @__PURE__ */ new Date;
514
+ var _isoCachedSecond = -1;
515
+ var _isoCachedPrefix = "";
516
+ function isoNow() {
517
+ const now = Date.now();
518
+ const sec = Math.floor(now / 1000);
519
+ if (sec !== _isoCachedSecond) {
520
+ _isoCachedSecond = sec;
521
+ _isoDate.setTime(now);
522
+ _isoCachedPrefix = _isoDate.toISOString().slice(0, 19);
523
+ }
524
+ return `${_isoCachedPrefix}.${String(now % 1000).padStart(3, "0")}Z`;
525
+ }
526
+
527
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/redact-C7FmdhwI.mjs
528
+ var DEFAULT_REPLACEMENT = "[REDACTED]";
529
+ function normalizeRedactPathPattern(pattern) {
530
+ if (!pattern.includes("*") && !pattern.includes("."))
531
+ return `**.${pattern}`;
532
+ return pattern;
533
+ }
534
+ function compileRedactPathMatchers(patterns) {
535
+ if (!patterns?.length)
536
+ return;
537
+ const exactPaths = /* @__PURE__ */ new Set;
538
+ const pathGlobs = [];
539
+ const keyGlobs = [];
540
+ const caseInsensitiveLeaves = /* @__PURE__ */ new Set;
541
+ for (const raw of patterns) {
542
+ if (!raw.includes("*")) {
543
+ if (raw.includes("."))
544
+ exactPaths.add(raw);
545
+ else
546
+ addPathGlobPattern(normalizeRedactPathPattern(raw), exactPaths, pathGlobs, caseInsensitiveLeaves);
547
+ continue;
548
+ }
549
+ if (!raw.includes("."))
550
+ keyGlobs.push(globToRegExp(raw, "."));
551
+ else
552
+ addPathGlobPattern(raw, exactPaths, pathGlobs, caseInsensitiveLeaves);
553
+ }
554
+ if (exactPaths.size === 0 && pathGlobs.length === 0 && keyGlobs.length === 0 && caseInsensitiveLeaves.size === 0)
555
+ return;
556
+ return {
557
+ exactPaths,
558
+ pathGlobs,
559
+ keyGlobs,
560
+ caseInsensitiveLeaves
561
+ };
562
+ }
563
+ function addPathGlobPattern(pattern, exactPaths, pathGlobs, caseInsensitiveLeaves) {
564
+ pathGlobs.push(globToRegExp(pattern, "."));
565
+ const leaf = pattern.match(/^\*\*\.([^.?*]+)$/);
566
+ if (leaf) {
567
+ exactPaths.add(leaf[1]);
568
+ caseInsensitiveLeaves.add(leaf[1].toLowerCase());
569
+ }
570
+ }
571
+ function matchesRedactPath(fullPath, leafKey, matchers) {
572
+ if (matchers.exactPaths.has(fullPath))
573
+ return true;
574
+ if (matchers.caseInsensitiveLeaves.has(leafKey.toLowerCase()))
575
+ return true;
576
+ for (const glob of matchers.pathGlobs) {
577
+ glob.lastIndex = 0;
578
+ if (glob.test(fullPath))
579
+ return true;
580
+ }
581
+ for (const glob of matchers.keyGlobs) {
582
+ glob.lastIndex = 0;
583
+ if (glob.test(leafKey))
584
+ return true;
585
+ }
586
+ return false;
587
+ }
588
+ function resolveReplacement(replacement, matched, ctx) {
589
+ if (typeof replacement === "string")
590
+ return replacement;
591
+ try {
592
+ const result = replacement(matched, ctx);
593
+ if (typeof result !== "string") {
594
+ console.error(`[evlog] redact replacement returned ${typeof result} for "${ctx.path}", expected string \u2014 using ${DEFAULT_REPLACEMENT}`);
595
+ return DEFAULT_REPLACEMENT;
596
+ }
597
+ return result;
598
+ } catch (err) {
599
+ console.error(`[evlog] redact replacement failed for "${ctx.path}":`, err);
600
+ return DEFAULT_REPLACEMENT;
601
+ }
602
+ }
603
+ function redactPathsInTree(obj, matchers, replacement, prefix = "") {
604
+ if (obj === null || obj === undefined)
605
+ return;
606
+ if (Array.isArray(obj)) {
607
+ for (let i = 0;i < obj.length; i++) {
608
+ const segment = String(i);
609
+ const fullPath = prefix ? `${prefix}.${segment}` : segment;
610
+ redactPathsInTree(obj[i], matchers, replacement, fullPath);
611
+ }
612
+ return;
613
+ }
614
+ if (typeof obj === "object") {
615
+ const record = obj;
616
+ for (const key of redactableKeys(record)) {
617
+ const fullPath = prefix ? `${prefix}.${key}` : key;
618
+ if (matchesRedactPath(fullPath, key, matchers))
619
+ setRedacted(record, key, resolveReplacement(replacement, record[key], {
620
+ path: fullPath,
621
+ key
622
+ }), fullPath);
623
+ else
624
+ redactPathsInTree(record[key], matchers, replacement, fullPath);
625
+ }
626
+ }
627
+ }
628
+ function redactableKeys(record) {
629
+ return Object.keys(record);
630
+ }
631
+ function setRedacted(record, key, value, path) {
632
+ if (Reflect.set(record, key, value))
633
+ return;
634
+ const desc = Object.getOwnPropertyDescriptor(record, key);
635
+ if (desc && "value" in desc && desc.configurable) {
636
+ Object.defineProperty(record, key, {
637
+ ...desc,
638
+ value
639
+ });
640
+ return;
641
+ }
642
+ console.warn(`[evlog] redact could not rewrite read-only field "${path}" \u2014 value left as-is`);
643
+ }
644
+ var builtinPatterns = {
645
+ creditCard: {
646
+ pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
647
+ mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
648
+ },
649
+ email: {
650
+ pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g,
651
+ mask: (m) => {
652
+ if (m.indexOf("@") < 1)
653
+ return "***@***";
654
+ const tld = m.slice(m.lastIndexOf("."));
655
+ return `${m[0]}***@***${tld}`;
656
+ }
657
+ },
658
+ ipv4: {
659
+ 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,
660
+ mask: (m) => `***.***.***.${m.split(".").pop()}`
661
+ },
662
+ phone: {
663
+ pattern: /(?:\+\d{1,3}[\s.-]?\(?\d{1,4}\)?|\(\d{1,4}\))(?:[\s.-]?\d{2,4}){2,4}\b/g,
664
+ mask: (m) => {
665
+ const digits = m.replace(/[^\d]/g, "");
666
+ if (m.startsWith("+") && digits.length > 4) {
667
+ const ccMatch = m.match(/^\+\d{1,3}/);
668
+ return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
669
+ }
670
+ if (digits.length > 2)
671
+ return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
672
+ return "***";
673
+ }
674
+ },
675
+ jwt: {
676
+ pattern: /\beyJ[\w-]*\.[\w-]*\.[\w-]*\b/g,
677
+ mask: () => "eyJ***.***"
678
+ },
679
+ bearer: {
680
+ pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
681
+ mask: () => "Bearer ***"
682
+ },
683
+ iban: {
684
+ 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,
685
+ mask: (m) => {
686
+ const clean = m.replace(/[\s-]/g, "");
687
+ return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
688
+ }
689
+ }
690
+ };
691
+ function resolveRedactConfig(input) {
692
+ if (input === undefined || input === false)
693
+ return;
694
+ if (input === true)
695
+ return { _maskers: allBuiltinMaskers() };
696
+ if (input.builtins === false)
697
+ return {
698
+ ...input,
699
+ _pathMatchers: compileRedactPathMatchers(input.paths)
700
+ };
701
+ const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
702
+ return {
703
+ ...input,
704
+ _maskers: maskers,
705
+ _pathMatchers: compileRedactPathMatchers(input.paths)
706
+ };
707
+ }
708
+ function allBuiltinMaskers() {
709
+ return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
710
+ }
711
+ function cloneRegex(re) {
712
+ return new RegExp(re.source, re.flags);
713
+ }
714
+ var globallyRedacted = Symbol.for("evlog.globallyRedacted");
715
+ function markGloballyRedacted(event) {
716
+ Object.defineProperty(event, globallyRedacted, {
717
+ value: true,
718
+ enumerable: false,
719
+ configurable: true
720
+ });
721
+ }
722
+ function isGloballyRedacted(event) {
723
+ return Reflect.has(event, globallyRedacted);
724
+ }
725
+ function cloneForRedaction(event) {
726
+ try {
727
+ return structuredClone(event);
728
+ } catch {
729
+ try {
730
+ return JSON.parse(JSON.stringify(event));
731
+ } catch {
732
+ console.warn("[cloneForRedaction] Shallow clone used \u2014 nested objects may be mutated by redactPath, redactPatterns, and applyMaskersToTree");
733
+ return { ...event };
734
+ }
735
+ }
736
+ }
737
+ function redactEvent(event, config) {
738
+ const clone = cloneForRedaction(event);
739
+ const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
740
+ if (config.transform)
741
+ try {
742
+ config.transform(clone);
743
+ } catch (err) {
744
+ console.error("[evlog] redact transform failed:", err);
745
+ }
746
+ const pathMatchers = config._pathMatchers ?? compileRedactPathMatchers(config.paths);
747
+ if (pathMatchers)
748
+ redactPathsInTree(clone, pathMatchers, replacement);
749
+ if (config._maskers?.length)
750
+ applyMaskersToTree(clone, config._maskers);
751
+ if (config.patterns?.length)
752
+ redactPatterns(clone, config.patterns, replacement);
753
+ return clone;
754
+ }
755
+ function redactPatterns(obj, patterns, replacement, prefix = "") {
756
+ if (obj === null || obj === undefined)
757
+ return;
758
+ if (Array.isArray(obj)) {
759
+ for (let i = 0;i < obj.length; i++) {
760
+ const key = String(i);
761
+ const fullPath = prefix ? `${prefix}.${key}` : key;
762
+ if (typeof obj[i] === "string")
763
+ obj[i] = applyPatterns(obj[i], patterns, replacement, fullPath, key);
764
+ else if (typeof obj[i] === "object")
765
+ redactPatterns(obj[i], patterns, replacement, fullPath);
766
+ }
767
+ return;
768
+ }
769
+ if (typeof obj === "object") {
770
+ const record = obj;
771
+ for (const key of redactableKeys(record)) {
772
+ const val = record[key];
773
+ const fullPath = prefix ? `${prefix}.${key}` : key;
774
+ if (typeof val === "string")
775
+ setRedacted(record, key, applyPatterns(val, patterns, replacement, fullPath, key), fullPath);
776
+ else if (typeof val === "object")
777
+ redactPatterns(val, patterns, replacement, fullPath);
778
+ }
779
+ }
780
+ }
781
+ function applyPatterns(value, patterns, replacement, path, key) {
782
+ let result = value;
783
+ for (const pattern of patterns) {
784
+ if (typeof replacement === "string") {
785
+ result = result.replace(pattern, replacement);
786
+ continue;
787
+ }
788
+ result = result.replace(pattern, (...args) => {
789
+ const match = args[0];
790
+ return resolveReplacement(replacement, match, {
791
+ path,
792
+ key,
793
+ groups: captureGroups(args)
794
+ });
795
+ });
796
+ }
797
+ return result;
798
+ }
799
+ function captureGroups(args) {
800
+ const last = args.at(-1);
801
+ const trailing = typeof last === "object" && last !== null ? 3 : 2;
802
+ return args.slice(1, Math.max(1, args.length - trailing));
803
+ }
804
+ function applyMaskersToTree(obj, maskers) {
805
+ if (obj === null || obj === undefined)
806
+ return;
807
+ if (Array.isArray(obj)) {
808
+ for (let i = 0;i < obj.length; i++)
809
+ if (typeof obj[i] === "string")
810
+ obj[i] = applyMaskers(obj[i], maskers);
811
+ else if (typeof obj[i] === "object")
812
+ applyMaskersToTree(obj[i], maskers);
813
+ return;
814
+ }
815
+ if (typeof obj === "object") {
816
+ const record = obj;
817
+ for (const key of redactableKeys(record)) {
818
+ const val = record[key];
819
+ if (typeof val === "string")
820
+ setRedacted(record, key, applyMaskers(val, maskers), key);
821
+ else if (typeof val === "object")
822
+ applyMaskersToTree(val, maskers);
823
+ }
824
+ }
825
+ }
826
+ function applyMaskers(value, maskers) {
827
+ let result = value;
828
+ for (const [pattern, mask] of maskers)
829
+ result = result.replace(pattern, mask);
830
+ return result;
831
+ }
832
+
833
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
834
+ function logPluginError(name, hook, err) {
835
+ console.error(`[evlog/${name}] ${hook} failed:`, err);
836
+ }
837
+ function createPluginRunner(plugins = []) {
838
+ const byName = /* @__PURE__ */ new Map;
839
+ for (const plugin of plugins)
840
+ byName.set(plugin.name, plugin);
841
+ const list = Array.from(byName.values());
842
+ return {
843
+ plugins: list,
844
+ hasEnrich: list.some((p) => typeof p.enrich === "function"),
845
+ hasDrain: list.some((p) => typeof p.drain === "function"),
846
+ hasKeep: list.some((p) => typeof p.keep === "function"),
847
+ hasRequestLifecycle: list.some((p) => typeof p.onRequestStart === "function" || typeof p.onRequestFinish === "function"),
848
+ hasClientLog: list.some((p) => typeof p.onClientLog === "function"),
849
+ hasExtendLogger: list.some((p) => typeof p.extendLogger === "function"),
850
+ applyExtendLogger(logger) {
851
+ for (const plugin of list) {
852
+ if (!plugin.extendLogger)
853
+ continue;
854
+ try {
855
+ plugin.extendLogger(logger);
856
+ } catch (err) {
857
+ logPluginError(plugin.name, "extendLogger", err);
858
+ }
859
+ }
860
+ },
861
+ runOnRequestStart(ctx) {
862
+ for (const plugin of list) {
863
+ if (!plugin.onRequestStart)
864
+ continue;
865
+ try {
866
+ plugin.onRequestStart(ctx);
867
+ } catch (err) {
868
+ logPluginError(plugin.name, "onRequestStart", err);
869
+ }
870
+ }
871
+ },
872
+ runOnRequestFinish(ctx) {
873
+ for (const plugin of list) {
874
+ if (!plugin.onRequestFinish)
875
+ continue;
876
+ try {
877
+ plugin.onRequestFinish(ctx);
878
+ } catch (err) {
879
+ logPluginError(plugin.name, "onRequestFinish", err);
880
+ }
881
+ }
882
+ },
883
+ async runEnrich(ctx) {
884
+ for (const plugin of list) {
885
+ if (!plugin.enrich)
886
+ continue;
887
+ try {
888
+ await plugin.enrich(ctx);
889
+ } catch (err) {
890
+ logPluginError(plugin.name, "enrich", err);
891
+ }
892
+ }
893
+ },
894
+ async runDrain(ctx) {
895
+ const drains = list.filter((p) => typeof p.drain === "function");
896
+ if (drains.length === 0)
897
+ return;
898
+ await Promise.allSettled(drains.map(async (plugin) => {
899
+ try {
900
+ await plugin.drain(ctx);
901
+ } catch (err) {
902
+ logPluginError(plugin.name, "drain", err);
903
+ }
904
+ }));
905
+ },
906
+ async runKeep(ctx) {
907
+ for (const plugin of list) {
908
+ if (!plugin.keep)
909
+ continue;
910
+ try {
911
+ await plugin.keep(ctx);
912
+ } catch (err) {
913
+ logPluginError(plugin.name, "keep", err);
914
+ }
915
+ }
916
+ },
917
+ runOnClientLog(ctx) {
918
+ for (const plugin of list) {
919
+ if (!plugin.onClientLog)
920
+ continue;
921
+ try {
922
+ plugin.onClientLog(ctx);
923
+ } catch (err) {
924
+ logPluginError(plugin.name, "onClientLog", err);
925
+ }
926
+ }
927
+ },
928
+ async runSetup(ctx) {
929
+ for (const plugin of list) {
930
+ if (!plugin.setup)
931
+ continue;
932
+ try {
933
+ await plugin.setup(ctx);
934
+ } catch (err) {
935
+ logPluginError(plugin.name, "setup", err);
936
+ }
937
+ }
938
+ }
939
+ };
940
+ }
941
+ var emptyRunner = createPluginRunner([]);
942
+ function getEmptyPluginRunner() {
943
+ return emptyRunner;
944
+ }
945
+ var EVLOG_MAJOR = 2;
946
+ var REGISTRY_KEY = Symbol.for(`evlog.registry.v${EVLOG_MAJOR}`);
947
+ var MAJORS_KEY = Symbol.for("evlog.majors");
948
+ function createConfig() {
949
+ return {
950
+ env: {
951
+ service: "app",
952
+ environment: "development"
953
+ },
954
+ pretty: isDev(),
955
+ prettyError: {
956
+ snippet: isDev(),
957
+ stackDepth: 2,
958
+ compact: isDev(),
959
+ detail: "full"
960
+ },
961
+ sampling: {},
962
+ stringify: true,
963
+ drain: undefined,
964
+ redact: undefined,
965
+ enabled: true,
966
+ silent: false,
967
+ minLevel: "debug",
968
+ locked: false,
969
+ initialized: false,
970
+ pluginRunner: getEmptyPluginRunner()
971
+ };
972
+ }
973
+ function warnOnMultiMajor(host) {
974
+ const majors = host[MAJORS_KEY] ??= /* @__PURE__ */ new Set;
975
+ if (majors.has(EVLOG_MAJOR))
976
+ return;
977
+ majors.add(EVLOG_MAJOR);
978
+ if (majors.size > 1)
979
+ console.warn(`[evlog] Multiple major versions of evlog are loaded in this process (${[...majors].map((m) => `${m}.x`).join(", ")}). They cannot share request scope or logger configuration: events emitted through the other copy will be undrained and unredacted, and useLogger() may throw. Deduplicate evlog to a single major.`);
980
+ }
981
+ function getRegistry() {
982
+ const host = globalThis;
983
+ warnOnMultiMajor(host);
984
+ return host[REGISTRY_KEY] ??= {
985
+ config: createConfig(),
986
+ storages: /* @__PURE__ */ new Map
987
+ };
988
+ }
989
+ var globalConfig = getRegistry().config;
990
+ function getSharedStorage(id, create) {
991
+ const { storages } = getRegistry();
992
+ let storage = storages.get(id);
993
+ if (!storage) {
994
+ storage = create();
995
+ storages.set(id, storage);
996
+ }
997
+ return storage;
998
+ }
999
+
1000
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
1001
+ var snippetReader = null;
1002
+ var PRETTY_ERROR_TREE_SPACER = "__EVLOG_TREE_SPACER__";
1003
+ function pushTreeSpacer(children) {
1004
+ children.push(PRETTY_ERROR_TREE_SPACER);
1005
+ }
1006
+ var SKIP_PATH_RE = /(?:^|[/\\])(?:node_modules|\.nuxt|\.next|\.output)(?:[/\\]|$)/;
1007
+ var SKIP_FRAME_PATH_RE = /(?:^|[/\\])(?:packages[/\\]evlog|evlog[/\\](?:dist|src))(?:[/\\]|$)/;
1008
+ var SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
1009
+ function isPlainObject(val) {
1010
+ return val !== null && typeof val === "object" && !Array.isArray(val);
1011
+ }
1012
+ function pickString(obj, key) {
1013
+ const val = obj[key];
1014
+ return typeof val === "string" && val.length > 0 ? val : undefined;
1015
+ }
1016
+ function pickNumber(obj, key) {
1017
+ const val = obj[key];
1018
+ return typeof val === "number" ? val : undefined;
1019
+ }
1020
+ function extractGuidance(data) {
1021
+ return {
1022
+ code: pickString(data, "code"),
1023
+ why: pickString(data, "why"),
1024
+ fix: pickString(data, "fix"),
1025
+ link: pickString(data, "link")
1026
+ };
1027
+ }
1028
+ function normalizeErrorContext(error) {
1029
+ if (error === null || error === undefined)
1030
+ return null;
1031
+ if (typeof error === "string")
1032
+ return { message: error };
1033
+ if (!isPlainObject(error))
1034
+ return { message: String(error) };
1035
+ const result = {
1036
+ message: pickString(error, "message") ?? pickString(error, "statusText") ?? pickString(error, "statusMessage") ?? "Unknown error",
1037
+ name: pickString(error, "name"),
1038
+ code: pickString(error, "code"),
1039
+ why: pickString(error, "why"),
1040
+ fix: pickString(error, "fix"),
1041
+ link: pickString(error, "link"),
1042
+ status: pickNumber(error, "status") ?? pickNumber(error, "statusCode"),
1043
+ stack: pickString(error, "stack")
1044
+ };
1045
+ const { data, cause } = error;
1046
+ if (isPlainObject(data)) {
1047
+ const guidance = extractGuidance(data);
1048
+ if (!result.code)
1049
+ result.code = guidance.code;
1050
+ if (!result.why)
1051
+ result.why = guidance.why;
1052
+ if (!result.fix)
1053
+ result.fix = guidance.fix;
1054
+ if (!result.link)
1055
+ result.link = guidance.link;
1056
+ }
1057
+ if (cause instanceof Error)
1058
+ result.cause = cause.message;
1059
+ else if (isPlainObject(cause) && pickString(cause, "message"))
1060
+ result.cause = pickString(cause, "message");
1061
+ return result;
1062
+ }
1063
+ function decodeFileUrl(file) {
1064
+ if (file.startsWith("file://"))
1065
+ try {
1066
+ return decodeURIComponent(new URL(file).pathname);
1067
+ } catch {
1068
+ return file.slice(7);
1069
+ }
1070
+ return file;
1071
+ }
1072
+ function isAppPath(file) {
1073
+ const normalized = decodeFileUrl(file).replace(/\\/g, "/");
1074
+ if (normalized.startsWith("node:"))
1075
+ return false;
1076
+ if (SKIP_PATH_RE.test(normalized))
1077
+ return false;
1078
+ if (normalized.includes("/node_modules/"))
1079
+ return false;
1080
+ if (isFrameworkRuntimePath(normalized))
1081
+ return false;
1082
+ return true;
1083
+ }
1084
+ function formatDisplayPath(file, cwd) {
1085
+ const decoded = decodeFileUrl(file).replace(/\\/g, "/");
1086
+ const cwdNorm = cwd.replace(/\\/g, "/").replace(/\/$/, "");
1087
+ if (cwdNorm && decoded.startsWith(`${cwdNorm}/`)) {
1088
+ const rel = decoded.slice(cwdNorm.length + 1);
1089
+ return rel.startsWith("./") ? rel.slice(2) : rel;
1090
+ }
1091
+ const serverIdx = decoded.indexOf("/server/");
1092
+ if (serverIdx >= 0)
1093
+ return decoded.slice(serverIdx + 1);
1094
+ const srcIdx = decoded.indexOf("/src/");
1095
+ if (srcIdx >= 0)
1096
+ return decoded.slice(srcIdx + 1);
1097
+ return decoded;
1098
+ }
1099
+ function compactStackForStorage(stack, maxFrames = 5) {
1100
+ if (!stack)
1101
+ return;
1102
+ const head = stack.split(`
1103
+ `)[0] ?? "";
1104
+ const useful = parseStackFrames(stack).filter((f) => f.file && f.line && f.isApp && !isInternalErrorFrame(f)).slice(0, maxFrames);
1105
+ if (useful.length === 0)
1106
+ return stack;
1107
+ return [head, ...useful.map((f) => f.raw)].join(`
1108
+ `);
1109
+ }
1110
+ function parseStackFrames(stack) {
1111
+ if (!stack)
1112
+ return [];
1113
+ const lines = stack.split(`
1114
+ `);
1115
+ const frames = [];
1116
+ for (const line of lines) {
1117
+ const trimmed = line.trim();
1118
+ if (!trimmed.startsWith("at "))
1119
+ continue;
1120
+ const withFn = trimmed.match(/^at (.+?) \((.+):(\d+):(\d+)\)$/);
1121
+ if (withFn) {
1122
+ const [, fn, file, lineStr, colStr] = withFn;
1123
+ frames.push({
1124
+ raw: trimmed,
1125
+ fn,
1126
+ file,
1127
+ line: Number(lineStr),
1128
+ column: Number(colStr),
1129
+ isApp: isAppPath(file)
1130
+ });
1131
+ continue;
1132
+ }
1133
+ const withoutFn = trimmed.match(/^at (.+):(\d+):(\d+)$/);
1134
+ if (withoutFn) {
1135
+ const [, file, lineStr, colStr] = withoutFn;
1136
+ frames.push({
1137
+ raw: trimmed,
1138
+ file,
1139
+ line: Number(lineStr),
1140
+ column: Number(colStr),
1141
+ isApp: isAppPath(file)
1142
+ });
1143
+ continue;
1144
+ }
1145
+ const asyncFn = trimmed.match(/^at async (.+?) \((.+):(\d+):(\d+)\)$/);
1146
+ if (asyncFn) {
1147
+ const [, fn, file, lineStr, colStr] = asyncFn;
1148
+ frames.push({
1149
+ raw: trimmed,
1150
+ fn: `async ${fn}`,
1151
+ file,
1152
+ line: Number(lineStr),
1153
+ column: Number(colStr),
1154
+ isApp: isAppPath(file)
1155
+ });
1156
+ }
1157
+ }
1158
+ return frames;
1159
+ }
1160
+ function isFrameworkRuntimePath(path) {
1161
+ const normalized = path.replace(/\\/g, "/");
1162
+ return normalized.includes("route-modules/") || normalized.includes("webpack://next/") || normalized.includes("/next/dist/") || normalized.includes("/compiled/next-server/");
1163
+ }
1164
+ function isFrameworkRuntimeFrame(frame) {
1165
+ if (!frame.file)
1166
+ return false;
1167
+ return isFrameworkRuntimePath(decodeFileUrl(frame.file));
1168
+ }
1169
+ function isInternalErrorFrame(frame) {
1170
+ if (isFrameworkRuntimeFrame(frame))
1171
+ return true;
1172
+ if (frame.fn) {
1173
+ const fn = frame.fn.replace(/^async /, "");
1174
+ if (SKIP_FRAME_FN_RE.test(fn))
1175
+ return true;
1176
+ }
1177
+ if (!frame.file)
1178
+ return true;
1179
+ const path = decodeFileUrl(frame.file).replace(/\\/g, "/");
1180
+ if (SKIP_FRAME_PATH_RE.test(path))
1181
+ return true;
1182
+ if (path.includes(".nuxt/"))
1183
+ return true;
1184
+ if (path.includes(".next/"))
1185
+ return true;
1186
+ return false;
1187
+ }
1188
+ function pickPrimaryFrame(frames) {
1189
+ for (const frame of frames)
1190
+ if (frame.isApp && frame.file && frame.line && !isInternalErrorFrame(frame))
1191
+ return frame;
1192
+ }
1193
+ function readCodeSnippet(file, line, contextLines = 2) {
1194
+ if (!isDev() || isBrowser() || !snippetReader)
1195
+ return null;
1196
+ const path = decodeFileUrl(file).replace(/\\/g, "/");
1197
+ if (path.includes(".next/") || path.includes(".nuxt/") || path.includes(".output/"))
1198
+ return null;
1199
+ return snippetReader(file, line, contextLines);
1200
+ }
1201
+ function formatSnippetLines(snippet) {
1202
+ const width = String(snippet[snippet.length - 1]?.line ?? 0).length;
1203
+ return snippet.map(({ line, content, isErrorLine }) => {
1204
+ const marker = isErrorLine ? `${colors.red}\u276F${colors.reset}` : `${colors.dim} ${colors.reset}`;
1205
+ const numColor = isErrorLine ? colors.red : colors.gray;
1206
+ const trimmed = content.length > 120 ? `${content.slice(0, 117)}\u2026` : content;
1207
+ return `${marker} ${numColor}${String(line).padStart(width, " ")}${colors.reset} ${colors.dim}\u2503${colors.reset} ${colors.dim}${trimmed}${colors.reset}`;
1208
+ });
1209
+ }
1210
+ function formatFrameLocation(frame, cwd) {
1211
+ const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
1212
+ const loc = frame.line ? `${file}:${frame.line}` : file;
1213
+ const fn = frame.fn && frame.fn !== "<unknown>" ? frame.fn : undefined;
1214
+ return fn ? `at ${fn} (${loc})` : `at ${loc}`;
1215
+ }
1216
+ function formatCollapsedFrame(frame, cwd) {
1217
+ const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
1218
+ const loc = frame.line ? `${file}:${frame.line}` : file;
1219
+ const prefix = frame.fn?.startsWith("async") ? "at async " : "at ";
1220
+ const fn = frame.fn?.replace(/^async /, "");
1221
+ if (fn && fn !== "<unknown>" && fn !== loc)
1222
+ return `${prefix}${fn} (${loc})`;
1223
+ return `${prefix}${loc}`;
1224
+ }
1225
+ var GUIDANCE_WRAP_WIDTH = 76;
1226
+ var GUIDANCE_CONTINUATION = " ";
1227
+ function formatGuidanceLine(label, text, labelColor) {
1228
+ const prefix = `${labelColor}${label}:${colors.reset} `;
1229
+ const lines = [];
1230
+ let remaining = text.trim();
1231
+ let first = true;
1232
+ while (remaining.length > 0) {
1233
+ const budget = first ? Math.max(24, GUIDANCE_WRAP_WIDTH - prefix.length) : Math.max(24, 71);
1234
+ if (remaining.length <= budget) {
1235
+ lines.push(first ? `${prefix}${remaining}` : `${GUIDANCE_CONTINUATION}${remaining}`);
1236
+ break;
1237
+ }
1238
+ let split = remaining.lastIndexOf(" ", budget);
1239
+ if (split <= 0)
1240
+ split = budget;
1241
+ const chunk = remaining.slice(0, split).trimEnd();
1242
+ lines.push(first ? `${prefix}${chunk}` : `${GUIDANCE_CONTINUATION}${chunk}`);
1243
+ remaining = remaining.slice(split).trimStart();
1244
+ first = false;
1245
+ }
1246
+ return lines;
1247
+ }
1248
+ function buildErrorEntries(error, options = {}) {
1249
+ const normalized = normalizeErrorContext(error);
1250
+ if (!normalized)
1251
+ return [];
1252
+ const cwd = options.cwd ?? (typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd() : ".");
1253
+ const compact = options.compact ?? isDev();
1254
+ const guidanceOnly = (options.detail ?? "full") === "guidance";
1255
+ const showFrames = !guidanceOnly && !isBrowser() && (options.snippet ?? isDev());
1256
+ const stackDepth = guidanceOnly ? 0 : options.stackDepth ?? (compact ? 2 : 3);
1257
+ const snippetContextLines = compact ? 1 : 2;
1258
+ const children = [];
1259
+ const frames = guidanceOnly ? [] : parseStackFrames(normalized.stack);
1260
+ const primary = guidanceOnly ? undefined : pickPrimaryFrame(frames);
1261
+ if (!guidanceOnly && primary?.file && primary.line) {
1262
+ pushTreeSpacer(children);
1263
+ if (showFrames) {
1264
+ const snippet = readCodeSnippet(primary.file, primary.line, snippetContextLines);
1265
+ children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
1266
+ if (snippet)
1267
+ children.push(...formatSnippetLines(snippet));
1268
+ } else
1269
+ children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
1270
+ }
1271
+ if (normalized.code)
1272
+ children.push(`${colors.dim}Code:${colors.reset} ${normalized.code}`);
1273
+ if (Boolean(normalized.why || normalized.fix || normalized.link))
1274
+ pushTreeSpacer(children);
1275
+ if (normalized.why)
1276
+ children.push(...formatGuidanceLine("Why", normalized.why, colors.yellow));
1277
+ if (normalized.fix)
1278
+ children.push(...formatGuidanceLine("Fix", normalized.fix, colors.cyan));
1279
+ if (normalized.link)
1280
+ children.push(`${colors.dim}More:${colors.reset} ${normalized.link}`);
1281
+ if (normalized.cause && normalized.cause !== normalized.message)
1282
+ children.push(`${colors.dim}Caused by:${colors.reset} ${normalized.cause}`);
1283
+ const hiddenCount = guidanceOnly ? 0 : frames.filter((f) => !f.isApp || isInternalErrorFrame(f)).length;
1284
+ const tailFrames = stackDepth > 0 ? frames.filter((f) => f !== primary && !isInternalErrorFrame(f)).slice(0, stackDepth) : [];
1285
+ if (!guidanceOnly && (hiddenCount > 0 || tailFrames.length > 0)) {
1286
+ pushTreeSpacer(children);
1287
+ if (hiddenCount > 0)
1288
+ children.push(`${colors.gray}stack (${hiddenCount} frame${hiddenCount === 1 ? "" : "s"} hidden in node_modules)${colors.reset}`);
1289
+ else
1290
+ children.push(`${colors.gray}stack${colors.reset}`);
1291
+ for (const frame of tailFrames)
1292
+ children.push(`${colors.gray} ${formatCollapsedFrame(frame, cwd)}${colors.reset}`);
1293
+ }
1294
+ return [{
1295
+ key: "error",
1296
+ value: `${colors.red}${colors.bold}${normalized.message}${colors.reset}`,
1297
+ children: children.length > 0 ? children : undefined
1298
+ }];
1299
+ }
1300
+
1301
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
1302
+ var DEV_PRESETS = {
1303
+ evlog: {
1304
+ frameworkOverlay: false,
1305
+ detail: "full"
1306
+ },
1307
+ nitro: {
1308
+ frameworkOverlay: true,
1309
+ detail: "guidance"
1310
+ },
1311
+ both: {
1312
+ frameworkOverlay: true,
1313
+ detail: "full"
1314
+ }
1315
+ };
1316
+ function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
1317
+ const compact = partial.compact ?? (inDev && pretty);
1318
+ const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
1319
+ const stackDepth = detail === "guidance" ? 0 : partial.stackDepth ?? (compact ? 2 : 3);
1320
+ return {
1321
+ snippet: partial.snippet ?? (detail === "full" && pretty && inDev),
1322
+ stackDepth,
1323
+ compact,
1324
+ detail
1325
+ };
1326
+ }
1327
+ function resolveDevTerminal(input = {}) {
1328
+ const pretty = input.pretty ?? isDev();
1329
+ const inDev = isDev();
1330
+ let frameworkOverlay;
1331
+ let prettyError = {};
1332
+ if (typeof input.dev === "string" && input.dev in DEV_PRESETS) {
1333
+ const { frameworkOverlay: presetOverlay, detail } = DEV_PRESETS[input.dev];
1334
+ frameworkOverlay = presetOverlay;
1335
+ prettyError = { detail };
1336
+ } else if (input.dev && typeof input.dev === "object") {
1337
+ const { frameworkOverlay: devOverlay, prettyError: devPrettyError } = input.dev;
1338
+ frameworkOverlay = devOverlay;
1339
+ if (devPrettyError)
1340
+ prettyError = devPrettyError;
1341
+ }
1342
+ if (frameworkOverlay === undefined)
1343
+ frameworkOverlay = !(pretty && inDev);
1344
+ return {
1345
+ frameworkOverlay,
1346
+ prettyError: finalizePrettyError(prettyError, frameworkOverlay, pretty, inDev)
1347
+ };
1348
+ }
1349
+
1350
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
1351
+ var publisher = null;
1352
+ function hasWideEventPublisher() {
1353
+ return publisher !== null;
1354
+ }
1355
+ function publishWideEvent(event) {
1356
+ if (!publisher)
1357
+ return;
1358
+ try {
1359
+ publisher(event);
1360
+ } catch (err) {
1361
+ console.error("[evlog] diagnostics channel publish failed:", err);
1362
+ }
1363
+ }
1364
+
1365
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
1366
+ var evlogErrorBrand = Symbol.for("evlog.error.brand");
1367
+ function isEvlogError(error) {
1368
+ return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
1369
+ }
1370
+
1371
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/error.mjs
1372
+ var evlogErrorInternalKey = Symbol.for("evlog.error.internal");
1373
+ var evlogErrorDataKey = Symbol.for("evlog.error.data");
1374
+ var EvlogError = class EvlogError extends Error {
1375
+ static isEvlogError(error) {
1376
+ return isEvlogError(error);
1377
+ }
1378
+ code;
1379
+ status;
1380
+ why;
1381
+ fix;
1382
+ link;
1383
+ get internal() {
1384
+ return this[evlogErrorInternalKey];
1385
+ }
1386
+ constructor(options) {
1387
+ const opts = typeof options === "string" ? { message: options } : options;
1388
+ super(opts.message, { cause: opts.cause });
1389
+ this.name = "EvlogError";
1390
+ this.code = opts.code;
1391
+ this.status = opts.status ?? 500;
1392
+ this.why = opts.why;
1393
+ this.fix = opts.fix;
1394
+ this.link = opts.link;
1395
+ if (opts.internal !== undefined)
1396
+ Object.defineProperty(this, evlogErrorInternalKey, {
1397
+ value: opts.internal,
1398
+ enumerable: false,
1399
+ writable: false,
1400
+ configurable: true
1401
+ });
1402
+ if (opts.data !== undefined)
1403
+ Object.defineProperty(this, evlogErrorDataKey, {
1404
+ value: opts.data,
1405
+ enumerable: false,
1406
+ writable: false,
1407
+ configurable: true
1408
+ });
1409
+ if (Error.captureStackTrace)
1410
+ Error.captureStackTrace(this, EvlogError);
1411
+ }
1412
+ get statusText() {
1413
+ return this.message;
1414
+ }
1415
+ get statusCode() {
1416
+ return this.status;
1417
+ }
1418
+ get statusMessage() {
1419
+ return this.message;
1420
+ }
1421
+ get data() {
1422
+ const extra = this[evlogErrorDataKey];
1423
+ if (!extra && !this.code && !this.why && !this.fix && !this.link)
1424
+ return;
1425
+ return {
1426
+ ...extra,
1427
+ ...this.code !== undefined && { code: this.code },
1428
+ ...this.why !== undefined && { why: this.why },
1429
+ ...this.fix !== undefined && { fix: this.fix },
1430
+ ...this.link !== undefined && { link: this.link }
1431
+ };
1432
+ }
1433
+ toString() {
1434
+ const useColors = isServer();
1435
+ const red = useColors ? colors.red : "";
1436
+ const yellow = useColors ? colors.yellow : "";
1437
+ const cyan = useColors ? colors.cyan : "";
1438
+ const dim = useColors ? colors.dim : "";
1439
+ const reset = useColors ? colors.reset : "";
1440
+ const bold = useColors ? colors.bold : "";
1441
+ const lines = [];
1442
+ lines.push(`${red}${bold}Error:${reset} ${this.message}`);
1443
+ if (this.code)
1444
+ lines.push(`${dim}Code:${reset} ${this.code}`);
1445
+ if (this.why)
1446
+ lines.push(`${yellow}Why:${reset} ${this.why}`);
1447
+ if (this.fix)
1448
+ lines.push(`${cyan}Fix:${reset} ${this.fix}`);
1449
+ if (this.link)
1450
+ lines.push(`${dim}More info:${reset} ${this.link}`);
1451
+ if (this.cause)
1452
+ lines.push(`${dim}Caused by:${reset} ${this.cause.message}`);
1453
+ return lines.join(`
1454
+ `);
1455
+ }
1456
+ toJSON() {
1457
+ const { data } = this;
1458
+ return {
1459
+ name: this.name,
1460
+ message: this.message,
1461
+ status: this.status,
1462
+ ...data && { data },
1463
+ ...this.cause instanceof Error && { cause: {
1464
+ name: this.cause.name,
1465
+ message: this.cause.message
1466
+ } }
1467
+ };
1468
+ }
1469
+ };
1470
+ Object.defineProperty(EvlogError.prototype, evlogErrorBrand, {
1471
+ value: true,
1472
+ enumerable: false
1473
+ });
1474
+
1475
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
1476
+ function extractSafeHeaders(headers) {
1477
+ const raw = {};
1478
+ headers.forEach((value, key) => {
1479
+ raw[key] = value;
1480
+ });
1481
+ return filterSafeHeaders(raw);
1482
+ }
1483
+ function extractSafeNodeHeaders(headers) {
1484
+ const raw = {};
1485
+ for (const [key, value] of Object.entries(headers)) {
1486
+ if (value === undefined)
1487
+ continue;
1488
+ raw[key] = Array.isArray(value) ? value.join(", ") : value;
1489
+ }
1490
+ return filterSafeHeaders(raw);
1491
+ }
1492
+
1493
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/audit-C8euLMvu.mjs
1494
+ var nativeStdoutWrite = typeof process !== "undefined" && typeof process.stdout?.write === "function" ? process.stdout.write.bind(process.stdout) : undefined;
1495
+ function writePrettyStdout(text) {
1496
+ (globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
1497
+ }
1498
+ function isPlainObject$1(val) {
1499
+ return val !== null && typeof val === "object" && !Array.isArray(val);
1500
+ }
1501
+ 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).";
1502
+ function warnPostEmit(method, detail) {
1503
+ console.warn(`[evlog] ${method} called after the wide event was emitted \u2014 ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}`);
1504
+ }
1505
+ function mergeInto(target, source) {
1506
+ for (const key in source) {
1507
+ const sourceVal = source[key];
1508
+ if (sourceVal === undefined || sourceVal === null)
1509
+ continue;
1510
+ const targetVal = target[key];
1511
+ if (sourceVal === targetVal)
1512
+ continue;
1513
+ if (isPlainObject$1(sourceVal) && isPlainObject$1(targetVal))
1514
+ mergeInto(targetVal, sourceVal);
1515
+ else if (Array.isArray(targetVal) && Array.isArray(sourceVal))
1516
+ target[key] = [...targetVal, ...sourceVal];
1517
+ else
1518
+ Reflect.set(target, key, sourceVal);
1519
+ }
1520
+ }
1521
+ var pendingDrainState = /* @__PURE__ */ new WeakMap;
1522
+ function isAiOnlyFieldUpdate(data) {
1523
+ const keys = Object.keys(data);
1524
+ return keys.length === 1 && keys[0] === "ai";
1525
+ }
1526
+ function markWideEventDrainStarted(event) {
1527
+ if (!event)
1528
+ return;
1529
+ const state = pendingDrainState.get(event);
1530
+ if (state)
1531
+ state.drainStarted = true;
1532
+ }
1533
+ var state = globalConfig;
1534
+ function initLogger(config = {}) {
1535
+ state.enabled = config.enabled ?? true;
1536
+ const detected = detectEnvironment();
1537
+ state.env = {
1538
+ service: config.env?.service ?? detected.service ?? "app",
1539
+ environment: config.env?.environment ?? detected.environment ?? "development",
1540
+ version: config.env?.version ?? detected.version,
1541
+ commitHash: config.env?.commitHash ?? detected.commitHash,
1542
+ region: config.env?.region ?? detected.region
1543
+ };
1544
+ state.pretty = config.pretty ?? isDev();
1545
+ state.prettyError = resolveDevTerminal(config).prettyError;
1546
+ state.sampling = config.sampling ?? {};
1547
+ state.stringify = config.stringify ?? true;
1548
+ state.drain = config.drain;
1549
+ state.redact = resolveRedactConfig(config.redact ?? !isDev());
1550
+ state.silent = config.silent ?? false;
1551
+ state.minLevel = config.minLevel ?? "debug";
1552
+ state.pluginRunner = config.plugins?.length ? createPluginRunner(config.plugins) : getEmptyPluginRunner();
1553
+ if (state.pluginRunner.plugins.length > 0)
1554
+ state.pluginRunner.runSetup({ env: { ...state.env } });
1555
+ const hasAnyDrain = !!state.drain || state.pluginRunner.hasDrain;
1556
+ if (state.silent && !hasAnyDrain && !config._suppressDrainWarning)
1557
+ 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).");
1558
+ state.initialized = true;
1559
+ }
1560
+ function getGlobalPluginRunner() {
1561
+ return state.pluginRunner;
1562
+ }
1563
+ function isEnabled() {
1564
+ return state.enabled;
1565
+ }
1566
+ function getGlobalDrain() {
1567
+ return state.drain;
1568
+ }
1569
+ function shouldSample(level) {
1570
+ const { rates } = state.sampling;
1571
+ if (!rates)
1572
+ return true;
1573
+ const percentage = level === "error" && rates.error === undefined ? 100 : rates[level] ?? 100;
1574
+ if (percentage <= 0)
1575
+ return false;
1576
+ if (percentage >= 100)
1577
+ return true;
1578
+ return Math.random() * 100 < percentage;
1579
+ }
1580
+ function shouldKeep(ctx) {
1581
+ const { keep } = state.sampling;
1582
+ if (!keep?.length)
1583
+ return false;
1584
+ return keep.some((condition) => {
1585
+ if (condition.status !== undefined && ctx.status !== undefined && ctx.status >= condition.status)
1586
+ return true;
1587
+ if (condition.duration !== undefined && ctx.duration !== undefined && ctx.duration >= condition.duration)
1588
+ return true;
1589
+ if (condition.path && ctx.path && matchesPattern(ctx.path, condition.path))
1590
+ return true;
1591
+ return false;
1592
+ });
1593
+ }
1594
+ function emitWideEvent(level, event, options = {}) {
1595
+ const { deferDrain = false, ownsEvent = false, waitUntil } = options;
1596
+ if (!state.enabled)
1597
+ return null;
1598
+ if (!ownsEvent) {
1599
+ if (!isLevelEnabled(level, state.minLevel))
1600
+ return null;
1601
+ if (!shouldSample(level))
1602
+ return null;
1603
+ }
1604
+ let formatted;
1605
+ if (ownsEvent) {
1606
+ event.timestamp = isoNow();
1607
+ event.level = level;
1608
+ if (event.service === undefined)
1609
+ event.service = state.env.service;
1610
+ if (event.environment === undefined)
1611
+ event.environment = state.env.environment;
1612
+ if (state.env.version !== undefined && event.version === undefined)
1613
+ event.version = state.env.version;
1614
+ if (state.env.commitHash !== undefined && event.commitHash === undefined)
1615
+ event.commitHash = state.env.commitHash;
1616
+ if (state.env.region !== undefined && event.region === undefined)
1617
+ event.region = state.env.region;
1618
+ formatted = event;
1619
+ } else
1620
+ formatted = {
1621
+ timestamp: isoNow(),
1622
+ level,
1623
+ ...state.env,
1624
+ ...event
1625
+ };
1626
+ finalizeAudit(formatted);
1627
+ if (state.redact) {
1628
+ formatted = redactEvent(formatted, state.redact);
1629
+ markGloballyRedacted(formatted);
1630
+ }
1631
+ if (!state.silent) {
1632
+ if (state.pretty)
1633
+ prettyPrintWideEvent(formatted);
1634
+ else if (state.stringify)
1635
+ console[getConsoleMethod(level)](JSON.stringify(formatted));
1636
+ else
1637
+ console[getConsoleMethod(level)](formatted);
1638
+ }
1639
+ if (!deferDrain) {
1640
+ publishWideEvent(formatted);
1641
+ const drainPromises = [];
1642
+ if (state.drain)
1643
+ drainPromises.push((async () => {
1644
+ try {
1645
+ await state.drain({ event: formatted });
1646
+ } catch (err) {
1647
+ console.error("[evlog] drain failed:", err);
1648
+ }
1649
+ })());
1650
+ if (state.pluginRunner.hasDrain)
1651
+ drainPromises.push(state.pluginRunner.runDrain({ event: formatted }));
1652
+ if (drainPromises.length > 0 && waitUntil)
1653
+ waitUntil(Promise.all(drainPromises));
1654
+ }
1655
+ return formatted;
1656
+ }
1657
+ function emitTaggedLog(level, tag, message) {
1658
+ if (!state.enabled)
1659
+ return;
1660
+ if (state.pretty && !state.silent) {
1661
+ if (!isLevelEnabled(level, state.minLevel))
1662
+ return;
1663
+ if (!shouldSample(level))
1664
+ return;
1665
+ if (isBrowser()) {
1666
+ const levelColor = getCssLevelColor(level);
1667
+ const timestamp = isoNow().slice(11, 23);
1668
+ console.log(`%c${timestamp}%c %c[${escapeFormatString(tag)}]%c ${escapeFormatString(message)}`, cssColors.dim, cssColors.reset, levelColor, cssColors.reset);
1669
+ } else {
1670
+ const color = getLevelColor(level);
1671
+ const timestamp = isoNow().slice(11, 23);
1672
+ console.log(`${colors.dim}${timestamp}${colors.reset} ${color}[${tag}]${colors.reset} ${message}`);
1673
+ }
1674
+ return;
1675
+ }
1676
+ emitWideEvent(level, {
1677
+ tag,
1678
+ message
1679
+ });
1680
+ }
1681
+ function formatValue(value) {
1682
+ if (value === null || value === undefined)
1683
+ return String(value);
1684
+ if (Array.isArray(value))
1685
+ return JSON.stringify(value);
1686
+ if (isPlainObject$1(value)) {
1687
+ const pairs = [];
1688
+ for (const [k, v] of Object.entries(value))
1689
+ if (v !== undefined && v !== null) {
1690
+ if (typeof v === "object")
1691
+ pairs.push(`${k}=${JSON.stringify(v)}`);
1692
+ else
1693
+ pairs.push(`${k}=${v}`);
1694
+ }
1695
+ return pairs.join(" ");
1696
+ }
1697
+ return String(value);
1698
+ }
1699
+ function formatCost(cost) {
1700
+ if (cost < 0.01)
1701
+ return `$${cost.toFixed(6)}`;
1702
+ if (cost < 1)
1703
+ return `$${cost.toFixed(4)}`;
1704
+ return `$${cost.toFixed(2)}`;
1705
+ }
1706
+ function asNumber(value) {
1707
+ return typeof value === "number" ? value : undefined;
1708
+ }
1709
+ function asStringArray(value) {
1710
+ if (!Array.isArray(value))
1711
+ return;
1712
+ return value.every((item) => typeof item === "string") ? value : undefined;
1713
+ }
1714
+ function isToolUsageEntry(value) {
1715
+ return isPlainObject$1(value) && typeof value.name === "string" && typeof value.durationMs === "number" && typeof value.success === "boolean";
1716
+ }
1717
+ function asToolUsageArray(value) {
1718
+ if (!Array.isArray(value))
1719
+ return;
1720
+ return value.every(isToolUsageEntry) ? value : undefined;
1721
+ }
1722
+ function serializeToolInput(input) {
1723
+ if (typeof input === "string")
1724
+ return input;
1725
+ const seen = /* @__PURE__ */ new WeakSet;
1726
+ try {
1727
+ return JSON.stringify(input, (_key, value) => {
1728
+ if (typeof value === "bigint")
1729
+ return value.toString();
1730
+ if (typeof value === "object" && value !== null) {
1731
+ if (seen.has(value))
1732
+ return "[Circular]";
1733
+ seen.add(value);
1734
+ }
1735
+ return value;
1736
+ }) ?? "";
1737
+ } catch {
1738
+ return "[unserializable tool input]";
1739
+ }
1740
+ }
1741
+ function isToolCallEntry(value) {
1742
+ return isPlainObject$1(value) && typeof value.name === "string" && "input" in value;
1743
+ }
1744
+ function asToolCallArray(value) {
1745
+ if (!Array.isArray(value))
1746
+ return;
1747
+ return value.every(isToolCallEntry) ? value : undefined;
1748
+ }
1749
+ var CAPTURED_LINE_MAX_LENGTH = 160;
1750
+ var CAPTURED_MAX_LINES = 8;
1751
+ function asCapturedLines(value) {
1752
+ if (typeof value !== "string" || value.length === 0)
1753
+ return;
1754
+ const lines = value.split(`
1755
+ `).map((line) => {
1756
+ return line.length > CAPTURED_LINE_MAX_LENGTH ? `${line.slice(0, CAPTURED_LINE_MAX_LENGTH)}\u2026` : line;
1757
+ });
1758
+ if (lines.length > CAPTURED_MAX_LINES) {
1759
+ lines.length = CAPTURED_MAX_LINES;
1760
+ lines.push(`+${value.split(`
1761
+ `).length - CAPTURED_MAX_LINES} more lines (full text in the event)`);
1762
+ }
1763
+ return lines;
1764
+ }
1765
+ function buildAIEntries(ai) {
1766
+ const entries = [];
1767
+ const headerParts = [];
1768
+ if (ai.model) {
1769
+ let m = String(ai.model);
1770
+ if (ai.provider)
1771
+ m += ` (${ai.provider})`;
1772
+ headerParts.push(m);
1773
+ }
1774
+ if (ai.calls) {
1775
+ const calls = asNumber(ai.calls);
1776
+ if (calls !== undefined)
1777
+ headerParts.push(`${calls} call${calls > 1 ? "s" : ""}`);
1778
+ }
1779
+ const steps = asNumber(ai.steps);
1780
+ if (steps !== undefined && steps > 1)
1781
+ headerParts.push(`${steps} steps`);
1782
+ entries.push({
1783
+ key: "ai",
1784
+ value: headerParts.join(" \xB7 ")
1785
+ });
1786
+ const inputTokens = asNumber(ai.inputTokens);
1787
+ const outputTokens = asNumber(ai.outputTokens);
1788
+ const totalTokens = asNumber(ai.totalTokens);
1789
+ if (inputTokens !== undefined && outputTokens !== undefined) {
1790
+ let tokLine = `${inputTokens} in \u2192 ${outputTokens} out`;
1791
+ if (totalTokens)
1792
+ tokLine += ` (${totalTokens} total)`;
1793
+ const extras = [];
1794
+ if (ai.cacheReadTokens)
1795
+ extras.push(`${ai.cacheReadTokens} cache read`);
1796
+ if (ai.cacheWriteTokens)
1797
+ extras.push(`${ai.cacheWriteTokens} cache write`);
1798
+ if (ai.reasoningTokens)
1799
+ extras.push(`${ai.reasoningTokens} reasoning`);
1800
+ if (extras.length)
1801
+ tokLine += ` \xB7 ${extras.join(" \xB7 ")}`;
1802
+ entries.push({
1803
+ key: "ai.tokens",
1804
+ value: tokLine
1805
+ });
1806
+ }
1807
+ const msFirst = asNumber(ai.msToFirstChunk);
1808
+ const msFinish = asNumber(ai.msToFinish);
1809
+ const tps = asNumber(ai.tokensPerSecond);
1810
+ if (msFirst !== undefined || msFinish !== undefined) {
1811
+ const parts = [];
1812
+ if (msFirst !== undefined)
1813
+ parts.push(`${formatDuration(msFirst)} to first chunk`);
1814
+ if (msFinish !== undefined)
1815
+ parts.push(`${formatDuration(msFinish)} total`);
1816
+ let streamLine = parts.join(" \u2192 ");
1817
+ if (tps)
1818
+ streamLine += ` \xB7 ${tps} tok/s`;
1819
+ entries.push({
1820
+ key: "ai.streaming",
1821
+ value: streamLine
1822
+ });
1823
+ }
1824
+ const estimatedCost = asNumber(ai.estimatedCost);
1825
+ if (estimatedCost !== undefined)
1826
+ entries.push({
1827
+ key: "ai.cost",
1828
+ value: formatCost(estimatedCost)
1829
+ });
1830
+ const totalDurationMs = asNumber(ai.totalDurationMs);
1831
+ if (totalDurationMs !== undefined)
1832
+ entries.push({
1833
+ key: "ai.totalDuration",
1834
+ value: formatDuration(totalDurationMs)
1835
+ });
1836
+ const toolCalls = Array.isArray(ai.toolCalls) ? ai.toolCalls : undefined;
1837
+ const tools = asToolUsageArray(ai.tools);
1838
+ const toolCallEntries = toolCalls ? asToolCallArray(toolCalls) : undefined;
1839
+ const hasInputs = toolCallEntries !== undefined && toolCallEntries.length > 0;
1840
+ if (tools?.length) {
1841
+ const children = tools.map((t, idx) => {
1842
+ const mark = t.success ? "\u2713" : "\u2717";
1843
+ let line = `${t.name} ${formatDuration(t.durationMs)} ${mark}`;
1844
+ if (t.error)
1845
+ line += ` ${t.error}`;
1846
+ if (hasInputs && toolCallEntries && idx < toolCallEntries.length) {
1847
+ const tc = toolCallEntries[idx];
1848
+ const inputStr = serializeToolInput(tc.input);
1849
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
1850
+ line += ` ${truncated}`;
1851
+ }
1852
+ return line;
1853
+ });
1854
+ entries.push({
1855
+ key: "ai.tools",
1856
+ value: "",
1857
+ children
1858
+ });
1859
+ } else if (toolCalls?.length) {
1860
+ if (toolCallEntries?.length) {
1861
+ const children = toolCallEntries.map((tc) => {
1862
+ const inputStr = serializeToolInput(tc.input);
1863
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
1864
+ return `${tc.name}(${truncated})`;
1865
+ });
1866
+ entries.push({
1867
+ key: "ai.tools",
1868
+ value: "",
1869
+ children
1870
+ });
1871
+ } else {
1872
+ const names = asStringArray(toolCalls);
1873
+ if (names?.length)
1874
+ entries.push({
1875
+ key: "ai.tools",
1876
+ value: names.join(", ")
1877
+ });
1878
+ }
1879
+ }
1880
+ const stepsUsage = Array.isArray(ai.stepsUsage) ? ai.stepsUsage.filter(isPlainObject$1) : undefined;
1881
+ if (stepsUsage?.length) {
1882
+ const firstModel = stepsUsage[0]?.model;
1883
+ const allSameModel = firstModel !== undefined && stepsUsage.every((s) => s.model === firstModel);
1884
+ const children = stepsUsage.map((s) => {
1885
+ let line = `${allSameModel ? "" : `${String(s.model)} `}${s.inputTokens} in \u2192 ${s.outputTokens} out`;
1886
+ const stepTools = asStringArray(s.toolCalls);
1887
+ if (stepTools?.length)
1888
+ line += ` [${stepTools.join(", ")}]`;
1889
+ return line;
1890
+ });
1891
+ entries.push({
1892
+ key: "ai.steps",
1893
+ value: "",
1894
+ children
1895
+ });
1896
+ } else if (steps !== undefined && steps > 1)
1897
+ entries.push({
1898
+ key: "ai.steps",
1899
+ value: String(steps)
1900
+ });
1901
+ const promptLines = asCapturedLines(ai.prompt);
1902
+ if (promptLines)
1903
+ entries.push({
1904
+ key: "ai.prompt",
1905
+ value: "",
1906
+ children: promptLines
1907
+ });
1908
+ const outputLines = asCapturedLines(ai.output);
1909
+ if (outputLines)
1910
+ entries.push({
1911
+ key: "ai.output",
1912
+ value: "",
1913
+ children: outputLines
1914
+ });
1915
+ const embedding = isPlainObject$1(ai.embedding) ? ai.embedding : undefined;
1916
+ if (embedding) {
1917
+ const parts = [];
1918
+ if (embedding.model)
1919
+ parts.push(String(embedding.model));
1920
+ parts.push(`${embedding.tokens} tokens`);
1921
+ if (embedding.dimensions)
1922
+ parts.push(`${embedding.dimensions}d`);
1923
+ if (embedding.count)
1924
+ parts.push(`${embedding.count} items`);
1925
+ entries.push({
1926
+ key: "ai.embedding",
1927
+ value: parts.join(" \xB7 ")
1928
+ });
1929
+ }
1930
+ if (ai.finishReason)
1931
+ entries.push({
1932
+ key: "ai.finishReason",
1933
+ value: String(ai.finishReason)
1934
+ });
1935
+ if (ai.error)
1936
+ entries.push({
1937
+ key: "ai.error",
1938
+ value: String(ai.error)
1939
+ });
1940
+ if (ai.responseId)
1941
+ entries.push({
1942
+ key: "ai.responseId",
1943
+ value: String(ai.responseId)
1944
+ });
1945
+ return entries;
1946
+ }
1947
+ function flushPrettyLines(lines) {
1948
+ if (lines.length === 0)
1949
+ return;
1950
+ const text = `${lines.join(`
1951
+ `)}
1952
+ `;
1953
+ if (nativeStdoutWrite && !isBrowser() && process.env.VITEST !== "true") {
1954
+ writePrettyStdout(text);
1955
+ return;
1956
+ }
1957
+ console.log(lines.join(`
1958
+ `));
1959
+ }
1960
+ function prettyPrintWideEvent(event) {
1961
+ const { timestamp, level, service, environment, version, ...rest } = event;
1962
+ const ts = typeof timestamp === "string" ? timestamp.slice(11, 23) : "";
1963
+ const levelLabel = typeof level === "string" ? level : "info";
1964
+ const browser = isBrowser();
1965
+ const lines = [];
1966
+ const writeLine = (...args) => {
1967
+ if (browser) {
1968
+ console.log(...args);
1969
+ return;
1970
+ }
1971
+ const [line] = args;
1972
+ if (typeof line === "string")
1973
+ lines.push(line);
1974
+ };
1975
+ const parts = [];
1976
+ const styles = [];
1977
+ if (browser) {
1978
+ const lc = getCssLevelColor(levelLabel);
1979
+ parts.push(`%c${ts}%c %c${levelLabel.toUpperCase()}%c %c[${escapeFormatString(String(service))}]%c`);
1980
+ styles.push(cssColors.dim, cssColors.reset, lc, cssColors.reset, cssColors.cyan, cssColors.reset);
1981
+ } else {
1982
+ const lc = getLevelColor(levelLabel);
1983
+ parts.push(`${colors.dim}${ts}${colors.reset} ${lc}${levelLabel.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
1984
+ }
1985
+ if (rest.method && rest.path) {
1986
+ parts.push(browser ? ` ${escapeFormatString(String(rest.method))} ${escapeFormatString(String(rest.path))}` : ` ${rest.method} ${rest.path}`);
1987
+ delete rest.method;
1988
+ delete rest.path;
1989
+ }
1990
+ if (rest.status) {
1991
+ const statusCode = asNumber(rest.status) ?? Number(rest.status);
1992
+ const sc = browser ? statusCode >= 400 ? cssColors.red : cssColors.green : statusCode >= 400 ? colors.red : colors.green;
1993
+ if (browser) {
1994
+ parts.push(` %c${rest.status}%c`);
1995
+ styles.push(sc, cssColors.reset);
1996
+ } else
1997
+ parts.push(` ${sc}${rest.status}${colors.reset}`);
1998
+ delete rest.status;
1999
+ }
2000
+ if (rest.duration) {
2001
+ if (browser) {
2002
+ parts.push(` %c${escapeFormatString(`in ${rest.duration}`)}%c`);
2003
+ styles.push(cssColors.dim, cssColors.reset);
2004
+ } else
2005
+ parts.push(` ${colors.dim}in ${rest.duration}${colors.reset}`);
2006
+ delete rest.duration;
2007
+ }
2008
+ delete rest.durationMs;
2009
+ writeLine(parts.join(""), ...styles);
2010
+ const aiData = isPlainObject$1(rest.ai) ? rest.ai : undefined;
2011
+ if (aiData)
2012
+ delete rest.ai;
2013
+ const errorData = rest.error;
2014
+ if (errorData !== undefined)
2015
+ delete rest.error;
2016
+ const restEntries = Object.entries(rest).filter(([_, v]) => v !== undefined);
2017
+ const aiEntries = aiData ? buildAIEntries(aiData) : [];
2018
+ const errorEntries = errorData !== undefined ? buildErrorEntries(errorData, state.prettyError) : [];
2019
+ const contextEntries = [...restEntries.map(([key, value]) => ({
2020
+ key,
2021
+ value: formatValue(value)
2022
+ })), ...aiEntries];
2023
+ const allEntries = errorEntries.length > 0 ? [...errorEntries, ...contextEntries] : contextEntries;
2024
+ for (let i = 0;i < allEntries.length; i++) {
2025
+ const entry = allEntries[i];
2026
+ if (!entry)
2027
+ continue;
2028
+ const { children } = entry;
2029
+ const hasChildren = children !== undefined && children.length > 0;
2030
+ const prefix = i === allEntries.length - 1 && !hasChildren ? "\u2514\u2500" : "\u251C\u2500";
2031
+ if (browser) {
2032
+ const val = entry.value ? ` ${escapeFormatString(entry.value)}` : "";
2033
+ writeLine(` %c${prefix}%c %c${escapeFormatString(entry.key)}:%c${val}`, cssColors.dim, cssColors.reset, cssColors.cyan, cssColors.reset);
2034
+ } else {
2035
+ const val = entry.value ? ` ${entry.value}` : "";
2036
+ writeLine(` ${colors.dim}${prefix}${colors.reset} ${colors.cyan}${entry.key}:${colors.reset}${val}`);
2037
+ }
2038
+ if (hasChildren && children) {
2039
+ const connector = i === allEntries.length - 1 ? " " : "\u2502";
2040
+ for (let j = 0;j < children.length; j++) {
2041
+ const child = children[j];
2042
+ if (child === undefined)
2043
+ continue;
2044
+ if (child === "__EVLOG_TREE_SPACER__") {
2045
+ writeLine(` ${colors.dim}${connector}${colors.reset}`);
2046
+ continue;
2047
+ }
2048
+ const childPrefix = j === children.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
2049
+ if (child === "") {
2050
+ writeLine("");
2051
+ continue;
2052
+ }
2053
+ if (browser)
2054
+ writeLine(` %c${connector} ${childPrefix}%c ${escapeFormatString(child)}`, cssColors.dim, cssColors.reset);
2055
+ else if (child.startsWith(" ") || child.startsWith("\x1B"))
2056
+ writeLine(` ${colors.dim}${connector}${colors.reset}${child}`);
2057
+ else
2058
+ writeLine(` ${colors.dim}${connector} ${childPrefix}${colors.reset} ${child}`);
2059
+ }
2060
+ }
2061
+ }
2062
+ if (!browser && lines.length > 0)
2063
+ flushPrettyLines(lines);
2064
+ }
2065
+ function removeErrorCycles(value, ancestors) {
2066
+ if (value === null || typeof value !== "object")
2067
+ return value;
2068
+ if (ancestors.has(value))
2069
+ return "[Circular]";
2070
+ ancestors.add(value);
2071
+ let changed = false;
2072
+ const visit = (item) => {
2073
+ const result = removeErrorCycles(item, ancestors);
2074
+ if (!Object.is(result, item))
2075
+ changed = true;
2076
+ return result;
2077
+ };
2078
+ const copy = Array.isArray(value) ? value.map(visit) : Object.fromEntries(Object.entries(value).map(([key, item]) => [key, visit(item)]));
2079
+ ancestors.delete(value);
2080
+ return changed ? copy : value;
2081
+ }
2082
+ function serializeError(err) {
2083
+ const errorObj = {
2084
+ name: err.name,
2085
+ message: err.message,
2086
+ stack: isDev() ? compactStackForStorage(err.stack) : err.stack
2087
+ };
2088
+ const errRecord = err;
2089
+ const ancestors = new WeakSet([err]);
2090
+ for (const k of [
2091
+ "code",
2092
+ "status",
2093
+ "statusText",
2094
+ "statusCode",
2095
+ "statusMessage",
2096
+ "data",
2097
+ "cause",
2098
+ "internal"
2099
+ ])
2100
+ if (k in err)
2101
+ errorObj[k] = removeErrorCycles(errRecord[k], ancestors);
2102
+ if (EvlogError.isEvlogError(err)) {
2103
+ if (err.code)
2104
+ errorObj.code = err.code;
2105
+ if (err.why)
2106
+ errorObj.why = err.why;
2107
+ if (err.fix)
2108
+ errorObj.fix = err.fix;
2109
+ if (err.link)
2110
+ errorObj.link = err.link;
2111
+ if (err.status)
2112
+ errorObj.status = err.status;
2113
+ }
2114
+ return errorObj;
2115
+ }
2116
+ function createLogMethod(level) {
2117
+ return function logMethod(tagOrEvent, message) {
2118
+ if (typeof tagOrEvent === "string" && message !== undefined)
2119
+ emitTaggedLog(level, tagOrEvent, message);
2120
+ else if (tagOrEvent instanceof Error)
2121
+ emitWideEvent(level, { error: serializeError(tagOrEvent) });
2122
+ else if (typeof tagOrEvent === "object")
2123
+ emitWideEvent(level, tagOrEvent);
2124
+ else
2125
+ emitTaggedLog(level, "log", String(tagOrEvent));
2126
+ };
2127
+ }
2128
+ var _log = {
2129
+ info: createLogMethod("info"),
2130
+ error: createLogMethod("error"),
2131
+ warn: createLogMethod("warn"),
2132
+ debug: createLogMethod("debug")
2133
+ };
2134
+ var noopLogger = {
2135
+ set() {},
2136
+ setLevel() {},
2137
+ error() {},
2138
+ info() {},
2139
+ warn() {},
2140
+ emit() {
2141
+ return null;
2142
+ },
2143
+ getContext() {
2144
+ return {};
2145
+ },
2146
+ audit: Object.assign(() => {}, { deny: () => {} })
2147
+ };
2148
+ function createLogger(initialContext = {}, internalOptions) {
2149
+ if (!state.enabled)
2150
+ return noopLogger;
2151
+ const deferDrain = internalOptions?._deferDrain ?? false;
2152
+ const waitUntil = internalOptions?.waitUntil;
2153
+ const startTime = Date.now();
2154
+ const context = { ...initialContext };
2155
+ let hasError = false;
2156
+ let hasWarn = false;
2157
+ let manualLevel;
2158
+ let emitted = false;
2159
+ let pendingWideEvent = null;
2160
+ function addLog(level, message) {
2161
+ if (!Array.isArray(context.requestLogs))
2162
+ context.requestLogs = [];
2163
+ context.requestLogs.push({
2164
+ level,
2165
+ message,
2166
+ timestamp: isoNow()
2167
+ });
2168
+ }
2169
+ const auditMethod = function audit(input) {
2170
+ if (emitted) {
2171
+ warnPostEmit("log.audit()", `Audit dropped: action=${input.action}.`);
2172
+ return;
2173
+ }
2174
+ const fields = buildAuditFields(input);
2175
+ if (!isPlainObject$1(context.audit))
2176
+ context.audit = fields;
2177
+ else
2178
+ mergeInto(context.audit, fields);
2179
+ context._auditForceKeep = true;
2180
+ };
2181
+ auditMethod.deny = function deny(reason, input) {
2182
+ auditMethod({
2183
+ ...input,
2184
+ outcome: "denied",
2185
+ reason
2186
+ });
2187
+ };
2188
+ return {
2189
+ audit: auditMethod,
2190
+ set(data) {
2191
+ if (emitted) {
2192
+ const record = data;
2193
+ const pendingState = pendingWideEvent ? pendingDrainState.get(pendingWideEvent) : undefined;
2194
+ if (pendingWideEvent && pendingState && !pendingState.drainStarted && isAiOnlyFieldUpdate(record)) {
2195
+ mergeInto(pendingWideEvent, record);
2196
+ return;
2197
+ }
2198
+ const keys = Object.keys(record);
2199
+ warnPostEmit("log.set()", `Keys dropped: ${keys.length ? keys.join(", ") : "(empty)"}.`);
2200
+ return;
2201
+ }
2202
+ mergeInto(context, data);
2203
+ },
2204
+ setLevel(level) {
2205
+ if (emitted) {
2206
+ warnPostEmit("log.setLevel()", `Level dropped: ${level}.`);
2207
+ return;
2208
+ }
2209
+ manualLevel = level;
2210
+ },
2211
+ error(error, errorContext) {
2212
+ if (emitted) {
2213
+ warnPostEmit("log.error()", `Keys dropped: ${(errorContext ? [...Object.keys(errorContext), "error"] : ["error"]).join(", ")}.`);
2214
+ return;
2215
+ }
2216
+ hasError = true;
2217
+ const err = typeof error === "string" ? new Error(error) : error;
2218
+ if (errorContext)
2219
+ mergeInto(context, errorContext);
2220
+ const errorObj = serializeError(err);
2221
+ if (isPlainObject$1(context.error))
2222
+ mergeInto(context.error, errorObj);
2223
+ else
2224
+ context.error = errorObj;
2225
+ },
2226
+ info(message, infoContext) {
2227
+ if (emitted) {
2228
+ warnPostEmit("log.info()", `Keys dropped: ${(infoContext ? ["message", ...Object.keys(infoContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
2229
+ return;
2230
+ }
2231
+ addLog("info", message);
2232
+ if (infoContext) {
2233
+ const { requestLogs: _, ...rest } = infoContext;
2234
+ mergeInto(context, rest);
2235
+ }
2236
+ },
2237
+ warn(message, warnContext) {
2238
+ if (emitted) {
2239
+ warnPostEmit("log.warn()", `Keys dropped: ${(warnContext ? ["message", ...Object.keys(warnContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
2240
+ return;
2241
+ }
2242
+ hasWarn = true;
2243
+ addLog("warn", message);
2244
+ if (warnContext) {
2245
+ const { requestLogs: _, ...rest } = warnContext;
2246
+ mergeInto(context, rest);
2247
+ }
2248
+ },
2249
+ emit(overrides) {
2250
+ if (emitted) {
2251
+ warnPostEmit("log.emit()", "Ignoring duplicate emit.");
2252
+ return null;
2253
+ }
2254
+ const durationMs = elapsedMs(startTime);
2255
+ const level = manualLevel ?? (hasError ? "error" : hasWarn ? "warn" : "info");
2256
+ let forceKeep = false;
2257
+ const auditForceKeep = consumeAuditForceKeep(context);
2258
+ if (overrides?._forceKeep)
2259
+ forceKeep = true;
2260
+ else if (auditForceKeep)
2261
+ forceKeep = true;
2262
+ else if (state.sampling.keep?.length)
2263
+ forceKeep = shouldKeep({
2264
+ status: overrides?.status ?? context.status,
2265
+ duration: durationMs,
2266
+ path: context.path,
2267
+ method: context.method,
2268
+ context
2269
+ });
2270
+ if (!forceKeep && !shouldSample(level)) {
2271
+ emitted = true;
2272
+ pendingWideEvent = null;
2273
+ return null;
2274
+ }
2275
+ if (overrides) {
2276
+ const obj = overrides;
2277
+ for (const key in obj)
2278
+ if (key !== "_forceKeep")
2279
+ context[key] = obj[key];
2280
+ }
2281
+ context.durationMs = durationMs;
2282
+ context.duration = formatDuration(durationMs);
2283
+ const wide = emitWideEvent(level, context, {
2284
+ deferDrain,
2285
+ ownsEvent: true,
2286
+ waitUntil
2287
+ });
2288
+ emitted = true;
2289
+ pendingWideEvent = wide;
2290
+ if (wide)
2291
+ pendingDrainState.set(wide, { drainStarted: !deferDrain });
2292
+ return wide;
2293
+ },
2294
+ getContext() {
2295
+ return { ...context };
2296
+ }
2297
+ };
2298
+ }
2299
+ function createRequestLogger(options = {}, internalOptions) {
2300
+ const { method, path, requestId, waitUntil: optionsWaitUntil } = options;
2301
+ const initial = {};
2302
+ if (method !== undefined)
2303
+ initial.method = method;
2304
+ if (path !== undefined)
2305
+ initial.path = path;
2306
+ if (requestId !== undefined)
2307
+ initial.requestId = requestId;
2308
+ return createLogger(initial, {
2309
+ ...internalOptions,
2310
+ waitUntil: internalOptions?.waitUntil ?? optionsWaitUntil
2311
+ });
2312
+ }
2313
+ if (typeof __EVLOG_CONFIG__ !== "undefined")
2314
+ initLogger(__EVLOG_CONFIG__);
2315
+ function isPlainObject2(value) {
2316
+ if (typeof value !== "object" || value === null || Array.isArray(value))
2317
+ return false;
2318
+ if (Object.prototype.toString.call(value) !== "[object Object]")
2319
+ return false;
2320
+ return Object.getPrototypeOf(value) === Object.prototype || value.constructor === Object;
2321
+ }
2322
+ function stableStringify(value, ancestors = /* @__PURE__ */ new WeakSet) {
2323
+ if (value === null || typeof value !== "object")
2324
+ return JSON.stringify(value);
2325
+ if (ancestors.has(value))
2326
+ return '"[Circular]"';
2327
+ if (!Array.isArray(value) && !isPlainObject2(value))
2328
+ return JSON.stringify(value);
2329
+ ancestors.add(value);
2330
+ const out = Array.isArray(value) ? `[${value.map((v) => stableStringify(v, ancestors)).join(",")}]` : `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(value[k], ancestors)}`).join(",")}}`;
2331
+ ancestors.delete(value);
2332
+ return out;
2333
+ }
2334
+ function fnv1a32(input, seed) {
2335
+ let h = seed >>> 0;
2336
+ for (let i = 0;i < input.length; i++) {
2337
+ h ^= input.charCodeAt(i) & 255;
2338
+ h = Math.imul(h, 16777619) >>> 0;
2339
+ }
2340
+ return h >>> 0;
2341
+ }
2342
+ function computeIdempotencyKey(audit, timestamp) {
2343
+ const seconds = timestamp.slice(0, 19);
2344
+ const payload = stableStringify({
2345
+ action: audit.action,
2346
+ actor: {
2347
+ type: audit.actor.type,
2348
+ id: audit.actor.id
2349
+ },
2350
+ target: audit.target ? {
2351
+ type: audit.target.type,
2352
+ id: audit.target.id
2353
+ } : undefined,
2354
+ outcome: audit.outcome,
2355
+ timestamp: seconds
2356
+ });
2357
+ const a = fnv1a32(payload, 2166136261).toString(16).padStart(8, "0");
2358
+ const b = fnv1a32(payload, 3735928559).toString(16).padStart(8, "0");
2359
+ const c = fnv1a32(payload, 528734635).toString(16).padStart(8, "0");
2360
+ const d = fnv1a32(payload, 1541459225).toString(16).padStart(8, "0");
2361
+ return a + b + c + d;
2362
+ }
2363
+ function buildAuditFields(input) {
2364
+ return {
2365
+ action: input.action,
2366
+ actor: input.actor,
2367
+ target: input.target,
2368
+ outcome: input.outcome ?? "success",
2369
+ reason: input.reason,
2370
+ changes: input.changes,
2371
+ causationId: input.causationId,
2372
+ correlationId: input.correlationId,
2373
+ version: input.version ?? 1
2374
+ };
2375
+ }
2376
+ var _testCollector = null;
2377
+ function decorateAudit(audit, timestamp) {
2378
+ if (audit.idempotencyKey)
2379
+ return audit;
2380
+ return {
2381
+ ...audit,
2382
+ idempotencyKey: computeIdempotencyKey(audit, timestamp)
2383
+ };
2384
+ }
2385
+ function consumeAuditForceKeep(context) {
2386
+ if (context._auditForceKeep) {
2387
+ delete context._auditForceKeep;
2388
+ return true;
2389
+ }
2390
+ if (context.audit)
2391
+ return true;
2392
+ return false;
2393
+ }
2394
+ function isCompleteAuditFields(a) {
2395
+ if (!a || typeof a !== "object")
2396
+ return false;
2397
+ const audit = a;
2398
+ return typeof audit.action === "string" && typeof audit.actor?.type === "string" && typeof audit.actor?.id === "string";
2399
+ }
2400
+ function finalizeAudit(event) {
2401
+ const a = event.audit;
2402
+ if (!isCompleteAuditFields(a))
2403
+ return;
2404
+ const decorated = decorateAudit(a, String(event.timestamp));
2405
+ event.audit = decorated;
2406
+ _testCollector?.(decorated, event);
2407
+ }
2408
+
2409
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/errors-CL8dDgIi.mjs
2410
+ function extractErrorStatus(error) {
2411
+ if (error === null || typeof error !== "object")
2412
+ return 500;
2413
+ const raw = error.status ?? error.statusCode;
2414
+ const status = Number(raw);
2415
+ return Number.isFinite(status) ? status : 500;
2416
+ }
2417
+
2418
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
2419
+ function shouldLog(path, include, exclude) {
2420
+ if (exclude && exclude.length > 0) {
2421
+ if (exclude.some((pattern) => matchesPattern(path, pattern)))
2422
+ return false;
2423
+ }
2424
+ if (!include || include.length === 0)
2425
+ return true;
2426
+ return include.some((pattern) => matchesPattern(path, pattern));
2427
+ }
2428
+ function getServiceForPath(path, routes) {
2429
+ if (!routes)
2430
+ return;
2431
+ for (const [pattern, config] of Object.entries(routes))
2432
+ if (matchesPattern(path, pattern))
2433
+ return config.service;
2434
+ }
2435
+ function extendDeferredDrain(drainPromise, waitUntil) {
2436
+ drainPromise.catch((err) => {
2437
+ console.error("[evlog] background drain failed:", err);
2438
+ });
2439
+ if (typeof waitUntil === "function")
2440
+ waitUntil(drainPromise);
2441
+ }
2442
+
2443
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/middleware-fam3VyaL.mjs
2444
+ var noopResult = {
2445
+ logger: noopLogger,
2446
+ finish: () => Promise.resolve(null),
2447
+ finishResponse: (response) => Promise.resolve(response),
2448
+ skipped: true
2449
+ };
2450
+ var runnerCache = /* @__PURE__ */ new WeakMap;
2451
+ function resolveMiddlewarePluginRunner(options) {
2452
+ const global = getGlobalPluginRunner();
2453
+ const local = options.plugins;
2454
+ if (!local || local.length === 0)
2455
+ return global;
2456
+ const cached = runnerCache.get(local);
2457
+ if (cached && cached.global === global)
2458
+ return cached.merged;
2459
+ const merged = /* @__PURE__ */ new Map;
2460
+ for (const plugin of global.plugins)
2461
+ merged.set(plugin.name, plugin);
2462
+ for (const plugin of local)
2463
+ merged.set(plugin.name, plugin);
2464
+ if (merged.size === 0)
2465
+ return getEmptyPluginRunner();
2466
+ const runner = createPluginRunner(Array.from(merged.values()));
2467
+ runnerCache.set(local, {
2468
+ global,
2469
+ merged: runner
2470
+ });
2471
+ return runner;
2472
+ }
2473
+ function assignRedactedEvent(target, redacted) {
2474
+ for (const key of Object.keys(target))
2475
+ if (!(key in redacted))
2476
+ delete target[key];
2477
+ Object.assign(target, redacted);
2478
+ }
2479
+ async function runEnrichAndDrain(emittedEvent, options, requestInfo, responseStatus, plugins) {
2480
+ const runner = plugins ?? resolveMiddlewarePluginRunner(options);
2481
+ const resolvedRedact = resolveRedactConfig(options.redact);
2482
+ if (resolvedRedact && !isGloballyRedacted(emittedEvent))
2483
+ assignRedactedEvent(emittedEvent, redactEvent(emittedEvent, resolvedRedact));
2484
+ if (options.enrich || runner.hasEnrich) {
2485
+ const enrichCtx = {
2486
+ event: emittedEvent,
2487
+ request: requestInfo,
2488
+ headers: options.headers,
2489
+ response: { status: responseStatus }
2490
+ };
2491
+ if (options.enrich)
2492
+ try {
2493
+ await options.enrich(enrichCtx);
2494
+ } catch (err) {
2495
+ console.error("[evlog] enrich failed:", err);
2496
+ }
2497
+ if (runner.hasEnrich)
2498
+ await runner.runEnrich(enrichCtx);
2499
+ }
2500
+ publishWideEvent(emittedEvent);
2501
+ markWideEventDrainStarted(emittedEvent);
2502
+ const drain = options.drain ?? getGlobalDrain();
2503
+ const hasUserDrain = !!drain;
2504
+ const hasPluginDrain = runner.hasDrain;
2505
+ if (hasUserDrain || hasPluginDrain) {
2506
+ const drainCtx = {
2507
+ event: emittedEvent,
2508
+ request: requestInfo,
2509
+ headers: options.headers
2510
+ };
2511
+ const tasks = [];
2512
+ if (hasUserDrain)
2513
+ tasks.push((async () => {
2514
+ try {
2515
+ await drain(drainCtx);
2516
+ } catch (err) {
2517
+ console.error("[evlog] drain failed:", err);
2518
+ }
2519
+ })());
2520
+ if (hasPluginDrain)
2521
+ tasks.push(runner.runDrain(drainCtx));
2522
+ const drainPromise = Promise.all(tasks);
2523
+ if (options.waitUntil) {
2524
+ extendDeferredDrain(drainPromise, options.waitUntil);
2525
+ if (hasUserDrain) {
2526
+ const { settled } = drain;
2527
+ if (typeof settled === "function")
2528
+ extendDeferredDrain(settled(), options.waitUntil);
2529
+ }
2530
+ return;
2531
+ }
2532
+ await drainPromise;
2533
+ }
2534
+ }
2535
+ function createMiddlewareLogger(options) {
2536
+ if (!isEnabled())
2537
+ return noopResult;
2538
+ const { method, path, requestId, include, exclude, routes, keep } = options;
2539
+ if (!shouldLog(path, include, exclude))
2540
+ return noopResult;
2541
+ const resolvedRequestId = requestId || crypto.randomUUID();
2542
+ const logger = createRequestLogger({
2543
+ method,
2544
+ path,
2545
+ requestId: resolvedRequestId
2546
+ }, { _deferDrain: true });
2547
+ const routeService = getServiceForPath(path, routes);
2548
+ if (routeService)
2549
+ logger.set({ service: routeService });
2550
+ const pluginRunner = resolveMiddlewarePluginRunner(options);
2551
+ if (pluginRunner.hasExtendLogger)
2552
+ pluginRunner.applyExtendLogger(logger);
2553
+ const startTime = Date.now();
2554
+ const requestInfo = {
2555
+ method,
2556
+ path,
2557
+ requestId: resolvedRequestId
2558
+ };
2559
+ if (pluginRunner.hasRequestLifecycle)
2560
+ pluginRunner.runOnRequestStart({
2561
+ logger,
2562
+ request: requestInfo,
2563
+ headers: options.headers
2564
+ });
2565
+ const finish = (opts) => {
2566
+ return performFinish(logger, opts);
2567
+ };
2568
+ const finishResponse = async (response, opts) => {
2569
+ const status = opts?.status ?? response.status;
2570
+ if (!shouldDeferEmitForResponse(response)) {
2571
+ await performFinish(logger, { status });
2572
+ return response;
2573
+ }
2574
+ return bindStreamingResponseLifecycle(response, async (meta) => {
2575
+ await performFinish(logger, {
2576
+ status: meta.status ?? status,
2577
+ error: meta.error
2578
+ });
2579
+ });
2580
+ };
2581
+ async function performFinish(requestLogger, opts) {
2582
+ const { status, error } = opts ?? {};
2583
+ if (error) {
2584
+ requestLogger.error(error);
2585
+ const errorStatus = extractErrorStatus(error);
2586
+ requestLogger.set({ status: errorStatus });
2587
+ } else if (status !== undefined)
2588
+ requestLogger.set({ status });
2589
+ const durationMs = elapsedMs(startTime);
2590
+ const resolvedStatus = error ? extractErrorStatus(error) : status ?? requestLogger.getContext().status;
2591
+ const tailCtx = {
2592
+ status: resolvedStatus,
2593
+ duration: durationMs,
2594
+ path,
2595
+ method,
2596
+ context: requestLogger.getContext(),
2597
+ shouldKeep: false
2598
+ };
2599
+ if (keep)
2600
+ await keep(tailCtx);
2601
+ if (pluginRunner.hasKeep)
2602
+ await pluginRunner.runKeep(tailCtx);
2603
+ const forceKeep = tailCtx.shouldKeep || shouldKeep(tailCtx);
2604
+ const emittedEvent = requestLogger.emit({ _forceKeep: forceKeep });
2605
+ if (emittedEvent && (options.enrich || options.drain || pluginRunner.hasEnrich || pluginRunner.hasDrain || getGlobalDrain() || hasWideEventPublisher()))
2606
+ await runEnrichAndDrain(emittedEvent, options, requestInfo, resolvedStatus, pluginRunner);
2607
+ if (pluginRunner.hasRequestLifecycle)
2608
+ pluginRunner.runOnRequestFinish({
2609
+ logger: requestLogger,
2610
+ request: requestInfo,
2611
+ headers: options.headers,
2612
+ event: emittedEvent,
2613
+ status: resolvedStatus,
2614
+ durationMs,
2615
+ error
2616
+ });
2617
+ return emittedEvent;
2618
+ }
2619
+ return {
2620
+ logger,
2621
+ finish,
2622
+ finishResponse,
2623
+ skipped: false
2624
+ };
2625
+ }
2626
+
2627
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/integration-CGD18W8r.mjs
2628
+ function attachForkToLogger(storage, parent, middlewareOptions, lifecycle) {
2629
+ const log = parent;
2630
+ log.fork = (label, fn) => {
2631
+ forkBackgroundLogger({
2632
+ storage,
2633
+ parent,
2634
+ middlewareOptions,
2635
+ label,
2636
+ fn,
2637
+ lifecycle
2638
+ });
2639
+ };
2640
+ }
2641
+ function forkBackgroundLogger(options) {
2642
+ const { storage, parent, middlewareOptions, label, fn, lifecycle } = options;
2643
+ const parentCtx = parent.getContext();
2644
+ const parentRequestId = parentCtx.requestId;
2645
+ if (typeof parentRequestId !== "string" || parentRequestId.length === 0)
2646
+ throw new Error("[evlog] log.fork() requires the parent logger to have a requestId. Ensure the request was created by evlog middleware.");
2647
+ const method = String(parentCtx.method ?? middlewareOptions.method);
2648
+ const path = String(parentCtx.path ?? middlewareOptions.path);
2649
+ const child = createRequestLogger({
2650
+ method,
2651
+ path,
2652
+ requestId: crypto.randomUUID()
2653
+ }, { _deferDrain: true });
2654
+ child.set({
2655
+ operation: label,
2656
+ _parentRequestId: parentRequestId
2657
+ });
2658
+ const childRequestInfo = {
2659
+ method,
2660
+ path,
2661
+ requestId: child.getContext().requestId
2662
+ };
2663
+ storage.run(child, () => {
2664
+ lifecycle?.onChildEnter?.(child);
2665
+ Promise.resolve().then(() => fn()).then(async () => {
2666
+ const emittedEvent = child.emit();
2667
+ const ctxStatus = child.getContext().status;
2668
+ const status = emittedEvent?.status ?? (typeof ctxStatus === "number" ? ctxStatus : undefined);
2669
+ if (emittedEvent && (middlewareOptions.enrich || middlewareOptions.drain || getGlobalDrain()))
2670
+ await runEnrichAndDrain(emittedEvent, middlewareOptions, childRequestInfo, status);
2671
+ }).catch(async (err) => {
2672
+ const error = err instanceof Error ? err : new Error(String(err));
2673
+ child.error(error);
2674
+ child.set({ status: extractErrorStatus(error) });
2675
+ const emittedEvent = child.emit();
2676
+ const status = extractErrorStatus(error);
2677
+ if (emittedEvent && (middlewareOptions.enrich || middlewareOptions.drain || getGlobalDrain()))
2678
+ await runEnrichAndDrain(emittedEvent, middlewareOptions, childRequestInfo, status);
2679
+ }).finally(() => {
2680
+ lifecycle?.onChildExit?.(child);
2681
+ });
2682
+ });
2683
+ }
2684
+ function normalizeHeaders(headers) {
2685
+ if (!headers)
2686
+ return;
2687
+ if (typeof headers.forEach === "function" && typeof headers.get === "function")
2688
+ return extractSafeHeaders(headers);
2689
+ return extractSafeNodeHeaders(headers);
2690
+ }
2691
+ function defineFrameworkIntegration(spec) {
2692
+ return { start(ctx, options = {}) {
2693
+ const extracted = spec.extractRequest(ctx);
2694
+ const headers = normalizeHeaders(extracted.headers);
2695
+ const waitUntil = options.waitUntil ?? spec.extractWaitUntil?.(ctx);
2696
+ const middlewareOptions = {
2697
+ method: extracted.method,
2698
+ path: extracted.path,
2699
+ requestId: extracted.requestId || crypto.randomUUID(),
2700
+ headers,
2701
+ ...options,
2702
+ waitUntil
2703
+ };
2704
+ const result = createMiddlewareLogger(middlewareOptions);
2705
+ if (!result.skipped) {
2706
+ if (spec.storage)
2707
+ attachForkToLogger(spec.storage, result.logger, middlewareOptions, spec.forkLifecycle);
2708
+ spec.attachLogger(ctx, result.logger);
2709
+ }
2710
+ const { storage } = spec;
2711
+ const runWith = async (fn) => {
2712
+ if (!storage || result.skipped)
2713
+ return await fn();
2714
+ return await storage.run(result.logger, fn);
2715
+ };
2716
+ return {
2717
+ ...result,
2718
+ middlewareOptions,
2719
+ runWith
2720
+ };
2721
+ } };
2722
+ }
2723
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/toolkit/storage.mjs
2724
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
2725
+ function createLoggerStorage(contextHint, id = contextHint) {
2726
+ const storage = getSharedStorage(id, () => new AsyncLocalStorage2);
2727
+ function useLogger() {
2728
+ const logger = storage.getStore();
2729
+ if (!logger)
2730
+ throw new Error(`[evlog] useLogger() was called outside of an evlog ${contextHint}`);
2731
+ return logger;
2732
+ }
2733
+ return {
2734
+ storage,
2735
+ useLogger
2736
+ };
2737
+ }
2738
+
2739
+ // src/server/evlog.ts
2740
+ var loggerStorage = createLoggerStorage("Furin request context. Make sure the Furin plugin is registered before your routes.", "@teyik0/furin:evlog");
2741
+ var integration = defineFrameworkIntegration({
2742
+ attachLogger: () => {
2743
+ return;
2744
+ },
2745
+ extractRequest: ({ request }) => {
2746
+ const url = new URL(request.url);
2747
+ return {
2748
+ headers: request.headers,
2749
+ method: request.method,
2750
+ path: url.pathname,
2751
+ requestId: request.headers.get("x-request-id") ?? undefined
2752
+ };
2753
+ },
2754
+ name: "furin",
2755
+ storage: loggerStorage.storage
2756
+ });
2757
+ var getRequestLogger = loggerStorage.useLogger;
2758
+ var runtimeWaitUntil = new Set;
2759
+ function setRuntimeEvlogWaitUntil(waitUntil) {
2760
+ runtimeWaitUntil.add(waitUntil);
2761
+ return () => runtimeWaitUntil.delete(waitUntil);
2762
+ }
2763
+
2764
+ // src/server/sync/stream.ts
2765
+ import { Elysia as Elysia2 } from "elysia";
2766
+ var cursorStates = new Map;
2767
+ var resolvedStates = new Set;
2768
+ var pendingUnsubscriptions = new Set;
2769
+ var unsubscriptions = new WeakMap;
2770
+ function trackUnsubscription(subscription) {
2771
+ const existing = unsubscriptions.get(subscription);
2772
+ if (existing) {
2773
+ return existing;
2774
+ }
2775
+ const pending = subscription.unsubscribe();
2776
+ unsubscriptions.set(subscription, pending);
2777
+ pendingUnsubscriptions.add(pending);
2778
+ pending.finally(() => pendingUnsubscriptions.delete(pending)).catch(() => {
2779
+ return;
2780
+ });
2781
+ return pending;
2782
+ }
2783
+ async function closeSyncCursorStates() {
2784
+ const pending = [...cursorStates.values()];
2785
+ cursorStates.clear();
2786
+ const states = await Promise.allSettled(pending);
2787
+ await Promise.allSettled(states.flatMap((result) => {
2788
+ if (result.status !== "fulfilled") {
2789
+ return [];
2790
+ }
2791
+ const state = result.value;
2792
+ if (state.safetyPoll) {
2793
+ clearInterval(state.safetyPoll);
2794
+ }
2795
+ state.listeners.clear();
2796
+ resolvedStates.delete(state);
2797
+ return [trackUnsubscription(state.subscription)];
2798
+ }));
2799
+ await waitForSyncCursorUnsubscriptions();
2800
+ }
2801
+ async function waitForSyncCursorUnsubscriptions() {
2802
+ await Promise.allSettled([...pendingUnsubscriptions]);
2803
+ }
2804
+
2805
+ // src/server/production-server.ts
2806
+ var DEFAULT_PRE_STOP_DELAY_MS = 5000;
2807
+ var DEFAULT_SHUTDOWN_TIMEOUT_MS = 30000;
2808
+ var activeShutdowns = new Set;
2809
+ var syncDrainsReached = new Set;
2810
+ var signalShutdown = () => {
2811
+ Promise.allSettled([...activeShutdowns].map((shutdown) => shutdown())).then((results) => {
2812
+ let code = process.exitCode ?? 0;
2813
+ for (const result of results) {
2814
+ if (result.status === "rejected") {
2815
+ console.error("[furin] Graceful shutdown failed", result.reason);
2816
+ code = 1;
2817
+ }
2818
+ }
2819
+ process.exit(code);
2820
+ });
2821
+ };
2822
+ function startProductionServer(options) {
2823
+ const { app } = options;
2824
+ const pendingEmissions = new Set;
2825
+ let draining = false;
2826
+ let rejecting = false;
2827
+ const unregisterWaitUntil = setRuntimeEvlogWaitUntil((emission) => {
2828
+ pendingEmissions.add(emission);
2829
+ emission.finally(() => pendingEmissions.delete(emission)).catch(() => {
2830
+ return;
2831
+ });
2832
+ });
2833
+ app.wrap((fetch) => (request, ...rest) => {
2834
+ const path = new URL(request.url).pathname;
2835
+ if (rejecting && path !== "/_furin/health/live" && path !== "/_furin/health/ready") {
2836
+ return Promise.resolve(new Response("Service Unavailable", { status: 503 }));
2837
+ }
2838
+ return fetch(request, ...rest);
2839
+ }).get("/_furin/health/live", () => Response.json({ status: "alive" }, { headers: { "cache-control": "no-store" } })).get("/_furin/health/ready", () => Response.json({ status: draining ? "draining" : "ready" }, { headers: { "cache-control": "no-store" }, status: draining ? 503 : 200 }));
2840
+ app.listen(options.idleTimeout === undefined ? options.port : { idleTimeout: options.idleTimeout, port: options.port });
2841
+ const { server } = app;
2842
+ if (!server) {
2843
+ throw new Error("[furin] Bun server did not start");
2844
+ }
2845
+ let shutdownPromise;
2846
+ const shutdown = () => {
2847
+ if (shutdownPromise) {
2848
+ return shutdownPromise;
2849
+ }
2850
+ draining = true;
2851
+ const timeoutMs = options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;
2852
+ const delayMs = options.preStopDelayMs ?? DEFAULT_PRE_STOP_DELAY_MS;
2853
+ shutdownPromise = (async () => {
2854
+ let timeout;
2855
+ try {
2856
+ await Bun.sleep(delayMs);
2857
+ rejecting = true;
2858
+ const deadline = new Promise((resolve) => {
2859
+ timeout = setTimeout(() => {
2860
+ console.error("[furin] Shutdown deadline exceeded; forcing server stop");
2861
+ server.stop(true).catch((error) => {
2862
+ console.error("[furin] Forced server stop failed", error);
2863
+ });
2864
+ resolve();
2865
+ }, timeoutMs);
2866
+ });
2867
+ const drain = async () => {
2868
+ closeBrowserEventConnections(server);
2869
+ server.closeIdleConnections();
2870
+ await server.stop();
2871
+ await waitForPendingISRRevalidations();
2872
+ await Promise.allSettled([...pendingEmissions]);
2873
+ syncDrainsReached.add(shutdown);
2874
+ if (syncDrainsReached.size === activeShutdowns.size) {
2875
+ await closeSyncCursorStates();
2876
+ } else {
2877
+ await waitForSyncCursorUnsubscriptions();
2878
+ }
2879
+ await options.onShutdown?.();
2880
+ };
2881
+ await Promise.race([drain(), deadline]);
2882
+ } finally {
2883
+ if (timeout) {
2884
+ clearTimeout(timeout);
2885
+ }
2886
+ activeShutdowns.delete(shutdown);
2887
+ syncDrainsReached.delete(shutdown);
2888
+ if (activeShutdowns.size === 0) {
2889
+ process.off("SIGTERM", signalShutdown);
2890
+ process.off("SIGINT", signalShutdown);
2891
+ }
2892
+ unregisterWaitUntil();
2893
+ }
2894
+ })();
2895
+ return shutdownPromise;
2896
+ };
2897
+ if (activeShutdowns.size === 0) {
2898
+ process.on("SIGTERM", signalShutdown);
2899
+ process.on("SIGINT", signalShutdown);
2900
+ }
2901
+ activeShutdowns.add(shutdown);
2902
+ return { server, shutdown };
2903
+ }
2904
+ export {
2905
+ startProductionServer
2906
+ };