@teyik0/furin 0.2.0-alpha.2 → 0.2.0-alpha.4

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 (134) hide show
  1. package/README.md +4 -0
  2. package/dist/adapter/bun.d.ts +3 -0
  3. package/dist/adapter/static.d.ts +3 -0
  4. package/dist/build/client.d.ts +25 -0
  5. package/dist/build/compile-entry.d.ts +9 -0
  6. package/dist/build/compile-entry.ts +109 -0
  7. package/dist/build/entry-template.d.ts +38 -0
  8. package/dist/build/entry-template.ts +156 -0
  9. package/dist/build/hydrate.d.ts +24 -0
  10. package/dist/build/index.d.ts +8 -0
  11. package/dist/build/index.js +8106 -0
  12. package/dist/build/route-types.d.ts +23 -0
  13. package/dist/build/scan-server.d.ts +8 -0
  14. package/dist/build/server-routes-entry.d.ts +13 -0
  15. package/dist/build/server-routes-entry.ts +36 -0
  16. package/dist/build/shared.d.ts +12 -0
  17. package/dist/build/ssg-cache.d.ts +4 -0
  18. package/dist/build/types.d.ts +80 -0
  19. package/dist/cli/config.d.ts +9 -0
  20. package/dist/cli/index.d.ts +2 -0
  21. package/dist/cli/index.js +8097 -0
  22. package/dist/client/boundaries.d.ts +117 -0
  23. package/dist/client/default-screens.d.ts +17 -0
  24. package/dist/client/link.d.ts +22 -0
  25. package/dist/client/link.js +4391 -0
  26. package/dist/client/router/abort.d.ts +1 -0
  27. package/dist/client/router/boundary-tree.d.ts +26 -0
  28. package/dist/client/router/context.d.ts +8 -0
  29. package/dist/client/router/history.d.ts +9 -0
  30. package/dist/client/router/index.d.ts +11 -0
  31. package/dist/client/router/link-utils.d.ts +53 -0
  32. package/dist/client/router/navigation.d.ts +10 -0
  33. package/dist/client/router/provider.d.ts +4 -0
  34. package/dist/client/router/search/index.d.ts +18 -0
  35. package/dist/client/router/search-store.d.ts +21 -0
  36. package/dist/client/router/spa-response.d.ts +58 -0
  37. package/dist/client/router/sync-catch-up.d.ts +29 -0
  38. package/dist/client/router/types.d.ts +292 -0
  39. package/dist/client/server-error.d.ts +12 -0
  40. package/dist/client/sync.d.ts +25 -0
  41. package/dist/client.d.ts +243 -0
  42. package/dist/client.js +140 -0
  43. package/dist/config.d.ts +57 -0
  44. package/dist/config.js +29 -0
  45. package/dist/env.d.ts +50 -0
  46. package/dist/furin.d.ts +77 -0
  47. package/dist/furin.js +8977 -0
  48. package/dist/plugin/index.d.ts +20 -0
  49. package/dist/plugin/index.js +1500 -0
  50. package/dist/plugin/transform-client.d.ts +10 -0
  51. package/dist/server/auto-invalidate/index.d.ts +4 -0
  52. package/dist/server/auto-invalidate/plugin.d.ts +38 -0
  53. package/dist/server/auto-invalidate/registry.d.ts +9 -0
  54. package/dist/server/auto-invalidate/runtime.d.ts +9 -0
  55. package/dist/server/auto-invalidate/types.d.ts +12 -0
  56. package/dist/server/cache/dev-loader.d.ts +28 -0
  57. package/dist/server/cache/index.d.ts +10 -0
  58. package/dist/server/cache/invalidation.d.ts +12 -0
  59. package/dist/server/cache/isr-ssg.d.ts +26 -0
  60. package/dist/server/cache/isr.d.ts +6 -0
  61. package/dist/server/cache/registry.d.ts +5 -0
  62. package/dist/server/cache/route-cache.d.ts +26 -0
  63. package/dist/server/cache/ssg.d.ts +5 -0
  64. package/dist/server/context-logger.d.ts +28 -0
  65. package/dist/server/dev-inspector.d.ts +89 -0
  66. package/dist/server/dev-page-plugin.d.ts +112 -0
  67. package/dist/server/internal.d.ts +35 -0
  68. package/dist/server/internal.js +17 -0
  69. package/dist/server/lang-detect.d.ts +5 -0
  70. package/dist/server/render/assemble.d.ts +49 -0
  71. package/dist/server/render/element.d.ts +24 -0
  72. package/dist/server/render/index.d.ts +7 -0
  73. package/dist/server/render/index.ts +22 -0
  74. package/dist/server/render/isr.d.ts +4 -0
  75. package/dist/server/render/loaders.d.ts +64 -0
  76. package/dist/server/render/not-found.d.ts +6 -0
  77. package/dist/server/render/shell.d.ts +39 -0
  78. package/dist/server/render/shell.ts +202 -0
  79. package/dist/server/render/ssg.d.ts +9 -0
  80. package/dist/server/render/ssr.d.ts +108 -0
  81. package/dist/server/render/template.d.ts +6 -0
  82. package/dist/server/router/discovery.d.ts +16 -0
  83. package/dist/server/router/hmr.d.ts +65 -0
  84. package/dist/server/router/index.d.ts +6 -0
  85. package/dist/server/router/index.js +27 -0
  86. package/dist/server/router/index.ts +28 -0
  87. package/dist/server/router/patterns.d.ts +40 -0
  88. package/dist/server/router/plugin.d.ts +21 -0
  89. package/dist/server/router/schemas.d.ts +59 -0
  90. package/dist/server/router/types.d.ts +60 -0
  91. package/dist/server/runtime-env.d.ts +3 -0
  92. package/dist/server/runtime-env.js +10 -0
  93. package/dist/server/sync/adapter.d.ts +62 -0
  94. package/dist/server/sync/config.d.ts +6 -0
  95. package/dist/server/sync/fingerprint.d.ts +6 -0
  96. package/dist/server/sync/index.d.ts +4 -0
  97. package/dist/server/sync/memory-adapter.d.ts +17 -0
  98. package/dist/server/sync/plugin.d.ts +186 -0
  99. package/dist/server/sync/response.d.ts +4 -0
  100. package/dist/server/sync/stream.d.ts +59 -0
  101. package/dist/shared/await.d.ts +67 -0
  102. package/dist/shared/deferred-ndjson.d.ts +32 -0
  103. package/dist/shared/digest.d.ts +16 -0
  104. package/dist/shared/error.d.ts +37 -0
  105. package/dist/shared/not-found.d.ts +19 -0
  106. package/dist/shared/search-params.d.ts +17 -0
  107. package/dist/shared/utils/ast-walk.d.ts +18 -0
  108. package/dist/shared/utils/index.d.ts +13 -0
  109. package/package.json +5 -5
  110. package/src/build/hydrate.ts +4 -1
  111. package/src/build/shared.ts +4 -3
  112. package/src/client/router/abort.ts +5 -0
  113. package/src/client/router/link-utils.ts +8 -1
  114. package/src/client/router/provider.tsx +130 -6
  115. package/src/client/router/sync-catch-up.ts +113 -0
  116. package/src/client/router/types.ts +5 -0
  117. package/src/client/sync.ts +98 -0
  118. package/src/client.ts +15 -1
  119. package/src/furin.ts +25 -4
  120. package/src/server/auto-invalidate/runtime.ts +3 -2
  121. package/src/server/dev-page-plugin.ts +15 -10
  122. package/src/server/render/assemble.ts +30 -3
  123. package/src/server/render/isr.ts +8 -2
  124. package/src/server/render/ssr.ts +9 -1
  125. package/src/server/router/plugin.ts +2 -2
  126. package/src/server/sync/adapter.ts +65 -0
  127. package/src/server/sync/config.ts +29 -0
  128. package/src/server/sync/fingerprint.ts +44 -0
  129. package/src/server/sync/index.ts +15 -0
  130. package/src/server/sync/memory-adapter.ts +196 -0
  131. package/src/server/sync/plugin.ts +200 -0
  132. package/src/server/sync/response.ts +77 -0
  133. package/src/server/sync/stream.ts +152 -0
  134. package/src/shared/deferred-ndjson.ts +7 -0
@@ -0,0 +1,4391 @@
1
+ // @bun
2
+ // src/client/link.tsx
3
+ import { createElement as createElement3, useCallback as useCallback3, useEffect as useEffect2, useRef as useRef2 } from "react";
4
+
5
+ // src/shared/search-params.ts
6
+ function routeSegmentSpecificity(segment) {
7
+ if (segment === "*") {
8
+ return 1;
9
+ }
10
+ if (segment.startsWith(":")) {
11
+ return 2;
12
+ }
13
+ return 3;
14
+ }
15
+ function compareSearchRouteSpecificity(a, b) {
16
+ const aSegments = a.split("/").filter((segment) => segment.length > 0);
17
+ const bSegments = b.split("/").filter((segment) => segment.length > 0);
18
+ const length = Math.max(aSegments.length, bSegments.length);
19
+ for (let i = 0;i < length; i++) {
20
+ const aSegment = aSegments[i];
21
+ const bSegment = bSegments[i];
22
+ if (aSegment === undefined) {
23
+ return -1;
24
+ }
25
+ if (bSegment === undefined) {
26
+ return 1;
27
+ }
28
+ const diff = routeSegmentSpecificity(aSegment) - routeSegmentSpecificity(bSegment);
29
+ if (diff !== 0) {
30
+ return diff;
31
+ }
32
+ }
33
+ return 0;
34
+ }
35
+ function isObject(value) {
36
+ return !!value && typeof value === "object" && !Array.isArray(value);
37
+ }
38
+ function arraysDeepEqual(a, b) {
39
+ if (a.length !== b.length) {
40
+ return false;
41
+ }
42
+ for (let i = 0;i < a.length; i++) {
43
+ if (!deepEqual(a[i], b[i])) {
44
+ return false;
45
+ }
46
+ }
47
+ return true;
48
+ }
49
+ function objectsDeepEqual(a, b) {
50
+ const aKeys = Object.keys(a);
51
+ if (aKeys.length !== Object.keys(b).length) {
52
+ return false;
53
+ }
54
+ for (const key of aKeys) {
55
+ if (!(Object.hasOwn(b, key) && deepEqual(a[key], b[key]))) {
56
+ return false;
57
+ }
58
+ }
59
+ return true;
60
+ }
61
+ function deepEqual(a, b) {
62
+ if (Object.is(a, b)) {
63
+ return true;
64
+ }
65
+ if (Array.isArray(a) && Array.isArray(b)) {
66
+ return arraysDeepEqual(a, b);
67
+ }
68
+ if (isObject(a) && isObject(b)) {
69
+ return objectsDeepEqual(a, b);
70
+ }
71
+ return false;
72
+ }
73
+ function stripSearchDefaults(search, defaults) {
74
+ if (!defaults) {
75
+ return search;
76
+ }
77
+ const stripped = {};
78
+ for (const [key, value] of Object.entries(search)) {
79
+ if (Object.hasOwn(defaults, key) && deepEqual(value, defaults[key])) {
80
+ continue;
81
+ }
82
+ stripped[key] = value;
83
+ }
84
+ return stripped;
85
+ }
86
+ function appendSearchParamValue(params, key, value) {
87
+ if (value == null) {
88
+ return;
89
+ }
90
+ if (Array.isArray(value)) {
91
+ for (const item of value) {
92
+ if (item != null) {
93
+ params.append(key, typeof item === "object" ? JSON.stringify(item) : String(item));
94
+ }
95
+ }
96
+ return;
97
+ }
98
+ params.set(key, typeof value === "object" ? JSON.stringify(value) : String(value));
99
+ }
100
+ function buildSearchParams(search, defaults) {
101
+ const params = new URLSearchParams;
102
+ for (const [key, value] of Object.entries(stripSearchDefaults(search, defaults))) {
103
+ appendSearchParamValue(params, key, value);
104
+ }
105
+ return params;
106
+ }
107
+ function findSearchDefaults(pathname, routes) {
108
+ let match;
109
+ for (const route of routes) {
110
+ if (!route.regex.test(pathname)) {
111
+ continue;
112
+ }
113
+ if (!match || compareSearchRouteSpecificity(route.pattern, match.pattern) > 0) {
114
+ match = route;
115
+ }
116
+ }
117
+ return match?.searchDefaults;
118
+ }
119
+ function findSearchDefaultsForRouteTarget(to, routes) {
120
+ if (to.startsWith("http://") || to.startsWith("https://") || to.startsWith("//")) {
121
+ return;
122
+ }
123
+ try {
124
+ const pathname = new URL(to, "http://furin.local").pathname;
125
+ return findSearchDefaults(pathname, routes);
126
+ } catch {
127
+ return;
128
+ }
129
+ }
130
+
131
+ // src/client/router/boundary-tree.tsx
132
+ import { createElement } from "react";
133
+
134
+ // src/client/boundaries.tsx
135
+ import { Component, Fragment } from "react";
136
+
137
+ // src/shared/digest.ts
138
+ function computeErrorDigest(err) {
139
+ let message = "";
140
+ let stack = "";
141
+ if (err instanceof Error) {
142
+ message = err.message;
143
+ stack = err.stack ?? "";
144
+ } else if (typeof err === "string") {
145
+ message = err;
146
+ } else {
147
+ try {
148
+ message = JSON.stringify(err) ?? String(err);
149
+ } catch {
150
+ message = String(err);
151
+ }
152
+ }
153
+ const input = `${message}
154
+ ${stack}`;
155
+ const hash = cyrb53(input);
156
+ const hex = hash.toString(16).padStart(14, "0");
157
+ return hex.slice(0, 10);
158
+ }
159
+ function cyrb53(input) {
160
+ let h1 = 3735928559;
161
+ let h2 = 1103547991;
162
+ for (let i = 0;i < input.length; i++) {
163
+ const ch = input.charCodeAt(i);
164
+ h1 = Math.imul(h1 ^ ch, 2654435761);
165
+ h2 = Math.imul(h2 ^ ch, 1597334677);
166
+ }
167
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
168
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
169
+ return 4294967296 * (2097151 & h2) + (4294967295 & h1);
170
+ }
171
+
172
+ // src/shared/error.ts
173
+ function getPublicErrorMessage(error) {
174
+ const branded = error;
175
+ if (branded?.__furinBrand === "FURIN_NOT_FOUND" || branded?.__furinBrand === "FURIN_SERVER_ERROR") {
176
+ return error.message;
177
+ }
178
+ return "Something went wrong";
179
+ }
180
+
181
+ // src/shared/not-found.ts
182
+ var NOT_FOUND_BRAND = "FURIN_NOT_FOUND";
183
+
184
+ class FurinNotFoundError extends Error {
185
+ __furinBrand = NOT_FOUND_BRAND;
186
+ data;
187
+ constructor(options) {
188
+ super(options?.message ?? "");
189
+ this.data = options?.data;
190
+ }
191
+ }
192
+ function isNotFoundError(err) {
193
+ return err instanceof FurinNotFoundError || typeof err === "object" && err !== null && err.__furinBrand === NOT_FOUND_BRAND;
194
+ }
195
+
196
+ // src/client/default-screens.tsx
197
+ import { jsxDEV } from "react/jsx-dev-runtime";
198
+ var FONT_SANS = '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
199
+ var FONT_MONO = 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace';
200
+ var COLOR_BG = "#000000";
201
+ var COLOR_TEXT = "#ffffff";
202
+ var COLOR_TEXT_DIM = "rgba(255, 255, 255, 0.7)";
203
+ var COLOR_TEXT_MUTED = "rgba(255, 255, 255, 0.45)";
204
+ var COLOR_GRID = "rgba(255, 255, 255, 0.04)";
205
+ var COLOR_BRACKET = "rgba(255, 255, 255, 0.55)";
206
+ var COLOR_DANGER_DIM = "rgba(239, 68, 68, 0.6)";
207
+ var PAGE_STYLE = {
208
+ alignItems: "center",
209
+ backgroundColor: COLOR_BG,
210
+ backgroundImage: `
211
+ linear-gradient(${COLOR_GRID} 1px, transparent 1px),
212
+ linear-gradient(90deg, ${COLOR_GRID} 1px, transparent 1px)
213
+ `,
214
+ backgroundSize: "32px 32px, 32px 32px",
215
+ boxSizing: "border-box",
216
+ color: COLOR_TEXT,
217
+ display: "flex",
218
+ fontFamily: FONT_SANS,
219
+ fontSize: "16px",
220
+ justifyContent: "center",
221
+ lineHeight: 1.5,
222
+ margin: 0,
223
+ minHeight: "100vh",
224
+ padding: "32px",
225
+ width: "100%"
226
+ };
227
+ var FRAME_STYLE = {
228
+ boxSizing: "border-box",
229
+ maxWidth: "880px",
230
+ position: "relative",
231
+ width: "100%"
232
+ };
233
+ var BRACKET_BASE = {
234
+ height: "40px",
235
+ position: "absolute",
236
+ width: "40px"
237
+ };
238
+ function CornerBracket({ corner }) {
239
+ const top = corner === "tl" || corner === "tr";
240
+ const left = corner === "tl" || corner === "bl";
241
+ const style = {
242
+ ...BRACKET_BASE,
243
+ [top ? "top" : "bottom"]: 0,
244
+ [left ? "left" : "right"]: 0,
245
+ [`border${top ? "Top" : "Bottom"}`]: `2px solid ${COLOR_BRACKET}`,
246
+ [`border${left ? "Left" : "Right"}`]: `2px solid ${COLOR_BRACKET}`
247
+ };
248
+ return /* @__PURE__ */ jsxDEV("span", {
249
+ "aria-hidden": "true",
250
+ style
251
+ }, undefined, false, undefined, this);
252
+ }
253
+ var CARD_STYLE = {
254
+ boxSizing: "border-box",
255
+ margin: "0 auto",
256
+ maxWidth: "640px",
257
+ padding: "64px 24px",
258
+ textAlign: "center"
259
+ };
260
+ var BADGE_STYLE = {
261
+ border: `1px solid ${COLOR_DANGER_DIM}`,
262
+ color: COLOR_TEXT,
263
+ display: "inline-block",
264
+ fontFamily: FONT_SANS,
265
+ fontSize: "32px",
266
+ fontWeight: 600,
267
+ letterSpacing: "0.08em",
268
+ marginBottom: "16px",
269
+ padding: "12px 36px"
270
+ };
271
+ var HEADING_STYLE = {
272
+ color: COLOR_TEXT,
273
+ fontFamily: FONT_SANS,
274
+ fontSize: "24px",
275
+ fontWeight: 600,
276
+ margin: "0 0 24px 0"
277
+ };
278
+ var CODE_BOX_STYLE = {
279
+ color: COLOR_TEXT_DIM,
280
+ display: "inline-block",
281
+ fontFamily: FONT_MONO,
282
+ fontSize: "13px",
283
+ letterSpacing: "0.02em",
284
+ margin: "0 0 32px 0",
285
+ padding: "8px 0"
286
+ };
287
+ var CODE_LABEL_STYLE = {
288
+ color: COLOR_TEXT_MUTED,
289
+ marginRight: "10px",
290
+ textTransform: "uppercase"
291
+ };
292
+ var DESCRIPTION_WRAPPER_STYLE = {
293
+ color: COLOR_TEXT_DIM,
294
+ fontSize: "15px",
295
+ margin: "0 auto 40px auto",
296
+ maxWidth: "440px",
297
+ padding: 0,
298
+ textAlign: "center"
299
+ };
300
+ var ACTIONS_STYLE = {
301
+ display: "flex",
302
+ flexWrap: "wrap",
303
+ gap: "16px",
304
+ justifyContent: "center"
305
+ };
306
+ var BUTTON_BASE = {
307
+ border: 0,
308
+ cursor: "pointer",
309
+ display: "inline-flex",
310
+ fontFamily: FONT_SANS,
311
+ fontSize: "14px",
312
+ fontWeight: 500,
313
+ lineHeight: 1,
314
+ minWidth: "120px",
315
+ padding: "10px 16px",
316
+ textAlign: "center",
317
+ textDecoration: "none",
318
+ transition: "background-color 120ms ease, color 120ms ease, opacity 120ms ease",
319
+ appearance: "none",
320
+ alignItems: "center",
321
+ justifyContent: "center",
322
+ boxSizing: "border-box"
323
+ };
324
+ var BUTTON_PRIMARY = {
325
+ ...BUTTON_BASE,
326
+ backgroundColor: COLOR_TEXT,
327
+ border: `1px solid ${COLOR_TEXT}`,
328
+ boxShadow: "0 10px 24px rgba(255, 255, 255, 0.08)",
329
+ color: COLOR_BG,
330
+ fontWeight: 600
331
+ };
332
+ var BUTTON_SECONDARY = {
333
+ ...BUTTON_BASE,
334
+ backgroundColor: "transparent",
335
+ border: "1px solid rgba(255, 255, 255, 0.22)",
336
+ color: COLOR_TEXT_DIM
337
+ };
338
+ var DIVIDER_STYLE = {
339
+ backgroundColor: "rgba(255, 255, 255, 0.12)",
340
+ border: 0,
341
+ height: "1px",
342
+ margin: "0 0 40px 0",
343
+ width: "100%"
344
+ };
345
+ var RESET_CSS = `
346
+ html, body {
347
+ margin: 0;
348
+ padding: 0;
349
+ background-color: ${COLOR_BG};
350
+ overscroll-behavior: none;
351
+ }
352
+ `;
353
+ function ScreenFrame({ badge, children }) {
354
+ return /* @__PURE__ */ jsxDEV("div", {
355
+ style: PAGE_STYLE,
356
+ children: [
357
+ /* @__PURE__ */ jsxDEV("style", {
358
+ children: RESET_CSS
359
+ }, undefined, false, undefined, this),
360
+ /* @__PURE__ */ jsxDEV("div", {
361
+ style: FRAME_STYLE,
362
+ children: [
363
+ /* @__PURE__ */ jsxDEV(CornerBracket, {
364
+ corner: "tl"
365
+ }, undefined, false, undefined, this),
366
+ /* @__PURE__ */ jsxDEV(CornerBracket, {
367
+ corner: "tr"
368
+ }, undefined, false, undefined, this),
369
+ /* @__PURE__ */ jsxDEV(CornerBracket, {
370
+ corner: "bl"
371
+ }, undefined, false, undefined, this),
372
+ /* @__PURE__ */ jsxDEV(CornerBracket, {
373
+ corner: "br"
374
+ }, undefined, false, undefined, this),
375
+ /* @__PURE__ */ jsxDEV("div", {
376
+ style: CARD_STYLE,
377
+ children: [
378
+ badge,
379
+ /* @__PURE__ */ jsxDEV("hr", {
380
+ style: DIVIDER_STYLE
381
+ }, undefined, false, undefined, this),
382
+ children
383
+ ]
384
+ }, undefined, true, undefined, this)
385
+ ]
386
+ }, undefined, true, undefined, this)
387
+ ]
388
+ }, undefined, true, undefined, this);
389
+ }
390
+ function DefaultErrorScreen({ message, digest, reset }) {
391
+ return /* @__PURE__ */ jsxDEV(ScreenFrame, {
392
+ badge: /* @__PURE__ */ jsxDEV("div", {
393
+ style: BADGE_STYLE,
394
+ children: "500 \u2014 ERROR"
395
+ }, undefined, false, undefined, this),
396
+ children: [
397
+ /* @__PURE__ */ jsxDEV("h1", {
398
+ style: HEADING_STYLE,
399
+ children: "Something went wrong"
400
+ }, undefined, false, undefined, this),
401
+ /* @__PURE__ */ jsxDEV("div", {
402
+ style: CODE_BOX_STYLE,
403
+ children: [
404
+ /* @__PURE__ */ jsxDEV("span", {
405
+ style: CODE_LABEL_STYLE,
406
+ children: "CODE:"
407
+ }, undefined, false, undefined, this),
408
+ /* @__PURE__ */ jsxDEV("span", {
409
+ children: digest
410
+ }, undefined, false, undefined, this)
411
+ ]
412
+ }, undefined, true, undefined, this),
413
+ /* @__PURE__ */ jsxDEV("p", {
414
+ style: DESCRIPTION_WRAPPER_STYLE,
415
+ children: message ? message : "We encountered an unexpected error. Please try again or return to the home page."
416
+ }, undefined, false, undefined, this),
417
+ /* @__PURE__ */ jsxDEV("div", {
418
+ style: ACTIONS_STYLE,
419
+ children: [
420
+ /* @__PURE__ */ jsxDEV(Link, {
421
+ style: BUTTON_PRIMARY,
422
+ to: "/",
423
+ children: "Go Home"
424
+ }, undefined, false, undefined, this),
425
+ /* @__PURE__ */ jsxDEV("button", {
426
+ onClick: reset,
427
+ style: BUTTON_SECONDARY,
428
+ type: "button",
429
+ children: "Try again"
430
+ }, undefined, false, undefined, this)
431
+ ]
432
+ }, undefined, true, undefined, this)
433
+ ]
434
+ }, undefined, true, undefined, this);
435
+ }
436
+ function DefaultNotFoundScreen({ message }) {
437
+ return /* @__PURE__ */ jsxDEV(ScreenFrame, {
438
+ badge: /* @__PURE__ */ jsxDEV("div", {
439
+ style: BADGE_STYLE,
440
+ children: "404 \u2014 NOT FOUND"
441
+ }, undefined, false, undefined, this),
442
+ children: [
443
+ /* @__PURE__ */ jsxDEV("h1", {
444
+ style: HEADING_STYLE,
445
+ children: "This page does not exist"
446
+ }, undefined, false, undefined, this),
447
+ /* @__PURE__ */ jsxDEV("p", {
448
+ style: DESCRIPTION_WRAPPER_STYLE,
449
+ children: message ? message : "The page you are looking for could not be found. It may have been moved or removed."
450
+ }, undefined, false, undefined, this),
451
+ /* @__PURE__ */ jsxDEV("div", {
452
+ style: ACTIONS_STYLE,
453
+ children: /* @__PURE__ */ jsxDEV(Link, {
454
+ style: BUTTON_PRIMARY,
455
+ to: "/",
456
+ children: "Go Home"
457
+ }, undefined, false, undefined, this)
458
+ }, undefined, false, undefined, this)
459
+ ]
460
+ }, undefined, true, undefined, this);
461
+ }
462
+ var DefaultErrorFallback = ({ error, reset }) => /* @__PURE__ */ jsxDEV(DefaultErrorScreen, {
463
+ digest: error.digest,
464
+ message: error.message,
465
+ reset
466
+ }, undefined, false, undefined, this);
467
+ var DefaultNotFoundFallback = ({ error }) => /* @__PURE__ */ jsxDEV(DefaultNotFoundScreen, {
468
+ message: error.message
469
+ }, undefined, false, undefined, this);
470
+
471
+ // src/client/server-error.ts
472
+ var SERVER_ERROR_BRAND = "FURIN_SERVER_ERROR";
473
+
474
+ class FurinServerError extends Error {
475
+ __furinBrand = SERVER_ERROR_BRAND;
476
+ digest;
477
+ status;
478
+ constructor(args) {
479
+ super(args.message);
480
+ this.status = args.status;
481
+ this.digest = args.digest;
482
+ }
483
+ }
484
+ function isFurinServerError(err) {
485
+ return err instanceof FurinServerError || typeof err === "object" && err !== null && err.__furinBrand === SERVER_ERROR_BRAND;
486
+ }
487
+
488
+ // src/client/boundaries.tsx
489
+ import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
490
+ var DEFAULT_ERROR_STATUS = 500;
491
+ var SERVER_RESET_NOOP = () => {};
492
+
493
+ class FurinErrorBoundary extends Component {
494
+ state = {
495
+ digest: null,
496
+ epoch: 0,
497
+ error: null
498
+ };
499
+ static getDerivedStateFromError(error) {
500
+ return { digest: computeErrorDigest(error), error };
501
+ }
502
+ componentDidUpdate(prevProps) {
503
+ if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
504
+ this.reset();
505
+ }
506
+ }
507
+ reset = () => {
508
+ this.setState((s) => ({ digest: null, epoch: s.epoch + 1, error: null }), () => {
509
+ this.props.onReset?.();
510
+ });
511
+ };
512
+ render() {
513
+ const { error, epoch, digest } = this.state;
514
+ if (error) {
515
+ if (isNotFoundError(error)) {
516
+ throw error;
517
+ }
518
+ const Fallback = this.props.fallback ?? DefaultErrorFallback;
519
+ const serverDigest = isFurinServerError(error) ? error.digest : undefined;
520
+ const finalDigest = serverDigest ?? digest ?? this.props.digest ?? computeErrorDigest(error);
521
+ const message = this.props.fallback ? error.message : getPublicErrorMessage(error);
522
+ const status = isFurinServerError(error) ? error.status : DEFAULT_ERROR_STATUS;
523
+ return /* @__PURE__ */ jsxDEV2(Fallback, {
524
+ error: { message, digest: finalDigest, status },
525
+ reset: typeof window === "undefined" ? SERVER_RESET_NOOP : this.reset
526
+ }, undefined, false, undefined, this);
527
+ }
528
+ return /* @__PURE__ */ jsxDEV2(Fragment, {
529
+ children: this.props.children
530
+ }, epoch, false, undefined, this);
531
+ }
532
+ }
533
+
534
+ class FurinNotFoundBoundary extends Component {
535
+ state = { epoch: 0, error: null };
536
+ static getDerivedStateFromError(error) {
537
+ return { error };
538
+ }
539
+ componentDidUpdate(prevProps) {
540
+ if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
541
+ this.setState((s) => ({ error: null, epoch: s.epoch + 1 }));
542
+ }
543
+ }
544
+ render() {
545
+ const { error, epoch } = this.state;
546
+ if (error) {
547
+ if (!isNotFoundError(error)) {
548
+ throw error;
549
+ }
550
+ const Fallback = this.props.fallback ?? DefaultNotFoundFallback;
551
+ return /* @__PURE__ */ jsxDEV2(Fallback, {
552
+ error: { message: error.message, data: error.data }
553
+ }, undefined, false, undefined, this);
554
+ }
555
+ return /* @__PURE__ */ jsxDEV2(Fragment, {
556
+ children: this.props.children
557
+ }, epoch, false, undefined, this);
558
+ }
559
+ }
560
+ function wrapSegmentBoundaries(inner, segment, options) {
561
+ if (!segment) {
562
+ return inner;
563
+ }
564
+ let wrapped = inner;
565
+ if (segment.notFound) {
566
+ wrapped = /* @__PURE__ */ jsxDEV2(FurinNotFoundBoundary, {
567
+ fallback: segment.notFound,
568
+ resetKey: options?.resetKey,
569
+ children: wrapped
570
+ }, undefined, false, undefined, this);
571
+ }
572
+ if (segment.error) {
573
+ wrapped = /* @__PURE__ */ jsxDEV2(FurinErrorBoundary, {
574
+ fallback: segment.error,
575
+ onReset: options?.onReset,
576
+ resetKey: options?.resetKey,
577
+ children: wrapped
578
+ }, undefined, false, undefined, this);
579
+ }
580
+ return wrapped;
581
+ }
582
+
583
+ // src/client/router/context.ts
584
+ import { createContext, useContext } from "react";
585
+ var RouterContext = createContext(null);
586
+ var CLIENT_FALLBACK_ROUTER = {
587
+ basePath: "",
588
+ currentHref: "/",
589
+ search: {},
590
+ searchRoutes: [],
591
+ navigate: (href, _opts) => {
592
+ window.location.href = href;
593
+ return Promise.resolve();
594
+ },
595
+ prefetch: (_href, _opts) => {},
596
+ invalidatePrefetch: (_path, _type) => {},
597
+ refresh: (_opts) => {
598
+ window.location.reload();
599
+ return Promise.resolve();
600
+ },
601
+ isNavigating: false,
602
+ defaultPreload: "intent",
603
+ defaultPreloadDelay: 50,
604
+ defaultPreloadStaleTime: 30000
605
+ };
606
+ function useRouter() {
607
+ const ctx = useContext(RouterContext);
608
+ return ctx ?? CLIENT_FALLBACK_ROUTER;
609
+ }
610
+
611
+ // src/client/router/boundary-tree.tsx
612
+ import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
613
+ function buildRouterTree(context, pageElement, options) {
614
+ return /* @__PURE__ */ jsxDEV3(RouterContext.Provider, {
615
+ value: context,
616
+ children: /* @__PURE__ */ jsxDEV3(FurinErrorBoundary, {
617
+ ...options,
618
+ children: pageElement
619
+ }, undefined, false, undefined, this)
620
+ }, undefined, false, undefined, this);
621
+ }
622
+ function RouteErrorThrower({
623
+ error
624
+ }) {
625
+ throw new FurinServerError(error);
626
+ }
627
+ function buildPageElement(match, root, data, options, error) {
628
+ let element = error ? createElement(RouteErrorThrower, { error }) : createElement(match.component, data);
629
+ const chain = [];
630
+ let current = match.pageRoute;
631
+ while (current) {
632
+ chain.unshift(current);
633
+ current = current.parent;
634
+ }
635
+ const byDepth = new Map;
636
+ for (const segment of match.segmentBoundaries ?? []) {
637
+ byDepth.set(segment.depth, segment);
638
+ }
639
+ const rootOffset = root ? 1 : 0;
640
+ for (let i = chain.length - 1;i >= rootOffset; i--) {
641
+ element = wrapSegmentBoundaries(element, byDepth.get(i), options);
642
+ const Layout = chain[i]?.layout;
643
+ if (Layout) {
644
+ element = createElement(Layout, { ...data }, element);
645
+ }
646
+ }
647
+ if (root) {
648
+ element = wrapSegmentBoundaries(element, byDepth.get(0), options);
649
+ if (root.layout) {
650
+ element = createElement(root.layout, { ...data }, element);
651
+ }
652
+ }
653
+ return element;
654
+ }
655
+ // src/client/router/history.ts
656
+ var SCROLL_STORAGE_KEY = "__furin_scroll__";
657
+ function getHistoryKey(state) {
658
+ return state?._furinKey;
659
+ }
660
+ function generateHistoryKey() {
661
+ return Math.random().toString(36).slice(2, 9);
662
+ }
663
+ function saveScrollPosition(key) {
664
+ try {
665
+ const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
666
+ const positions = raw ? JSON.parse(raw) : {};
667
+ positions[key] = window.scrollY;
668
+ const keys = Object.keys(positions);
669
+ if (keys.length > 50) {
670
+ delete positions[keys[0]];
671
+ }
672
+ sessionStorage.setItem(SCROLL_STORAGE_KEY, JSON.stringify(positions));
673
+ } catch {}
674
+ }
675
+ function isStaleDeployResponse(res) {
676
+ const serverBuildId = res.headers.get("x-furin-build-id");
677
+ if (!serverBuildId) {
678
+ return false;
679
+ }
680
+ const metaEl = typeof document === "undefined" ? null : document.querySelector('meta[name="furin-build-id"]');
681
+ const clientBuildId = metaEl?.content;
682
+ return Boolean(clientBuildId && serverBuildId !== clientBuildId);
683
+ }
684
+ // src/client/router/link-utils.ts
685
+ var HASH_FRAGMENT_RE = /#.*$/;
686
+ var TRAILING_SLASHES_RE = /\/+$/;
687
+ function buildHref(to, search, hash, searchDefaults) {
688
+ let url = to;
689
+ if (search && Object.keys(search).length > 0) {
690
+ const params = buildSearchParams(search, searchDefaults);
691
+ const qs = params.toString();
692
+ if (qs) {
693
+ url += `?${qs}`;
694
+ }
695
+ }
696
+ if (hash) {
697
+ url += `#${hash}`;
698
+ }
699
+ return url;
700
+ }
701
+ function applyRevalidateHeader(headers, invalidate) {
702
+ const headerValue = headers.get("x-furin-revalidate");
703
+ if (!headerValue) {
704
+ return;
705
+ }
706
+ applyRevalidateEntries(headerValue.split(","), invalidate);
707
+ }
708
+ function applyRevalidateEntries(entries, invalidate) {
709
+ for (const entry of entries) {
710
+ const trimmed = entry.trim();
711
+ if (!trimmed) {
712
+ continue;
713
+ }
714
+ if (trimmed.endsWith(":layout")) {
715
+ invalidate(trimmed.slice(0, -":layout".length), "layout");
716
+ } else {
717
+ invalidate(trimmed, "page");
718
+ }
719
+ }
720
+ }
721
+ function shouldAutoRefreshPath(currentPath, invalidations) {
722
+ const normalizedCurrent = currentPath.split("?")[0] ?? currentPath;
723
+ return invalidations.some(({ path, type }) => {
724
+ if (type === "page") {
725
+ return path === normalizedCurrent;
726
+ }
727
+ const prefix = path === "/" || path.endsWith("/") ? path : `${path}/`;
728
+ return normalizedCurrent === path || normalizedCurrent.startsWith(prefix);
729
+ });
730
+ }
731
+ function stripHashFromHref(href) {
732
+ return href.replace(HASH_FRAGMENT_RE, "");
733
+ }
734
+ function normalizeHref(href) {
735
+ const url = new URL(href, "http://localhost");
736
+ let pathname = url.pathname;
737
+ if (pathname !== "/") {
738
+ pathname = pathname.replace(/\/+$/g, "");
739
+ }
740
+ return pathname + url.search + url.hash;
741
+ }
742
+ function normalizePath(path) {
743
+ if (path === "/" || path === "") {
744
+ return path;
745
+ }
746
+ return path.endsWith("/") ? path.slice(0, -1) : path;
747
+ }
748
+ function shouldRefetch(entry) {
749
+ return Date.now() - entry.createdAt > entry.staleTime;
750
+ }
751
+ function shouldInterceptClick(anchor, event, basePath, currentOrigin, currentPathname) {
752
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
753
+ return null;
754
+ }
755
+ if (anchor.target && anchor.target !== "_self") {
756
+ return null;
757
+ }
758
+ if (anchor.hasAttribute("download")) {
759
+ return null;
760
+ }
761
+ const href = anchor.href;
762
+ if (!href) {
763
+ return null;
764
+ }
765
+ let url;
766
+ try {
767
+ url = new URL(href, currentOrigin);
768
+ } catch {
769
+ return null;
770
+ }
771
+ if (url.origin !== currentOrigin) {
772
+ return null;
773
+ }
774
+ if (normalizePath(url.pathname) === normalizePath(currentPathname) && url.hash) {
775
+ return null;
776
+ }
777
+ const logicalPath = normalizeHref(toLogical(url.pathname, basePath));
778
+ const normalizedBase = normalizePath(basePath);
779
+ const normalizedPathname = normalizePath(url.pathname);
780
+ if (normalizedBase && normalizedPathname !== normalizedBase && !normalizedPathname.startsWith(`${normalizedBase}/`)) {
781
+ return null;
782
+ }
783
+ return logicalPath + url.search + url.hash;
784
+ }
785
+ function toLogical(physicalPathname, basePath) {
786
+ if (basePath && physicalPathname.startsWith(basePath) && (physicalPathname.length === basePath.length || physicalPathname[basePath.length] === "/")) {
787
+ return physicalPathname.slice(basePath.length) || "/";
788
+ }
789
+ return physicalPathname;
790
+ }
791
+ // src/client/router/navigation.ts
792
+ import { useCallback } from "react";
793
+ function isExternalAbsoluteHref(href) {
794
+ if (href.startsWith("//")) {
795
+ return true;
796
+ }
797
+ if (!(href.startsWith("http://") || href.startsWith("https://"))) {
798
+ return false;
799
+ }
800
+ if (typeof window === "undefined") {
801
+ return true;
802
+ }
803
+ return new URL(href).origin !== window.location.origin;
804
+ }
805
+ function useNavigate() {
806
+ const router = useRouter();
807
+ return useCallback((next) => {
808
+ const searchDefaults = findSearchDefaultsForRouteTarget(next.to, router.searchRoutes);
809
+ const href = buildHref(next.to, next.search, next.hash, searchDefaults);
810
+ if (isExternalAbsoluteHref(href) && typeof window !== "undefined") {
811
+ window.location.assign(href);
812
+ return Promise.resolve();
813
+ }
814
+ const opts = next.replace === undefined && next.resetScroll === undefined ? undefined : { replace: next.replace, resetScroll: next.resetScroll };
815
+ return router.navigate(href, opts);
816
+ }, [router]);
817
+ }
818
+ // ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/utils.mjs
819
+ function formatDuration(ms) {
820
+ if (ms < 1000)
821
+ return `${Math.round(ms)}ms`;
822
+ return `${(ms / 1000).toFixed(2)}s`;
823
+ }
824
+ function isBrowser() {
825
+ if (typeof window === "undefined")
826
+ return false;
827
+ if (typeof document === "undefined")
828
+ return false;
829
+ if (typeof navigator !== "undefined" && navigator.product === "ReactNative")
830
+ return false;
831
+ return true;
832
+ }
833
+ function isDev() {
834
+ if (typeof process !== "undefined")
835
+ return true;
836
+ if (typeof window !== "undefined")
837
+ return true;
838
+ return false;
839
+ }
840
+ function detectEnvironment() {
841
+ const env = typeof process !== "undefined" ? process.env : {};
842
+ const defaultEnvironment = isDev() ? "development" : "production";
843
+ return {
844
+ environment: env.NODE_ENV || defaultEnvironment,
845
+ service: env.SERVICE_NAME || "app",
846
+ version: env.APP_VERSION,
847
+ commitHash: env.COMMIT_SHA || env.GITHUB_SHA || env.VERCEL_GIT_COMMIT_SHA || env.CF_PAGES_COMMIT_SHA,
848
+ region: env.VERCEL_REGION || env.AWS_REGION || env.FLY_REGION || env.CF_REGION
849
+ };
850
+ }
851
+ var LEVEL_ORDER = {
852
+ debug: 0,
853
+ info: 1,
854
+ warn: 2,
855
+ error: 3
856
+ };
857
+ function isLevelEnabled(level, minLevel) {
858
+ return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];
859
+ }
860
+ function getConsoleMethod(level) {
861
+ return level;
862
+ }
863
+ var colors = {
864
+ reset: "\x1B[0m",
865
+ bold: "\x1B[1m",
866
+ dim: "\x1B[2m",
867
+ red: "\x1B[31m",
868
+ green: "\x1B[32m",
869
+ yellow: "\x1B[33m",
870
+ blue: "\x1B[34m",
871
+ magenta: "\x1B[35m",
872
+ cyan: "\x1B[36m",
873
+ white: "\x1B[37m",
874
+ gray: "\x1B[90m"
875
+ };
876
+ var levelColorMap = {
877
+ error: colors.red,
878
+ warn: colors.yellow,
879
+ info: colors.cyan,
880
+ debug: colors.gray
881
+ };
882
+ function getLevelColor(level) {
883
+ return levelColorMap[level] ?? colors.white;
884
+ }
885
+ var cssColors = {
886
+ dim: "color: #6b7280",
887
+ red: "color: #ef4444; font-weight: bold",
888
+ green: "color: #22c55e",
889
+ yellow: "color: #f59e0b; font-weight: bold",
890
+ cyan: "color: #06b6d4; font-weight: bold",
891
+ gray: "color: #6b7280; font-weight: bold",
892
+ reset: "color: inherit; font-weight: normal"
893
+ };
894
+ var cssLevelColorMap = {
895
+ error: cssColors.red,
896
+ warn: cssColors.yellow,
897
+ info: cssColors.cyan,
898
+ debug: cssColors.gray
899
+ };
900
+ function getCssLevelColor(level) {
901
+ return cssLevelColorMap[level] ?? cssColors.reset;
902
+ }
903
+ function escapeFormatString(str) {
904
+ return str.replace(/%/g, "%%");
905
+ }
906
+ var SENSITIVE_HEADERS = [
907
+ "authorization",
908
+ "cookie",
909
+ "set-cookie",
910
+ "x-api-key",
911
+ "x-auth-token",
912
+ "proxy-authorization"
913
+ ];
914
+ var SENSITIVE_HEADER_SET = new Set(SENSITIVE_HEADERS);
915
+ var patternCache = /* @__PURE__ */ new Map;
916
+ function globToRegExp(pattern, separator = "/") {
917
+ const cacheKey = `${separator}:${pattern}`;
918
+ let regex = patternCache.get(cacheKey);
919
+ if (!regex) {
920
+ const segment = separator === "/" ? "[^/]*" : "[^.]*";
921
+ const char = separator === "/" ? "[^/]" : "[^.]";
922
+ const regexPattern = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, segment).replace(/{{GLOBSTAR}}/g, ".*").replace(/\?/g, char);
923
+ regex = new RegExp(`^${regexPattern}$`);
924
+ patternCache.set(cacheKey, regex);
925
+ }
926
+ return regex;
927
+ }
928
+
929
+ // ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/pretty-error-THg0U0w9.mjs
930
+ var snippetReader = null;
931
+ var PRETTY_ERROR_TREE_SPACER = "__EVLOG_TREE_SPACER__";
932
+ function pushTreeSpacer(children) {
933
+ children.push(PRETTY_ERROR_TREE_SPACER);
934
+ }
935
+ var SKIP_PATH_RE = /(?:^|[/\\])(?:node_modules|\.nuxt|\.next|\.output)(?:[/\\]|$)/;
936
+ var SKIP_FRAME_PATH_RE = /(?:^|[/\\])(?:packages[/\\]evlog|evlog[/\\](?:dist|src))(?:[/\\]|$)/;
937
+ var SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
938
+ function isPlainObject(val) {
939
+ return val !== null && typeof val === "object" && !Array.isArray(val);
940
+ }
941
+ function pickString(obj, key) {
942
+ const val = obj[key];
943
+ return typeof val === "string" && val.length > 0 ? val : undefined;
944
+ }
945
+ function pickNumber(obj, key) {
946
+ const val = obj[key];
947
+ return typeof val === "number" ? val : undefined;
948
+ }
949
+ function extractGuidance(data) {
950
+ return {
951
+ code: pickString(data, "code"),
952
+ why: pickString(data, "why"),
953
+ fix: pickString(data, "fix"),
954
+ link: pickString(data, "link")
955
+ };
956
+ }
957
+ function normalizeErrorContext(error) {
958
+ if (error === null || error === undefined)
959
+ return null;
960
+ if (typeof error === "string")
961
+ return { message: error };
962
+ if (!isPlainObject(error))
963
+ return { message: String(error) };
964
+ const result = {
965
+ message: pickString(error, "message") ?? pickString(error, "statusText") ?? pickString(error, "statusMessage") ?? "Unknown error",
966
+ name: pickString(error, "name"),
967
+ code: pickString(error, "code"),
968
+ why: pickString(error, "why"),
969
+ fix: pickString(error, "fix"),
970
+ link: pickString(error, "link"),
971
+ status: pickNumber(error, "status") ?? pickNumber(error, "statusCode"),
972
+ stack: pickString(error, "stack")
973
+ };
974
+ const { data, cause } = error;
975
+ if (isPlainObject(data)) {
976
+ const guidance = extractGuidance(data);
977
+ if (!result.code)
978
+ result.code = guidance.code;
979
+ if (!result.why)
980
+ result.why = guidance.why;
981
+ if (!result.fix)
982
+ result.fix = guidance.fix;
983
+ if (!result.link)
984
+ result.link = guidance.link;
985
+ }
986
+ if (cause instanceof Error)
987
+ result.cause = cause.message;
988
+ else if (isPlainObject(cause) && pickString(cause, "message"))
989
+ result.cause = pickString(cause, "message");
990
+ return result;
991
+ }
992
+ function decodeFileUrl(file) {
993
+ if (file.startsWith("file://"))
994
+ try {
995
+ return decodeURIComponent(new URL(file).pathname);
996
+ } catch {
997
+ return file.slice(7);
998
+ }
999
+ return file;
1000
+ }
1001
+ function isAppPath(file) {
1002
+ const normalized = decodeFileUrl(file).replace(/\\/g, "/");
1003
+ if (normalized.startsWith("node:"))
1004
+ return false;
1005
+ if (SKIP_PATH_RE.test(normalized))
1006
+ return false;
1007
+ if (normalized.includes("/node_modules/"))
1008
+ return false;
1009
+ if (isFrameworkRuntimePath(normalized))
1010
+ return false;
1011
+ return true;
1012
+ }
1013
+ function formatDisplayPath(file, cwd) {
1014
+ const decoded = decodeFileUrl(file).replace(/\\/g, "/");
1015
+ const cwdNorm = cwd.replace(/\\/g, "/").replace(/\/$/, "");
1016
+ if (cwdNorm && decoded.startsWith(`${cwdNorm}/`)) {
1017
+ const rel = decoded.slice(cwdNorm.length + 1);
1018
+ return rel.startsWith("./") ? rel.slice(2) : rel;
1019
+ }
1020
+ const serverIdx = decoded.indexOf("/server/");
1021
+ if (serverIdx >= 0)
1022
+ return decoded.slice(serverIdx + 1);
1023
+ const srcIdx = decoded.indexOf("/src/");
1024
+ if (srcIdx >= 0)
1025
+ return decoded.slice(srcIdx + 1);
1026
+ return decoded;
1027
+ }
1028
+ function parseStackFrames(stack) {
1029
+ if (!stack)
1030
+ return [];
1031
+ const lines = stack.split(`
1032
+ `);
1033
+ const frames = [];
1034
+ for (const line of lines) {
1035
+ const trimmed = line.trim();
1036
+ if (!trimmed.startsWith("at "))
1037
+ continue;
1038
+ const withFn = trimmed.match(/^at (.+?) \((.+):(\d+):(\d+)\)$/);
1039
+ if (withFn) {
1040
+ const [, fn, file, lineStr, colStr] = withFn;
1041
+ frames.push({
1042
+ raw: trimmed,
1043
+ fn,
1044
+ file,
1045
+ line: Number(lineStr),
1046
+ column: Number(colStr),
1047
+ isApp: isAppPath(file)
1048
+ });
1049
+ continue;
1050
+ }
1051
+ const withoutFn = trimmed.match(/^at (.+):(\d+):(\d+)$/);
1052
+ if (withoutFn) {
1053
+ const [, file, lineStr, colStr] = withoutFn;
1054
+ frames.push({
1055
+ raw: trimmed,
1056
+ file,
1057
+ line: Number(lineStr),
1058
+ column: Number(colStr),
1059
+ isApp: isAppPath(file)
1060
+ });
1061
+ continue;
1062
+ }
1063
+ const asyncFn = trimmed.match(/^at async (.+?) \((.+):(\d+):(\d+)\)$/);
1064
+ if (asyncFn) {
1065
+ const [, fn, file, lineStr, colStr] = asyncFn;
1066
+ frames.push({
1067
+ raw: trimmed,
1068
+ fn: `async ${fn}`,
1069
+ file,
1070
+ line: Number(lineStr),
1071
+ column: Number(colStr),
1072
+ isApp: isAppPath(file)
1073
+ });
1074
+ }
1075
+ }
1076
+ return frames;
1077
+ }
1078
+ function isFrameworkRuntimePath(path) {
1079
+ const normalized = path.replace(/\\/g, "/");
1080
+ return normalized.includes("route-modules/") || normalized.includes("webpack://next/") || normalized.includes("/next/dist/") || normalized.includes("/compiled/next-server/");
1081
+ }
1082
+ function isFrameworkRuntimeFrame(frame) {
1083
+ if (!frame.file)
1084
+ return false;
1085
+ return isFrameworkRuntimePath(decodeFileUrl(frame.file));
1086
+ }
1087
+ function isInternalErrorFrame(frame) {
1088
+ if (isFrameworkRuntimeFrame(frame))
1089
+ return true;
1090
+ if (frame.fn) {
1091
+ const fn = frame.fn.replace(/^async /, "");
1092
+ if (SKIP_FRAME_FN_RE.test(fn))
1093
+ return true;
1094
+ }
1095
+ if (!frame.file)
1096
+ return true;
1097
+ const path = decodeFileUrl(frame.file).replace(/\\/g, "/");
1098
+ if (SKIP_FRAME_PATH_RE.test(path))
1099
+ return true;
1100
+ if (path.includes(".nuxt/"))
1101
+ return true;
1102
+ if (path.includes(".next/"))
1103
+ return true;
1104
+ return false;
1105
+ }
1106
+ function pickPrimaryFrame(frames) {
1107
+ for (const frame of frames)
1108
+ if (frame.isApp && frame.file && frame.line && !isInternalErrorFrame(frame))
1109
+ return frame;
1110
+ }
1111
+ function readCodeSnippet(file, line, contextLines = 2) {
1112
+ if (!isDev() || isBrowser() || !snippetReader)
1113
+ return null;
1114
+ const path = decodeFileUrl(file).replace(/\\/g, "/");
1115
+ if (path.includes(".next/") || path.includes(".nuxt/") || path.includes(".output/"))
1116
+ return null;
1117
+ return snippetReader(file, line, contextLines);
1118
+ }
1119
+ function formatSnippetLines(snippet) {
1120
+ const width = String(snippet[snippet.length - 1]?.line ?? 0).length;
1121
+ return snippet.map(({ line, content, isErrorLine }) => {
1122
+ const marker = isErrorLine ? `${colors.red}\u276F${colors.reset}` : `${colors.dim} ${colors.reset}`;
1123
+ const numColor = isErrorLine ? colors.red : colors.gray;
1124
+ const trimmed = content.length > 120 ? `${content.slice(0, 117)}\u2026` : content;
1125
+ return `${marker} ${numColor}${String(line).padStart(width, " ")}${colors.reset} ${colors.dim}\u2503${colors.reset} ${colors.dim}${trimmed}${colors.reset}`;
1126
+ });
1127
+ }
1128
+ function formatFrameLocation(frame, cwd) {
1129
+ const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
1130
+ const loc = frame.line ? `${file}:${frame.line}` : file;
1131
+ const fn = frame.fn && frame.fn !== "<unknown>" ? frame.fn : undefined;
1132
+ return fn ? `at ${fn} (${loc})` : `at ${loc}`;
1133
+ }
1134
+ function formatCollapsedFrame(frame, cwd) {
1135
+ const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
1136
+ const loc = frame.line ? `${file}:${frame.line}` : file;
1137
+ const prefix = frame.fn?.startsWith("async") ? "at async " : "at ";
1138
+ const fn = frame.fn?.replace(/^async /, "");
1139
+ if (fn && fn !== "<unknown>" && fn !== loc)
1140
+ return `${prefix}${fn} (${loc})`;
1141
+ return `${prefix}${loc}`;
1142
+ }
1143
+ var GUIDANCE_WRAP_WIDTH = 76;
1144
+ var GUIDANCE_CONTINUATION = " ";
1145
+ function formatGuidanceLine(label, text, labelColor) {
1146
+ const prefix = `${labelColor}${label}:${colors.reset} `;
1147
+ const lines = [];
1148
+ let remaining = text.trim();
1149
+ let first = true;
1150
+ while (remaining.length > 0) {
1151
+ const budget = first ? Math.max(24, GUIDANCE_WRAP_WIDTH - prefix.length) : Math.max(24, GUIDANCE_WRAP_WIDTH - 5);
1152
+ if (remaining.length <= budget) {
1153
+ lines.push(first ? `${prefix}${remaining}` : `${GUIDANCE_CONTINUATION}${remaining}`);
1154
+ break;
1155
+ }
1156
+ let split = remaining.lastIndexOf(" ", budget);
1157
+ if (split <= 0)
1158
+ split = budget;
1159
+ const chunk = remaining.slice(0, split).trimEnd();
1160
+ lines.push(first ? `${prefix}${chunk}` : `${GUIDANCE_CONTINUATION}${chunk}`);
1161
+ remaining = remaining.slice(split).trimStart();
1162
+ first = false;
1163
+ }
1164
+ return lines;
1165
+ }
1166
+ function buildErrorEntries(error, options = {}) {
1167
+ const normalized = normalizeErrorContext(error);
1168
+ if (!normalized)
1169
+ return [];
1170
+ const cwd = options.cwd ?? (typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd() : ".");
1171
+ const compact = options.compact ?? isDev();
1172
+ const guidanceOnly = (options.detail ?? "full") === "guidance";
1173
+ const showFrames = !guidanceOnly && !isBrowser() && (options.snippet ?? isDev());
1174
+ const stackDepth = guidanceOnly ? 0 : options.stackDepth ?? (compact ? 2 : 3);
1175
+ const snippetContextLines = compact ? 1 : 2;
1176
+ const children = [];
1177
+ const frames = guidanceOnly ? [] : parseStackFrames(normalized.stack);
1178
+ const primary = guidanceOnly ? undefined : pickPrimaryFrame(frames);
1179
+ if (!guidanceOnly && primary?.file && primary.line) {
1180
+ pushTreeSpacer(children);
1181
+ if (showFrames) {
1182
+ const snippet = readCodeSnippet(primary.file, primary.line, snippetContextLines);
1183
+ children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
1184
+ if (snippet)
1185
+ children.push(...formatSnippetLines(snippet));
1186
+ } else
1187
+ children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
1188
+ }
1189
+ if (normalized.code)
1190
+ children.push(`${colors.dim}Code:${colors.reset} ${normalized.code}`);
1191
+ if (Boolean(normalized.why || normalized.fix || normalized.link))
1192
+ pushTreeSpacer(children);
1193
+ if (normalized.why)
1194
+ children.push(...formatGuidanceLine("Why", normalized.why, colors.yellow));
1195
+ if (normalized.fix)
1196
+ children.push(...formatGuidanceLine("Fix", normalized.fix, colors.cyan));
1197
+ if (normalized.link)
1198
+ children.push(`${colors.dim}More:${colors.reset} ${normalized.link}`);
1199
+ if (normalized.cause && normalized.cause !== normalized.message)
1200
+ children.push(`${colors.dim}Caused by:${colors.reset} ${normalized.cause}`);
1201
+ const hiddenCount = guidanceOnly ? 0 : frames.filter((f) => !f.isApp || isInternalErrorFrame(f)).length;
1202
+ const tailFrames = stackDepth > 0 ? frames.filter((f) => f !== primary && !isInternalErrorFrame(f)).slice(0, stackDepth) : [];
1203
+ if (!guidanceOnly && (hiddenCount > 0 || tailFrames.length > 0)) {
1204
+ pushTreeSpacer(children);
1205
+ if (hiddenCount > 0)
1206
+ children.push(`${colors.gray}stack (${hiddenCount} frame${hiddenCount === 1 ? "" : "s"} hidden in node_modules)${colors.reset}`);
1207
+ else
1208
+ children.push(`${colors.gray}stack${colors.reset}`);
1209
+ for (const frame of tailFrames)
1210
+ children.push(`${colors.gray} ${formatCollapsedFrame(frame, cwd)}${colors.reset}`);
1211
+ }
1212
+ return [{
1213
+ key: "error",
1214
+ value: `${colors.red}${colors.bold}${normalized.message}${colors.reset}`,
1215
+ children: children.length > 0 ? children : undefined
1216
+ }];
1217
+ }
1218
+
1219
+ // ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/dev-terminal-D4UaEm17.mjs
1220
+ var DEV_PRESETS = {
1221
+ evlog: {
1222
+ frameworkOverlay: false,
1223
+ detail: "full"
1224
+ },
1225
+ nitro: {
1226
+ frameworkOverlay: true,
1227
+ detail: "guidance"
1228
+ },
1229
+ both: {
1230
+ frameworkOverlay: true,
1231
+ detail: "full"
1232
+ }
1233
+ };
1234
+ function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
1235
+ const compact = partial.compact ?? (inDev && pretty);
1236
+ const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
1237
+ const stackDepth = detail === "guidance" ? 0 : partial.stackDepth ?? (compact ? 2 : 3);
1238
+ return {
1239
+ snippet: partial.snippet ?? (detail === "full" && pretty && inDev),
1240
+ stackDepth,
1241
+ compact,
1242
+ detail
1243
+ };
1244
+ }
1245
+ function resolveDevTerminal(input = {}) {
1246
+ const pretty = input.pretty ?? isDev();
1247
+ const inDev = isDev();
1248
+ let frameworkOverlay;
1249
+ let prettyError = {};
1250
+ if (typeof input.dev === "string" && input.dev in DEV_PRESETS) {
1251
+ const { frameworkOverlay: presetOverlay, detail } = DEV_PRESETS[input.dev];
1252
+ frameworkOverlay = presetOverlay;
1253
+ prettyError = { detail };
1254
+ } else if (input.dev && typeof input.dev === "object") {
1255
+ const { frameworkOverlay: devOverlay, prettyError: devPrettyError } = input.dev;
1256
+ frameworkOverlay = devOverlay;
1257
+ if (devPrettyError)
1258
+ prettyError = devPrettyError;
1259
+ }
1260
+ if (frameworkOverlay === undefined)
1261
+ frameworkOverlay = !(pretty && inDev);
1262
+ return {
1263
+ frameworkOverlay,
1264
+ prettyError: finalizePrettyError(prettyError, frameworkOverlay, pretty, inDev)
1265
+ };
1266
+ }
1267
+
1268
+ // ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/audit-CL0q7GJU.mjs
1269
+ var DEFAULT_REPLACEMENT = "[REDACTED]";
1270
+ function normalizeRedactPathPattern(pattern) {
1271
+ if (!pattern.includes("*") && !pattern.includes("."))
1272
+ return `**.${pattern}`;
1273
+ return pattern;
1274
+ }
1275
+ function compileRedactPathMatchers(patterns) {
1276
+ if (!patterns?.length)
1277
+ return;
1278
+ const exactPaths = /* @__PURE__ */ new Set;
1279
+ const pathGlobs = [];
1280
+ const keyGlobs = [];
1281
+ const caseInsensitiveLeaves = /* @__PURE__ */ new Set;
1282
+ for (const raw of patterns) {
1283
+ if (!raw.includes("*")) {
1284
+ if (raw.includes("."))
1285
+ exactPaths.add(raw);
1286
+ else
1287
+ addPathGlobPattern(normalizeRedactPathPattern(raw), exactPaths, pathGlobs, caseInsensitiveLeaves);
1288
+ continue;
1289
+ }
1290
+ if (!raw.includes("."))
1291
+ keyGlobs.push(globToRegExp(raw, "."));
1292
+ else
1293
+ addPathGlobPattern(raw, exactPaths, pathGlobs, caseInsensitiveLeaves);
1294
+ }
1295
+ if (exactPaths.size === 0 && pathGlobs.length === 0 && keyGlobs.length === 0 && caseInsensitiveLeaves.size === 0)
1296
+ return;
1297
+ return {
1298
+ exactPaths,
1299
+ pathGlobs,
1300
+ keyGlobs,
1301
+ caseInsensitiveLeaves
1302
+ };
1303
+ }
1304
+ function addPathGlobPattern(pattern, exactPaths, pathGlobs, caseInsensitiveLeaves) {
1305
+ pathGlobs.push(globToRegExp(pattern, "."));
1306
+ const leaf = pattern.match(/^\*\*\.([^.?*]+)$/);
1307
+ if (leaf) {
1308
+ exactPaths.add(leaf[1]);
1309
+ caseInsensitiveLeaves.add(leaf[1].toLowerCase());
1310
+ }
1311
+ }
1312
+ function matchesRedactPath(fullPath, leafKey, matchers) {
1313
+ if (matchers.exactPaths.has(fullPath))
1314
+ return true;
1315
+ if (matchers.caseInsensitiveLeaves.has(leafKey.toLowerCase()))
1316
+ return true;
1317
+ for (const glob of matchers.pathGlobs) {
1318
+ glob.lastIndex = 0;
1319
+ if (glob.test(fullPath))
1320
+ return true;
1321
+ }
1322
+ for (const glob of matchers.keyGlobs) {
1323
+ glob.lastIndex = 0;
1324
+ if (glob.test(leafKey))
1325
+ return true;
1326
+ }
1327
+ return false;
1328
+ }
1329
+ function redactPathsInTree(obj, matchers, replacement, prefix = "") {
1330
+ if (obj === null || obj === undefined)
1331
+ return;
1332
+ if (Array.isArray(obj)) {
1333
+ for (let i = 0;i < obj.length; i++) {
1334
+ const segment = String(i);
1335
+ const fullPath = prefix ? `${prefix}.${segment}` : segment;
1336
+ redactPathsInTree(obj[i], matchers, replacement, fullPath);
1337
+ }
1338
+ return;
1339
+ }
1340
+ if (typeof obj === "object") {
1341
+ const record = obj;
1342
+ for (const key in record) {
1343
+ const fullPath = prefix ? `${prefix}.${key}` : key;
1344
+ if (matchesRedactPath(fullPath, key, matchers))
1345
+ record[key] = replacement;
1346
+ else
1347
+ redactPathsInTree(record[key], matchers, replacement, fullPath);
1348
+ }
1349
+ }
1350
+ }
1351
+ var builtinPatterns = {
1352
+ creditCard: {
1353
+ pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
1354
+ mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
1355
+ },
1356
+ email: {
1357
+ pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g,
1358
+ mask: (m) => {
1359
+ if (m.indexOf("@") < 1)
1360
+ return "***@***";
1361
+ const tld = m.slice(m.lastIndexOf("."));
1362
+ return `${m[0]}***@***${tld}`;
1363
+ }
1364
+ },
1365
+ ipv4: {
1366
+ 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,
1367
+ mask: (m) => `***.***.***.${m.split(".").pop()}`
1368
+ },
1369
+ phone: {
1370
+ pattern: /(?:\+\d{1,3}[\s.-]?\(?\d{1,4}\)?|\(\d{1,4}\))(?:[\s.-]?\d{2,4}){2,4}\b/g,
1371
+ mask: (m) => {
1372
+ const digits = m.replace(/[^\d]/g, "");
1373
+ if (m.startsWith("+") && digits.length > 4) {
1374
+ const ccMatch = m.match(/^\+\d{1,3}/);
1375
+ return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
1376
+ }
1377
+ if (digits.length > 2)
1378
+ return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
1379
+ return "***";
1380
+ }
1381
+ },
1382
+ jwt: {
1383
+ pattern: /\beyJ[\w-]*\.[\w-]*\.[\w-]*\b/g,
1384
+ mask: () => "eyJ***.***"
1385
+ },
1386
+ bearer: {
1387
+ pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
1388
+ mask: () => "Bearer ***"
1389
+ },
1390
+ iban: {
1391
+ 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,
1392
+ mask: (m) => {
1393
+ const clean = m.replace(/[\s-]/g, "");
1394
+ return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
1395
+ }
1396
+ }
1397
+ };
1398
+ function resolveRedactConfig(input) {
1399
+ if (input === undefined || input === false)
1400
+ return;
1401
+ if (input === true)
1402
+ return { _maskers: allBuiltinMaskers() };
1403
+ if (input.builtins === false)
1404
+ return {
1405
+ ...input,
1406
+ _pathMatchers: compileRedactPathMatchers(input.paths)
1407
+ };
1408
+ const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
1409
+ return {
1410
+ ...input,
1411
+ _maskers: maskers,
1412
+ _pathMatchers: compileRedactPathMatchers(input.paths)
1413
+ };
1414
+ }
1415
+ function allBuiltinMaskers() {
1416
+ return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
1417
+ }
1418
+ function cloneRegex(re) {
1419
+ return new RegExp(re.source, re.flags);
1420
+ }
1421
+ var globallyRedacted = Symbol.for("evlog.globallyRedacted");
1422
+ function markGloballyRedacted(event) {
1423
+ Object.defineProperty(event, globallyRedacted, {
1424
+ value: true,
1425
+ enumerable: false,
1426
+ configurable: true
1427
+ });
1428
+ }
1429
+ function cloneForRedaction(event) {
1430
+ try {
1431
+ return structuredClone(event);
1432
+ } catch {
1433
+ try {
1434
+ return JSON.parse(JSON.stringify(event));
1435
+ } catch {
1436
+ console.warn("[cloneForRedaction] Shallow clone used \u2014 nested objects may be mutated by redactPath, redactPatterns, and applyMaskersToTree");
1437
+ return { ...event };
1438
+ }
1439
+ }
1440
+ }
1441
+ function redactEvent(event, config) {
1442
+ const clone = cloneForRedaction(event);
1443
+ const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
1444
+ const pathMatchers = config._pathMatchers ?? compileRedactPathMatchers(config.paths);
1445
+ if (pathMatchers)
1446
+ redactPathsInTree(clone, pathMatchers, replacement);
1447
+ if (config._maskers?.length)
1448
+ applyMaskersToTree(clone, config._maskers);
1449
+ if (config.patterns?.length)
1450
+ redactPatterns(clone, config.patterns, replacement);
1451
+ return clone;
1452
+ }
1453
+ function redactPatterns(obj, patterns, replacement) {
1454
+ if (obj === null || obj === undefined)
1455
+ return;
1456
+ if (Array.isArray(obj)) {
1457
+ for (let i = 0;i < obj.length; i++)
1458
+ if (typeof obj[i] === "string")
1459
+ obj[i] = applyPatterns(obj[i], patterns, replacement);
1460
+ else if (typeof obj[i] === "object")
1461
+ redactPatterns(obj[i], patterns, replacement);
1462
+ return;
1463
+ }
1464
+ if (typeof obj === "object") {
1465
+ const record = obj;
1466
+ for (const key in record) {
1467
+ const val = record[key];
1468
+ if (typeof val === "string")
1469
+ record[key] = applyPatterns(val, patterns, replacement);
1470
+ else if (typeof val === "object")
1471
+ redactPatterns(val, patterns, replacement);
1472
+ }
1473
+ }
1474
+ }
1475
+ function applyPatterns(value, patterns, replacement) {
1476
+ let result = value;
1477
+ for (const pattern of patterns)
1478
+ result = result.replace(pattern, replacement);
1479
+ return result;
1480
+ }
1481
+ function applyMaskersToTree(obj, maskers) {
1482
+ if (obj === null || obj === undefined)
1483
+ return;
1484
+ if (Array.isArray(obj)) {
1485
+ for (let i = 0;i < obj.length; i++)
1486
+ if (typeof obj[i] === "string")
1487
+ obj[i] = applyMaskers(obj[i], maskers);
1488
+ else if (typeof obj[i] === "object")
1489
+ applyMaskersToTree(obj[i], maskers);
1490
+ return;
1491
+ }
1492
+ if (typeof obj === "object") {
1493
+ const record = obj;
1494
+ for (const key in record) {
1495
+ const val = record[key];
1496
+ if (typeof val === "string")
1497
+ record[key] = applyMaskers(val, maskers);
1498
+ else if (typeof val === "object")
1499
+ applyMaskersToTree(val, maskers);
1500
+ }
1501
+ }
1502
+ }
1503
+ function applyMaskers(value, maskers) {
1504
+ let result = value;
1505
+ for (const [pattern, mask] of maskers)
1506
+ result = result.replace(pattern, mask);
1507
+ return result;
1508
+ }
1509
+ function logPluginError(name, hook, err) {
1510
+ console.error(`[evlog/${name}] ${hook} failed:`, err);
1511
+ }
1512
+ function createPluginRunner(plugins = []) {
1513
+ const byName = /* @__PURE__ */ new Map;
1514
+ for (const plugin of plugins)
1515
+ byName.set(plugin.name, plugin);
1516
+ const list = Array.from(byName.values());
1517
+ return {
1518
+ plugins: list,
1519
+ hasEnrich: list.some((p) => typeof p.enrich === "function"),
1520
+ hasDrain: list.some((p) => typeof p.drain === "function"),
1521
+ hasKeep: list.some((p) => typeof p.keep === "function"),
1522
+ hasRequestLifecycle: list.some((p) => typeof p.onRequestStart === "function" || typeof p.onRequestFinish === "function"),
1523
+ hasClientLog: list.some((p) => typeof p.onClientLog === "function"),
1524
+ hasExtendLogger: list.some((p) => typeof p.extendLogger === "function"),
1525
+ applyExtendLogger(logger) {
1526
+ for (const plugin of list) {
1527
+ if (!plugin.extendLogger)
1528
+ continue;
1529
+ try {
1530
+ plugin.extendLogger(logger);
1531
+ } catch (err) {
1532
+ logPluginError(plugin.name, "extendLogger", err);
1533
+ }
1534
+ }
1535
+ },
1536
+ runOnRequestStart(ctx) {
1537
+ for (const plugin of list) {
1538
+ if (!plugin.onRequestStart)
1539
+ continue;
1540
+ try {
1541
+ plugin.onRequestStart(ctx);
1542
+ } catch (err) {
1543
+ logPluginError(plugin.name, "onRequestStart", err);
1544
+ }
1545
+ }
1546
+ },
1547
+ runOnRequestFinish(ctx) {
1548
+ for (const plugin of list) {
1549
+ if (!plugin.onRequestFinish)
1550
+ continue;
1551
+ try {
1552
+ plugin.onRequestFinish(ctx);
1553
+ } catch (err) {
1554
+ logPluginError(plugin.name, "onRequestFinish", err);
1555
+ }
1556
+ }
1557
+ },
1558
+ async runEnrich(ctx) {
1559
+ for (const plugin of list) {
1560
+ if (!plugin.enrich)
1561
+ continue;
1562
+ try {
1563
+ await plugin.enrich(ctx);
1564
+ } catch (err) {
1565
+ logPluginError(plugin.name, "enrich", err);
1566
+ }
1567
+ }
1568
+ },
1569
+ async runDrain(ctx) {
1570
+ const drains = list.filter((p) => typeof p.drain === "function");
1571
+ if (drains.length === 0)
1572
+ return;
1573
+ await Promise.allSettled(drains.map(async (plugin) => {
1574
+ try {
1575
+ await plugin.drain(ctx);
1576
+ } catch (err) {
1577
+ logPluginError(plugin.name, "drain", err);
1578
+ }
1579
+ }));
1580
+ },
1581
+ async runKeep(ctx) {
1582
+ for (const plugin of list) {
1583
+ if (!plugin.keep)
1584
+ continue;
1585
+ try {
1586
+ await plugin.keep(ctx);
1587
+ } catch (err) {
1588
+ logPluginError(plugin.name, "keep", err);
1589
+ }
1590
+ }
1591
+ },
1592
+ runOnClientLog(ctx) {
1593
+ for (const plugin of list) {
1594
+ if (!plugin.onClientLog)
1595
+ continue;
1596
+ try {
1597
+ plugin.onClientLog(ctx);
1598
+ } catch (err) {
1599
+ logPluginError(plugin.name, "onClientLog", err);
1600
+ }
1601
+ }
1602
+ },
1603
+ async runSetup(ctx) {
1604
+ for (const plugin of list) {
1605
+ if (!plugin.setup)
1606
+ continue;
1607
+ try {
1608
+ await plugin.setup(ctx);
1609
+ } catch (err) {
1610
+ logPluginError(plugin.name, "setup", err);
1611
+ }
1612
+ }
1613
+ }
1614
+ };
1615
+ }
1616
+ var emptyRunner = createPluginRunner([]);
1617
+ function getEmptyPluginRunner() {
1618
+ return emptyRunner;
1619
+ }
1620
+ var nativeStdoutWrite = typeof process !== "undefined" && typeof process.stdout?.write === "function" ? process.stdout.write.bind(process.stdout) : undefined;
1621
+ function writePrettyStdout(text) {
1622
+ (globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
1623
+ }
1624
+ function isPlainObject$1(val) {
1625
+ return val !== null && typeof val === "object" && !Array.isArray(val);
1626
+ }
1627
+ var _tsDate = /* @__PURE__ */ new Date;
1628
+ function isoNow() {
1629
+ _tsDate.setTime(Date.now());
1630
+ return _tsDate.toISOString();
1631
+ }
1632
+ var globalEnv = {
1633
+ service: "app",
1634
+ environment: "development"
1635
+ };
1636
+ var globalPretty = isDev();
1637
+ var globalPrettyError = {
1638
+ snippet: isDev(),
1639
+ stackDepth: 2,
1640
+ compact: isDev(),
1641
+ detail: "full"
1642
+ };
1643
+ var globalSampling = {};
1644
+ var globalStringify = true;
1645
+ var globalDrain;
1646
+ var globalRedact;
1647
+ var globalEnabled = true;
1648
+ var globalSilent = false;
1649
+ var globalMinLevel = "debug";
1650
+ var globalPluginRunner = getEmptyPluginRunner();
1651
+ function initLogger(config = {}) {
1652
+ globalEnabled = config.enabled ?? true;
1653
+ const detected = detectEnvironment();
1654
+ globalEnv = {
1655
+ service: config.env?.service ?? detected.service ?? "app",
1656
+ environment: config.env?.environment ?? detected.environment ?? "development",
1657
+ version: config.env?.version ?? detected.version,
1658
+ commitHash: config.env?.commitHash ?? detected.commitHash,
1659
+ region: config.env?.region ?? detected.region
1660
+ };
1661
+ globalPretty = config.pretty ?? isDev();
1662
+ globalPrettyError = resolveDevTerminal(config).prettyError;
1663
+ globalSampling = config.sampling ?? {};
1664
+ globalStringify = config.stringify ?? true;
1665
+ globalDrain = config.drain;
1666
+ globalRedact = resolveRedactConfig(config.redact ?? !isDev());
1667
+ globalSilent = config.silent ?? false;
1668
+ globalMinLevel = config.minLevel ?? "debug";
1669
+ globalPluginRunner = config.plugins?.length ? createPluginRunner(config.plugins) : getEmptyPluginRunner();
1670
+ if (globalPluginRunner.plugins.length > 0)
1671
+ globalPluginRunner.runSetup({ env: { ...globalEnv } });
1672
+ const hasAnyDrain = !!globalDrain || globalPluginRunner.hasDrain;
1673
+ if (globalSilent && !hasAnyDrain && !config._suppressDrainWarning)
1674
+ 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).");
1675
+ }
1676
+ function shouldSample(level) {
1677
+ const { rates } = globalSampling;
1678
+ if (!rates)
1679
+ return true;
1680
+ const percentage = level === "error" && rates.error === undefined ? 100 : rates[level] ?? 100;
1681
+ if (percentage <= 0)
1682
+ return false;
1683
+ if (percentage >= 100)
1684
+ return true;
1685
+ return Math.random() * 100 < percentage;
1686
+ }
1687
+ function emitWideEvent(level, event, options = {}) {
1688
+ const { deferDrain = false, ownsEvent = false, waitUntil } = options;
1689
+ if (!globalEnabled)
1690
+ return null;
1691
+ if (!ownsEvent) {
1692
+ if (!isLevelEnabled(level, globalMinLevel))
1693
+ return null;
1694
+ if (!shouldSample(level))
1695
+ return null;
1696
+ }
1697
+ let formatted;
1698
+ if (ownsEvent) {
1699
+ event.timestamp = isoNow();
1700
+ event.level = level;
1701
+ if (event.service === undefined)
1702
+ event.service = globalEnv.service;
1703
+ if (event.environment === undefined)
1704
+ event.environment = globalEnv.environment;
1705
+ if (globalEnv.version !== undefined && event.version === undefined)
1706
+ event.version = globalEnv.version;
1707
+ if (globalEnv.commitHash !== undefined && event.commitHash === undefined)
1708
+ event.commitHash = globalEnv.commitHash;
1709
+ if (globalEnv.region !== undefined && event.region === undefined)
1710
+ event.region = globalEnv.region;
1711
+ formatted = event;
1712
+ } else
1713
+ formatted = {
1714
+ timestamp: isoNow(),
1715
+ level,
1716
+ ...globalEnv,
1717
+ ...event
1718
+ };
1719
+ finalizeAudit(formatted);
1720
+ if (globalRedact) {
1721
+ formatted = redactEvent(formatted, globalRedact);
1722
+ markGloballyRedacted(formatted);
1723
+ }
1724
+ if (!globalSilent)
1725
+ if (globalPretty)
1726
+ prettyPrintWideEvent(formatted);
1727
+ else if (globalStringify)
1728
+ console[getConsoleMethod(level)](JSON.stringify(formatted));
1729
+ else
1730
+ console[getConsoleMethod(level)](formatted);
1731
+ if (!deferDrain) {
1732
+ const drainPromises = [];
1733
+ if (globalDrain)
1734
+ drainPromises.push((async () => {
1735
+ try {
1736
+ await globalDrain({ event: formatted });
1737
+ } catch (err) {
1738
+ console.error("[evlog] drain failed:", err);
1739
+ }
1740
+ })());
1741
+ if (globalPluginRunner.hasDrain)
1742
+ drainPromises.push(globalPluginRunner.runDrain({ event: formatted }));
1743
+ if (drainPromises.length > 0 && waitUntil)
1744
+ waitUntil(Promise.all(drainPromises));
1745
+ }
1746
+ return formatted;
1747
+ }
1748
+ function emitTaggedLog(level, tag, message) {
1749
+ if (!globalEnabled)
1750
+ return;
1751
+ if (globalPretty && !globalSilent) {
1752
+ if (!isLevelEnabled(level, globalMinLevel))
1753
+ return;
1754
+ if (!shouldSample(level))
1755
+ return;
1756
+ if (isBrowser()) {
1757
+ const levelColor = getCssLevelColor(level);
1758
+ const timestamp = isoNow().slice(11, 23);
1759
+ console.log(`%c${timestamp}%c %c[${escapeFormatString(tag)}]%c ${escapeFormatString(message)}`, cssColors.dim, cssColors.reset, levelColor, cssColors.reset);
1760
+ } else {
1761
+ const color = getLevelColor(level);
1762
+ const timestamp = isoNow().slice(11, 23);
1763
+ console.log(`${colors.dim}${timestamp}${colors.reset} ${color}[${tag}]${colors.reset} ${message}`);
1764
+ }
1765
+ return;
1766
+ }
1767
+ emitWideEvent(level, {
1768
+ tag,
1769
+ message
1770
+ });
1771
+ }
1772
+ function formatValue(value) {
1773
+ if (value === null || value === undefined)
1774
+ return String(value);
1775
+ if (isPlainObject$1(value)) {
1776
+ const pairs = [];
1777
+ for (const [k, v] of Object.entries(value))
1778
+ if (v !== undefined && v !== null)
1779
+ if (typeof v === "object")
1780
+ pairs.push(`${k}=${JSON.stringify(v)}`);
1781
+ else
1782
+ pairs.push(`${k}=${v}`);
1783
+ return pairs.join(" ");
1784
+ }
1785
+ return String(value);
1786
+ }
1787
+ function formatCost(cost) {
1788
+ if (cost < 0.01)
1789
+ return `$${cost.toFixed(6)}`;
1790
+ if (cost < 1)
1791
+ return `$${cost.toFixed(4)}`;
1792
+ return `$${cost.toFixed(2)}`;
1793
+ }
1794
+ function asNumber(value) {
1795
+ return typeof value === "number" ? value : undefined;
1796
+ }
1797
+ function asStringArray(value) {
1798
+ if (!Array.isArray(value))
1799
+ return;
1800
+ return value.every((item) => typeof item === "string") ? value : undefined;
1801
+ }
1802
+ function isToolUsageEntry(value) {
1803
+ return isPlainObject$1(value) && typeof value.name === "string" && typeof value.durationMs === "number" && typeof value.success === "boolean";
1804
+ }
1805
+ function asToolUsageArray(value) {
1806
+ if (!Array.isArray(value))
1807
+ return;
1808
+ return value.every(isToolUsageEntry) ? value : undefined;
1809
+ }
1810
+ function serializeToolInput(input) {
1811
+ if (typeof input === "string")
1812
+ return input;
1813
+ const seen = /* @__PURE__ */ new WeakSet;
1814
+ try {
1815
+ return JSON.stringify(input, (_key, value) => {
1816
+ if (typeof value === "bigint")
1817
+ return value.toString();
1818
+ if (typeof value === "object" && value !== null) {
1819
+ if (seen.has(value))
1820
+ return "[Circular]";
1821
+ seen.add(value);
1822
+ }
1823
+ return value;
1824
+ }) ?? "";
1825
+ } catch {
1826
+ return "[unserializable tool input]";
1827
+ }
1828
+ }
1829
+ function isToolCallEntry(value) {
1830
+ return isPlainObject$1(value) && typeof value.name === "string" && "input" in value;
1831
+ }
1832
+ function asToolCallArray(value) {
1833
+ if (!Array.isArray(value))
1834
+ return;
1835
+ return value.every(isToolCallEntry) ? value : undefined;
1836
+ }
1837
+ function buildAIEntries(ai) {
1838
+ const entries = [];
1839
+ const headerParts = [];
1840
+ if (ai.model) {
1841
+ let m = String(ai.model);
1842
+ if (ai.provider)
1843
+ m += ` (${ai.provider})`;
1844
+ headerParts.push(m);
1845
+ }
1846
+ if (ai.calls) {
1847
+ const calls = asNumber(ai.calls);
1848
+ if (calls !== undefined)
1849
+ headerParts.push(`${calls} call${calls > 1 ? "s" : ""}`);
1850
+ }
1851
+ const steps = asNumber(ai.steps);
1852
+ if (steps !== undefined && steps > 1)
1853
+ headerParts.push(`${steps} steps`);
1854
+ entries.push({
1855
+ key: "ai",
1856
+ value: headerParts.join(" \xB7 ")
1857
+ });
1858
+ const inputTokens = asNumber(ai.inputTokens);
1859
+ const outputTokens = asNumber(ai.outputTokens);
1860
+ const totalTokens = asNumber(ai.totalTokens);
1861
+ if (inputTokens !== undefined && outputTokens !== undefined) {
1862
+ let tokLine = `${inputTokens} in \u2192 ${outputTokens} out`;
1863
+ if (totalTokens)
1864
+ tokLine += ` (${totalTokens} total)`;
1865
+ const extras = [];
1866
+ if (ai.cacheReadTokens)
1867
+ extras.push(`${ai.cacheReadTokens} cache read`);
1868
+ if (ai.cacheWriteTokens)
1869
+ extras.push(`${ai.cacheWriteTokens} cache write`);
1870
+ if (ai.reasoningTokens)
1871
+ extras.push(`${ai.reasoningTokens} reasoning`);
1872
+ if (extras.length)
1873
+ tokLine += ` \xB7 ${extras.join(" \xB7 ")}`;
1874
+ entries.push({
1875
+ key: "ai.tokens",
1876
+ value: tokLine
1877
+ });
1878
+ }
1879
+ const msFirst = asNumber(ai.msToFirstChunk);
1880
+ const msFinish = asNumber(ai.msToFinish);
1881
+ const tps = asNumber(ai.tokensPerSecond);
1882
+ if (msFirst !== undefined || msFinish !== undefined) {
1883
+ const parts = [];
1884
+ if (msFirst !== undefined)
1885
+ parts.push(`${formatDuration(msFirst)} to first chunk`);
1886
+ if (msFinish !== undefined)
1887
+ parts.push(`${formatDuration(msFinish)} total`);
1888
+ let streamLine = parts.join(" \u2192 ");
1889
+ if (tps)
1890
+ streamLine += ` \xB7 ${tps} tok/s`;
1891
+ entries.push({
1892
+ key: "ai.streaming",
1893
+ value: streamLine
1894
+ });
1895
+ }
1896
+ const estimatedCost = asNumber(ai.estimatedCost);
1897
+ if (estimatedCost !== undefined)
1898
+ entries.push({
1899
+ key: "ai.cost",
1900
+ value: formatCost(estimatedCost)
1901
+ });
1902
+ const totalDurationMs = asNumber(ai.totalDurationMs);
1903
+ if (totalDurationMs !== undefined)
1904
+ entries.push({
1905
+ key: "ai.totalDuration",
1906
+ value: formatDuration(totalDurationMs)
1907
+ });
1908
+ const toolCalls = Array.isArray(ai.toolCalls) ? ai.toolCalls : undefined;
1909
+ const tools = asToolUsageArray(ai.tools);
1910
+ const toolCallEntries = toolCalls ? asToolCallArray(toolCalls) : undefined;
1911
+ const hasInputs = toolCallEntries !== undefined && toolCallEntries.length > 0;
1912
+ if (tools?.length) {
1913
+ const children = tools.map((t, idx) => {
1914
+ const mark = t.success ? "\u2713" : "\u2717";
1915
+ let line = `${t.name} ${formatDuration(t.durationMs)} ${mark}`;
1916
+ if (t.error)
1917
+ line += ` ${t.error}`;
1918
+ if (hasInputs && toolCallEntries && idx < toolCallEntries.length) {
1919
+ const tc = toolCallEntries[idx];
1920
+ const inputStr = serializeToolInput(tc.input);
1921
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
1922
+ line += ` ${truncated}`;
1923
+ }
1924
+ return line;
1925
+ });
1926
+ entries.push({
1927
+ key: "ai.tools",
1928
+ value: "",
1929
+ children
1930
+ });
1931
+ } else if (toolCalls?.length)
1932
+ if (toolCallEntries?.length) {
1933
+ const children = toolCallEntries.map((tc) => {
1934
+ const inputStr = serializeToolInput(tc.input);
1935
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
1936
+ return `${tc.name}(${truncated})`;
1937
+ });
1938
+ entries.push({
1939
+ key: "ai.tools",
1940
+ value: "",
1941
+ children
1942
+ });
1943
+ } else {
1944
+ const names = asStringArray(toolCalls);
1945
+ if (names?.length)
1946
+ entries.push({
1947
+ key: "ai.tools",
1948
+ value: names.join(", ")
1949
+ });
1950
+ }
1951
+ const stepsUsage = Array.isArray(ai.stepsUsage) ? ai.stepsUsage.filter(isPlainObject$1) : undefined;
1952
+ if (stepsUsage?.length) {
1953
+ const firstModel = stepsUsage[0]?.model;
1954
+ const allSameModel = firstModel !== undefined && stepsUsage.every((s) => s.model === firstModel);
1955
+ const children = stepsUsage.map((s) => {
1956
+ let line = `${allSameModel ? "" : `${String(s.model)} `}${s.inputTokens} in \u2192 ${s.outputTokens} out`;
1957
+ const stepTools = asStringArray(s.toolCalls);
1958
+ if (stepTools?.length)
1959
+ line += ` [${stepTools.join(", ")}]`;
1960
+ return line;
1961
+ });
1962
+ entries.push({
1963
+ key: "ai.steps",
1964
+ value: "",
1965
+ children
1966
+ });
1967
+ } else if (steps !== undefined && steps > 1)
1968
+ entries.push({
1969
+ key: "ai.steps",
1970
+ value: String(steps)
1971
+ });
1972
+ const embedding = isPlainObject$1(ai.embedding) ? ai.embedding : undefined;
1973
+ if (embedding) {
1974
+ const parts = [];
1975
+ if (embedding.model)
1976
+ parts.push(String(embedding.model));
1977
+ parts.push(`${embedding.tokens} tokens`);
1978
+ if (embedding.dimensions)
1979
+ parts.push(`${embedding.dimensions}d`);
1980
+ if (embedding.count)
1981
+ parts.push(`${embedding.count} items`);
1982
+ entries.push({
1983
+ key: "ai.embedding",
1984
+ value: parts.join(" \xB7 ")
1985
+ });
1986
+ }
1987
+ if (ai.finishReason)
1988
+ entries.push({
1989
+ key: "ai.finishReason",
1990
+ value: String(ai.finishReason)
1991
+ });
1992
+ if (ai.error)
1993
+ entries.push({
1994
+ key: "ai.error",
1995
+ value: String(ai.error)
1996
+ });
1997
+ if (ai.responseId)
1998
+ entries.push({
1999
+ key: "ai.responseId",
2000
+ value: String(ai.responseId)
2001
+ });
2002
+ return entries;
2003
+ }
2004
+ function flushPrettyLines(lines) {
2005
+ if (lines.length === 0)
2006
+ return;
2007
+ const text = `${lines.join(`
2008
+ `)}
2009
+ `;
2010
+ if (nativeStdoutWrite && !isBrowser() && process.env.VITEST !== "true") {
2011
+ writePrettyStdout(text);
2012
+ return;
2013
+ }
2014
+ console.log(lines.join(`
2015
+ `));
2016
+ }
2017
+ function prettyPrintWideEvent(event) {
2018
+ const { timestamp, level, service, environment, version, ...rest } = event;
2019
+ const ts = typeof timestamp === "string" ? timestamp.slice(11, 23) : "";
2020
+ const levelLabel = typeof level === "string" ? level : "info";
2021
+ const browser = isBrowser();
2022
+ const lines = [];
2023
+ const writeLine = (...args) => {
2024
+ if (browser) {
2025
+ console.log(...args);
2026
+ return;
2027
+ }
2028
+ const [line] = args;
2029
+ if (typeof line === "string")
2030
+ lines.push(line);
2031
+ };
2032
+ const parts = [];
2033
+ const styles = [];
2034
+ if (browser) {
2035
+ const lc = getCssLevelColor(levelLabel);
2036
+ parts.push(`%c${ts}%c %c${levelLabel.toUpperCase()}%c %c[${escapeFormatString(String(service))}]%c`);
2037
+ styles.push(cssColors.dim, cssColors.reset, lc, cssColors.reset, cssColors.cyan, cssColors.reset);
2038
+ } else {
2039
+ const lc = getLevelColor(levelLabel);
2040
+ if (isDev())
2041
+ parts.push(`${lc}${levelLabel.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
2042
+ else
2043
+ parts.push(`${colors.dim}${ts}${colors.reset} ${lc}${levelLabel.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
2044
+ }
2045
+ if (rest.method && rest.path) {
2046
+ parts.push(browser ? ` ${escapeFormatString(String(rest.method))} ${escapeFormatString(String(rest.path))}` : ` ${rest.method} ${rest.path}`);
2047
+ delete rest.method;
2048
+ delete rest.path;
2049
+ }
2050
+ if (rest.status) {
2051
+ const statusCode = asNumber(rest.status) ?? Number(rest.status);
2052
+ const sc = browser ? statusCode >= 400 ? cssColors.red : cssColors.green : statusCode >= 400 ? colors.red : colors.green;
2053
+ if (browser) {
2054
+ parts.push(` %c${rest.status}%c`);
2055
+ styles.push(sc, cssColors.reset);
2056
+ } else
2057
+ parts.push(` ${sc}${rest.status}${colors.reset}`);
2058
+ delete rest.status;
2059
+ }
2060
+ if (rest.duration) {
2061
+ if (browser) {
2062
+ parts.push(` %c${escapeFormatString(`in ${rest.duration}`)}%c`);
2063
+ styles.push(cssColors.dim, cssColors.reset);
2064
+ } else
2065
+ parts.push(` ${colors.dim}in ${rest.duration}${colors.reset}`);
2066
+ delete rest.duration;
2067
+ }
2068
+ writeLine(parts.join(""), ...styles);
2069
+ const aiData = isPlainObject$1(rest.ai) ? rest.ai : undefined;
2070
+ if (aiData)
2071
+ delete rest.ai;
2072
+ const errorData = rest.error;
2073
+ if (errorData !== undefined)
2074
+ delete rest.error;
2075
+ const restEntries = Object.entries(rest).filter(([_, v]) => v !== undefined);
2076
+ const aiEntries = aiData ? buildAIEntries(aiData) : [];
2077
+ const errorEntries = errorData !== undefined ? buildErrorEntries(errorData, globalPrettyError) : [];
2078
+ const contextEntries = [...restEntries.map(([key, value]) => ({
2079
+ key,
2080
+ value: formatValue(value)
2081
+ })), ...aiEntries];
2082
+ const allEntries = errorEntries.length > 0 ? [...errorEntries, ...contextEntries] : contextEntries;
2083
+ for (let i = 0;i < allEntries.length; i++) {
2084
+ const entry = allEntries[i];
2085
+ if (!entry)
2086
+ continue;
2087
+ const { children } = entry;
2088
+ const hasChildren = children !== undefined && children.length > 0;
2089
+ const prefix = i === allEntries.length - 1 && !hasChildren ? "\u2514\u2500" : "\u251C\u2500";
2090
+ if (browser) {
2091
+ const val = entry.value ? ` ${escapeFormatString(entry.value)}` : "";
2092
+ writeLine(` %c${prefix}%c %c${escapeFormatString(entry.key)}:%c${val}`, cssColors.dim, cssColors.reset, cssColors.cyan, cssColors.reset);
2093
+ } else {
2094
+ const val = entry.value ? ` ${entry.value}` : "";
2095
+ writeLine(` ${colors.dim}${prefix}${colors.reset} ${colors.cyan}${entry.key}:${colors.reset}${val}`);
2096
+ }
2097
+ if (hasChildren && children) {
2098
+ const connector = i === allEntries.length - 1 ? " " : "\u2502";
2099
+ for (let j = 0;j < children.length; j++) {
2100
+ const child = children[j];
2101
+ if (child === undefined)
2102
+ continue;
2103
+ if (child === "__EVLOG_TREE_SPACER__") {
2104
+ writeLine(` ${colors.dim}${connector}${colors.reset}`);
2105
+ continue;
2106
+ }
2107
+ const childPrefix = j === children.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
2108
+ if (child === "") {
2109
+ writeLine("");
2110
+ continue;
2111
+ }
2112
+ if (browser)
2113
+ writeLine(` %c${connector} ${childPrefix}%c ${escapeFormatString(child)}`, cssColors.dim, cssColors.reset);
2114
+ else if (child.startsWith(" ") || child.startsWith("\x1B"))
2115
+ writeLine(` ${colors.dim}${connector}${colors.reset}${child}`);
2116
+ else
2117
+ writeLine(` ${colors.dim}${connector} ${childPrefix}${colors.reset} ${child}`);
2118
+ }
2119
+ }
2120
+ }
2121
+ if (!browser && lines.length > 0)
2122
+ flushPrettyLines(lines);
2123
+ }
2124
+ function createLogMethod(level) {
2125
+ return function logMethod(tagOrEvent, message) {
2126
+ if (typeof tagOrEvent === "string" && message !== undefined)
2127
+ emitTaggedLog(level, tagOrEvent, message);
2128
+ else if (typeof tagOrEvent === "object")
2129
+ emitWideEvent(level, tagOrEvent);
2130
+ else
2131
+ emitTaggedLog(level, "log", String(tagOrEvent));
2132
+ };
2133
+ }
2134
+ var _log = {
2135
+ info: createLogMethod("info"),
2136
+ error: createLogMethod("error"),
2137
+ warn: createLogMethod("warn"),
2138
+ debug: createLogMethod("debug")
2139
+ };
2140
+ var noopLogger = {
2141
+ set() {},
2142
+ setLevel() {},
2143
+ error() {},
2144
+ info() {},
2145
+ warn() {},
2146
+ emit() {
2147
+ return null;
2148
+ },
2149
+ getContext() {
2150
+ return {};
2151
+ },
2152
+ audit: Object.assign(() => {}, { deny: () => {} })
2153
+ };
2154
+ if (typeof __EVLOG_CONFIG__ !== "undefined")
2155
+ initLogger(__EVLOG_CONFIG__);
2156
+ function isPlainObject2(value) {
2157
+ if (typeof value !== "object" || value === null || Array.isArray(value))
2158
+ return false;
2159
+ if (Object.prototype.toString.call(value) !== "[object Object]")
2160
+ return false;
2161
+ return Object.getPrototypeOf(value) === Object.prototype || value.constructor === Object;
2162
+ }
2163
+ function stableStringify(value, ancestors = /* @__PURE__ */ new WeakSet) {
2164
+ if (value === null || typeof value !== "object")
2165
+ return JSON.stringify(value);
2166
+ if (ancestors.has(value))
2167
+ return '"[Circular]"';
2168
+ if (!Array.isArray(value) && !isPlainObject2(value))
2169
+ return JSON.stringify(value);
2170
+ ancestors.add(value);
2171
+ 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(",")}}`;
2172
+ ancestors.delete(value);
2173
+ return out;
2174
+ }
2175
+ function fnv1a32(input, seed) {
2176
+ let h = seed >>> 0;
2177
+ for (let i = 0;i < input.length; i++) {
2178
+ h ^= input.charCodeAt(i) & 255;
2179
+ h = Math.imul(h, 16777619) >>> 0;
2180
+ }
2181
+ return h >>> 0;
2182
+ }
2183
+ function computeIdempotencyKey(audit, timestamp) {
2184
+ const seconds = timestamp.slice(0, 19);
2185
+ const payload = stableStringify({
2186
+ action: audit.action,
2187
+ actor: {
2188
+ type: audit.actor.type,
2189
+ id: audit.actor.id
2190
+ },
2191
+ target: audit.target ? {
2192
+ type: audit.target.type,
2193
+ id: audit.target.id
2194
+ } : undefined,
2195
+ outcome: audit.outcome,
2196
+ timestamp: seconds
2197
+ });
2198
+ const a = fnv1a32(payload, 2166136261).toString(16).padStart(8, "0");
2199
+ const b = fnv1a32(payload, 3735928559).toString(16).padStart(8, "0");
2200
+ const c = fnv1a32(payload, 528734635).toString(16).padStart(8, "0");
2201
+ const d = fnv1a32(payload, 1541459225).toString(16).padStart(8, "0");
2202
+ return a + b + c + d;
2203
+ }
2204
+ var _testCollector = null;
2205
+ function decorateAudit(audit, timestamp) {
2206
+ if (audit.idempotencyKey)
2207
+ return audit;
2208
+ return {
2209
+ ...audit,
2210
+ idempotencyKey: computeIdempotencyKey(audit, timestamp)
2211
+ };
2212
+ }
2213
+ function finalizeAudit(event) {
2214
+ const a = event.audit;
2215
+ if (!a)
2216
+ return;
2217
+ const decorated = decorateAudit(a, String(event.timestamp));
2218
+ event.audit = decorated;
2219
+ _testCollector?.(decorated, event);
2220
+ }
2221
+ // src/client/router/provider.tsx
2222
+ import { useCallback as useCallback2, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
2223
+
2224
+ // ../../node_modules/.bun/seroval@1.5.4/node_modules/seroval/dist/esm/development/index.mjs
2225
+ var ALL_ENABLED = 1 | 2 | 4 | 8 | 16 | 32;
2226
+ var SYM_ASYNC_ITERATOR = Symbol.asyncIterator;
2227
+ var SYM_HAS_INSTANCE = Symbol.hasInstance;
2228
+ var SYM_IS_CONCAT_SPREADABLE = Symbol.isConcatSpreadable;
2229
+ var SYM_ITERATOR = Symbol.iterator;
2230
+ var SYM_MATCH = Symbol.match;
2231
+ var SYM_MATCH_ALL = Symbol.matchAll;
2232
+ var SYM_REPLACE = Symbol.replace;
2233
+ var SYM_SEARCH = Symbol.search;
2234
+ var SYM_SPECIES = Symbol.species;
2235
+ var SYM_SPLIT = Symbol.split;
2236
+ var SYM_TO_PRIMITIVE = Symbol.toPrimitive;
2237
+ var SYM_TO_STRING_TAG = Symbol.toStringTag;
2238
+ var SYM_UNSCOPABLES = Symbol.unscopables;
2239
+ var INV_SYMBOL_REF = {
2240
+ [SYM_ASYNC_ITERATOR]: 0,
2241
+ [SYM_HAS_INSTANCE]: 1,
2242
+ [SYM_IS_CONCAT_SPREADABLE]: 2,
2243
+ [SYM_ITERATOR]: 3,
2244
+ [SYM_MATCH]: 4,
2245
+ [SYM_MATCH_ALL]: 5,
2246
+ [SYM_REPLACE]: 6,
2247
+ [SYM_SEARCH]: 7,
2248
+ [SYM_SPECIES]: 8,
2249
+ [SYM_SPLIT]: 9,
2250
+ [SYM_TO_PRIMITIVE]: 10,
2251
+ [SYM_TO_STRING_TAG]: 11,
2252
+ [SYM_UNSCOPABLES]: 12
2253
+ };
2254
+ var SYMBOL_REF = {
2255
+ [0]: SYM_ASYNC_ITERATOR,
2256
+ [1]: SYM_HAS_INSTANCE,
2257
+ [2]: SYM_IS_CONCAT_SPREADABLE,
2258
+ [3]: SYM_ITERATOR,
2259
+ [4]: SYM_MATCH,
2260
+ [5]: SYM_MATCH_ALL,
2261
+ [6]: SYM_REPLACE,
2262
+ [7]: SYM_SEARCH,
2263
+ [8]: SYM_SPECIES,
2264
+ [9]: SYM_SPLIT,
2265
+ [10]: SYM_TO_PRIMITIVE,
2266
+ [11]: SYM_TO_STRING_TAG,
2267
+ [12]: SYM_UNSCOPABLES
2268
+ };
2269
+ var NIL = undefined;
2270
+ var CONSTANT_VAL = {
2271
+ [2]: true,
2272
+ [3]: false,
2273
+ [1]: NIL,
2274
+ [0]: null,
2275
+ [4]: -0,
2276
+ [5]: Number.POSITIVE_INFINITY,
2277
+ [6]: Number.NEGATIVE_INFINITY,
2278
+ [7]: Number.NaN
2279
+ };
2280
+ var ERROR_CONSTRUCTOR = {
2281
+ [0]: Error,
2282
+ [1]: EvalError,
2283
+ [2]: RangeError,
2284
+ [3]: ReferenceError,
2285
+ [4]: SyntaxError,
2286
+ [5]: TypeError,
2287
+ [6]: URIError
2288
+ };
2289
+ function serializeChar(str) {
2290
+ switch (str) {
2291
+ case '"':
2292
+ return "\\\"";
2293
+ case "\\":
2294
+ return "\\\\";
2295
+ case `
2296
+ `:
2297
+ return "\\n";
2298
+ case "\r":
2299
+ return "\\r";
2300
+ case "\b":
2301
+ return "\\b";
2302
+ case "\t":
2303
+ return "\\t";
2304
+ case "\f":
2305
+ return "\\f";
2306
+ case "<":
2307
+ return "\\x3C";
2308
+ case "\u2028":
2309
+ return "\\u2028";
2310
+ case "\u2029":
2311
+ return "\\u2029";
2312
+ default:
2313
+ return NIL;
2314
+ }
2315
+ }
2316
+ function serializeString(str) {
2317
+ let result = "";
2318
+ let lastPos = 0;
2319
+ let replacement;
2320
+ for (let i = 0, len = str.length;i < len; i++) {
2321
+ replacement = serializeChar(str[i]);
2322
+ if (replacement) {
2323
+ result += str.slice(lastPos, i) + replacement;
2324
+ lastPos = i + 1;
2325
+ }
2326
+ }
2327
+ if (lastPos === 0) {
2328
+ result = str;
2329
+ } else {
2330
+ result += str.slice(lastPos);
2331
+ }
2332
+ return result;
2333
+ }
2334
+ function deserializeReplacer(str) {
2335
+ switch (str) {
2336
+ case "\\\\":
2337
+ return "\\";
2338
+ case "\\\"":
2339
+ return '"';
2340
+ case "\\n":
2341
+ return `
2342
+ `;
2343
+ case "\\r":
2344
+ return "\r";
2345
+ case "\\b":
2346
+ return "\b";
2347
+ case "\\t":
2348
+ return "\t";
2349
+ case "\\f":
2350
+ return "\f";
2351
+ case "\\x3C":
2352
+ return "<";
2353
+ case "\\u2028":
2354
+ return "\u2028";
2355
+ case "\\u2029":
2356
+ return "\u2029";
2357
+ default:
2358
+ return str;
2359
+ }
2360
+ }
2361
+ function deserializeString(str) {
2362
+ return str.replace(/(\\\\|\\"|\\n|\\r|\\b|\\t|\\f|\\u2028|\\u2029|\\x3C)/g, deserializeReplacer);
2363
+ }
2364
+ var REFERENCES_KEY = "__SEROVAL_REFS__";
2365
+ var GLOBAL_CONTEXT_REFERENCES = "$R";
2366
+ var GLOBAL_CONTEXT_R = `self.${GLOBAL_CONTEXT_REFERENCES}`;
2367
+ var INV_REFERENCE = /* @__PURE__ */ new Map;
2368
+ function hasReference(id) {
2369
+ return INV_REFERENCE.has(id);
2370
+ }
2371
+ function getReference(id) {
2372
+ if (hasReference(id)) {
2373
+ return INV_REFERENCE.get(id);
2374
+ }
2375
+ throw new SerovalMissingReferenceForIdError(id);
2376
+ }
2377
+ if (typeof globalThis !== "undefined") {
2378
+ Object.defineProperty(globalThis, REFERENCES_KEY, {
2379
+ value: INV_REFERENCE,
2380
+ configurable: true,
2381
+ writable: false,
2382
+ enumerable: false
2383
+ });
2384
+ } else if (typeof window !== "undefined") {
2385
+ Object.defineProperty(window, REFERENCES_KEY, {
2386
+ value: INV_REFERENCE,
2387
+ configurable: true,
2388
+ writable: false,
2389
+ enumerable: false
2390
+ });
2391
+ } else if (typeof self !== "undefined") {
2392
+ Object.defineProperty(self, REFERENCES_KEY, {
2393
+ value: INV_REFERENCE,
2394
+ configurable: true,
2395
+ writable: false,
2396
+ enumerable: false
2397
+ });
2398
+ } else if (typeof global !== "undefined") {
2399
+ Object.defineProperty(global, REFERENCES_KEY, {
2400
+ value: INV_REFERENCE,
2401
+ configurable: true,
2402
+ writable: false,
2403
+ enumerable: false
2404
+ });
2405
+ }
2406
+ var { toString: objectToString } = Object.prototype;
2407
+ function getErrorMessageDev(type, cause) {
2408
+ if (cause instanceof Error) {
2409
+ return `Seroval caught an error during the ${type} process.
2410
+
2411
+ ${cause.name}
2412
+ ${cause.message}
2413
+
2414
+ - For more information, please check the "cause" property of this error.
2415
+ - If you believe this is an error in Seroval, please submit an issue at https://github.com/lxsmnsyc/seroval/issues/new`;
2416
+ }
2417
+ return `Seroval caught an error during the ${type} process.
2418
+
2419
+ "${objectToString.call(cause)}"
2420
+
2421
+ For more information, please check the "cause" property of this error.`;
2422
+ }
2423
+ var getErrorMessage = (type, cause) => getErrorMessageDev(type, cause);
2424
+ var SerovalError = class extends Error {
2425
+ constructor(type, cause) {
2426
+ super(getErrorMessage(type, cause));
2427
+ this.cause = cause;
2428
+ }
2429
+ };
2430
+ var SerovalDeserializationError = class extends SerovalError {
2431
+ constructor(cause) {
2432
+ super("deserialization", cause);
2433
+ }
2434
+ };
2435
+ var SerovalUnsupportedNodeError = class extends Error {
2436
+ constructor(node) {
2437
+ super('Unsupported node type "' + node.t + '".');
2438
+ }
2439
+ };
2440
+ var SerovalMissingPluginError = class extends Error {
2441
+ constructor(tag) {
2442
+ super('Missing plugin for tag "' + tag + '".');
2443
+ }
2444
+ };
2445
+ var SerovalMissingInstanceError = class extends Error {
2446
+ constructor(tag) {
2447
+ super('Missing "' + tag + '" instance.');
2448
+ }
2449
+ };
2450
+ var SerovalMissingReferenceForIdError = class extends Error {
2451
+ constructor(id) {
2452
+ super('Missing reference for id "' + serializeString(id) + '"');
2453
+ }
2454
+ };
2455
+ var SerovalUnknownTypedArrayError = class extends Error {
2456
+ constructor(name) {
2457
+ super('Unknown TypedArray "' + name + '"');
2458
+ }
2459
+ };
2460
+ var SerovalMalformedNodeError = class extends Error {
2461
+ constructor(node) {
2462
+ super('Malformed node type "' + node.t + '".');
2463
+ }
2464
+ };
2465
+ var SerovalDepthLimitError = class extends Error {
2466
+ constructor(limit) {
2467
+ super("Depth limit of " + limit + " reached");
2468
+ }
2469
+ };
2470
+ var PROMISE_CONSTRUCTOR = () => {
2471
+ const resolver = {
2472
+ p: 0,
2473
+ s: 0,
2474
+ f: 0
2475
+ };
2476
+ resolver.p = new Promise((resolve, reject) => {
2477
+ resolver.s = resolve;
2478
+ resolver.f = reject;
2479
+ });
2480
+ return resolver;
2481
+ };
2482
+ var STREAM_CONSTRUCTOR = () => {
2483
+ const buffer = [];
2484
+ const listeners = [];
2485
+ let alive = true;
2486
+ let success = false;
2487
+ let count = 0;
2488
+ const flush = (value, mode, x) => {
2489
+ for (x = 0;x < count; x++) {
2490
+ if (listeners[x]) {
2491
+ listeners[x][mode](value);
2492
+ }
2493
+ }
2494
+ };
2495
+ const up = (listener, x, z, current) => {
2496
+ for (x = 0, z = buffer.length;x < z; x++) {
2497
+ current = buffer[x];
2498
+ if (!alive && x === z - 1) {
2499
+ listener[success ? "return" : "throw"](current);
2500
+ } else {
2501
+ listener.next(current);
2502
+ }
2503
+ }
2504
+ };
2505
+ const on = (listener, temp) => {
2506
+ if (alive) {
2507
+ temp = count++;
2508
+ listeners[temp] = listener;
2509
+ }
2510
+ up(listener);
2511
+ return () => {
2512
+ if (alive) {
2513
+ listeners[temp] = listeners[count];
2514
+ listeners[count--] = undefined;
2515
+ }
2516
+ };
2517
+ };
2518
+ return {
2519
+ __SEROVAL_STREAM__: true,
2520
+ on: (listener) => on(listener),
2521
+ next: (value) => {
2522
+ if (alive) {
2523
+ buffer.push(value);
2524
+ flush(value, "next");
2525
+ }
2526
+ },
2527
+ throw: (value) => {
2528
+ if (alive) {
2529
+ buffer.push(value);
2530
+ flush(value, "throw");
2531
+ alive = false;
2532
+ success = false;
2533
+ listeners.length = 0;
2534
+ }
2535
+ },
2536
+ return: (value) => {
2537
+ if (alive) {
2538
+ buffer.push(value);
2539
+ flush(value, "return");
2540
+ alive = false;
2541
+ success = true;
2542
+ listeners.length = 0;
2543
+ }
2544
+ }
2545
+ };
2546
+ };
2547
+ var ITERATOR_CONSTRUCTOR = (symbol) => (sequence) => () => {
2548
+ let index = 0;
2549
+ const instance = {
2550
+ [symbol]: () => instance,
2551
+ next: () => {
2552
+ if (index > sequence.d) {
2553
+ return {
2554
+ done: true,
2555
+ value: undefined
2556
+ };
2557
+ }
2558
+ const currentIndex = index++;
2559
+ const data = sequence.v[currentIndex];
2560
+ if (currentIndex === sequence.t) {
2561
+ throw data;
2562
+ }
2563
+ return {
2564
+ done: currentIndex === sequence.d,
2565
+ value: data
2566
+ };
2567
+ }
2568
+ };
2569
+ return instance;
2570
+ };
2571
+ var ASYNC_ITERATOR_CONSTRUCTOR = (symbol, createPromise) => (stream) => () => {
2572
+ let count = 0;
2573
+ let doneAt = -1;
2574
+ let isThrow = false;
2575
+ const buffer = [];
2576
+ const pending = [];
2577
+ const finalize = (i = 0, len = pending.length) => {
2578
+ for (;i < len; i++) {
2579
+ pending[i].s({
2580
+ done: true,
2581
+ value: undefined
2582
+ });
2583
+ }
2584
+ };
2585
+ stream.on({
2586
+ next: (value) => {
2587
+ const temp = pending.shift();
2588
+ if (temp) {
2589
+ temp.s({ done: false, value });
2590
+ }
2591
+ buffer.push(value);
2592
+ },
2593
+ throw: (value) => {
2594
+ const temp = pending.shift();
2595
+ if (temp) {
2596
+ temp.f(value);
2597
+ }
2598
+ finalize();
2599
+ doneAt = buffer.length;
2600
+ isThrow = true;
2601
+ buffer.push(value);
2602
+ },
2603
+ return: (value) => {
2604
+ const temp = pending.shift();
2605
+ if (temp) {
2606
+ temp.s({ done: true, value });
2607
+ }
2608
+ finalize();
2609
+ doneAt = buffer.length;
2610
+ buffer.push(value);
2611
+ }
2612
+ });
2613
+ const instance = {
2614
+ [symbol]: () => instance,
2615
+ next: () => {
2616
+ if (doneAt === -1) {
2617
+ const index2 = count++;
2618
+ if (index2 >= buffer.length) {
2619
+ const temp = createPromise();
2620
+ pending.push(temp);
2621
+ return temp.p;
2622
+ }
2623
+ return {
2624
+ done: false,
2625
+ value: buffer[index2]
2626
+ };
2627
+ }
2628
+ if (count > doneAt) {
2629
+ return {
2630
+ done: true,
2631
+ value: undefined
2632
+ };
2633
+ }
2634
+ const index = count++;
2635
+ const value = buffer[index];
2636
+ if (index !== doneAt) {
2637
+ return {
2638
+ done: false,
2639
+ value
2640
+ };
2641
+ }
2642
+ if (isThrow) {
2643
+ throw value;
2644
+ }
2645
+ return {
2646
+ done: true,
2647
+ value
2648
+ };
2649
+ }
2650
+ };
2651
+ return instance;
2652
+ };
2653
+ var ARRAY_BUFFER_CONSTRUCTOR = (b64) => {
2654
+ const decoded = atob(b64);
2655
+ const length = decoded.length;
2656
+ const arr = new Uint8Array(length);
2657
+ for (let i = 0;i < length; i++) {
2658
+ arr[i] = decoded.charCodeAt(i);
2659
+ }
2660
+ return arr.buffer;
2661
+ };
2662
+ function createSequence(values, throwAt, doneAt) {
2663
+ return {
2664
+ __SEROVAL_SEQUENCE__: true,
2665
+ v: values,
2666
+ t: throwAt,
2667
+ d: doneAt
2668
+ };
2669
+ }
2670
+ var createIterator = ITERATOR_CONSTRUCTOR(SYM_ITERATOR);
2671
+ function sequenceToIterator(sequence) {
2672
+ return createIterator(sequence);
2673
+ }
2674
+ function createStream() {
2675
+ return STREAM_CONSTRUCTOR();
2676
+ }
2677
+ var createAsyncIterable = ASYNC_ITERATOR_CONSTRUCTOR(SYM_ASYNC_ITERATOR, PROMISE_CONSTRUCTOR);
2678
+ function streamToAsyncIterable(stream) {
2679
+ return createAsyncIterable(stream);
2680
+ }
2681
+ function dedupePlugins(deduped, plugins) {
2682
+ for (let i = 0, len = plugins.length;i < len; i++) {
2683
+ const current = plugins[i];
2684
+ if (!deduped.has(current)) {
2685
+ deduped.add(current);
2686
+ if (current.extends) {
2687
+ dedupePlugins(deduped, current.extends);
2688
+ }
2689
+ }
2690
+ }
2691
+ }
2692
+ function resolvePlugins(plugins) {
2693
+ if (plugins) {
2694
+ const deduped = /* @__PURE__ */ new Set;
2695
+ dedupePlugins(deduped, plugins);
2696
+ return [...deduped];
2697
+ }
2698
+ return;
2699
+ }
2700
+ function getTypedArrayConstructor(name) {
2701
+ switch (name) {
2702
+ case "Int8Array":
2703
+ return Int8Array;
2704
+ case "Int16Array":
2705
+ return Int16Array;
2706
+ case "Int32Array":
2707
+ return Int32Array;
2708
+ case "Uint8Array":
2709
+ return Uint8Array;
2710
+ case "Uint16Array":
2711
+ return Uint16Array;
2712
+ case "Uint32Array":
2713
+ return Uint32Array;
2714
+ case "Uint8ClampedArray":
2715
+ return Uint8ClampedArray;
2716
+ case "Float32Array":
2717
+ return Float32Array;
2718
+ case "Float64Array":
2719
+ return Float64Array;
2720
+ case "BigInt64Array":
2721
+ return BigInt64Array;
2722
+ case "BigUint64Array":
2723
+ return BigUint64Array;
2724
+ default:
2725
+ throw new SerovalUnknownTypedArrayError(name);
2726
+ }
2727
+ }
2728
+ var MAX_BASE64_LENGTH = 1e6;
2729
+ var MAX_BIGINT_LENGTH = 1e4;
2730
+ var MAX_REGEXP_SOURCE_LENGTH = 20000;
2731
+ function applyObjectFlag(obj, flag) {
2732
+ switch (flag) {
2733
+ case 3:
2734
+ return Object.freeze(obj);
2735
+ case 1:
2736
+ return Object.preventExtensions(obj);
2737
+ case 2:
2738
+ return Object.seal(obj);
2739
+ default:
2740
+ return obj;
2741
+ }
2742
+ }
2743
+ var DEFAULT_DEPTH_LIMIT = 1000;
2744
+ function createBaseDeserializerContext(mode, options) {
2745
+ var _a;
2746
+ const refs = options.refs || /* @__PURE__ */ new Map;
2747
+ if (!("types" in refs)) {
2748
+ Object.assign(refs, {
2749
+ types: /* @__PURE__ */ new Map
2750
+ });
2751
+ }
2752
+ return {
2753
+ mode,
2754
+ plugins: options.plugins,
2755
+ refs,
2756
+ features: (_a = options.features) != null ? _a : ALL_ENABLED ^ (options.disabledFeatures || 0),
2757
+ depthLimit: options.depthLimit || DEFAULT_DEPTH_LIMIT
2758
+ };
2759
+ }
2760
+ function createCrossDeserializerContext(options) {
2761
+ return {
2762
+ mode: 2,
2763
+ base: createBaseDeserializerContext(2, options),
2764
+ child: NIL
2765
+ };
2766
+ }
2767
+ var DeserializePluginContext = class {
2768
+ constructor(_p, depth) {
2769
+ this._p = _p;
2770
+ this.depth = depth;
2771
+ }
2772
+ deserialize(node) {
2773
+ return deserialize(this._p, this.depth, node);
2774
+ }
2775
+ };
2776
+ function guardIndexedValue(ctx, id) {
2777
+ if (id < 0 || !Number.isFinite(id) || !Number.isInteger(id)) {
2778
+ throw new SerovalMalformedNodeError({
2779
+ t: 4,
2780
+ i: id
2781
+ });
2782
+ }
2783
+ if (ctx.refs.has(id)) {
2784
+ throw new Error("Conflicted ref id: " + id);
2785
+ }
2786
+ }
2787
+ function assignIndexedValueVanilla(ctx, id, value) {
2788
+ guardIndexedValue(ctx.base, id);
2789
+ if (ctx.state.marked.has(id)) {
2790
+ ctx.base.refs.set(id, value);
2791
+ }
2792
+ return value;
2793
+ }
2794
+ function assignIndexedValueCross(ctx, id, value) {
2795
+ guardIndexedValue(ctx.base, id);
2796
+ ctx.base.refs.set(id, value);
2797
+ return value;
2798
+ }
2799
+ function assignIndexedValue(ctx, id, value) {
2800
+ return ctx.mode === 1 ? assignIndexedValueVanilla(ctx, id, value) : assignIndexedValueCross(ctx, id, value);
2801
+ }
2802
+ function deserializeKnownValue(node, record, key) {
2803
+ if (Object.hasOwn(record, key)) {
2804
+ return record[key];
2805
+ }
2806
+ throw new SerovalMalformedNodeError(node);
2807
+ }
2808
+ function deserializeReference(ctx, node) {
2809
+ return assignIndexedValue(ctx, node.i, getReference(deserializeString(node.s)));
2810
+ }
2811
+ function deserializeArray(ctx, depth, node) {
2812
+ const items = node.a;
2813
+ const len = items.length;
2814
+ const result = assignIndexedValue(ctx, node.i, new Array(len));
2815
+ for (let i = 0, item;i < len; i++) {
2816
+ item = items[i];
2817
+ if (item) {
2818
+ result[i] = deserialize(ctx, depth, item);
2819
+ }
2820
+ }
2821
+ applyObjectFlag(result, node.o);
2822
+ return result;
2823
+ }
2824
+ function isValidKey(key) {
2825
+ switch (key) {
2826
+ case "constructor":
2827
+ case "__proto__":
2828
+ case "prototype":
2829
+ case "__defineGetter__":
2830
+ case "__defineSetter__":
2831
+ case "__lookupGetter__":
2832
+ case "__lookupSetter__":
2833
+ return false;
2834
+ default:
2835
+ return true;
2836
+ }
2837
+ }
2838
+ function isValidSymbol(symbol) {
2839
+ switch (symbol) {
2840
+ case SYM_ASYNC_ITERATOR:
2841
+ case SYM_IS_CONCAT_SPREADABLE:
2842
+ case SYM_TO_STRING_TAG:
2843
+ case SYM_ITERATOR:
2844
+ return true;
2845
+ default:
2846
+ return false;
2847
+ }
2848
+ }
2849
+ function assignStringProperty(object, key, value) {
2850
+ if (isValidKey(key)) {
2851
+ object[key] = value;
2852
+ } else {
2853
+ Object.defineProperty(object, key, {
2854
+ value,
2855
+ configurable: true,
2856
+ enumerable: true,
2857
+ writable: true
2858
+ });
2859
+ }
2860
+ }
2861
+ function assignProperty(ctx, depth, object, key, value) {
2862
+ if (typeof key === "string") {
2863
+ assignStringProperty(object, deserializeString(key), deserialize(ctx, depth, value));
2864
+ } else {
2865
+ const actual = deserialize(ctx, depth, key);
2866
+ switch (typeof actual) {
2867
+ case "string":
2868
+ assignStringProperty(object, actual, deserialize(ctx, depth, value));
2869
+ break;
2870
+ case "symbol":
2871
+ if (isValidSymbol(actual)) {
2872
+ object[actual] = deserialize(ctx, depth, value);
2873
+ }
2874
+ break;
2875
+ default:
2876
+ throw new SerovalMalformedNodeError(key);
2877
+ }
2878
+ }
2879
+ }
2880
+ function assignNodeType(ctx, id, type) {
2881
+ ctx.base.refs.types.set(id, type);
2882
+ }
2883
+ function validateNodeType(ctx, node, id, type) {
2884
+ if (ctx.base.refs.types.get(id) !== type) {
2885
+ throw new SerovalMalformedNodeError(node);
2886
+ }
2887
+ }
2888
+ function deserializeProperties(ctx, depth, node, result) {
2889
+ const keys = node.k;
2890
+ const len = keys.length;
2891
+ if (len > 0) {
2892
+ for (let i = 0, vals = node.v, len2 = keys.length;i < len2; i++) {
2893
+ assignProperty(ctx, depth, result, keys[i], vals[i]);
2894
+ }
2895
+ }
2896
+ return result;
2897
+ }
2898
+ function deserializeObject(ctx, depth, node) {
2899
+ const result = assignIndexedValue(ctx, node.i, node.t === 10 ? {} : /* @__PURE__ */ Object.create(null));
2900
+ deserializeProperties(ctx, depth, node.p, result);
2901
+ applyObjectFlag(result, node.o);
2902
+ return result;
2903
+ }
2904
+ function deserializeDate(ctx, node) {
2905
+ return assignIndexedValue(ctx, node.i, new Date(node.s));
2906
+ }
2907
+ function deserializeRegExp(ctx, node) {
2908
+ if (ctx.base.features & 32) {
2909
+ const source = deserializeString(node.c);
2910
+ if (source.length > MAX_REGEXP_SOURCE_LENGTH) {
2911
+ throw new SerovalMalformedNodeError(node);
2912
+ }
2913
+ return assignIndexedValue(ctx, node.i, new RegExp(source, node.m));
2914
+ }
2915
+ throw new SerovalUnsupportedNodeError(node);
2916
+ }
2917
+ function deserializeSet(ctx, depth, node) {
2918
+ const result = assignIndexedValue(ctx, node.i, /* @__PURE__ */ new Set);
2919
+ for (let i = 0, items = node.a, len = items.length;i < len; i++) {
2920
+ result.add(deserialize(ctx, depth, items[i]));
2921
+ }
2922
+ return result;
2923
+ }
2924
+ function deserializeMap(ctx, depth, node) {
2925
+ const result = assignIndexedValue(ctx, node.i, /* @__PURE__ */ new Map);
2926
+ for (let i = 0, keys = node.e.k, vals = node.e.v, len = keys.length;i < len; i++) {
2927
+ result.set(deserialize(ctx, depth, keys[i]), deserialize(ctx, depth, vals[i]));
2928
+ }
2929
+ return result;
2930
+ }
2931
+ function deserializeArrayBuffer(ctx, node) {
2932
+ if (node.s.length > MAX_BASE64_LENGTH) {
2933
+ throw new SerovalMalformedNodeError(node);
2934
+ }
2935
+ const result = assignIndexedValue(ctx, node.i, ARRAY_BUFFER_CONSTRUCTOR(deserializeString(node.s)));
2936
+ return result;
2937
+ }
2938
+ function deserializeTypedArray(ctx, depth, node) {
2939
+ var _a;
2940
+ const construct = getTypedArrayConstructor(node.c);
2941
+ const source = deserialize(ctx, depth, node.f);
2942
+ const offset = (_a = node.b) != null ? _a : 0;
2943
+ if (offset < 0 || offset > source.byteLength) {
2944
+ throw new SerovalMalformedNodeError(node);
2945
+ }
2946
+ const result = assignIndexedValue(ctx, node.i, new construct(source, offset, node.l));
2947
+ return result;
2948
+ }
2949
+ function deserializeDataView(ctx, depth, node) {
2950
+ var _a;
2951
+ const source = deserialize(ctx, depth, node.f);
2952
+ const offset = (_a = node.b) != null ? _a : 0;
2953
+ if (offset < 0 || offset > source.byteLength) {
2954
+ throw new SerovalMalformedNodeError(node);
2955
+ }
2956
+ const result = assignIndexedValue(ctx, node.i, new DataView(source, offset, node.l));
2957
+ return result;
2958
+ }
2959
+ function deserializeDictionary(ctx, depth, node, result) {
2960
+ if (node.p) {
2961
+ const fields = deserializeProperties(ctx, depth, node.p, {});
2962
+ Object.defineProperties(result, Object.getOwnPropertyDescriptors(fields));
2963
+ }
2964
+ return result;
2965
+ }
2966
+ function deserializeAggregateError(ctx, depth, node) {
2967
+ const result = assignIndexedValue(ctx, node.i, new AggregateError([], deserializeString(node.m)));
2968
+ return deserializeDictionary(ctx, depth, node, result);
2969
+ }
2970
+ function deserializeError(ctx, depth, node) {
2971
+ const construct = deserializeKnownValue(node, ERROR_CONSTRUCTOR, node.s);
2972
+ const result = assignIndexedValue(ctx, node.i, new construct(deserializeString(node.m)));
2973
+ return deserializeDictionary(ctx, depth, node, result);
2974
+ }
2975
+ function deserializePromise(ctx, depth, node) {
2976
+ const deferred = PROMISE_CONSTRUCTOR();
2977
+ const result = assignIndexedValue(ctx, node.i, deferred.p);
2978
+ const deserialized = deserialize(ctx, depth, node.f);
2979
+ if (node.s) {
2980
+ deferred.s(deserialized);
2981
+ } else {
2982
+ deferred.f(deserialized);
2983
+ }
2984
+ return result;
2985
+ }
2986
+ function deserializeBoxed(ctx, depth, node) {
2987
+ return assignIndexedValue(ctx, node.i, Object(deserialize(ctx, depth, node.f)));
2988
+ }
2989
+ function deserializePlugin(ctx, depth, node) {
2990
+ const currentPlugins = ctx.base.plugins;
2991
+ if (currentPlugins) {
2992
+ const tag = deserializeString(node.c);
2993
+ for (let i = 0, len = currentPlugins.length;i < len; i++) {
2994
+ const plugin = currentPlugins[i];
2995
+ if (plugin.tag === tag) {
2996
+ return assignIndexedValue(ctx, node.i, plugin.deserialize(node.s, new DeserializePluginContext(ctx, depth), {
2997
+ id: node.i
2998
+ }));
2999
+ }
3000
+ }
3001
+ }
3002
+ throw new SerovalMissingPluginError(node.c);
3003
+ }
3004
+ function deserializePromiseConstructor(ctx, node) {
3005
+ const value = assignIndexedValue(ctx, node.i, assignIndexedValue(ctx, node.s, PROMISE_CONSTRUCTOR()).p);
3006
+ assignNodeType(ctx, node.s, 22);
3007
+ return value;
3008
+ }
3009
+ function deserializePromiseResolve(ctx, depth, node) {
3010
+ const deferred = ctx.base.refs.get(node.i);
3011
+ if (deferred) {
3012
+ validateNodeType(ctx, node, node.i, 22);
3013
+ deferred.s(deserialize(ctx, depth, node.a[1]));
3014
+ return NIL;
3015
+ }
3016
+ throw new SerovalMissingInstanceError("Promise");
3017
+ }
3018
+ function deserializePromiseReject(ctx, depth, node) {
3019
+ const deferred = ctx.base.refs.get(node.i);
3020
+ if (deferred) {
3021
+ validateNodeType(ctx, node, node.i, 22);
3022
+ deferred.f(deserialize(ctx, depth, node.a[1]));
3023
+ return NIL;
3024
+ }
3025
+ throw new SerovalMissingInstanceError("Promise");
3026
+ }
3027
+ function deserializeIteratorFactoryInstance(ctx, depth, node) {
3028
+ deserialize(ctx, depth, node.a[0]);
3029
+ const source = deserialize(ctx, depth, node.a[1]);
3030
+ return sequenceToIterator(source);
3031
+ }
3032
+ function deserializeAsyncIteratorFactoryInstance(ctx, depth, node) {
3033
+ deserialize(ctx, depth, node.a[0]);
3034
+ const source = deserialize(ctx, depth, node.a[1]);
3035
+ return streamToAsyncIterable(source);
3036
+ }
3037
+ function deserializeStreamConstructor(ctx, depth, node) {
3038
+ const result = assignIndexedValue(ctx, node.i, createStream());
3039
+ assignNodeType(ctx, node.i, 31);
3040
+ const items = node.a;
3041
+ const len = items.length;
3042
+ if (len) {
3043
+ for (let i = 0;i < len; i++) {
3044
+ deserialize(ctx, depth, items[i]);
3045
+ }
3046
+ }
3047
+ return result;
3048
+ }
3049
+ function deserializeStreamNext(ctx, depth, node) {
3050
+ const deferred = ctx.base.refs.get(node.i);
3051
+ if (deferred) {
3052
+ validateNodeType(ctx, node, node.i, 31);
3053
+ deferred.next(deserialize(ctx, depth, node.f));
3054
+ return NIL;
3055
+ }
3056
+ throw new SerovalMissingInstanceError("Stream");
3057
+ }
3058
+ function deserializeStreamThrow(ctx, depth, node) {
3059
+ const deferred = ctx.base.refs.get(node.i);
3060
+ if (deferred) {
3061
+ validateNodeType(ctx, node, node.i, 31);
3062
+ deferred.throw(deserialize(ctx, depth, node.f));
3063
+ return NIL;
3064
+ }
3065
+ throw new SerovalMissingInstanceError("Stream");
3066
+ }
3067
+ function deserializeStreamReturn(ctx, depth, node) {
3068
+ const deferred = ctx.base.refs.get(node.i);
3069
+ if (deferred) {
3070
+ validateNodeType(ctx, node, node.i, 31);
3071
+ deferred.return(deserialize(ctx, depth, node.f));
3072
+ return NIL;
3073
+ }
3074
+ throw new SerovalMissingInstanceError("Stream");
3075
+ }
3076
+ function deserializeIteratorFactory(ctx, depth, node) {
3077
+ deserialize(ctx, depth, node.f);
3078
+ return NIL;
3079
+ }
3080
+ function deserializeAsyncIteratorFactory(ctx, depth, node) {
3081
+ deserialize(ctx, depth, node.a[1]);
3082
+ return NIL;
3083
+ }
3084
+ function deserializeSequence(ctx, depth, node) {
3085
+ const result = assignIndexedValue(ctx, node.i, createSequence([], node.s, node.l));
3086
+ for (let i = 0, len = node.a.length;i < len; i++) {
3087
+ result.v[i] = deserialize(ctx, depth, node.a[i]);
3088
+ }
3089
+ return result;
3090
+ }
3091
+ function deserialize(ctx, depth, node) {
3092
+ if (depth > ctx.base.depthLimit) {
3093
+ throw new SerovalDepthLimitError(ctx.base.depthLimit);
3094
+ }
3095
+ depth += 1;
3096
+ switch (node.t) {
3097
+ case 2:
3098
+ return deserializeKnownValue(node, CONSTANT_VAL, node.s);
3099
+ case 0:
3100
+ return Number(node.s);
3101
+ case 1:
3102
+ return deserializeString(String(node.s));
3103
+ case 3:
3104
+ if (String(node.s).length > MAX_BIGINT_LENGTH) {
3105
+ throw new SerovalMalformedNodeError(node);
3106
+ }
3107
+ return BigInt(node.s);
3108
+ case 4:
3109
+ return ctx.base.refs.get(node.i);
3110
+ case 18:
3111
+ return deserializeReference(ctx, node);
3112
+ case 9:
3113
+ return deserializeArray(ctx, depth, node);
3114
+ case 10:
3115
+ case 11:
3116
+ return deserializeObject(ctx, depth, node);
3117
+ case 5:
3118
+ return deserializeDate(ctx, node);
3119
+ case 6:
3120
+ return deserializeRegExp(ctx, node);
3121
+ case 7:
3122
+ return deserializeSet(ctx, depth, node);
3123
+ case 8:
3124
+ return deserializeMap(ctx, depth, node);
3125
+ case 19:
3126
+ return deserializeArrayBuffer(ctx, node);
3127
+ case 16:
3128
+ case 15:
3129
+ return deserializeTypedArray(ctx, depth, node);
3130
+ case 20:
3131
+ return deserializeDataView(ctx, depth, node);
3132
+ case 14:
3133
+ return deserializeAggregateError(ctx, depth, node);
3134
+ case 13:
3135
+ return deserializeError(ctx, depth, node);
3136
+ case 12:
3137
+ return deserializePromise(ctx, depth, node);
3138
+ case 17:
3139
+ return deserializeKnownValue(node, SYMBOL_REF, node.s);
3140
+ case 21:
3141
+ return deserializeBoxed(ctx, depth, node);
3142
+ case 25:
3143
+ return deserializePlugin(ctx, depth, node);
3144
+ case 22:
3145
+ return deserializePromiseConstructor(ctx, node);
3146
+ case 23:
3147
+ return deserializePromiseResolve(ctx, depth, node);
3148
+ case 24:
3149
+ return deserializePromiseReject(ctx, depth, node);
3150
+ case 28:
3151
+ return deserializeIteratorFactoryInstance(ctx, depth, node);
3152
+ case 30:
3153
+ return deserializeAsyncIteratorFactoryInstance(ctx, depth, node);
3154
+ case 31:
3155
+ return deserializeStreamConstructor(ctx, depth, node);
3156
+ case 32:
3157
+ return deserializeStreamNext(ctx, depth, node);
3158
+ case 33:
3159
+ return deserializeStreamThrow(ctx, depth, node);
3160
+ case 34:
3161
+ return deserializeStreamReturn(ctx, depth, node);
3162
+ case 27:
3163
+ return deserializeIteratorFactory(ctx, depth, node);
3164
+ case 29:
3165
+ return deserializeAsyncIteratorFactory(ctx, depth, node);
3166
+ case 35:
3167
+ return deserializeSequence(ctx, depth, node);
3168
+ default:
3169
+ throw new SerovalUnsupportedNodeError(node);
3170
+ }
3171
+ }
3172
+ function deserializeTop(ctx, node) {
3173
+ try {
3174
+ return deserialize(ctx, 0, node);
3175
+ } catch (error) {
3176
+ throw new SerovalDeserializationError(error);
3177
+ }
3178
+ }
3179
+ var REF_START_CHARS = "hjkmoquxzABCDEFGHIJKLNPQRTUVWXYZ$_";
3180
+ var REF_START_CHARS_LEN = REF_START_CHARS.length;
3181
+ var REF_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$_";
3182
+ var REF_CHARS_LEN = REF_CHARS.length;
3183
+ function fromCrossJSON(source, options) {
3184
+ const plugins = resolvePlugins(options.plugins);
3185
+ const ctx = createCrossDeserializerContext({
3186
+ plugins,
3187
+ refs: options.refs,
3188
+ features: options.features,
3189
+ disabledFeatures: options.disabledFeatures,
3190
+ depthLimit: options.depthLimit
3191
+ });
3192
+ return deserializeTop(ctx, source);
3193
+ }
3194
+
3195
+ // src/shared/deferred-ndjson.ts
3196
+ function makeAbortError(reason) {
3197
+ const message = reason instanceof Error ? reason.message || "The operation was aborted." : "aborted";
3198
+ const err = new Error(message);
3199
+ err.name = "AbortError";
3200
+ return err;
3201
+ }
3202
+ async function parseDeferredNdjson(stream, signal) {
3203
+ const reader = stream.getReader();
3204
+ const decoder = new TextDecoder;
3205
+ let buffer = "";
3206
+ let abortHandler;
3207
+ const cancelReader = (reason) => {
3208
+ reader.cancel(reason).catch(() => {});
3209
+ };
3210
+ if (signal?.aborted) {
3211
+ const err = makeAbortError(signal.reason);
3212
+ await reader.cancel(err).catch(() => {});
3213
+ try {
3214
+ reader.releaseLock();
3215
+ } catch {}
3216
+ return { syncData: {}, deferredPromises: {} };
3217
+ }
3218
+ if (signal !== undefined && !signal.aborted) {
3219
+ abortHandler = () => cancelReader(makeAbortError(signal.reason));
3220
+ signal.addEventListener("abort", abortHandler, { once: true });
3221
+ }
3222
+ const cleanupAbortHandler = () => {
3223
+ if (signal !== undefined && abortHandler !== undefined) {
3224
+ signal.removeEventListener("abort", abortHandler);
3225
+ abortHandler = undefined;
3226
+ }
3227
+ };
3228
+ async function readLine() {
3229
+ for (;; ) {
3230
+ const newlineIndex = buffer.indexOf(`
3231
+ `);
3232
+ if (newlineIndex >= 0) {
3233
+ const line = buffer.slice(0, newlineIndex).trim();
3234
+ buffer = buffer.slice(newlineIndex + 1);
3235
+ if (line.length > 0) {
3236
+ return line;
3237
+ }
3238
+ continue;
3239
+ }
3240
+ const { done, value } = await reader.read();
3241
+ if (done) {
3242
+ buffer += decoder.decode();
3243
+ const line = buffer.trim();
3244
+ buffer = "";
3245
+ return line.length > 0 ? line : undefined;
3246
+ }
3247
+ buffer += decoder.decode(value, { stream: true });
3248
+ }
3249
+ }
3250
+ const firstLine = await readLine();
3251
+ if (!firstLine) {
3252
+ cleanupAbortHandler();
3253
+ try {
3254
+ reader.releaseLock();
3255
+ } catch {}
3256
+ return { syncData: {}, deferredPromises: {} };
3257
+ }
3258
+ const node = JSON.parse(firstLine);
3259
+ const deserialized = fromCrossJSON(node, {});
3260
+ const syncData = {};
3261
+ const deferredPromises = {};
3262
+ const resolvers = {};
3263
+ const deferredKeys = Array.isArray(deserialized.__furinDeferredKeys) ? deserialized.__furinDeferredKeys.filter((key) => typeof key === "string") : [];
3264
+ for (const [key, value] of Object.entries(deserialized)) {
3265
+ if (key === "__furinDeferredKeys") {
3266
+ continue;
3267
+ }
3268
+ if (value instanceof Promise) {
3269
+ deferredPromises[key] = value;
3270
+ } else {
3271
+ syncData[key] = value;
3272
+ }
3273
+ }
3274
+ for (const key of deferredKeys) {
3275
+ if (!(key in deferredPromises)) {
3276
+ deferredPromises[key] = new Promise((resolve, reject) => {
3277
+ resolvers[key] = { resolve, reject };
3278
+ });
3279
+ }
3280
+ }
3281
+ for (const promise of Object.values(deferredPromises)) {
3282
+ promise.catch(() => {
3283
+ return;
3284
+ });
3285
+ }
3286
+ if (deferredKeys.length === 0) {
3287
+ cleanupAbortHandler();
3288
+ try {
3289
+ reader.releaseLock();
3290
+ } catch {}
3291
+ return { syncData, deferredPromises };
3292
+ }
3293
+ const rejectAllPending = (reason) => {
3294
+ for (const key of Object.keys(resolvers)) {
3295
+ resolvers[key]?.reject(reason);
3296
+ delete resolvers[key];
3297
+ }
3298
+ cancelReader(reason);
3299
+ };
3300
+ if (signal !== undefined) {
3301
+ if (signal.aborted) {
3302
+ rejectAllPending(makeAbortError(signal.reason));
3303
+ return { syncData, deferredPromises };
3304
+ }
3305
+ cleanupAbortHandler();
3306
+ abortHandler = () => {
3307
+ rejectAllPending(makeAbortError(signal.reason));
3308
+ };
3309
+ signal.addEventListener("abort", abortHandler, { once: true });
3310
+ }
3311
+ readDeferredLines(readLine, resolvers).then(() => {
3312
+ for (const key of Object.keys(resolvers)) {
3313
+ const err = new Error(`[furin] deferred stream closed before "${key}" was resolved`);
3314
+ resolvers[key]?.reject(err);
3315
+ delete resolvers[key];
3316
+ }
3317
+ }).catch((err) => {
3318
+ for (const resolver of Object.values(resolvers)) {
3319
+ resolver.reject(err);
3320
+ }
3321
+ }).finally(() => {
3322
+ cleanupAbortHandler();
3323
+ try {
3324
+ reader.releaseLock();
3325
+ } catch {}
3326
+ });
3327
+ return { syncData, deferredPromises };
3328
+ }
3329
+ async function readDeferredLines(readLine, resolvers) {
3330
+ for (;; ) {
3331
+ const line = await readLine();
3332
+ if (!line) {
3333
+ return;
3334
+ }
3335
+ const entry = JSON.parse(line);
3336
+ if (typeof entry.key !== "string" || !entry.value) {
3337
+ continue;
3338
+ }
3339
+ const resolver = resolvers[entry.key];
3340
+ if (!resolver) {
3341
+ continue;
3342
+ }
3343
+ const value = fromCrossJSON(entry.value, {});
3344
+ if (entry.action === "reject") {
3345
+ resolver.reject(value);
3346
+ } else {
3347
+ resolver.resolve(value);
3348
+ }
3349
+ delete resolvers[entry.key];
3350
+ }
3351
+ }
3352
+
3353
+ // src/client/router/abort.ts
3354
+ function isAbortError(error) {
3355
+ return error !== null && typeof error === "object" && "name" in error && error.name === "AbortError";
3356
+ }
3357
+
3358
+ // src/client/router/search-store.ts
3359
+ import { createContext as createContext2 } from "react";
3360
+ function searchSnapshotChanged(a, b) {
3361
+ return a.currentHref !== b.currentHref || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
3362
+ }
3363
+ function createSearchStore(initialSnapshot) {
3364
+ let snapshot = initialSnapshot;
3365
+ let version = 0;
3366
+ let flushedVersion = 0;
3367
+ const listeners = new Set;
3368
+ return {
3369
+ flush: () => {
3370
+ if (flushedVersion === version) {
3371
+ return;
3372
+ }
3373
+ flushedVersion = version;
3374
+ for (const listener of [...listeners]) {
3375
+ listener();
3376
+ }
3377
+ },
3378
+ getServerSnapshot: () => snapshot,
3379
+ getSnapshot: () => snapshot,
3380
+ setSnapshot: (next) => {
3381
+ if (!searchSnapshotChanged(snapshot, next)) {
3382
+ return;
3383
+ }
3384
+ snapshot = next;
3385
+ version++;
3386
+ },
3387
+ subscribe: (listener) => {
3388
+ listeners.add(listener);
3389
+ return () => {
3390
+ listeners.delete(listener);
3391
+ };
3392
+ }
3393
+ };
3394
+ }
3395
+ function searchSnapshotFromRouterContext(context) {
3396
+ return {
3397
+ currentHref: context.currentHref,
3398
+ navigate: context.navigate,
3399
+ search: context.search,
3400
+ searchRoutes: context.searchRoutes
3401
+ };
3402
+ }
3403
+ var FALLBACK_SEARCH_STORE = createSearchStore({
3404
+ currentHref: "/",
3405
+ navigate: (href, _opts) => {
3406
+ if (typeof window !== "undefined") {
3407
+ window.location.href = href;
3408
+ }
3409
+ return Promise.resolve();
3410
+ },
3411
+ search: {},
3412
+ searchRoutes: []
3413
+ });
3414
+ var SearchStoreContext = createContext2(null);
3415
+
3416
+ // src/client/router/spa-response.ts
3417
+ import { createElement as createElement2 } from "react";
3418
+ function isFurinErrorPayload(value) {
3419
+ if (!value || typeof value !== "object") {
3420
+ return false;
3421
+ }
3422
+ const v = value;
3423
+ return typeof v.digest === "string" && typeof v.message === "string" && typeof v.status === "number";
3424
+ }
3425
+ function classifySpaResponse(status, data) {
3426
+ if (!data) {
3427
+ return { kind: "bail" };
3428
+ }
3429
+ if (isFurinErrorPayload(data.__furinError)) {
3430
+ return { kind: "error", error: data.__furinError };
3431
+ }
3432
+ if ((status >= 200 && status < 300 || status === 404) && data.__furinStatus === 404) {
3433
+ const notFound = data.__furinNotFound;
3434
+ return { kind: "not-found", error: notFound ?? {} };
3435
+ }
3436
+ if (status >= 200 && status < 300) {
3437
+ return { kind: "ok" };
3438
+ }
3439
+ return { kind: "bail" };
3440
+ }
3441
+ function pickDeepestNotFound(boundaries) {
3442
+ if (!boundaries) {
3443
+ return;
3444
+ }
3445
+ for (let i = boundaries.length - 1;i >= 0; i--) {
3446
+ const seg = boundaries[i];
3447
+ if (seg?.notFound) {
3448
+ return seg.notFound;
3449
+ }
3450
+ }
3451
+ return;
3452
+ }
3453
+ var DefaultClientNotFoundFallback = ({ error }) => createElement2(DefaultNotFoundScreen, { message: error.message });
3454
+ function buildNotFoundPageElement(boundaries, error) {
3455
+ const Fallback = pickDeepestNotFound(boundaries) ?? DefaultClientNotFoundFallback;
3456
+ return createElement2(Fallback, { error });
3457
+ }
3458
+ async function parsePageResponse(res, basePath) {
3459
+ let finalHref;
3460
+ if (res.redirected) {
3461
+ const final = new URL(res.url);
3462
+ finalHref = toLogical(final.pathname, basePath) + final.search;
3463
+ }
3464
+ const html = await res.text();
3465
+ const doc = new DOMParser().parseFromString(html, "text/html");
3466
+ const dataEl = doc.getElementById("__FURIN_DATA__");
3467
+ const data = dataEl ? JSON.parse(dataEl.textContent || "{}") : null;
3468
+ return { data, finalHref, title: doc.title };
3469
+ }
3470
+ function buildDataEndpoint(basePath, logicalHref, staticMode) {
3471
+ if (!staticMode) {
3472
+ return `${basePath}/_furin/data?path=${encodeURIComponent(logicalHref)}`;
3473
+ }
3474
+ const parsed = new URL(logicalHref, "http://x");
3475
+ const pathname = parsed.pathname.replace(TRAILING_SLASHES_RE, "");
3476
+ return `${basePath}${pathname}/__furin_data.ndjson`;
3477
+ }
3478
+ function detectStaticMode() {
3479
+ if (typeof document === "undefined") {
3480
+ return false;
3481
+ }
3482
+ const meta = document.querySelector('meta[name="furin-mode"]');
3483
+ return meta?.content === "static";
3484
+ }
3485
+
3486
+ // src/client/router/sync-catch-up.ts
3487
+ function createInvalidationRefresh(options) {
3488
+ let running;
3489
+ let requested = false;
3490
+ const refreshUntilCurrent = async () => {
3491
+ do {
3492
+ requested = false;
3493
+ try {
3494
+ await options.refresh();
3495
+ } catch (error) {
3496
+ if (!isAbortError(error)) {
3497
+ throw error;
3498
+ }
3499
+ }
3500
+ } while (requested);
3501
+ };
3502
+ return {
3503
+ run() {
3504
+ requested = true;
3505
+ if (!running) {
3506
+ running = refreshUntilCurrent().catch((error) => {
3507
+ if (!isAbortError(error)) {
3508
+ options.onError(error);
3509
+ }
3510
+ }).finally(() => {
3511
+ running = undefined;
3512
+ });
3513
+ }
3514
+ return running;
3515
+ }
3516
+ };
3517
+ }
3518
+ function createSyncCatchUp(options) {
3519
+ let currentCursor;
3520
+ let running;
3521
+ let requested = false;
3522
+ const readUntilCurrent = async () => {
3523
+ do {
3524
+ requested = false;
3525
+ let page;
3526
+ do {
3527
+ page = await options.fetchPage(currentCursor ?? "0");
3528
+ if (page.reset) {
3529
+ options.onInvalidations(["/:layout"]);
3530
+ currentCursor = page.cursor;
3531
+ break;
3532
+ }
3533
+ for (const change of page.changes) {
3534
+ options.onInvalidations(change.invalidations);
3535
+ }
3536
+ currentCursor = page.cursor;
3537
+ } while (page.hasMore);
3538
+ } while (requested);
3539
+ };
3540
+ return {
3541
+ async initialize() {
3542
+ const page = await options.fetchPage(undefined);
3543
+ currentCursor = page.cursor;
3544
+ },
3545
+ catchUp() {
3546
+ requested = true;
3547
+ if (!running) {
3548
+ running = readUntilCurrent().finally(() => {
3549
+ running = undefined;
3550
+ });
3551
+ }
3552
+ return running;
3553
+ },
3554
+ cursor: () => currentCursor
3555
+ };
3556
+ }
3557
+
3558
+ // src/client/router/provider.tsx
3559
+ import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
3560
+ var EMPTY_SEARCH = {};
3561
+ function setPrefetchCacheEntry(cache, href, entry, maxSize) {
3562
+ if (cache.has(href)) {
3563
+ cache.delete(href);
3564
+ }
3565
+ cache.set(href, entry);
3566
+ if (cache.size > maxSize) {
3567
+ const oldest = cache.keys().next().value;
3568
+ if (typeof oldest === "string") {
3569
+ cache.delete(oldest);
3570
+ }
3571
+ }
3572
+ }
3573
+ function RouterProvider({
3574
+ routes,
3575
+ root,
3576
+ initialMatch,
3577
+ initialData,
3578
+ initialDigest,
3579
+ initialNotFound,
3580
+ autoRefresh,
3581
+ basePath,
3582
+ defaultPreload,
3583
+ defaultPreloadDelay,
3584
+ defaultPreloadStaleTime,
3585
+ prefetchCacheSize,
3586
+ syncStream
3587
+ }) {
3588
+ const [state, setState] = useState(() => ({
3589
+ match: initialMatch,
3590
+ data: initialData,
3591
+ notFound: initialNotFound
3592
+ }));
3593
+ const [isNavigating, setIsNavigating] = useState(false);
3594
+ const [currentHref, setCurrentHref] = useState(() => {
3595
+ if (typeof window === "undefined") {
3596
+ return "/";
3597
+ }
3598
+ return normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
3599
+ });
3600
+ const prefetchCache = useRef(new Map);
3601
+ const navVersion = useRef(0);
3602
+ const navAbortRef = useRef(null);
3603
+ const pendingScrollRef = useRef(null);
3604
+ const currentMatchRef = useRef(initialMatch);
3605
+ const staticModeRef = useRef(detectStaticMode());
3606
+ const resolvedSearch = state.data.query ?? EMPTY_SEARCH;
3607
+ const searchStoreRef = useRef(null);
3608
+ const rootBoundaries = useMemo(() => {
3609
+ for (const route of routes) {
3610
+ const depth0 = route.segmentBoundaries?.find((b) => b.depth === 0);
3611
+ if (depth0) {
3612
+ return [depth0];
3613
+ }
3614
+ }
3615
+ return;
3616
+ }, [routes]);
3617
+ const resolveNoMatchState = useCallback2(async (physicalHref, signal) => {
3618
+ const res = await fetch(physicalHref, { signal });
3619
+ if (isStaleDeployResponse(res)) {
3620
+ window.location.href = physicalHref;
3621
+ return null;
3622
+ }
3623
+ const { data, finalHref, title } = await parsePageResponse(res, basePath);
3624
+ const kind = classifySpaResponse(res.status, data);
3625
+ if (kind.kind !== "not-found") {
3626
+ return null;
3627
+ }
3628
+ const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = data ?? {};
3629
+ return {
3630
+ match: currentMatchRef.current,
3631
+ data: cleanData,
3632
+ title,
3633
+ finalHref,
3634
+ notFound: kind.error,
3635
+ notFoundBoundaries: rootBoundaries
3636
+ };
3637
+ }, [basePath, rootBoundaries]);
3638
+ const fetchPageState = useCallback2(async (rawLogicalHref, signal) => {
3639
+ const logicalHref = normalizeHref(rawLogicalHref);
3640
+ try {
3641
+ const physicalHref = basePath + logicalHref;
3642
+ const url = new URL(physicalHref, window.location.origin);
3643
+ const logicalPathname = toLogical(url.pathname, basePath);
3644
+ const match = routes.find((r) => r.regex.test(logicalPathname));
3645
+ if (!match) {
3646
+ return await resolveNoMatchState(physicalHref, signal);
3647
+ }
3648
+ const dataEndpoint = buildDataEndpoint(basePath, logicalHref, staticModeRef.current);
3649
+ const [res, loadedMod] = await Promise.all([fetch(dataEndpoint, { signal }), match.load()]);
3650
+ if (isStaleDeployResponse(res)) {
3651
+ window.location.href = physicalHref;
3652
+ return null;
3653
+ }
3654
+ const body = res.body ?? new ReadableStream({ start: (c) => c.close() });
3655
+ let parsed;
3656
+ try {
3657
+ parsed = await parseDeferredNdjson(body, signal);
3658
+ } catch (parseErr) {
3659
+ _log.warn({
3660
+ action: "navigate_server_error",
3661
+ href: physicalHref,
3662
+ status: res.status,
3663
+ error: String(parseErr)
3664
+ });
3665
+ return null;
3666
+ }
3667
+ const { syncData, deferredPromises } = parsed;
3668
+ const {
3669
+ __furinStatus,
3670
+ __furinNotFound,
3671
+ __furinRedirect,
3672
+ __furinError,
3673
+ __furinTitle,
3674
+ ...cleanSyncData
3675
+ } = syncData;
3676
+ const finalHref = typeof __furinRedirect === "string" ? __furinRedirect : undefined;
3677
+ const data = { ...cleanSyncData, ...deferredPromises };
3678
+ const title = typeof __furinTitle === "string" ? __furinTitle : "";
3679
+ const loadedMatch = {
3680
+ ...match,
3681
+ component: loadedMod.default.component,
3682
+ pageRoute: loadedMod.default._route,
3683
+ segmentBoundaries: loadedMod.segmentBoundaries ?? match.segmentBoundaries
3684
+ };
3685
+ if (__furinError) {
3686
+ return {
3687
+ match: loadedMatch,
3688
+ data: {},
3689
+ title,
3690
+ finalHref,
3691
+ error: __furinError
3692
+ };
3693
+ }
3694
+ if (!res.ok && res.status !== 404) {
3695
+ _log.warn({ action: "navigate_server_error", href: physicalHref, status: res.status });
3696
+ return null;
3697
+ }
3698
+ if (__furinStatus === 404) {
3699
+ return {
3700
+ match: loadedMatch,
3701
+ data,
3702
+ title,
3703
+ finalHref,
3704
+ notFound: __furinNotFound ?? {}
3705
+ };
3706
+ }
3707
+ if (finalHref) {
3708
+ return { match: null, data, title, finalHref };
3709
+ }
3710
+ return { match: loadedMatch, data, title, finalHref };
3711
+ } catch (err) {
3712
+ if (!isAbortError(err)) {
3713
+ _log.error({
3714
+ action: "navigate_failed",
3715
+ href: basePath + logicalHref,
3716
+ error: String(err)
3717
+ });
3718
+ }
3719
+ return null;
3720
+ }
3721
+ }, [routes, basePath, resolveNoMatchState]);
3722
+ const invalidatePrefetch = useCallback2((path, type) => {
3723
+ const normalizedPath = stripHashFromHref(path);
3724
+ if (type === "page") {
3725
+ for (const key of [...prefetchCache.current.keys()]) {
3726
+ if (stripHashFromHref(key) === normalizedPath) {
3727
+ prefetchCache.current.delete(key);
3728
+ }
3729
+ }
3730
+ return;
3731
+ }
3732
+ const prefix = normalizedPath === "/" || normalizedPath.endsWith("/") ? normalizedPath : `${normalizedPath}/`;
3733
+ for (const key of [...prefetchCache.current.keys()]) {
3734
+ const normalizedKey = stripHashFromHref(key);
3735
+ if (normalizedKey === normalizedPath || normalizedKey.startsWith(prefix)) {
3736
+ prefetchCache.current.delete(key);
3737
+ }
3738
+ }
3739
+ }, []);
3740
+ const prefetch = useCallback2((href, opts) => {
3741
+ const staleTime = opts?.staleTime ?? defaultPreloadStaleTime;
3742
+ const existing = prefetchCache.current.get(href);
3743
+ if (existing && !shouldRefetch(existing)) {
3744
+ return;
3745
+ }
3746
+ setPrefetchCacheEntry(prefetchCache.current, href, {
3747
+ promise: fetchPageState(href, undefined),
3748
+ createdAt: Date.now(),
3749
+ staleTime
3750
+ }, prefetchCacheSize);
3751
+ }, [fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]);
3752
+ async function resolveRedirectState(redirectLogical, myVersion, signal) {
3753
+ const cached = prefetchCache.current.get(redirectLogical);
3754
+ const state2 = cached && !shouldRefetch(cached) ? await cached.promise : await fetchPageState(redirectLogical, signal);
3755
+ if (navVersion.current !== myVersion) {
3756
+ return null;
3757
+ }
3758
+ return state2;
3759
+ }
3760
+ const navigate = useCallback2(async function navigateTo(rawLogicalHref, opts) {
3761
+ const logicalHref = normalizeHref(rawLogicalHref);
3762
+ const myVersion = ++navVersion.current;
3763
+ navAbortRef.current?.abort();
3764
+ const navAbort = new AbortController;
3765
+ navAbortRef.current = navAbort;
3766
+ const navSignal = navAbort.signal;
3767
+ setIsNavigating(true);
3768
+ try {
3769
+ const cached = prefetchCache.current.get(logicalHref);
3770
+ let newState = cached && !shouldRefetch(cached) ? await cached.promise : await fetchPageState(logicalHref, navSignal);
3771
+ if (navVersion.current !== myVersion) {
3772
+ return;
3773
+ }
3774
+ if (newState && (!cached || shouldRefetch(cached))) {
3775
+ setPrefetchCacheEntry(prefetchCache.current, logicalHref, {
3776
+ promise: Promise.resolve(newState),
3777
+ createdAt: Date.now(),
3778
+ staleTime: defaultPreloadStaleTime
3779
+ }, prefetchCacheSize);
3780
+ }
3781
+ if (!newState) {
3782
+ _log.warn({
3783
+ action: "navigate_fallback",
3784
+ href: logicalHref,
3785
+ reason: "prefetch_returned_null"
3786
+ });
3787
+ window.location.href = basePath + logicalHref;
3788
+ return;
3789
+ }
3790
+ let redirectLogical;
3791
+ if (newState.finalHref && !newState.match && !newState.notFound) {
3792
+ redirectLogical = normalizeHref(newState.finalHref);
3793
+ const redirectPhysical = basePath + redirectLogical;
3794
+ window.history.replaceState({
3795
+ ...history.state ?? {},
3796
+ _furinKey: getHistoryKey(history.state) ?? generateHistoryKey()
3797
+ }, "", redirectPhysical);
3798
+ setCurrentHref(redirectLogical);
3799
+ const redirectState = await resolveRedirectState(redirectLogical, myVersion, navSignal);
3800
+ if (!redirectState) {
3801
+ if (navVersion.current === myVersion) {
3802
+ window.location.href = redirectPhysical;
3803
+ }
3804
+ return;
3805
+ }
3806
+ newState = redirectState;
3807
+ }
3808
+ currentMatchRef.current = newState.match;
3809
+ setState(newState);
3810
+ if (newState.title) {
3811
+ document.title = newState.title;
3812
+ }
3813
+ const effectiveLogical = newState.finalHref ?? redirectLogical ?? logicalHref;
3814
+ const physicalEffective = basePath + effectiveLogical;
3815
+ if (opts?.replace) {
3816
+ window.history.replaceState({
3817
+ ...history.state ?? {},
3818
+ _furinKey: getHistoryKey(history.state) ?? generateHistoryKey()
3819
+ }, "", physicalEffective);
3820
+ } else {
3821
+ const currentKey = getHistoryKey(history.state);
3822
+ if (currentKey) {
3823
+ saveScrollPosition(currentKey);
3824
+ }
3825
+ window.history.pushState({ _furinKey: generateHistoryKey() }, "", physicalEffective);
3826
+ }
3827
+ const effectiveUrl = new URL(physicalEffective, window.location.origin);
3828
+ const logicalPath = normalizeHref(toLogical(effectiveUrl.pathname, basePath));
3829
+ setCurrentHref(logicalPath + effectiveUrl.search);
3830
+ if (opts?.resetScroll ?? true) {
3831
+ pendingScrollRef.current = { type: "reset", href: physicalEffective };
3832
+ }
3833
+ } finally {
3834
+ if (navVersion.current === myVersion) {
3835
+ setIsNavigating(false);
3836
+ }
3837
+ }
3838
+ }, [basePath, fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]);
3839
+ if (searchStoreRef.current === null) {
3840
+ searchStoreRef.current = createSearchStore({
3841
+ currentHref,
3842
+ navigate,
3843
+ search: resolvedSearch,
3844
+ searchRoutes: routes
3845
+ });
3846
+ }
3847
+ const searchStore = searchStoreRef.current;
3848
+ const searchSnapshot = useMemo(() => ({
3849
+ currentHref,
3850
+ navigate,
3851
+ search: resolvedSearch,
3852
+ searchRoutes: routes
3853
+ }), [currentHref, navigate, resolvedSearch, routes]);
3854
+ useLayoutEffect(() => {
3855
+ searchStore.setSnapshot(searchSnapshot);
3856
+ searchStore.flush();
3857
+ }, [searchStore, searchSnapshot]);
3858
+ const refresh = useCallback2(async (opts) => {
3859
+ const logicalPath = toLogical(window.location.pathname, basePath);
3860
+ const logicalHref = logicalPath + window.location.search;
3861
+ invalidatePrefetch(logicalHref, "page");
3862
+ await navigate(logicalHref, { replace: true, resetScroll: opts?.resetScroll ?? false });
3863
+ }, [navigate, invalidatePrefetch, basePath]);
3864
+ const invalidationRefresh = useMemo(() => createInvalidationRefresh({
3865
+ onError: (error) => {
3866
+ _log.warn({ action: "sync_refresh_failed", error: String(error) });
3867
+ },
3868
+ refresh: () => refresh(undefined)
3869
+ }), [refresh]);
3870
+ useEffect(() => {
3871
+ if (typeof window !== "undefined") {
3872
+ window.__FURIN_HMR_REFRESH__ = refresh;
3873
+ return () => {
3874
+ window.__FURIN_HMR_REFRESH__ = undefined;
3875
+ };
3876
+ }
3877
+ }, [refresh]);
3878
+ const handlePopState = useCallback2(() => {
3879
+ const destKey = getHistoryKey(history.state);
3880
+ const logicalPath = normalizeHref(toLogical(window.location.pathname, basePath));
3881
+ const logicalHref = logicalPath + window.location.search;
3882
+ const myVersion = ++navVersion.current;
3883
+ navAbortRef.current?.abort();
3884
+ const navAbort = new AbortController;
3885
+ navAbortRef.current = navAbort;
3886
+ const navSignal = navAbort.signal;
3887
+ setIsNavigating(true);
3888
+ (async () => {
3889
+ try {
3890
+ const cached = prefetchCache.current.get(logicalHref);
3891
+ let newState;
3892
+ if (cached && !shouldRefetch(cached)) {
3893
+ newState = await cached.promise;
3894
+ } else {
3895
+ newState = await fetchPageState(logicalHref, navSignal);
3896
+ }
3897
+ if (navVersion.current !== myVersion) {
3898
+ return;
3899
+ }
3900
+ if (!newState) {
3901
+ _log.warn({
3902
+ action: "popstate_fallback",
3903
+ href: logicalHref,
3904
+ reason: "fetchPageState_returned_null"
3905
+ });
3906
+ window.location.reload();
3907
+ return;
3908
+ }
3909
+ let redirectLogical;
3910
+ if (newState.finalHref && !newState.match && !newState.notFound) {
3911
+ redirectLogical = normalizeHref(newState.finalHref);
3912
+ window.history.replaceState(history.state, "", basePath + redirectLogical);
3913
+ setCurrentHref(redirectLogical);
3914
+ const redirectState = await resolveRedirectState(redirectLogical, myVersion, navSignal);
3915
+ if (!redirectState) {
3916
+ if (navVersion.current === myVersion) {
3917
+ window.location.reload();
3918
+ }
3919
+ return;
3920
+ }
3921
+ newState = redirectState;
3922
+ }
3923
+ currentMatchRef.current = newState.match;
3924
+ setState(newState);
3925
+ if (newState.title) {
3926
+ document.title = newState.title;
3927
+ }
3928
+ const effectiveLogical = newState.finalHref ?? redirectLogical ?? logicalHref;
3929
+ if (newState.finalHref) {
3930
+ window.history.replaceState(history.state, "", basePath + effectiveLogical);
3931
+ }
3932
+ setCurrentHref(normalizeHref(effectiveLogical));
3933
+ if (destKey) {
3934
+ pendingScrollRef.current = { type: "restore", key: destKey };
3935
+ } else {
3936
+ window.scrollTo({ top: 0, behavior: "instant" });
3937
+ }
3938
+ } finally {
3939
+ if (navVersion.current === myVersion) {
3940
+ setIsNavigating(false);
3941
+ }
3942
+ }
3943
+ })();
3944
+ }, [fetchPageState, basePath]);
3945
+ useEffect(() => {
3946
+ history.scrollRestoration = "manual";
3947
+ if (!getHistoryKey(history.state)) {
3948
+ history.replaceState({ ...history.state ?? {}, _furinKey: generateHistoryKey() }, "");
3949
+ }
3950
+ }, []);
3951
+ useLayoutEffect(() => {
3952
+ const instruction = pendingScrollRef.current;
3953
+ if (!instruction) {
3954
+ return;
3955
+ }
3956
+ pendingScrollRef.current = null;
3957
+ if (instruction.type === "restore") {
3958
+ try {
3959
+ const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
3960
+ const positions = raw ? JSON.parse(raw) : {};
3961
+ const y = positions[instruction.key] ?? 0;
3962
+ window.scrollTo({ top: y, behavior: "instant" });
3963
+ } catch {
3964
+ window.scrollTo({ top: 0, behavior: "instant" });
3965
+ }
3966
+ return;
3967
+ }
3968
+ const destUrl = new URL(instruction.href, window.location.origin);
3969
+ if (destUrl.hash) {
3970
+ const id = decodeURIComponent(destUrl.hash.slice(1));
3971
+ const element = document.getElementById(id);
3972
+ if (element) {
3973
+ element.scrollIntoView({ behavior: "instant", block: "start" });
3974
+ }
3975
+ } else {
3976
+ window.scrollTo({ top: 0, behavior: "instant" });
3977
+ }
3978
+ }, [currentHref]);
3979
+ useEffect(() => {
3980
+ window.addEventListener("popstate", handlePopState);
3981
+ return () => window.removeEventListener("popstate", handlePopState);
3982
+ }, [handlePopState]);
3983
+ useEffect(() => {
3984
+ if (typeof window === "undefined") {
3985
+ return;
3986
+ }
3987
+ const handler = (e) => {
3988
+ if (e.defaultPrevented) {
3989
+ return;
3990
+ }
3991
+ const anchor = e.target.closest("a");
3992
+ if (!(anchor instanceof HTMLAnchorElement)) {
3993
+ return;
3994
+ }
3995
+ if (anchor.closest("a[data-furin-link]")) {
3996
+ return;
3997
+ }
3998
+ const logicalHref = shouldInterceptClick(anchor, e, basePath, window.location.origin, window.location.pathname);
3999
+ if (logicalHref === null) {
4000
+ return;
4001
+ }
4002
+ e.preventDefault();
4003
+ navigate(logicalHref, { resetScroll: !logicalHref.includes("#") });
4004
+ };
4005
+ document.addEventListener("click", handler);
4006
+ return () => document.removeEventListener("click", handler);
4007
+ }, [navigate, basePath]);
4008
+ useEffect(() => {
4009
+ if (typeof window === "undefined") {
4010
+ return;
4011
+ }
4012
+ const originalFetch = window.fetch;
4013
+ const wrapped = async (...args) => {
4014
+ const response = await originalFetch.apply(window, args);
4015
+ const invalidated = [];
4016
+ applyRevalidateHeader(response.headers, (path, type) => {
4017
+ const resolvedType = type ?? "page";
4018
+ invalidatePrefetch(path, resolvedType);
4019
+ invalidated.push({ path, type: resolvedType });
4020
+ });
4021
+ if (autoRefresh && invalidated.length > 0) {
4022
+ const currentLogicalPath = normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
4023
+ if (shouldAutoRefreshPath(currentLogicalPath, invalidated)) {
4024
+ invalidationRefresh.run();
4025
+ }
4026
+ }
4027
+ return response;
4028
+ };
4029
+ Object.assign(wrapped, originalFetch);
4030
+ window.fetch = wrapped;
4031
+ return () => {
4032
+ window.fetch = originalFetch;
4033
+ };
4034
+ }, [invalidatePrefetch, invalidationRefresh, autoRefresh, basePath]);
4035
+ useEffect(() => {
4036
+ if (!syncStream || typeof window === "undefined" || typeof EventSource === "undefined") {
4037
+ return;
4038
+ }
4039
+ const streamUrl = syncStream.startsWith("/") ? `${basePath}${syncStream}` : `${basePath}/${syncStream}`;
4040
+ let source;
4041
+ let disposed = false;
4042
+ const applyInvalidations = (entries) => {
4043
+ if (disposed) {
4044
+ return;
4045
+ }
4046
+ const invalidations = [];
4047
+ applyRevalidateEntries(entries, (path, type) => {
4048
+ const resolvedType = type ?? "page";
4049
+ invalidatePrefetch(path, resolvedType);
4050
+ invalidations.push({ path, type: resolvedType });
4051
+ });
4052
+ if (autoRefresh && invalidations.length > 0) {
4053
+ const currentLogicalPath = normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
4054
+ if (shouldAutoRefreshPath(currentLogicalPath, invalidations)) {
4055
+ invalidationRefresh.run();
4056
+ }
4057
+ }
4058
+ };
4059
+ const catchUp = createSyncCatchUp({
4060
+ fetchPage: async (after) => {
4061
+ const url = new URL(`${streamUrl}/changes`, window.location.origin);
4062
+ if (after !== undefined) {
4063
+ url.searchParams.set("after", after);
4064
+ }
4065
+ const response = await window.fetch(url);
4066
+ if (!response.ok) {
4067
+ throw new Error(`Sync catch-up failed with status ${response.status}`);
4068
+ }
4069
+ return await response.json();
4070
+ },
4071
+ onInvalidations: applyInvalidations
4072
+ });
4073
+ const recover = () => {
4074
+ if (disposed) {
4075
+ return;
4076
+ }
4077
+ catchUp.catchUp().catch((error) => {
4078
+ if (!disposed) {
4079
+ _log.warn({ action: "sync_catch_up_failed", error: String(error) });
4080
+ }
4081
+ });
4082
+ };
4083
+ const onSync = (event) => {
4084
+ try {
4085
+ const payload = JSON.parse(event.data);
4086
+ if (typeof payload.cursor !== "string") {
4087
+ throw new Error("Missing sync cursor");
4088
+ }
4089
+ } catch {
4090
+ _log.warn({ action: "sync_invalid_event", event: "furin.sync" });
4091
+ return;
4092
+ }
4093
+ recover();
4094
+ };
4095
+ const connect = () => {
4096
+ if (disposed || source) {
4097
+ return;
4098
+ }
4099
+ source = new EventSource(streamUrl);
4100
+ source.addEventListener("furin.sync", onSync);
4101
+ };
4102
+ catchUp.initialize().then(() => {
4103
+ if (disposed) {
4104
+ return;
4105
+ }
4106
+ connect();
4107
+ recover();
4108
+ }).catch((error) => {
4109
+ if (disposed) {
4110
+ return;
4111
+ }
4112
+ _log.warn({ action: "sync_initialize_failed", error: String(error) });
4113
+ connect();
4114
+ });
4115
+ return () => {
4116
+ disposed = true;
4117
+ source?.removeEventListener("furin.sync", onSync);
4118
+ source?.close();
4119
+ };
4120
+ }, [syncStream, basePath, invalidatePrefetch, invalidationRefresh, autoRefresh]);
4121
+ let pageElement;
4122
+ if (state.notFound || !state.match) {
4123
+ pageElement = buildNotFoundPageElement(state.notFoundBoundaries ?? state.match?.segmentBoundaries ?? rootBoundaries, state.notFound ?? {});
4124
+ } else {
4125
+ pageElement = buildPageElement(state.match, root, state.data, {
4126
+ onReset: () => {
4127
+ refresh(undefined).catch((err) => {
4128
+ _log.error({ action: "boundary_reset_failed", error: String(err) });
4129
+ });
4130
+ },
4131
+ resetKey: currentHref
4132
+ }, state.error);
4133
+ }
4134
+ return /* @__PURE__ */ jsxDEV4(SearchStoreContext.Provider, {
4135
+ value: searchStore,
4136
+ children: buildRouterTree({
4137
+ basePath,
4138
+ currentHref,
4139
+ search: resolvedSearch,
4140
+ searchRoutes: routes,
4141
+ navigate,
4142
+ prefetch,
4143
+ refresh,
4144
+ invalidatePrefetch,
4145
+ isNavigating,
4146
+ defaultPreload,
4147
+ defaultPreloadDelay,
4148
+ defaultPreloadStaleTime
4149
+ }, pageElement, {
4150
+ digest: initialDigest,
4151
+ onReset: () => {
4152
+ refresh(undefined).catch((err) => {
4153
+ _log.error({ action: "boundary_reset_failed", error: String(err) });
4154
+ });
4155
+ },
4156
+ resetKey: currentHref
4157
+ })
4158
+ }, undefined, false, undefined, this);
4159
+ }
4160
+ // src/client/link.tsx
4161
+ function computeLinkView({
4162
+ to,
4163
+ search,
4164
+ hash,
4165
+ children,
4166
+ activeProps,
4167
+ inactiveProps
4168
+ }, router2) {
4169
+ const searchDefaults = findSearchDefaultsForRouteTarget(to, router2.searchRoutes);
4170
+ const logicalHref = buildHref(to, search, hash, searchDefaults);
4171
+ const logicalHrefWithoutHash = buildHref(to, search, undefined, searchDefaults);
4172
+ const isAbsolute = logicalHref.startsWith("http://") || logicalHref.startsWith("https://") || logicalHref.startsWith("//");
4173
+ const href = isAbsolute ? logicalHref : router2.basePath + logicalHref;
4174
+ const isActive = !isAbsolute && router2.currentHref === normalizeHref(logicalHrefWithoutHash);
4175
+ const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
4176
+ const extraProps = {
4177
+ ...inactiveProps && !isActive ? inactiveProps() : {},
4178
+ ...activeProps ? activeProps({ isActive }) : {}
4179
+ };
4180
+ return { logicalHref, href, isActive, resolvedChildren, extraProps };
4181
+ }
4182
+ function LinkInteractive({
4183
+ to,
4184
+ search,
4185
+ hash,
4186
+ preload,
4187
+ preloadDelay,
4188
+ preloadStaleTime,
4189
+ replace,
4190
+ disabled,
4191
+ resetScroll,
4192
+ activeProps,
4193
+ inactiveProps,
4194
+ onClick,
4195
+ onMouseEnter,
4196
+ onMouseLeave,
4197
+ onFocus,
4198
+ children,
4199
+ href: _href,
4200
+ ...anchorProps
4201
+ }) {
4202
+ const router2 = useRouter();
4203
+ const anchorRef = useRef2(null);
4204
+ const intentTimerRef = useRef2(null);
4205
+ const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ to, search, hash, children, activeProps, inactiveProps }, router2);
4206
+ const effectivePreload = preload ?? router2.defaultPreload;
4207
+ const effectiveDelay = preloadDelay ?? router2.defaultPreloadDelay;
4208
+ const effectiveStaleTime = preloadStaleTime ?? router2.defaultPreloadStaleTime;
4209
+ const { prefetch } = router2;
4210
+ const triggerPrefetch = useCallback3(() => {
4211
+ prefetch(logicalHref, { staleTime: effectiveStaleTime });
4212
+ }, [prefetch, logicalHref, effectiveStaleTime]);
4213
+ useEffect2(() => {
4214
+ if (effectivePreload === "render") {
4215
+ triggerPrefetch();
4216
+ }
4217
+ }, [effectivePreload, triggerPrefetch]);
4218
+ useEffect2(() => {
4219
+ if (effectivePreload !== "viewport" || !anchorRef.current) {
4220
+ return;
4221
+ }
4222
+ const observer = new IntersectionObserver(([entry]) => {
4223
+ if (entry?.isIntersecting) {
4224
+ triggerPrefetch();
4225
+ observer.disconnect();
4226
+ }
4227
+ }, { rootMargin: "200px" });
4228
+ observer.observe(anchorRef.current);
4229
+ return () => observer.disconnect();
4230
+ }, [effectivePreload, triggerPrefetch]);
4231
+ useEffect2(() => () => {
4232
+ if (intentTimerRef.current !== null) {
4233
+ clearTimeout(intentTimerRef.current);
4234
+ intentTimerRef.current = null;
4235
+ }
4236
+ }, []);
4237
+ const isInternal = (url) => {
4238
+ try {
4239
+ return new URL(url, window.location.origin).origin === window.location.origin;
4240
+ } catch {
4241
+ return false;
4242
+ }
4243
+ };
4244
+ const handleClick = (e) => {
4245
+ onClick?.(e);
4246
+ if (e.defaultPrevented) {
4247
+ return;
4248
+ }
4249
+ if (disabled) {
4250
+ e.preventDefault();
4251
+ return;
4252
+ }
4253
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
4254
+ return;
4255
+ }
4256
+ if (anchorProps.target && anchorProps.target !== "_self") {
4257
+ return;
4258
+ }
4259
+ if (!isInternal(href)) {
4260
+ return;
4261
+ }
4262
+ e.preventDefault();
4263
+ if (typeof window !== "undefined" && router2.navigate === CLIENT_FALLBACK_ROUTER.navigate) {
4264
+ window.location.href = href;
4265
+ return;
4266
+ }
4267
+ router2.navigate(logicalHref, { replace, resetScroll: resetScroll ?? true });
4268
+ };
4269
+ const handleMouseEnter = (e) => {
4270
+ onMouseEnter?.(e);
4271
+ if (!disabled && effectivePreload === "intent" && isInternal(href)) {
4272
+ intentTimerRef.current = setTimeout(triggerPrefetch, effectiveDelay);
4273
+ }
4274
+ };
4275
+ const handleMouseLeave = (e) => {
4276
+ onMouseLeave?.(e);
4277
+ if (intentTimerRef.current !== null) {
4278
+ clearTimeout(intentTimerRef.current);
4279
+ intentTimerRef.current = null;
4280
+ }
4281
+ };
4282
+ const handleFocus = (e) => {
4283
+ onFocus?.(e);
4284
+ if (!disabled && effectivePreload === "intent" && isInternal(href)) {
4285
+ triggerPrefetch();
4286
+ }
4287
+ };
4288
+ return createElement3("a", {
4289
+ ref: anchorRef,
4290
+ href,
4291
+ "data-furin-link": true,
4292
+ onClick: handleClick,
4293
+ onMouseEnter: handleMouseEnter,
4294
+ onMouseLeave: handleMouseLeave,
4295
+ onFocus: handleFocus,
4296
+ ...isActive ? { "data-status": "active" } : {},
4297
+ ...anchorProps,
4298
+ ...extraProps,
4299
+ ...disabled ? { "aria-disabled": true } : {}
4300
+ }, resolvedChildren);
4301
+ }
4302
+ var SSR_FALLBACK_ROUTER = {
4303
+ basePath: "",
4304
+ currentHref: "/",
4305
+ search: {},
4306
+ searchRoutes: [],
4307
+ navigate: (_href, _opts) => Promise.resolve(),
4308
+ prefetch: (_href, _opts) => {},
4309
+ invalidatePrefetch: (_path, _type) => {},
4310
+ refresh: (_opts) => Promise.resolve(),
4311
+ isNavigating: false,
4312
+ defaultPreload: "intent",
4313
+ defaultPreloadDelay: 50,
4314
+ defaultPreloadStaleTime: 30000
4315
+ };
4316
+ function renderLinkElement(props, router2) {
4317
+ const { href, isActive, resolvedChildren, extraProps } = computeLinkView(props, router2);
4318
+ const {
4319
+ to: _to,
4320
+ search: _search,
4321
+ hash: _hash,
4322
+ children: _children,
4323
+ activeProps: _ap,
4324
+ inactiveProps: _ip,
4325
+ disabled,
4326
+ preload: _p,
4327
+ preloadDelay: _pd,
4328
+ preloadStaleTime: _ps,
4329
+ replace: _r,
4330
+ resetScroll: _rs,
4331
+ onClick: _oc,
4332
+ onMouseEnter: _ome,
4333
+ onMouseLeave: _oml,
4334
+ onFocus: _of,
4335
+ href: _href,
4336
+ ...anchorProps
4337
+ } = props;
4338
+ return createElement3("a", {
4339
+ href,
4340
+ "data-furin-link": true,
4341
+ ...isActive ? { "data-status": "active" } : {},
4342
+ ...anchorProps,
4343
+ ...extraProps,
4344
+ ...disabled ? { "aria-disabled": true } : {}
4345
+ }, resolvedChildren);
4346
+ }
4347
+ function Link(props) {
4348
+ if (typeof window === "undefined") {
4349
+ return createElement3(RouterContext.Consumer, {
4350
+ children: (routerCtx) => renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER)
4351
+ });
4352
+ }
4353
+ return createElement3(LinkInteractive, props);
4354
+ }
4355
+ export {
4356
+ useRouter,
4357
+ useNavigate,
4358
+ toLogical,
4359
+ stripHashFromHref,
4360
+ shouldRefetch,
4361
+ shouldInterceptClick,
4362
+ shouldAutoRefreshPath,
4363
+ searchSnapshotFromRouterContext,
4364
+ saveScrollPosition,
4365
+ pickDeepestNotFound,
4366
+ parsePageResponse,
4367
+ normalizePath,
4368
+ normalizeHref,
4369
+ isStaleDeployResponse,
4370
+ getHistoryKey,
4371
+ generateHistoryKey,
4372
+ fromCrossJSON,
4373
+ detectStaticMode,
4374
+ createSearchStore,
4375
+ classifySpaResponse,
4376
+ buildRouterTree,
4377
+ buildPageElement,
4378
+ buildNotFoundPageElement,
4379
+ buildHref,
4380
+ buildDataEndpoint,
4381
+ applyRevalidateHeader,
4382
+ TRAILING_SLASHES_RE,
4383
+ SearchStoreContext,
4384
+ SSR_FALLBACK_ROUTER,
4385
+ SCROLL_STORAGE_KEY,
4386
+ RouterProvider,
4387
+ RouterContext,
4388
+ Link,
4389
+ FALLBACK_SEARCH_STORE,
4390
+ CLIENT_FALLBACK_ROUTER
4391
+ };