@teyik0/furin 0.1.0-alpha.9 → 0.2.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -0
  3. package/dist/adapter/bun.d.ts +2 -2
  4. package/dist/adapter/static.d.ts +1 -1
  5. package/dist/build/client.d.ts +2 -2
  6. package/dist/build/compile-entry.d.ts +2 -16
  7. package/dist/build/compile-entry.ts +109 -0
  8. package/dist/build/entry-template.d.ts +24 -0
  9. package/dist/build/entry-template.ts +156 -0
  10. package/dist/build/hydrate.d.ts +3 -3
  11. package/dist/build/index.d.ts +1 -0
  12. package/dist/build/index.js +4027 -685
  13. package/dist/build/route-types.d.ts +1 -1
  14. package/dist/build/server-routes-entry.d.ts +2 -12
  15. package/dist/build/server-routes-entry.ts +36 -0
  16. package/dist/build/shared.d.ts +1 -1
  17. package/dist/build/ssg-cache.d.ts +4 -0
  18. package/dist/build/types.d.ts +5 -1
  19. package/dist/cli/index.js +4007 -687
  20. package/dist/client/boundaries.d.ts +117 -0
  21. package/dist/client/default-screens.d.ts +17 -0
  22. package/dist/client/link.d.ts +22 -0
  23. package/dist/client/link.js +3450 -0
  24. package/dist/client/router/boundary-tree.d.ts +26 -0
  25. package/dist/client/router/context.d.ts +8 -0
  26. package/dist/client/router/history.d.ts +9 -0
  27. package/dist/client/router/index.d.ts +7 -0
  28. package/dist/client/router/link-utils.d.ts +51 -0
  29. package/dist/client/router/provider.d.ts +4 -0
  30. package/dist/client/router/spa-response.d.ts +58 -0
  31. package/dist/{link.d.ts → client/router/types.d.ts} +114 -80
  32. package/dist/client/server-error.d.ts +12 -0
  33. package/dist/client.d.ts +51 -4
  34. package/dist/client.js +77 -1
  35. package/dist/config.d.ts +12 -2
  36. package/dist/config.js +1 -0
  37. package/dist/env.d.ts +50 -0
  38. package/dist/furin.d.ts +37 -2
  39. package/dist/furin.js +5291 -662
  40. package/dist/plugin/index.js +140 -48
  41. package/dist/plugin/transform-client.d.ts +2 -1
  42. package/dist/server/auto-invalidate/index.d.ts +4 -0
  43. package/dist/server/auto-invalidate/plugin.d.ts +38 -0
  44. package/dist/server/auto-invalidate/registry.d.ts +9 -0
  45. package/dist/server/auto-invalidate/runtime.d.ts +9 -0
  46. package/dist/server/auto-invalidate/types.d.ts +12 -0
  47. package/dist/server/cache/dev-loader.d.ts +28 -0
  48. package/dist/server/cache/index.d.ts +10 -0
  49. package/dist/server/cache/invalidation.d.ts +12 -0
  50. package/dist/server/cache/isr-ssg.d.ts +26 -0
  51. package/dist/server/cache/isr.d.ts +6 -0
  52. package/dist/server/cache/registry.d.ts +5 -0
  53. package/dist/server/cache/route-cache.d.ts +26 -0
  54. package/dist/server/cache/ssg.d.ts +5 -0
  55. package/dist/{context-logger.d.ts → server/context-logger.d.ts} +2 -0
  56. package/dist/server/dev-inspector.d.ts +89 -0
  57. package/dist/{internal.d.ts → server/internal.d.ts} +16 -0
  58. package/dist/server/internal.js +17 -0
  59. package/dist/server/lang-detect.d.ts +5 -0
  60. package/dist/server/render/assemble.d.ts +47 -0
  61. package/dist/server/render/element.d.ts +24 -0
  62. package/dist/server/render/index.d.ts +7 -0
  63. package/dist/server/render/index.ts +22 -0
  64. package/dist/server/render/isr.d.ts +3 -0
  65. package/dist/server/render/loaders.d.ts +64 -0
  66. package/dist/server/render/not-found.d.ts +6 -0
  67. package/dist/{render → server/render}/shell.d.ts +17 -7
  68. package/{src → dist/server}/render/shell.ts +28 -13
  69. package/dist/server/render/ssg.d.ts +8 -0
  70. package/dist/server/render/ssr.d.ts +107 -0
  71. package/dist/server/router/discovery.d.ts +16 -0
  72. package/dist/server/router/hmr.d.ts +64 -0
  73. package/dist/server/router/index.d.ts +6 -0
  74. package/dist/server/router/index.js +28 -0
  75. package/dist/server/router/index.ts +29 -0
  76. package/dist/server/router/patterns.d.ts +40 -0
  77. package/dist/server/router/plugin.d.ts +20 -0
  78. package/dist/server/router/schemas.d.ts +51 -0
  79. package/dist/server/router/types.d.ts +60 -0
  80. package/dist/server/runtime-env.js +10 -0
  81. package/dist/shared/await.d.ts +67 -0
  82. package/dist/shared/deferred-ndjson.d.ts +32 -0
  83. package/dist/shared/digest.d.ts +16 -0
  84. package/dist/shared/error.d.ts +37 -0
  85. package/dist/shared/not-found.d.ts +19 -0
  86. package/dist/shared/utils/ast-walk.d.ts +18 -0
  87. package/dist/shared/utils/index.d.ts +13 -0
  88. package/package.json +56 -25
  89. package/src/adapter/bun.ts +90 -41
  90. package/src/adapter/static.ts +79 -36
  91. package/src/build/client.ts +8 -12
  92. package/src/build/compile-entry.ts +20 -14
  93. package/src/build/entry-template.ts +90 -8
  94. package/src/build/hydrate.ts +213 -36
  95. package/src/build/index.ts +10 -9
  96. package/src/build/route-types.ts +30 -4
  97. package/src/build/scan-server.ts +52 -67
  98. package/src/build/server-routes-entry.ts +7 -11
  99. package/src/build/shared.ts +1 -1
  100. package/src/build/ssg-cache.ts +31 -0
  101. package/src/build/types.ts +5 -1
  102. package/src/cli/index.ts +1 -0
  103. package/src/client/boundaries.tsx +259 -0
  104. package/src/client/default-screens.tsx +304 -0
  105. package/src/client/link.tsx +338 -0
  106. package/src/client/router/boundary-tree.tsx +116 -0
  107. package/src/client/router/context.ts +38 -0
  108. package/src/client/router/history.ts +41 -0
  109. package/src/client/router/index.ts +47 -0
  110. package/src/client/router/link-utils.ts +180 -0
  111. package/src/client/router/provider.tsx +723 -0
  112. package/src/client/router/spa-response.ts +143 -0
  113. package/src/client/router/types.ts +263 -0
  114. package/src/client/server-error.ts +47 -0
  115. package/src/client.ts +80 -3
  116. package/src/config.ts +11 -3
  117. package/src/env.d.ts +1 -0
  118. package/src/furin.ts +104 -26
  119. package/src/plugin/index.ts +7 -8
  120. package/src/plugin/transform-client.ts +146 -120
  121. package/src/server/auto-invalidate/index.ts +10 -0
  122. package/src/server/auto-invalidate/plugin.ts +25 -0
  123. package/src/server/auto-invalidate/registry.ts +60 -0
  124. package/src/server/auto-invalidate/runtime.ts +133 -0
  125. package/src/server/auto-invalidate/types.ts +16 -0
  126. package/src/server/cache/dev-loader.ts +211 -0
  127. package/src/server/cache/index.ts +34 -0
  128. package/src/server/cache/invalidation.ts +111 -0
  129. package/src/server/cache/isr-ssg.ts +41 -0
  130. package/src/server/cache/isr.ts +17 -0
  131. package/src/server/cache/registry.ts +35 -0
  132. package/src/server/cache/route-cache.ts +124 -0
  133. package/src/server/cache/ssg.ts +15 -0
  134. package/src/{context-logger.ts → server/context-logger.ts} +5 -0
  135. package/src/server/dev-inspector.ts +60 -0
  136. package/src/{dev-page-plugin.ts → server/dev-page-plugin.ts} +15 -0
  137. package/src/{internal.ts → server/internal.ts} +17 -0
  138. package/src/server/lang-detect.ts +46 -0
  139. package/src/server/render/assemble.ts +133 -0
  140. package/src/server/render/element.tsx +113 -0
  141. package/src/server/render/index.ts +22 -0
  142. package/src/server/render/isr.ts +295 -0
  143. package/src/server/render/loaders.ts +328 -0
  144. package/src/server/render/not-found.ts +96 -0
  145. package/src/server/render/shell.ts +202 -0
  146. package/src/server/render/ssg.ts +137 -0
  147. package/src/server/render/ssr.ts +545 -0
  148. package/src/server/router/discovery.ts +474 -0
  149. package/src/server/router/hmr.ts +372 -0
  150. package/src/server/router/index.ts +29 -0
  151. package/src/server/router/patterns.ts +214 -0
  152. package/src/server/router/plugin.ts +401 -0
  153. package/src/server/router/schemas.ts +163 -0
  154. package/src/server/router/types.ts +59 -0
  155. package/src/shared/await.tsx +192 -0
  156. package/src/shared/deferred-ndjson.ts +244 -0
  157. package/src/shared/digest.ts +71 -0
  158. package/src/shared/error.ts +49 -0
  159. package/src/shared/not-found.ts +40 -0
  160. package/src/shared/utils/ast-walk.ts +51 -0
  161. package/src/{utils.ts → shared/utils/index.ts} +32 -1
  162. package/dist/link.js +0 -1232
  163. package/dist/render/assemble.d.ts +0 -15
  164. package/dist/render/cache.d.ts +0 -95
  165. package/dist/render/element.d.ts +0 -4
  166. package/dist/render/index.d.ts +0 -27
  167. package/dist/render/loaders.d.ts +0 -12
  168. package/dist/router.d.ts +0 -45
  169. package/dist/router.js +0 -1671
  170. package/dist/utils.d.ts +0 -6
  171. package/src/link.tsx +0 -1120
  172. package/src/render/assemble.ts +0 -66
  173. package/src/render/cache.ts +0 -241
  174. package/src/render/element.tsx +0 -28
  175. package/src/render/index.ts +0 -483
  176. package/src/render/loaders.ts +0 -117
  177. package/src/router.ts +0 -439
  178. /package/dist/{dev-page-plugin.d.ts → server/dev-page-plugin.d.ts} +0 -0
  179. /package/dist/{render → server/render}/template.d.ts +0 -0
  180. /package/dist/{runtime-env.d.ts → server/runtime-env.d.ts} +0 -0
  181. /package/src/{render → server/render}/template.ts +0 -0
  182. /package/src/{runtime-env.ts → server/runtime-env.ts} +0 -0
@@ -0,0 +1,3450 @@
1
+ // @bun
2
+ // src/client/link.tsx
3
+ import { createElement as createElement3, useCallback as useCallback2, useEffect as useEffect2, useRef as useRef2 } from "react";
4
+
5
+ // src/client/router/boundary-tree.tsx
6
+ import { createElement } from "react";
7
+
8
+ // src/client/boundaries.tsx
9
+ import { Component, Fragment } from "react";
10
+
11
+ // src/shared/digest.ts
12
+ function computeErrorDigest(err) {
13
+ let message = "";
14
+ let stack = "";
15
+ if (err instanceof Error) {
16
+ message = err.message;
17
+ stack = err.stack ?? "";
18
+ } else if (typeof err === "string") {
19
+ message = err;
20
+ } else {
21
+ try {
22
+ message = JSON.stringify(err) ?? String(err);
23
+ } catch {
24
+ message = String(err);
25
+ }
26
+ }
27
+ const input = `${message}
28
+ ${stack}`;
29
+ const hash = cyrb53(input);
30
+ const hex = hash.toString(16).padStart(14, "0");
31
+ return hex.slice(0, 10);
32
+ }
33
+ function cyrb53(input) {
34
+ let h1 = 3735928559;
35
+ let h2 = 1103547991;
36
+ for (let i = 0;i < input.length; i++) {
37
+ const ch = input.charCodeAt(i);
38
+ h1 = Math.imul(h1 ^ ch, 2654435761);
39
+ h2 = Math.imul(h2 ^ ch, 1597334677);
40
+ }
41
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
42
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
43
+ return 4294967296 * (2097151 & h2) + (4294967295 & h1);
44
+ }
45
+
46
+ // src/shared/error.ts
47
+ function getPublicErrorMessage(error) {
48
+ const branded = error;
49
+ if (branded?.__furinBrand === "FURIN_NOT_FOUND" || branded?.__furinBrand === "FURIN_SERVER_ERROR") {
50
+ return error.message;
51
+ }
52
+ return "Something went wrong";
53
+ }
54
+
55
+ // src/shared/not-found.ts
56
+ var NOT_FOUND_BRAND = "FURIN_NOT_FOUND";
57
+
58
+ class FurinNotFoundError extends Error {
59
+ __furinBrand = NOT_FOUND_BRAND;
60
+ data;
61
+ constructor(options) {
62
+ super(options?.message ?? "");
63
+ this.data = options?.data;
64
+ }
65
+ }
66
+ function isNotFoundError(err) {
67
+ return err instanceof FurinNotFoundError || typeof err === "object" && err !== null && err.__furinBrand === NOT_FOUND_BRAND;
68
+ }
69
+
70
+ // src/client/default-screens.tsx
71
+ import { jsxDEV } from "react/jsx-dev-runtime";
72
+ var FONT_SANS = '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
73
+ var FONT_MONO = 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace';
74
+ var COLOR_BG = "#000000";
75
+ var COLOR_TEXT = "#ffffff";
76
+ var COLOR_TEXT_DIM = "rgba(255, 255, 255, 0.7)";
77
+ var COLOR_TEXT_MUTED = "rgba(255, 255, 255, 0.45)";
78
+ var COLOR_GRID = "rgba(255, 255, 255, 0.04)";
79
+ var COLOR_BRACKET = "rgba(255, 255, 255, 0.55)";
80
+ var COLOR_DANGER_DIM = "rgba(239, 68, 68, 0.6)";
81
+ var PAGE_STYLE = {
82
+ alignItems: "center",
83
+ backgroundColor: COLOR_BG,
84
+ backgroundImage: `
85
+ linear-gradient(${COLOR_GRID} 1px, transparent 1px),
86
+ linear-gradient(90deg, ${COLOR_GRID} 1px, transparent 1px)
87
+ `,
88
+ backgroundSize: "32px 32px, 32px 32px",
89
+ boxSizing: "border-box",
90
+ color: COLOR_TEXT,
91
+ display: "flex",
92
+ fontFamily: FONT_SANS,
93
+ fontSize: "16px",
94
+ justifyContent: "center",
95
+ lineHeight: 1.5,
96
+ margin: 0,
97
+ minHeight: "100vh",
98
+ padding: "32px",
99
+ width: "100%"
100
+ };
101
+ var FRAME_STYLE = {
102
+ boxSizing: "border-box",
103
+ maxWidth: "880px",
104
+ position: "relative",
105
+ width: "100%"
106
+ };
107
+ var BRACKET_BASE = {
108
+ height: "40px",
109
+ position: "absolute",
110
+ width: "40px"
111
+ };
112
+ function CornerBracket({ corner }) {
113
+ const top = corner === "tl" || corner === "tr";
114
+ const left = corner === "tl" || corner === "bl";
115
+ const style = {
116
+ ...BRACKET_BASE,
117
+ [top ? "top" : "bottom"]: 0,
118
+ [left ? "left" : "right"]: 0,
119
+ [`border${top ? "Top" : "Bottom"}`]: `2px solid ${COLOR_BRACKET}`,
120
+ [`border${left ? "Left" : "Right"}`]: `2px solid ${COLOR_BRACKET}`
121
+ };
122
+ return /* @__PURE__ */ jsxDEV("span", {
123
+ "aria-hidden": "true",
124
+ style
125
+ }, undefined, false, undefined, this);
126
+ }
127
+ var CARD_STYLE = {
128
+ boxSizing: "border-box",
129
+ margin: "0 auto",
130
+ maxWidth: "640px",
131
+ padding: "64px 24px",
132
+ textAlign: "center"
133
+ };
134
+ var BADGE_STYLE = {
135
+ border: `1px solid ${COLOR_DANGER_DIM}`,
136
+ color: COLOR_TEXT,
137
+ display: "inline-block",
138
+ fontFamily: FONT_SANS,
139
+ fontSize: "32px",
140
+ fontWeight: 600,
141
+ letterSpacing: "0.08em",
142
+ marginBottom: "16px",
143
+ padding: "12px 36px"
144
+ };
145
+ var HEADING_STYLE = {
146
+ color: COLOR_TEXT,
147
+ fontFamily: FONT_SANS,
148
+ fontSize: "24px",
149
+ fontWeight: 600,
150
+ margin: "0 0 24px 0"
151
+ };
152
+ var CODE_BOX_STYLE = {
153
+ color: COLOR_TEXT_DIM,
154
+ display: "inline-block",
155
+ fontFamily: FONT_MONO,
156
+ fontSize: "13px",
157
+ letterSpacing: "0.02em",
158
+ margin: "0 0 32px 0",
159
+ padding: "8px 0"
160
+ };
161
+ var CODE_LABEL_STYLE = {
162
+ color: COLOR_TEXT_MUTED,
163
+ marginRight: "10px",
164
+ textTransform: "uppercase"
165
+ };
166
+ var DESCRIPTION_WRAPPER_STYLE = {
167
+ color: COLOR_TEXT_DIM,
168
+ fontSize: "15px",
169
+ margin: "0 auto 40px auto",
170
+ maxWidth: "440px",
171
+ padding: 0,
172
+ textAlign: "center"
173
+ };
174
+ var ACTIONS_STYLE = {
175
+ display: "flex",
176
+ flexWrap: "wrap",
177
+ gap: "16px",
178
+ justifyContent: "center"
179
+ };
180
+ var BUTTON_BASE = {
181
+ border: 0,
182
+ cursor: "pointer",
183
+ display: "inline-flex",
184
+ fontFamily: FONT_SANS,
185
+ fontSize: "14px",
186
+ fontWeight: 500,
187
+ lineHeight: 1,
188
+ minWidth: "120px",
189
+ padding: "10px 16px",
190
+ textAlign: "center",
191
+ textDecoration: "none",
192
+ transition: "background-color 120ms ease, color 120ms ease, opacity 120ms ease",
193
+ appearance: "none",
194
+ alignItems: "center",
195
+ justifyContent: "center",
196
+ boxSizing: "border-box"
197
+ };
198
+ var BUTTON_PRIMARY = {
199
+ ...BUTTON_BASE,
200
+ backgroundColor: COLOR_TEXT,
201
+ border: `1px solid ${COLOR_TEXT}`,
202
+ boxShadow: "0 10px 24px rgba(255, 255, 255, 0.08)",
203
+ color: COLOR_BG,
204
+ fontWeight: 600
205
+ };
206
+ var BUTTON_SECONDARY = {
207
+ ...BUTTON_BASE,
208
+ backgroundColor: "transparent",
209
+ border: "1px solid rgba(255, 255, 255, 0.22)",
210
+ color: COLOR_TEXT_DIM
211
+ };
212
+ var DIVIDER_STYLE = {
213
+ backgroundColor: "rgba(255, 255, 255, 0.12)",
214
+ border: 0,
215
+ height: "1px",
216
+ margin: "0 0 40px 0",
217
+ width: "100%"
218
+ };
219
+ var RESET_CSS = `
220
+ html, body {
221
+ margin: 0;
222
+ padding: 0;
223
+ background-color: ${COLOR_BG};
224
+ overscroll-behavior: none;
225
+ }
226
+ `;
227
+ function ScreenFrame({ badge, children }) {
228
+ return /* @__PURE__ */ jsxDEV("div", {
229
+ style: PAGE_STYLE,
230
+ children: [
231
+ /* @__PURE__ */ jsxDEV("style", {
232
+ children: RESET_CSS
233
+ }, undefined, false, undefined, this),
234
+ /* @__PURE__ */ jsxDEV("div", {
235
+ style: FRAME_STYLE,
236
+ children: [
237
+ /* @__PURE__ */ jsxDEV(CornerBracket, {
238
+ corner: "tl"
239
+ }, undefined, false, undefined, this),
240
+ /* @__PURE__ */ jsxDEV(CornerBracket, {
241
+ corner: "tr"
242
+ }, undefined, false, undefined, this),
243
+ /* @__PURE__ */ jsxDEV(CornerBracket, {
244
+ corner: "bl"
245
+ }, undefined, false, undefined, this),
246
+ /* @__PURE__ */ jsxDEV(CornerBracket, {
247
+ corner: "br"
248
+ }, undefined, false, undefined, this),
249
+ /* @__PURE__ */ jsxDEV("div", {
250
+ style: CARD_STYLE,
251
+ children: [
252
+ badge,
253
+ /* @__PURE__ */ jsxDEV("hr", {
254
+ style: DIVIDER_STYLE
255
+ }, undefined, false, undefined, this),
256
+ children
257
+ ]
258
+ }, undefined, true, undefined, this)
259
+ ]
260
+ }, undefined, true, undefined, this)
261
+ ]
262
+ }, undefined, true, undefined, this);
263
+ }
264
+ function DefaultErrorScreen({ message, digest, reset }) {
265
+ return /* @__PURE__ */ jsxDEV(ScreenFrame, {
266
+ badge: /* @__PURE__ */ jsxDEV("div", {
267
+ style: BADGE_STYLE,
268
+ children: "500 \u2014 ERROR"
269
+ }, undefined, false, undefined, this),
270
+ children: [
271
+ /* @__PURE__ */ jsxDEV("h1", {
272
+ style: HEADING_STYLE,
273
+ children: "Something went wrong"
274
+ }, undefined, false, undefined, this),
275
+ /* @__PURE__ */ jsxDEV("div", {
276
+ style: CODE_BOX_STYLE,
277
+ children: [
278
+ /* @__PURE__ */ jsxDEV("span", {
279
+ style: CODE_LABEL_STYLE,
280
+ children: "CODE:"
281
+ }, undefined, false, undefined, this),
282
+ /* @__PURE__ */ jsxDEV("span", {
283
+ children: digest
284
+ }, undefined, false, undefined, this)
285
+ ]
286
+ }, undefined, true, undefined, this),
287
+ /* @__PURE__ */ jsxDEV("p", {
288
+ style: DESCRIPTION_WRAPPER_STYLE,
289
+ children: message ? message : "We encountered an unexpected error. Please try again or return to the home page."
290
+ }, undefined, false, undefined, this),
291
+ /* @__PURE__ */ jsxDEV("div", {
292
+ style: ACTIONS_STYLE,
293
+ children: [
294
+ /* @__PURE__ */ jsxDEV(Link, {
295
+ style: BUTTON_PRIMARY,
296
+ to: "/",
297
+ children: "Go Home"
298
+ }, undefined, false, undefined, this),
299
+ /* @__PURE__ */ jsxDEV("button", {
300
+ onClick: reset,
301
+ style: BUTTON_SECONDARY,
302
+ type: "button",
303
+ children: "Try again"
304
+ }, undefined, false, undefined, this)
305
+ ]
306
+ }, undefined, true, undefined, this)
307
+ ]
308
+ }, undefined, true, undefined, this);
309
+ }
310
+ function DefaultNotFoundScreen({ message }) {
311
+ return /* @__PURE__ */ jsxDEV(ScreenFrame, {
312
+ badge: /* @__PURE__ */ jsxDEV("div", {
313
+ style: BADGE_STYLE,
314
+ children: "404 \u2014 NOT FOUND"
315
+ }, undefined, false, undefined, this),
316
+ children: [
317
+ /* @__PURE__ */ jsxDEV("h1", {
318
+ style: HEADING_STYLE,
319
+ children: "This page does not exist"
320
+ }, undefined, false, undefined, this),
321
+ /* @__PURE__ */ jsxDEV("p", {
322
+ style: DESCRIPTION_WRAPPER_STYLE,
323
+ children: message ? message : "The page you are looking for could not be found. It may have been moved or removed."
324
+ }, undefined, false, undefined, this),
325
+ /* @__PURE__ */ jsxDEV("div", {
326
+ style: ACTIONS_STYLE,
327
+ children: /* @__PURE__ */ jsxDEV(Link, {
328
+ style: BUTTON_PRIMARY,
329
+ to: "/",
330
+ children: "Go Home"
331
+ }, undefined, false, undefined, this)
332
+ }, undefined, false, undefined, this)
333
+ ]
334
+ }, undefined, true, undefined, this);
335
+ }
336
+ var DefaultErrorFallback = ({ error, reset }) => /* @__PURE__ */ jsxDEV(DefaultErrorScreen, {
337
+ digest: error.digest,
338
+ message: error.message,
339
+ reset
340
+ }, undefined, false, undefined, this);
341
+ var DefaultNotFoundFallback = ({ error }) => /* @__PURE__ */ jsxDEV(DefaultNotFoundScreen, {
342
+ message: error.message
343
+ }, undefined, false, undefined, this);
344
+
345
+ // src/client/server-error.ts
346
+ var SERVER_ERROR_BRAND = "FURIN_SERVER_ERROR";
347
+
348
+ class FurinServerError extends Error {
349
+ __furinBrand = SERVER_ERROR_BRAND;
350
+ digest;
351
+ status;
352
+ constructor(args) {
353
+ super(args.message);
354
+ this.status = args.status;
355
+ this.digest = args.digest;
356
+ }
357
+ }
358
+ function isFurinServerError(err) {
359
+ return err instanceof FurinServerError || typeof err === "object" && err !== null && err.__furinBrand === SERVER_ERROR_BRAND;
360
+ }
361
+
362
+ // src/client/boundaries.tsx
363
+ import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
364
+ var DEFAULT_ERROR_STATUS = 500;
365
+ var SERVER_RESET_NOOP = () => {};
366
+
367
+ class FurinErrorBoundary extends Component {
368
+ state = {
369
+ digest: null,
370
+ epoch: 0,
371
+ error: null
372
+ };
373
+ static getDerivedStateFromError(error) {
374
+ return { digest: computeErrorDigest(error), error };
375
+ }
376
+ componentDidUpdate(prevProps) {
377
+ if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
378
+ this.reset();
379
+ }
380
+ }
381
+ reset = () => {
382
+ this.setState((s) => ({ digest: null, epoch: s.epoch + 1, error: null }), () => {
383
+ this.props.onReset?.();
384
+ });
385
+ };
386
+ render() {
387
+ const { error, epoch, digest } = this.state;
388
+ if (error) {
389
+ if (isNotFoundError(error)) {
390
+ throw error;
391
+ }
392
+ const Fallback = this.props.fallback ?? DefaultErrorFallback;
393
+ const serverDigest = isFurinServerError(error) ? error.digest : undefined;
394
+ const finalDigest = serverDigest ?? digest ?? this.props.digest ?? computeErrorDigest(error);
395
+ const message = this.props.fallback ? error.message : getPublicErrorMessage(error);
396
+ const status = isFurinServerError(error) ? error.status : DEFAULT_ERROR_STATUS;
397
+ return /* @__PURE__ */ jsxDEV2(Fallback, {
398
+ error: { message, digest: finalDigest, status },
399
+ reset: typeof window === "undefined" ? SERVER_RESET_NOOP : this.reset
400
+ }, undefined, false, undefined, this);
401
+ }
402
+ return /* @__PURE__ */ jsxDEV2(Fragment, {
403
+ children: this.props.children
404
+ }, epoch, false, undefined, this);
405
+ }
406
+ }
407
+
408
+ class FurinNotFoundBoundary extends Component {
409
+ state = { epoch: 0, error: null };
410
+ static getDerivedStateFromError(error) {
411
+ return { error };
412
+ }
413
+ componentDidUpdate(prevProps) {
414
+ if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
415
+ this.setState((s) => ({ error: null, epoch: s.epoch + 1 }));
416
+ }
417
+ }
418
+ render() {
419
+ const { error, epoch } = this.state;
420
+ if (error) {
421
+ if (!isNotFoundError(error)) {
422
+ throw error;
423
+ }
424
+ const Fallback = this.props.fallback ?? DefaultNotFoundFallback;
425
+ return /* @__PURE__ */ jsxDEV2(Fallback, {
426
+ error: { message: error.message, data: error.data }
427
+ }, undefined, false, undefined, this);
428
+ }
429
+ return /* @__PURE__ */ jsxDEV2(Fragment, {
430
+ children: this.props.children
431
+ }, epoch, false, undefined, this);
432
+ }
433
+ }
434
+ function wrapSegmentBoundaries(inner, segment, options) {
435
+ if (!segment) {
436
+ return inner;
437
+ }
438
+ let wrapped = inner;
439
+ if (segment.notFound) {
440
+ wrapped = /* @__PURE__ */ jsxDEV2(FurinNotFoundBoundary, {
441
+ fallback: segment.notFound,
442
+ resetKey: options?.resetKey,
443
+ children: wrapped
444
+ }, undefined, false, undefined, this);
445
+ }
446
+ if (segment.error) {
447
+ wrapped = /* @__PURE__ */ jsxDEV2(FurinErrorBoundary, {
448
+ fallback: segment.error,
449
+ onReset: options?.onReset,
450
+ resetKey: options?.resetKey,
451
+ children: wrapped
452
+ }, undefined, false, undefined, this);
453
+ }
454
+ return wrapped;
455
+ }
456
+
457
+ // src/client/router/context.ts
458
+ import { createContext, useContext } from "react";
459
+ var RouterContext = createContext(null);
460
+ var CLIENT_FALLBACK_ROUTER = {
461
+ basePath: "",
462
+ currentHref: "/",
463
+ navigate: (href, _opts) => {
464
+ window.location.href = href;
465
+ return Promise.resolve();
466
+ },
467
+ prefetch: (_href, _opts) => {},
468
+ invalidatePrefetch: (_path, _type) => {},
469
+ refresh: (_opts) => {
470
+ window.location.reload();
471
+ return Promise.resolve();
472
+ },
473
+ isNavigating: false,
474
+ defaultPreload: "intent",
475
+ defaultPreloadDelay: 50,
476
+ defaultPreloadStaleTime: 30000
477
+ };
478
+ function useRouter() {
479
+ const ctx = useContext(RouterContext);
480
+ return ctx ?? CLIENT_FALLBACK_ROUTER;
481
+ }
482
+
483
+ // src/client/router/boundary-tree.tsx
484
+ import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
485
+ function buildRouterTree(context, pageElement, options) {
486
+ return /* @__PURE__ */ jsxDEV3(RouterContext.Provider, {
487
+ value: context,
488
+ children: /* @__PURE__ */ jsxDEV3(FurinErrorBoundary, {
489
+ ...options,
490
+ children: pageElement
491
+ }, undefined, false, undefined, this)
492
+ }, undefined, false, undefined, this);
493
+ }
494
+ function RouteErrorThrower({
495
+ error
496
+ }) {
497
+ throw new FurinServerError(error);
498
+ }
499
+ function buildPageElement(match, root, data, options, error) {
500
+ let element = error ? createElement(RouteErrorThrower, { error }) : createElement(match.component, data);
501
+ const chain = [];
502
+ let current = match.pageRoute;
503
+ while (current) {
504
+ chain.unshift(current);
505
+ current = current.parent;
506
+ }
507
+ const byDepth = new Map;
508
+ for (const segment of match.segmentBoundaries ?? []) {
509
+ byDepth.set(segment.depth, segment);
510
+ }
511
+ const rootOffset = root ? 1 : 0;
512
+ for (let i = chain.length - 1;i >= rootOffset; i--) {
513
+ element = wrapSegmentBoundaries(element, byDepth.get(i), options);
514
+ const Layout = chain[i]?.layout;
515
+ if (Layout) {
516
+ element = createElement(Layout, { ...data }, element);
517
+ }
518
+ }
519
+ if (root) {
520
+ element = wrapSegmentBoundaries(element, byDepth.get(0), options);
521
+ if (root.layout) {
522
+ element = createElement(root.layout, { ...data }, element);
523
+ }
524
+ }
525
+ return element;
526
+ }
527
+ // src/client/router/history.ts
528
+ var SCROLL_STORAGE_KEY = "__furin_scroll__";
529
+ function getHistoryKey(state) {
530
+ return state?._furinKey;
531
+ }
532
+ function generateHistoryKey() {
533
+ return Math.random().toString(36).slice(2, 9);
534
+ }
535
+ function saveScrollPosition(key) {
536
+ try {
537
+ const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
538
+ const positions = raw ? JSON.parse(raw) : {};
539
+ positions[key] = window.scrollY;
540
+ const keys = Object.keys(positions);
541
+ if (keys.length > 50) {
542
+ delete positions[keys[0]];
543
+ }
544
+ sessionStorage.setItem(SCROLL_STORAGE_KEY, JSON.stringify(positions));
545
+ } catch {}
546
+ }
547
+ function isStaleDeployResponse(res) {
548
+ const serverBuildId = res.headers.get("x-furin-build-id");
549
+ if (!serverBuildId) {
550
+ return false;
551
+ }
552
+ const metaEl = typeof document === "undefined" ? null : document.querySelector('meta[name="furin-build-id"]');
553
+ const clientBuildId = metaEl?.content;
554
+ return Boolean(clientBuildId && serverBuildId !== clientBuildId);
555
+ }
556
+ // src/client/router/link-utils.ts
557
+ var HASH_FRAGMENT_RE = /#.*$/;
558
+ var TRAILING_SLASHES_RE = /\/+$/;
559
+ function buildHref(to, search, hash) {
560
+ let url = to;
561
+ if (search && Object.keys(search).length > 0) {
562
+ const params = new URLSearchParams;
563
+ for (const [k, v] of Object.entries(search)) {
564
+ if (v != null) {
565
+ params.set(k, String(v));
566
+ }
567
+ }
568
+ const qs = params.toString();
569
+ if (qs) {
570
+ url += `?${qs}`;
571
+ }
572
+ }
573
+ if (hash) {
574
+ url += `#${hash}`;
575
+ }
576
+ return url;
577
+ }
578
+ function applyRevalidateHeader(headers, invalidate) {
579
+ const headerValue = headers.get("x-furin-revalidate");
580
+ if (!headerValue) {
581
+ return;
582
+ }
583
+ for (const entry of headerValue.split(",")) {
584
+ const trimmed = entry.trim();
585
+ if (!trimmed) {
586
+ continue;
587
+ }
588
+ if (trimmed.endsWith(":layout")) {
589
+ invalidate(trimmed.slice(0, -":layout".length), "layout");
590
+ } else {
591
+ invalidate(trimmed, "page");
592
+ }
593
+ }
594
+ }
595
+ function shouldAutoRefreshPath(currentPath, invalidations) {
596
+ const normalizedCurrent = currentPath.split("?")[0] ?? currentPath;
597
+ return invalidations.some(({ path, type }) => {
598
+ if (type === "page") {
599
+ return path === normalizedCurrent;
600
+ }
601
+ const prefix = path === "/" || path.endsWith("/") ? path : `${path}/`;
602
+ return normalizedCurrent === path || normalizedCurrent.startsWith(prefix);
603
+ });
604
+ }
605
+ function stripHashFromHref(href) {
606
+ return href.replace(HASH_FRAGMENT_RE, "");
607
+ }
608
+ function normalizeHref(href) {
609
+ const url = new URL(href, "http://localhost");
610
+ let pathname = url.pathname;
611
+ if (pathname !== "/") {
612
+ pathname = pathname.replace(/\/+$/g, "");
613
+ }
614
+ return pathname + url.search + url.hash;
615
+ }
616
+ function normalizePath(path) {
617
+ if (path === "/" || path === "") {
618
+ return path;
619
+ }
620
+ return path.endsWith("/") ? path.slice(0, -1) : path;
621
+ }
622
+ function shouldRefetch(entry) {
623
+ return Date.now() - entry.createdAt > entry.staleTime;
624
+ }
625
+ function shouldInterceptClick(anchor, event, basePath, currentOrigin, currentPathname) {
626
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
627
+ return null;
628
+ }
629
+ if (anchor.target && anchor.target !== "_self") {
630
+ return null;
631
+ }
632
+ if (anchor.hasAttribute("download")) {
633
+ return null;
634
+ }
635
+ const href = anchor.href;
636
+ if (!href) {
637
+ return null;
638
+ }
639
+ let url;
640
+ try {
641
+ url = new URL(href, currentOrigin);
642
+ } catch {
643
+ return null;
644
+ }
645
+ if (url.origin !== currentOrigin) {
646
+ return null;
647
+ }
648
+ if (normalizePath(url.pathname) === normalizePath(currentPathname) && url.hash) {
649
+ return null;
650
+ }
651
+ const logicalPath = normalizeHref(toLogical(url.pathname, basePath));
652
+ const normalizedBase = normalizePath(basePath);
653
+ const normalizedPathname = normalizePath(url.pathname);
654
+ if (normalizedBase && normalizedPathname !== normalizedBase && !normalizedPathname.startsWith(`${normalizedBase}/`)) {
655
+ return null;
656
+ }
657
+ return logicalPath + url.search + url.hash;
658
+ }
659
+ function toLogical(physicalPathname, basePath) {
660
+ if (basePath && physicalPathname.startsWith(basePath) && (physicalPathname.length === basePath.length || physicalPathname[basePath.length] === "/")) {
661
+ return physicalPathname.slice(basePath.length) || "/";
662
+ }
663
+ return physicalPathname;
664
+ }
665
+ // ../../node_modules/.bun/evlog@2.18.1+21e9b0bb4450b609/node_modules/evlog/dist/utils.mjs
666
+ function formatDuration(ms) {
667
+ if (ms < 1000)
668
+ return `${Math.round(ms)}ms`;
669
+ return `${(ms / 1000).toFixed(2)}s`;
670
+ }
671
+ function isBrowser() {
672
+ if (typeof window === "undefined")
673
+ return false;
674
+ if (typeof document === "undefined")
675
+ return false;
676
+ if (typeof navigator !== "undefined" && navigator.product === "ReactNative")
677
+ return false;
678
+ return true;
679
+ }
680
+ function isDev() {
681
+ if (typeof process !== "undefined")
682
+ return true;
683
+ if (typeof window !== "undefined")
684
+ return true;
685
+ return false;
686
+ }
687
+ function detectEnvironment() {
688
+ const env = typeof process !== "undefined" ? process.env : {};
689
+ const defaultEnvironment = isDev() ? "development" : "production";
690
+ return {
691
+ environment: env.NODE_ENV || defaultEnvironment,
692
+ service: env.SERVICE_NAME || "app",
693
+ version: env.APP_VERSION,
694
+ commitHash: env.COMMIT_SHA || env.GITHUB_SHA || env.VERCEL_GIT_COMMIT_SHA || env.CF_PAGES_COMMIT_SHA,
695
+ region: env.VERCEL_REGION || env.AWS_REGION || env.FLY_REGION || env.CF_REGION
696
+ };
697
+ }
698
+ var LEVEL_ORDER = {
699
+ debug: 0,
700
+ info: 1,
701
+ warn: 2,
702
+ error: 3
703
+ };
704
+ function isLevelEnabled(level, minLevel) {
705
+ return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];
706
+ }
707
+ function getConsoleMethod(level) {
708
+ return level;
709
+ }
710
+ var colors = {
711
+ reset: "\x1B[0m",
712
+ bold: "\x1B[1m",
713
+ dim: "\x1B[2m",
714
+ red: "\x1B[31m",
715
+ green: "\x1B[32m",
716
+ yellow: "\x1B[33m",
717
+ blue: "\x1B[34m",
718
+ magenta: "\x1B[35m",
719
+ cyan: "\x1B[36m",
720
+ white: "\x1B[37m",
721
+ gray: "\x1B[90m"
722
+ };
723
+ var levelColorMap = {
724
+ error: colors.red,
725
+ warn: colors.yellow,
726
+ info: colors.cyan,
727
+ debug: colors.gray
728
+ };
729
+ function getLevelColor(level) {
730
+ return levelColorMap[level] ?? colors.white;
731
+ }
732
+ var cssColors = {
733
+ dim: "color: #6b7280",
734
+ red: "color: #ef4444; font-weight: bold",
735
+ green: "color: #22c55e",
736
+ yellow: "color: #f59e0b; font-weight: bold",
737
+ cyan: "color: #06b6d4; font-weight: bold",
738
+ gray: "color: #6b7280; font-weight: bold",
739
+ reset: "color: inherit; font-weight: normal"
740
+ };
741
+ var cssLevelColorMap = {
742
+ error: cssColors.red,
743
+ warn: cssColors.yellow,
744
+ info: cssColors.cyan,
745
+ debug: cssColors.gray
746
+ };
747
+ function getCssLevelColor(level) {
748
+ return cssLevelColorMap[level] ?? cssColors.reset;
749
+ }
750
+ function escapeFormatString(str) {
751
+ return str.replace(/%/g, "%%");
752
+ }
753
+
754
+ // ../../node_modules/.bun/evlog@2.18.1+21e9b0bb4450b609/node_modules/evlog/dist/audit-BUI3af4w.mjs
755
+ var DEFAULT_REPLACEMENT = "[REDACTED]";
756
+ var builtinPatterns = {
757
+ creditCard: {
758
+ pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
759
+ mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
760
+ },
761
+ email: {
762
+ pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g,
763
+ mask: (m) => {
764
+ if (m.indexOf("@") < 1)
765
+ return "***@***";
766
+ const tld = m.slice(m.lastIndexOf("."));
767
+ return `${m[0]}***@***${tld}`;
768
+ }
769
+ },
770
+ ipv4: {
771
+ 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,
772
+ mask: (m) => `***.***.***.${m.split(".").pop()}`
773
+ },
774
+ phone: {
775
+ pattern: /(?:\+\d{1,3}[\s.-]?\(?\d{1,4}\)?|\(\d{1,4}\))(?:[\s.-]?\d{2,4}){2,4}\b/g,
776
+ mask: (m) => {
777
+ const digits = m.replace(/[^\d]/g, "");
778
+ if (m.startsWith("+") && digits.length > 4) {
779
+ const ccMatch = m.match(/^\+\d{1,3}/);
780
+ return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
781
+ }
782
+ if (digits.length > 2)
783
+ return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
784
+ return "***";
785
+ }
786
+ },
787
+ jwt: {
788
+ pattern: /\beyJ[\w-]*\.[\w-]*\.[\w-]*\b/g,
789
+ mask: () => "eyJ***.***"
790
+ },
791
+ bearer: {
792
+ pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
793
+ mask: () => "Bearer ***"
794
+ },
795
+ iban: {
796
+ 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,
797
+ mask: (m) => {
798
+ const clean = m.replace(/[\s-]/g, "");
799
+ return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
800
+ }
801
+ }
802
+ };
803
+ function resolveRedactConfig(input) {
804
+ if (input === undefined || input === false)
805
+ return;
806
+ if (input === true)
807
+ return { _maskers: allBuiltinMaskers() };
808
+ if (input.builtins === false)
809
+ return input;
810
+ const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
811
+ return {
812
+ ...input,
813
+ _maskers: maskers
814
+ };
815
+ }
816
+ function allBuiltinMaskers() {
817
+ return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
818
+ }
819
+ function cloneRegex(re) {
820
+ return new RegExp(re.source, re.flags);
821
+ }
822
+ function redactEvent(event, config) {
823
+ const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
824
+ if (config.paths?.length)
825
+ for (const path of config.paths)
826
+ redactPath(event, path.split("."), replacement);
827
+ if (config._maskers?.length)
828
+ applyMaskersToTree(event, config._maskers);
829
+ if (config.patterns?.length)
830
+ redactPatterns(event, config.patterns, replacement);
831
+ }
832
+ function redactPath(obj, segments, replacement) {
833
+ let current = obj;
834
+ for (let i = 0;i < segments.length - 1; i++) {
835
+ if (current === null || current === undefined || typeof current !== "object")
836
+ return;
837
+ current = current[segments[i]];
838
+ }
839
+ if (current === null || current === undefined || typeof current !== "object")
840
+ return;
841
+ const leaf = segments[segments.length - 1];
842
+ if (leaf in current)
843
+ current[leaf] = replacement;
844
+ }
845
+ function redactPatterns(obj, patterns, replacement) {
846
+ if (obj === null || obj === undefined)
847
+ return;
848
+ if (Array.isArray(obj)) {
849
+ for (let i = 0;i < obj.length; i++)
850
+ if (typeof obj[i] === "string")
851
+ obj[i] = applyPatterns(obj[i], patterns, replacement);
852
+ else if (typeof obj[i] === "object")
853
+ redactPatterns(obj[i], patterns, replacement);
854
+ return;
855
+ }
856
+ if (typeof obj === "object") {
857
+ const record = obj;
858
+ for (const key in record) {
859
+ const val = record[key];
860
+ if (typeof val === "string")
861
+ record[key] = applyPatterns(val, patterns, replacement);
862
+ else if (typeof val === "object")
863
+ redactPatterns(val, patterns, replacement);
864
+ }
865
+ }
866
+ }
867
+ function applyPatterns(value, patterns, replacement) {
868
+ let result = value;
869
+ for (const pattern of patterns) {
870
+ pattern.lastIndex = 0;
871
+ result = result.replace(pattern, replacement);
872
+ }
873
+ return result;
874
+ }
875
+ function applyMaskersToTree(obj, maskers) {
876
+ if (obj === null || obj === undefined)
877
+ return;
878
+ if (Array.isArray(obj)) {
879
+ for (let i = 0;i < obj.length; i++)
880
+ if (typeof obj[i] === "string")
881
+ obj[i] = applyMaskers(obj[i], maskers);
882
+ else if (typeof obj[i] === "object")
883
+ applyMaskersToTree(obj[i], maskers);
884
+ return;
885
+ }
886
+ if (typeof obj === "object") {
887
+ const record = obj;
888
+ for (const key in record) {
889
+ const val = record[key];
890
+ if (typeof val === "string")
891
+ record[key] = applyMaskers(val, maskers);
892
+ else if (typeof val === "object")
893
+ applyMaskersToTree(val, maskers);
894
+ }
895
+ }
896
+ }
897
+ function applyMaskers(value, maskers) {
898
+ let result = value;
899
+ for (const [pattern, mask] of maskers) {
900
+ pattern.lastIndex = 0;
901
+ result = result.replace(pattern, mask);
902
+ }
903
+ return result;
904
+ }
905
+ function logPluginError(name, hook, err) {
906
+ console.error(`[evlog/${name}] ${hook} failed:`, err);
907
+ }
908
+ function createPluginRunner(plugins = []) {
909
+ const byName = /* @__PURE__ */ new Map;
910
+ for (const plugin of plugins)
911
+ byName.set(plugin.name, plugin);
912
+ const list = Array.from(byName.values());
913
+ return {
914
+ plugins: list,
915
+ hasEnrich: list.some((p) => typeof p.enrich === "function"),
916
+ hasDrain: list.some((p) => typeof p.drain === "function"),
917
+ hasKeep: list.some((p) => typeof p.keep === "function"),
918
+ hasRequestLifecycle: list.some((p) => typeof p.onRequestStart === "function" || typeof p.onRequestFinish === "function"),
919
+ hasClientLog: list.some((p) => typeof p.onClientLog === "function"),
920
+ hasExtendLogger: list.some((p) => typeof p.extendLogger === "function"),
921
+ applyExtendLogger(logger) {
922
+ for (const plugin of list) {
923
+ if (!plugin.extendLogger)
924
+ continue;
925
+ try {
926
+ plugin.extendLogger(logger);
927
+ } catch (err) {
928
+ logPluginError(plugin.name, "extendLogger", err);
929
+ }
930
+ }
931
+ },
932
+ runOnRequestStart(ctx) {
933
+ for (const plugin of list) {
934
+ if (!plugin.onRequestStart)
935
+ continue;
936
+ try {
937
+ plugin.onRequestStart(ctx);
938
+ } catch (err) {
939
+ logPluginError(plugin.name, "onRequestStart", err);
940
+ }
941
+ }
942
+ },
943
+ runOnRequestFinish(ctx) {
944
+ for (const plugin of list) {
945
+ if (!plugin.onRequestFinish)
946
+ continue;
947
+ try {
948
+ plugin.onRequestFinish(ctx);
949
+ } catch (err) {
950
+ logPluginError(plugin.name, "onRequestFinish", err);
951
+ }
952
+ }
953
+ },
954
+ async runEnrich(ctx) {
955
+ for (const plugin of list) {
956
+ if (!plugin.enrich)
957
+ continue;
958
+ try {
959
+ await plugin.enrich(ctx);
960
+ } catch (err) {
961
+ logPluginError(plugin.name, "enrich", err);
962
+ }
963
+ }
964
+ },
965
+ async runDrain(ctx) {
966
+ const drains = list.filter((p) => typeof p.drain === "function");
967
+ if (drains.length === 0)
968
+ return;
969
+ await Promise.allSettled(drains.map(async (plugin) => {
970
+ try {
971
+ await plugin.drain(ctx);
972
+ } catch (err) {
973
+ logPluginError(plugin.name, "drain", err);
974
+ }
975
+ }));
976
+ },
977
+ async runKeep(ctx) {
978
+ for (const plugin of list) {
979
+ if (!plugin.keep)
980
+ continue;
981
+ try {
982
+ await plugin.keep(ctx);
983
+ } catch (err) {
984
+ logPluginError(plugin.name, "keep", err);
985
+ }
986
+ }
987
+ },
988
+ runOnClientLog(ctx) {
989
+ for (const plugin of list) {
990
+ if (!plugin.onClientLog)
991
+ continue;
992
+ try {
993
+ plugin.onClientLog(ctx);
994
+ } catch (err) {
995
+ logPluginError(plugin.name, "onClientLog", err);
996
+ }
997
+ }
998
+ },
999
+ async runSetup(ctx) {
1000
+ for (const plugin of list) {
1001
+ if (!plugin.setup)
1002
+ continue;
1003
+ try {
1004
+ await plugin.setup(ctx);
1005
+ } catch (err) {
1006
+ logPluginError(plugin.name, "setup", err);
1007
+ }
1008
+ }
1009
+ }
1010
+ };
1011
+ }
1012
+ var emptyRunner = createPluginRunner([]);
1013
+ function getEmptyPluginRunner() {
1014
+ return emptyRunner;
1015
+ }
1016
+ function isPlainObject$1(val) {
1017
+ return val !== null && typeof val === "object" && !Array.isArray(val);
1018
+ }
1019
+ var _tsDate = /* @__PURE__ */ new Date;
1020
+ function isoNow() {
1021
+ _tsDate.setTime(Date.now());
1022
+ return _tsDate.toISOString();
1023
+ }
1024
+ var globalEnv = {
1025
+ service: "app",
1026
+ environment: "development"
1027
+ };
1028
+ var globalPretty = isDev();
1029
+ var globalSampling = {};
1030
+ var globalStringify = true;
1031
+ var globalDrain;
1032
+ var globalRedact;
1033
+ var globalEnabled = true;
1034
+ var globalSilent = false;
1035
+ var globalMinLevel = "debug";
1036
+ var globalPluginRunner = getEmptyPluginRunner();
1037
+ function initLogger(config = {}) {
1038
+ globalEnabled = config.enabled ?? true;
1039
+ const detected = detectEnvironment();
1040
+ globalEnv = {
1041
+ service: config.env?.service ?? detected.service ?? "app",
1042
+ environment: config.env?.environment ?? detected.environment ?? "development",
1043
+ version: config.env?.version ?? detected.version,
1044
+ commitHash: config.env?.commitHash ?? detected.commitHash,
1045
+ region: config.env?.region ?? detected.region
1046
+ };
1047
+ globalPretty = config.pretty ?? isDev();
1048
+ globalSampling = config.sampling ?? {};
1049
+ globalStringify = config.stringify ?? true;
1050
+ globalDrain = config.drain;
1051
+ globalRedact = resolveRedactConfig(config.redact ?? !isDev());
1052
+ globalSilent = config.silent ?? false;
1053
+ globalMinLevel = config.minLevel ?? "debug";
1054
+ globalPluginRunner = config.plugins?.length ? createPluginRunner(config.plugins) : getEmptyPluginRunner();
1055
+ if (globalPluginRunner.plugins.length > 0)
1056
+ globalPluginRunner.runSetup({ env: { ...globalEnv } });
1057
+ const hasAnyDrain = !!globalDrain || globalPluginRunner.hasDrain;
1058
+ if (globalSilent && !hasAnyDrain && !config._suppressDrainWarning)
1059
+ 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).");
1060
+ }
1061
+ function shouldSample(level) {
1062
+ const { rates } = globalSampling;
1063
+ if (!rates)
1064
+ return true;
1065
+ const percentage = level === "error" && rates.error === undefined ? 100 : rates[level] ?? 100;
1066
+ if (percentage <= 0)
1067
+ return false;
1068
+ if (percentage >= 100)
1069
+ return true;
1070
+ return Math.random() * 100 < percentage;
1071
+ }
1072
+ function emitWideEvent(level, event, options = {}) {
1073
+ const { deferDrain = false, ownsEvent = false, waitUntil } = options;
1074
+ if (!globalEnabled)
1075
+ return null;
1076
+ if (!ownsEvent) {
1077
+ if (!isLevelEnabled(level, globalMinLevel))
1078
+ return null;
1079
+ if (!shouldSample(level))
1080
+ return null;
1081
+ }
1082
+ let formatted;
1083
+ if (ownsEvent) {
1084
+ event.timestamp = isoNow();
1085
+ event.level = level;
1086
+ if (event.service === undefined)
1087
+ event.service = globalEnv.service;
1088
+ if (event.environment === undefined)
1089
+ event.environment = globalEnv.environment;
1090
+ if (globalEnv.version !== undefined && event.version === undefined)
1091
+ event.version = globalEnv.version;
1092
+ if (globalEnv.commitHash !== undefined && event.commitHash === undefined)
1093
+ event.commitHash = globalEnv.commitHash;
1094
+ if (globalEnv.region !== undefined && event.region === undefined)
1095
+ event.region = globalEnv.region;
1096
+ formatted = event;
1097
+ } else
1098
+ formatted = {
1099
+ timestamp: isoNow(),
1100
+ level,
1101
+ ...globalEnv,
1102
+ ...event
1103
+ };
1104
+ finalizeAudit(formatted);
1105
+ if (globalRedact)
1106
+ redactEvent(formatted, globalRedact);
1107
+ if (!globalSilent)
1108
+ if (globalPretty)
1109
+ prettyPrintWideEvent(formatted);
1110
+ else if (globalStringify)
1111
+ console[getConsoleMethod(level)](JSON.stringify(formatted));
1112
+ else
1113
+ console[getConsoleMethod(level)](formatted);
1114
+ if (!deferDrain) {
1115
+ const drainPromises = [];
1116
+ if (globalDrain)
1117
+ drainPromises.push((async () => {
1118
+ try {
1119
+ await globalDrain({ event: formatted });
1120
+ } catch (err) {
1121
+ console.error("[evlog] drain failed:", err);
1122
+ }
1123
+ })());
1124
+ if (globalPluginRunner.hasDrain)
1125
+ drainPromises.push(globalPluginRunner.runDrain({ event: formatted }));
1126
+ if (drainPromises.length > 0 && waitUntil)
1127
+ waitUntil(Promise.all(drainPromises));
1128
+ }
1129
+ return formatted;
1130
+ }
1131
+ function emitTaggedLog(level, tag, message) {
1132
+ if (!globalEnabled)
1133
+ return;
1134
+ if (globalPretty && !globalSilent) {
1135
+ if (!isLevelEnabled(level, globalMinLevel))
1136
+ return;
1137
+ if (!shouldSample(level))
1138
+ return;
1139
+ if (isBrowser()) {
1140
+ const levelColor = getCssLevelColor(level);
1141
+ const timestamp = isoNow().slice(11, 23);
1142
+ console.log(`%c${timestamp}%c %c[${escapeFormatString(tag)}]%c ${escapeFormatString(message)}`, cssColors.dim, cssColors.reset, levelColor, cssColors.reset);
1143
+ } else {
1144
+ const color = getLevelColor(level);
1145
+ const timestamp = isoNow().slice(11, 23);
1146
+ console.log(`${colors.dim}${timestamp}${colors.reset} ${color}[${tag}]${colors.reset} ${message}`);
1147
+ }
1148
+ return;
1149
+ }
1150
+ emitWideEvent(level, {
1151
+ tag,
1152
+ message
1153
+ });
1154
+ }
1155
+ function formatValue(value) {
1156
+ if (value === null || value === undefined)
1157
+ return String(value);
1158
+ if (isPlainObject$1(value)) {
1159
+ const pairs = [];
1160
+ for (const [k, v] of Object.entries(value))
1161
+ if (v !== undefined && v !== null)
1162
+ if (typeof v === "object")
1163
+ pairs.push(`${k}=${JSON.stringify(v)}`);
1164
+ else
1165
+ pairs.push(`${k}=${v}`);
1166
+ return pairs.join(" ");
1167
+ }
1168
+ return String(value);
1169
+ }
1170
+ function formatCost(cost) {
1171
+ if (cost < 0.01)
1172
+ return `$${cost.toFixed(6)}`;
1173
+ if (cost < 1)
1174
+ return `$${cost.toFixed(4)}`;
1175
+ return `$${cost.toFixed(2)}`;
1176
+ }
1177
+ function asNumber(value) {
1178
+ return typeof value === "number" ? value : undefined;
1179
+ }
1180
+ function asStringArray(value) {
1181
+ if (!Array.isArray(value))
1182
+ return;
1183
+ return value.every((item) => typeof item === "string") ? value : undefined;
1184
+ }
1185
+ function isToolUsageEntry(value) {
1186
+ return isPlainObject$1(value) && typeof value.name === "string" && typeof value.durationMs === "number" && typeof value.success === "boolean";
1187
+ }
1188
+ function asToolUsageArray(value) {
1189
+ if (!Array.isArray(value))
1190
+ return;
1191
+ return value.every(isToolUsageEntry) ? value : undefined;
1192
+ }
1193
+ function serializeToolInput(input) {
1194
+ if (typeof input === "string")
1195
+ return input;
1196
+ const seen = /* @__PURE__ */ new WeakSet;
1197
+ try {
1198
+ return JSON.stringify(input, (_key, value) => {
1199
+ if (typeof value === "bigint")
1200
+ return value.toString();
1201
+ if (typeof value === "object" && value !== null) {
1202
+ if (seen.has(value))
1203
+ return "[Circular]";
1204
+ seen.add(value);
1205
+ }
1206
+ return value;
1207
+ }) ?? "";
1208
+ } catch {
1209
+ return "[unserializable tool input]";
1210
+ }
1211
+ }
1212
+ function isToolCallEntry(value) {
1213
+ return isPlainObject$1(value) && typeof value.name === "string" && "input" in value;
1214
+ }
1215
+ function asToolCallArray(value) {
1216
+ if (!Array.isArray(value))
1217
+ return;
1218
+ return value.every(isToolCallEntry) ? value : undefined;
1219
+ }
1220
+ function buildAIEntries(ai) {
1221
+ const entries = [];
1222
+ const headerParts = [];
1223
+ if (ai.model) {
1224
+ let m = String(ai.model);
1225
+ if (ai.provider)
1226
+ m += ` (${ai.provider})`;
1227
+ headerParts.push(m);
1228
+ }
1229
+ if (ai.calls) {
1230
+ const calls = asNumber(ai.calls);
1231
+ if (calls !== undefined)
1232
+ headerParts.push(`${calls} call${calls > 1 ? "s" : ""}`);
1233
+ }
1234
+ const steps = asNumber(ai.steps);
1235
+ if (steps !== undefined && steps > 1)
1236
+ headerParts.push(`${steps} steps`);
1237
+ entries.push({
1238
+ key: "ai",
1239
+ value: headerParts.join(" \xB7 ")
1240
+ });
1241
+ const inputTokens = asNumber(ai.inputTokens);
1242
+ const outputTokens = asNumber(ai.outputTokens);
1243
+ const totalTokens = asNumber(ai.totalTokens);
1244
+ if (inputTokens !== undefined && outputTokens !== undefined) {
1245
+ let tokLine = `${inputTokens} in \u2192 ${outputTokens} out`;
1246
+ if (totalTokens)
1247
+ tokLine += ` (${totalTokens} total)`;
1248
+ const extras = [];
1249
+ if (ai.cacheReadTokens)
1250
+ extras.push(`${ai.cacheReadTokens} cache read`);
1251
+ if (ai.cacheWriteTokens)
1252
+ extras.push(`${ai.cacheWriteTokens} cache write`);
1253
+ if (ai.reasoningTokens)
1254
+ extras.push(`${ai.reasoningTokens} reasoning`);
1255
+ if (extras.length)
1256
+ tokLine += ` \xB7 ${extras.join(" \xB7 ")}`;
1257
+ entries.push({
1258
+ key: "ai.tokens",
1259
+ value: tokLine
1260
+ });
1261
+ }
1262
+ const msFirst = asNumber(ai.msToFirstChunk);
1263
+ const msFinish = asNumber(ai.msToFinish);
1264
+ const tps = asNumber(ai.tokensPerSecond);
1265
+ if (msFirst !== undefined || msFinish !== undefined) {
1266
+ const parts = [];
1267
+ if (msFirst !== undefined)
1268
+ parts.push(`${formatDuration(msFirst)} to first chunk`);
1269
+ if (msFinish !== undefined)
1270
+ parts.push(`${formatDuration(msFinish)} total`);
1271
+ let streamLine = parts.join(" \u2192 ");
1272
+ if (tps)
1273
+ streamLine += ` \xB7 ${tps} tok/s`;
1274
+ entries.push({
1275
+ key: "ai.streaming",
1276
+ value: streamLine
1277
+ });
1278
+ }
1279
+ const estimatedCost = asNumber(ai.estimatedCost);
1280
+ if (estimatedCost !== undefined)
1281
+ entries.push({
1282
+ key: "ai.cost",
1283
+ value: formatCost(estimatedCost)
1284
+ });
1285
+ const totalDurationMs = asNumber(ai.totalDurationMs);
1286
+ if (totalDurationMs !== undefined)
1287
+ entries.push({
1288
+ key: "ai.totalDuration",
1289
+ value: formatDuration(totalDurationMs)
1290
+ });
1291
+ const toolCalls = Array.isArray(ai.toolCalls) ? ai.toolCalls : undefined;
1292
+ const tools = asToolUsageArray(ai.tools);
1293
+ const toolCallEntries = toolCalls ? asToolCallArray(toolCalls) : undefined;
1294
+ const hasInputs = toolCallEntries !== undefined && toolCallEntries.length > 0;
1295
+ if (tools?.length) {
1296
+ const children = tools.map((t, idx) => {
1297
+ const mark = t.success ? "\u2713" : "\u2717";
1298
+ let line = `${t.name} ${formatDuration(t.durationMs)} ${mark}`;
1299
+ if (t.error)
1300
+ line += ` ${t.error}`;
1301
+ if (hasInputs && toolCallEntries && idx < toolCallEntries.length) {
1302
+ const tc = toolCallEntries[idx];
1303
+ const inputStr = serializeToolInput(tc.input);
1304
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
1305
+ line += ` ${truncated}`;
1306
+ }
1307
+ return line;
1308
+ });
1309
+ entries.push({
1310
+ key: "ai.tools",
1311
+ value: "",
1312
+ children
1313
+ });
1314
+ } else if (toolCalls?.length)
1315
+ if (toolCallEntries?.length) {
1316
+ const children = toolCallEntries.map((tc) => {
1317
+ const inputStr = serializeToolInput(tc.input);
1318
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
1319
+ return `${tc.name}(${truncated})`;
1320
+ });
1321
+ entries.push({
1322
+ key: "ai.tools",
1323
+ value: "",
1324
+ children
1325
+ });
1326
+ } else {
1327
+ const names = asStringArray(toolCalls);
1328
+ if (names?.length)
1329
+ entries.push({
1330
+ key: "ai.tools",
1331
+ value: names.join(", ")
1332
+ });
1333
+ }
1334
+ const stepsUsage = Array.isArray(ai.stepsUsage) ? ai.stepsUsage.filter(isPlainObject$1) : undefined;
1335
+ if (stepsUsage?.length) {
1336
+ const firstModel = stepsUsage[0]?.model;
1337
+ const allSameModel = firstModel !== undefined && stepsUsage.every((s) => s.model === firstModel);
1338
+ const children = stepsUsage.map((s) => {
1339
+ let line = `${allSameModel ? "" : `${String(s.model)} `}${s.inputTokens} in \u2192 ${s.outputTokens} out`;
1340
+ const stepTools = asStringArray(s.toolCalls);
1341
+ if (stepTools?.length)
1342
+ line += ` [${stepTools.join(", ")}]`;
1343
+ return line;
1344
+ });
1345
+ entries.push({
1346
+ key: "ai.steps",
1347
+ value: "",
1348
+ children
1349
+ });
1350
+ } else if (steps !== undefined && steps > 1)
1351
+ entries.push({
1352
+ key: "ai.steps",
1353
+ value: String(steps)
1354
+ });
1355
+ const embedding = isPlainObject$1(ai.embedding) ? ai.embedding : undefined;
1356
+ if (embedding) {
1357
+ const parts = [];
1358
+ if (embedding.model)
1359
+ parts.push(String(embedding.model));
1360
+ parts.push(`${embedding.tokens} tokens`);
1361
+ if (embedding.dimensions)
1362
+ parts.push(`${embedding.dimensions}d`);
1363
+ if (embedding.count)
1364
+ parts.push(`${embedding.count} items`);
1365
+ entries.push({
1366
+ key: "ai.embedding",
1367
+ value: parts.join(" \xB7 ")
1368
+ });
1369
+ }
1370
+ if (ai.finishReason)
1371
+ entries.push({
1372
+ key: "ai.finishReason",
1373
+ value: String(ai.finishReason)
1374
+ });
1375
+ if (ai.error)
1376
+ entries.push({
1377
+ key: "ai.error",
1378
+ value: String(ai.error)
1379
+ });
1380
+ if (ai.responseId)
1381
+ entries.push({
1382
+ key: "ai.responseId",
1383
+ value: String(ai.responseId)
1384
+ });
1385
+ return entries;
1386
+ }
1387
+ function prettyPrintWideEvent(event) {
1388
+ const { timestamp, level, service, environment, version, ...rest } = event;
1389
+ const ts = typeof timestamp === "string" ? timestamp.slice(11, 23) : "";
1390
+ const levelLabel = typeof level === "string" ? level : "info";
1391
+ const browser = isBrowser();
1392
+ const parts = [];
1393
+ const styles = [];
1394
+ if (browser) {
1395
+ const lc = getCssLevelColor(levelLabel);
1396
+ parts.push(`%c${ts}%c %c${levelLabel.toUpperCase()}%c %c[${escapeFormatString(String(service))}]%c`);
1397
+ styles.push(cssColors.dim, cssColors.reset, lc, cssColors.reset, cssColors.cyan, cssColors.reset);
1398
+ } else {
1399
+ const lc = getLevelColor(levelLabel);
1400
+ parts.push(`${colors.dim}${ts}${colors.reset} ${lc}${levelLabel.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
1401
+ }
1402
+ if (rest.method && rest.path) {
1403
+ parts.push(browser ? ` ${escapeFormatString(String(rest.method))} ${escapeFormatString(String(rest.path))}` : ` ${rest.method} ${rest.path}`);
1404
+ delete rest.method;
1405
+ delete rest.path;
1406
+ }
1407
+ if (rest.status) {
1408
+ const statusCode = asNumber(rest.status) ?? Number(rest.status);
1409
+ const sc = browser ? statusCode >= 400 ? cssColors.red : cssColors.green : statusCode >= 400 ? colors.red : colors.green;
1410
+ if (browser) {
1411
+ parts.push(` %c${rest.status}%c`);
1412
+ styles.push(sc, cssColors.reset);
1413
+ } else
1414
+ parts.push(` ${sc}${rest.status}${colors.reset}`);
1415
+ delete rest.status;
1416
+ }
1417
+ if (rest.duration) {
1418
+ if (browser) {
1419
+ parts.push(` %c${escapeFormatString(`in ${rest.duration}`)}%c`);
1420
+ styles.push(cssColors.dim, cssColors.reset);
1421
+ } else
1422
+ parts.push(` ${colors.dim}in ${rest.duration}${colors.reset}`);
1423
+ delete rest.duration;
1424
+ }
1425
+ console.log(parts.join(""), ...styles);
1426
+ const aiData = isPlainObject$1(rest.ai) ? rest.ai : undefined;
1427
+ if (aiData)
1428
+ delete rest.ai;
1429
+ const restEntries = Object.entries(rest).filter(([_, v]) => v !== undefined);
1430
+ const aiEntries = aiData ? buildAIEntries(aiData) : [];
1431
+ const allEntries = [...restEntries.map(([key, value]) => ({
1432
+ key,
1433
+ value: formatValue(value)
1434
+ })), ...aiEntries];
1435
+ for (let i = 0;i < allEntries.length; i++) {
1436
+ const entry = allEntries[i];
1437
+ if (!entry)
1438
+ continue;
1439
+ const { children } = entry;
1440
+ const hasChildren = children !== undefined && children.length > 0;
1441
+ const prefix = i === allEntries.length - 1 && !hasChildren ? "\u2514\u2500" : "\u251C\u2500";
1442
+ if (browser) {
1443
+ const val = entry.value ? ` ${escapeFormatString(entry.value)}` : "";
1444
+ console.log(` %c${prefix}%c %c${escapeFormatString(entry.key)}:%c${val}`, cssColors.dim, cssColors.reset, cssColors.cyan, cssColors.reset);
1445
+ } else {
1446
+ const val = entry.value ? ` ${entry.value}` : "";
1447
+ console.log(` ${colors.dim}${prefix}${colors.reset} ${colors.cyan}${entry.key}:${colors.reset}${val}`);
1448
+ }
1449
+ if (hasChildren && children) {
1450
+ const connector = i === allEntries.length - 1 ? " " : "\u2502";
1451
+ for (let j = 0;j < children.length; j++) {
1452
+ const child = children[j];
1453
+ if (child === undefined)
1454
+ continue;
1455
+ const childPrefix = j === children.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
1456
+ if (browser)
1457
+ console.log(` %c${connector} ${childPrefix}%c ${escapeFormatString(child)}`, cssColors.dim, cssColors.reset);
1458
+ else
1459
+ console.log(` ${colors.dim}${connector} ${childPrefix}${colors.reset} ${child}`);
1460
+ }
1461
+ }
1462
+ }
1463
+ }
1464
+ function createLogMethod(level) {
1465
+ return function logMethod(tagOrEvent, message) {
1466
+ if (typeof tagOrEvent === "string" && message !== undefined)
1467
+ emitTaggedLog(level, tagOrEvent, message);
1468
+ else if (typeof tagOrEvent === "object")
1469
+ emitWideEvent(level, tagOrEvent);
1470
+ else
1471
+ emitTaggedLog(level, "log", String(tagOrEvent));
1472
+ };
1473
+ }
1474
+ var _log = {
1475
+ info: createLogMethod("info"),
1476
+ error: createLogMethod("error"),
1477
+ warn: createLogMethod("warn"),
1478
+ debug: createLogMethod("debug")
1479
+ };
1480
+ var noopLogger = {
1481
+ set() {},
1482
+ setLevel() {},
1483
+ error() {},
1484
+ info() {},
1485
+ warn() {},
1486
+ emit() {
1487
+ return null;
1488
+ },
1489
+ getContext() {
1490
+ return {};
1491
+ },
1492
+ audit: Object.assign(() => {}, { deny: () => {} })
1493
+ };
1494
+ if (typeof __EVLOG_CONFIG__ !== "undefined")
1495
+ initLogger(__EVLOG_CONFIG__);
1496
+ function isPlainObject(value) {
1497
+ if (typeof value !== "object" || value === null || Array.isArray(value))
1498
+ return false;
1499
+ if (Object.prototype.toString.call(value) !== "[object Object]")
1500
+ return false;
1501
+ return Object.getPrototypeOf(value) === Object.prototype || value.constructor === Object;
1502
+ }
1503
+ function stableStringify(value) {
1504
+ if (value === null || typeof value !== "object")
1505
+ return JSON.stringify(value);
1506
+ if (Array.isArray(value))
1507
+ return `[${value.map(stableStringify).join(",")}]`;
1508
+ if (!isPlainObject(value))
1509
+ return JSON.stringify(value);
1510
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;
1511
+ }
1512
+ function fnv1a32(input, seed) {
1513
+ let h = seed >>> 0;
1514
+ for (let i = 0;i < input.length; i++) {
1515
+ h ^= input.charCodeAt(i) & 255;
1516
+ h = Math.imul(h, 16777619) >>> 0;
1517
+ }
1518
+ return h >>> 0;
1519
+ }
1520
+ function computeIdempotencyKey(audit, timestamp) {
1521
+ const seconds = timestamp.slice(0, 19);
1522
+ const payload = stableStringify({
1523
+ action: audit.action,
1524
+ actor: {
1525
+ type: audit.actor.type,
1526
+ id: audit.actor.id
1527
+ },
1528
+ target: audit.target ? {
1529
+ type: audit.target.type,
1530
+ id: audit.target.id
1531
+ } : undefined,
1532
+ outcome: audit.outcome,
1533
+ timestamp: seconds
1534
+ });
1535
+ const a = fnv1a32(payload, 2166136261).toString(16).padStart(8, "0");
1536
+ const b = fnv1a32(payload, 3735928559).toString(16).padStart(8, "0");
1537
+ const c = fnv1a32(payload, 528734635).toString(16).padStart(8, "0");
1538
+ const d = fnv1a32(payload, 1541459225).toString(16).padStart(8, "0");
1539
+ return a + b + c + d;
1540
+ }
1541
+ function decorateAudit(audit, timestamp) {
1542
+ if (audit.idempotencyKey)
1543
+ return audit;
1544
+ return {
1545
+ ...audit,
1546
+ idempotencyKey: computeIdempotencyKey(audit, timestamp)
1547
+ };
1548
+ }
1549
+ function finalizeAudit(event) {
1550
+ const a = event.audit;
1551
+ if (!a)
1552
+ return;
1553
+ event.audit = decorateAudit(a, String(event.timestamp));
1554
+ }
1555
+
1556
+ // src/client/router/provider.tsx
1557
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
1558
+
1559
+ // ../../node_modules/.bun/seroval@1.5.4/node_modules/seroval/dist/esm/development/index.mjs
1560
+ var ALL_ENABLED = 1 | 2 | 4 | 8 | 16 | 32;
1561
+ var SYM_ASYNC_ITERATOR = Symbol.asyncIterator;
1562
+ var SYM_HAS_INSTANCE = Symbol.hasInstance;
1563
+ var SYM_IS_CONCAT_SPREADABLE = Symbol.isConcatSpreadable;
1564
+ var SYM_ITERATOR = Symbol.iterator;
1565
+ var SYM_MATCH = Symbol.match;
1566
+ var SYM_MATCH_ALL = Symbol.matchAll;
1567
+ var SYM_REPLACE = Symbol.replace;
1568
+ var SYM_SEARCH = Symbol.search;
1569
+ var SYM_SPECIES = Symbol.species;
1570
+ var SYM_SPLIT = Symbol.split;
1571
+ var SYM_TO_PRIMITIVE = Symbol.toPrimitive;
1572
+ var SYM_TO_STRING_TAG = Symbol.toStringTag;
1573
+ var SYM_UNSCOPABLES = Symbol.unscopables;
1574
+ var INV_SYMBOL_REF = {
1575
+ [SYM_ASYNC_ITERATOR]: 0,
1576
+ [SYM_HAS_INSTANCE]: 1,
1577
+ [SYM_IS_CONCAT_SPREADABLE]: 2,
1578
+ [SYM_ITERATOR]: 3,
1579
+ [SYM_MATCH]: 4,
1580
+ [SYM_MATCH_ALL]: 5,
1581
+ [SYM_REPLACE]: 6,
1582
+ [SYM_SEARCH]: 7,
1583
+ [SYM_SPECIES]: 8,
1584
+ [SYM_SPLIT]: 9,
1585
+ [SYM_TO_PRIMITIVE]: 10,
1586
+ [SYM_TO_STRING_TAG]: 11,
1587
+ [SYM_UNSCOPABLES]: 12
1588
+ };
1589
+ var SYMBOL_REF = {
1590
+ [0]: SYM_ASYNC_ITERATOR,
1591
+ [1]: SYM_HAS_INSTANCE,
1592
+ [2]: SYM_IS_CONCAT_SPREADABLE,
1593
+ [3]: SYM_ITERATOR,
1594
+ [4]: SYM_MATCH,
1595
+ [5]: SYM_MATCH_ALL,
1596
+ [6]: SYM_REPLACE,
1597
+ [7]: SYM_SEARCH,
1598
+ [8]: SYM_SPECIES,
1599
+ [9]: SYM_SPLIT,
1600
+ [10]: SYM_TO_PRIMITIVE,
1601
+ [11]: SYM_TO_STRING_TAG,
1602
+ [12]: SYM_UNSCOPABLES
1603
+ };
1604
+ var NIL = undefined;
1605
+ var CONSTANT_VAL = {
1606
+ [2]: true,
1607
+ [3]: false,
1608
+ [1]: NIL,
1609
+ [0]: null,
1610
+ [4]: -0,
1611
+ [5]: Number.POSITIVE_INFINITY,
1612
+ [6]: Number.NEGATIVE_INFINITY,
1613
+ [7]: Number.NaN
1614
+ };
1615
+ var ERROR_CONSTRUCTOR = {
1616
+ [0]: Error,
1617
+ [1]: EvalError,
1618
+ [2]: RangeError,
1619
+ [3]: ReferenceError,
1620
+ [4]: SyntaxError,
1621
+ [5]: TypeError,
1622
+ [6]: URIError
1623
+ };
1624
+ function serializeChar(str) {
1625
+ switch (str) {
1626
+ case '"':
1627
+ return "\\\"";
1628
+ case "\\":
1629
+ return "\\\\";
1630
+ case `
1631
+ `:
1632
+ return "\\n";
1633
+ case "\r":
1634
+ return "\\r";
1635
+ case "\b":
1636
+ return "\\b";
1637
+ case "\t":
1638
+ return "\\t";
1639
+ case "\f":
1640
+ return "\\f";
1641
+ case "<":
1642
+ return "\\x3C";
1643
+ case "\u2028":
1644
+ return "\\u2028";
1645
+ case "\u2029":
1646
+ return "\\u2029";
1647
+ default:
1648
+ return NIL;
1649
+ }
1650
+ }
1651
+ function serializeString(str) {
1652
+ let result = "";
1653
+ let lastPos = 0;
1654
+ let replacement;
1655
+ for (let i = 0, len = str.length;i < len; i++) {
1656
+ replacement = serializeChar(str[i]);
1657
+ if (replacement) {
1658
+ result += str.slice(lastPos, i) + replacement;
1659
+ lastPos = i + 1;
1660
+ }
1661
+ }
1662
+ if (lastPos === 0) {
1663
+ result = str;
1664
+ } else {
1665
+ result += str.slice(lastPos);
1666
+ }
1667
+ return result;
1668
+ }
1669
+ function deserializeReplacer(str) {
1670
+ switch (str) {
1671
+ case "\\\\":
1672
+ return "\\";
1673
+ case "\\\"":
1674
+ return '"';
1675
+ case "\\n":
1676
+ return `
1677
+ `;
1678
+ case "\\r":
1679
+ return "\r";
1680
+ case "\\b":
1681
+ return "\b";
1682
+ case "\\t":
1683
+ return "\t";
1684
+ case "\\f":
1685
+ return "\f";
1686
+ case "\\x3C":
1687
+ return "<";
1688
+ case "\\u2028":
1689
+ return "\u2028";
1690
+ case "\\u2029":
1691
+ return "\u2029";
1692
+ default:
1693
+ return str;
1694
+ }
1695
+ }
1696
+ function deserializeString(str) {
1697
+ return str.replace(/(\\\\|\\"|\\n|\\r|\\b|\\t|\\f|\\u2028|\\u2029|\\x3C)/g, deserializeReplacer);
1698
+ }
1699
+ var REFERENCES_KEY = "__SEROVAL_REFS__";
1700
+ var GLOBAL_CONTEXT_REFERENCES = "$R";
1701
+ var GLOBAL_CONTEXT_R = `self.${GLOBAL_CONTEXT_REFERENCES}`;
1702
+ var INV_REFERENCE = /* @__PURE__ */ new Map;
1703
+ function hasReference(id) {
1704
+ return INV_REFERENCE.has(id);
1705
+ }
1706
+ function getReference(id) {
1707
+ if (hasReference(id)) {
1708
+ return INV_REFERENCE.get(id);
1709
+ }
1710
+ throw new SerovalMissingReferenceForIdError(id);
1711
+ }
1712
+ if (typeof globalThis !== "undefined") {
1713
+ Object.defineProperty(globalThis, REFERENCES_KEY, {
1714
+ value: INV_REFERENCE,
1715
+ configurable: true,
1716
+ writable: false,
1717
+ enumerable: false
1718
+ });
1719
+ } else if (typeof window !== "undefined") {
1720
+ Object.defineProperty(window, REFERENCES_KEY, {
1721
+ value: INV_REFERENCE,
1722
+ configurable: true,
1723
+ writable: false,
1724
+ enumerable: false
1725
+ });
1726
+ } else if (typeof self !== "undefined") {
1727
+ Object.defineProperty(self, REFERENCES_KEY, {
1728
+ value: INV_REFERENCE,
1729
+ configurable: true,
1730
+ writable: false,
1731
+ enumerable: false
1732
+ });
1733
+ } else if (typeof global !== "undefined") {
1734
+ Object.defineProperty(global, REFERENCES_KEY, {
1735
+ value: INV_REFERENCE,
1736
+ configurable: true,
1737
+ writable: false,
1738
+ enumerable: false
1739
+ });
1740
+ }
1741
+ var { toString: objectToString } = Object.prototype;
1742
+ function getErrorMessageDev(type, cause) {
1743
+ if (cause instanceof Error) {
1744
+ return `Seroval caught an error during the ${type} process.
1745
+
1746
+ ${cause.name}
1747
+ ${cause.message}
1748
+
1749
+ - For more information, please check the "cause" property of this error.
1750
+ - If you believe this is an error in Seroval, please submit an issue at https://github.com/lxsmnsyc/seroval/issues/new`;
1751
+ }
1752
+ return `Seroval caught an error during the ${type} process.
1753
+
1754
+ "${objectToString.call(cause)}"
1755
+
1756
+ For more information, please check the "cause" property of this error.`;
1757
+ }
1758
+ var getErrorMessage = (type, cause) => getErrorMessageDev(type, cause);
1759
+ var SerovalError = class extends Error {
1760
+ constructor(type, cause) {
1761
+ super(getErrorMessage(type, cause));
1762
+ this.cause = cause;
1763
+ }
1764
+ };
1765
+ var SerovalDeserializationError = class extends SerovalError {
1766
+ constructor(cause) {
1767
+ super("deserialization", cause);
1768
+ }
1769
+ };
1770
+ var SerovalUnsupportedNodeError = class extends Error {
1771
+ constructor(node) {
1772
+ super('Unsupported node type "' + node.t + '".');
1773
+ }
1774
+ };
1775
+ var SerovalMissingPluginError = class extends Error {
1776
+ constructor(tag) {
1777
+ super('Missing plugin for tag "' + tag + '".');
1778
+ }
1779
+ };
1780
+ var SerovalMissingInstanceError = class extends Error {
1781
+ constructor(tag) {
1782
+ super('Missing "' + tag + '" instance.');
1783
+ }
1784
+ };
1785
+ var SerovalMissingReferenceForIdError = class extends Error {
1786
+ constructor(id) {
1787
+ super('Missing reference for id "' + serializeString(id) + '"');
1788
+ }
1789
+ };
1790
+ var SerovalUnknownTypedArrayError = class extends Error {
1791
+ constructor(name) {
1792
+ super('Unknown TypedArray "' + name + '"');
1793
+ }
1794
+ };
1795
+ var SerovalMalformedNodeError = class extends Error {
1796
+ constructor(node) {
1797
+ super('Malformed node type "' + node.t + '".');
1798
+ }
1799
+ };
1800
+ var SerovalDepthLimitError = class extends Error {
1801
+ constructor(limit) {
1802
+ super("Depth limit of " + limit + " reached");
1803
+ }
1804
+ };
1805
+ var PROMISE_CONSTRUCTOR = () => {
1806
+ const resolver = {
1807
+ p: 0,
1808
+ s: 0,
1809
+ f: 0
1810
+ };
1811
+ resolver.p = new Promise((resolve, reject) => {
1812
+ resolver.s = resolve;
1813
+ resolver.f = reject;
1814
+ });
1815
+ return resolver;
1816
+ };
1817
+ var STREAM_CONSTRUCTOR = () => {
1818
+ const buffer = [];
1819
+ const listeners = [];
1820
+ let alive = true;
1821
+ let success = false;
1822
+ let count = 0;
1823
+ const flush = (value, mode, x) => {
1824
+ for (x = 0;x < count; x++) {
1825
+ if (listeners[x]) {
1826
+ listeners[x][mode](value);
1827
+ }
1828
+ }
1829
+ };
1830
+ const up = (listener, x, z, current) => {
1831
+ for (x = 0, z = buffer.length;x < z; x++) {
1832
+ current = buffer[x];
1833
+ if (!alive && x === z - 1) {
1834
+ listener[success ? "return" : "throw"](current);
1835
+ } else {
1836
+ listener.next(current);
1837
+ }
1838
+ }
1839
+ };
1840
+ const on = (listener, temp) => {
1841
+ if (alive) {
1842
+ temp = count++;
1843
+ listeners[temp] = listener;
1844
+ }
1845
+ up(listener);
1846
+ return () => {
1847
+ if (alive) {
1848
+ listeners[temp] = listeners[count];
1849
+ listeners[count--] = undefined;
1850
+ }
1851
+ };
1852
+ };
1853
+ return {
1854
+ __SEROVAL_STREAM__: true,
1855
+ on: (listener) => on(listener),
1856
+ next: (value) => {
1857
+ if (alive) {
1858
+ buffer.push(value);
1859
+ flush(value, "next");
1860
+ }
1861
+ },
1862
+ throw: (value) => {
1863
+ if (alive) {
1864
+ buffer.push(value);
1865
+ flush(value, "throw");
1866
+ alive = false;
1867
+ success = false;
1868
+ listeners.length = 0;
1869
+ }
1870
+ },
1871
+ return: (value) => {
1872
+ if (alive) {
1873
+ buffer.push(value);
1874
+ flush(value, "return");
1875
+ alive = false;
1876
+ success = true;
1877
+ listeners.length = 0;
1878
+ }
1879
+ }
1880
+ };
1881
+ };
1882
+ var ITERATOR_CONSTRUCTOR = (symbol) => (sequence) => () => {
1883
+ let index = 0;
1884
+ const instance = {
1885
+ [symbol]: () => instance,
1886
+ next: () => {
1887
+ if (index > sequence.d) {
1888
+ return {
1889
+ done: true,
1890
+ value: undefined
1891
+ };
1892
+ }
1893
+ const currentIndex = index++;
1894
+ const data = sequence.v[currentIndex];
1895
+ if (currentIndex === sequence.t) {
1896
+ throw data;
1897
+ }
1898
+ return {
1899
+ done: currentIndex === sequence.d,
1900
+ value: data
1901
+ };
1902
+ }
1903
+ };
1904
+ return instance;
1905
+ };
1906
+ var ASYNC_ITERATOR_CONSTRUCTOR = (symbol, createPromise) => (stream) => () => {
1907
+ let count = 0;
1908
+ let doneAt = -1;
1909
+ let isThrow = false;
1910
+ const buffer = [];
1911
+ const pending = [];
1912
+ const finalize = (i = 0, len = pending.length) => {
1913
+ for (;i < len; i++) {
1914
+ pending[i].s({
1915
+ done: true,
1916
+ value: undefined
1917
+ });
1918
+ }
1919
+ };
1920
+ stream.on({
1921
+ next: (value) => {
1922
+ const temp = pending.shift();
1923
+ if (temp) {
1924
+ temp.s({ done: false, value });
1925
+ }
1926
+ buffer.push(value);
1927
+ },
1928
+ throw: (value) => {
1929
+ const temp = pending.shift();
1930
+ if (temp) {
1931
+ temp.f(value);
1932
+ }
1933
+ finalize();
1934
+ doneAt = buffer.length;
1935
+ isThrow = true;
1936
+ buffer.push(value);
1937
+ },
1938
+ return: (value) => {
1939
+ const temp = pending.shift();
1940
+ if (temp) {
1941
+ temp.s({ done: true, value });
1942
+ }
1943
+ finalize();
1944
+ doneAt = buffer.length;
1945
+ buffer.push(value);
1946
+ }
1947
+ });
1948
+ const instance = {
1949
+ [symbol]: () => instance,
1950
+ next: () => {
1951
+ if (doneAt === -1) {
1952
+ const index2 = count++;
1953
+ if (index2 >= buffer.length) {
1954
+ const temp = createPromise();
1955
+ pending.push(temp);
1956
+ return temp.p;
1957
+ }
1958
+ return {
1959
+ done: false,
1960
+ value: buffer[index2]
1961
+ };
1962
+ }
1963
+ if (count > doneAt) {
1964
+ return {
1965
+ done: true,
1966
+ value: undefined
1967
+ };
1968
+ }
1969
+ const index = count++;
1970
+ const value = buffer[index];
1971
+ if (index !== doneAt) {
1972
+ return {
1973
+ done: false,
1974
+ value
1975
+ };
1976
+ }
1977
+ if (isThrow) {
1978
+ throw value;
1979
+ }
1980
+ return {
1981
+ done: true,
1982
+ value
1983
+ };
1984
+ }
1985
+ };
1986
+ return instance;
1987
+ };
1988
+ var ARRAY_BUFFER_CONSTRUCTOR = (b64) => {
1989
+ const decoded = atob(b64);
1990
+ const length = decoded.length;
1991
+ const arr = new Uint8Array(length);
1992
+ for (let i = 0;i < length; i++) {
1993
+ arr[i] = decoded.charCodeAt(i);
1994
+ }
1995
+ return arr.buffer;
1996
+ };
1997
+ function createSequence(values, throwAt, doneAt) {
1998
+ return {
1999
+ __SEROVAL_SEQUENCE__: true,
2000
+ v: values,
2001
+ t: throwAt,
2002
+ d: doneAt
2003
+ };
2004
+ }
2005
+ var createIterator = ITERATOR_CONSTRUCTOR(SYM_ITERATOR);
2006
+ function sequenceToIterator(sequence) {
2007
+ return createIterator(sequence);
2008
+ }
2009
+ function createStream() {
2010
+ return STREAM_CONSTRUCTOR();
2011
+ }
2012
+ var createAsyncIterable = ASYNC_ITERATOR_CONSTRUCTOR(SYM_ASYNC_ITERATOR, PROMISE_CONSTRUCTOR);
2013
+ function streamToAsyncIterable(stream) {
2014
+ return createAsyncIterable(stream);
2015
+ }
2016
+ function dedupePlugins(deduped, plugins) {
2017
+ for (let i = 0, len = plugins.length;i < len; i++) {
2018
+ const current = plugins[i];
2019
+ if (!deduped.has(current)) {
2020
+ deduped.add(current);
2021
+ if (current.extends) {
2022
+ dedupePlugins(deduped, current.extends);
2023
+ }
2024
+ }
2025
+ }
2026
+ }
2027
+ function resolvePlugins(plugins) {
2028
+ if (plugins) {
2029
+ const deduped = /* @__PURE__ */ new Set;
2030
+ dedupePlugins(deduped, plugins);
2031
+ return [...deduped];
2032
+ }
2033
+ return;
2034
+ }
2035
+ function getTypedArrayConstructor(name) {
2036
+ switch (name) {
2037
+ case "Int8Array":
2038
+ return Int8Array;
2039
+ case "Int16Array":
2040
+ return Int16Array;
2041
+ case "Int32Array":
2042
+ return Int32Array;
2043
+ case "Uint8Array":
2044
+ return Uint8Array;
2045
+ case "Uint16Array":
2046
+ return Uint16Array;
2047
+ case "Uint32Array":
2048
+ return Uint32Array;
2049
+ case "Uint8ClampedArray":
2050
+ return Uint8ClampedArray;
2051
+ case "Float32Array":
2052
+ return Float32Array;
2053
+ case "Float64Array":
2054
+ return Float64Array;
2055
+ case "BigInt64Array":
2056
+ return BigInt64Array;
2057
+ case "BigUint64Array":
2058
+ return BigUint64Array;
2059
+ default:
2060
+ throw new SerovalUnknownTypedArrayError(name);
2061
+ }
2062
+ }
2063
+ var MAX_BASE64_LENGTH = 1e6;
2064
+ var MAX_BIGINT_LENGTH = 1e4;
2065
+ var MAX_REGEXP_SOURCE_LENGTH = 20000;
2066
+ function applyObjectFlag(obj, flag) {
2067
+ switch (flag) {
2068
+ case 3:
2069
+ return Object.freeze(obj);
2070
+ case 1:
2071
+ return Object.preventExtensions(obj);
2072
+ case 2:
2073
+ return Object.seal(obj);
2074
+ default:
2075
+ return obj;
2076
+ }
2077
+ }
2078
+ var DEFAULT_DEPTH_LIMIT = 1000;
2079
+ function createBaseDeserializerContext(mode, options) {
2080
+ var _a;
2081
+ const refs = options.refs || /* @__PURE__ */ new Map;
2082
+ if (!("types" in refs)) {
2083
+ Object.assign(refs, {
2084
+ types: /* @__PURE__ */ new Map
2085
+ });
2086
+ }
2087
+ return {
2088
+ mode,
2089
+ plugins: options.plugins,
2090
+ refs,
2091
+ features: (_a = options.features) != null ? _a : ALL_ENABLED ^ (options.disabledFeatures || 0),
2092
+ depthLimit: options.depthLimit || DEFAULT_DEPTH_LIMIT
2093
+ };
2094
+ }
2095
+ function createCrossDeserializerContext(options) {
2096
+ return {
2097
+ mode: 2,
2098
+ base: createBaseDeserializerContext(2, options),
2099
+ child: NIL
2100
+ };
2101
+ }
2102
+ var DeserializePluginContext = class {
2103
+ constructor(_p, depth) {
2104
+ this._p = _p;
2105
+ this.depth = depth;
2106
+ }
2107
+ deserialize(node) {
2108
+ return deserialize(this._p, this.depth, node);
2109
+ }
2110
+ };
2111
+ function guardIndexedValue(ctx, id) {
2112
+ if (id < 0 || !Number.isFinite(id) || !Number.isInteger(id)) {
2113
+ throw new SerovalMalformedNodeError({
2114
+ t: 4,
2115
+ i: id
2116
+ });
2117
+ }
2118
+ if (ctx.refs.has(id)) {
2119
+ throw new Error("Conflicted ref id: " + id);
2120
+ }
2121
+ }
2122
+ function assignIndexedValueVanilla(ctx, id, value) {
2123
+ guardIndexedValue(ctx.base, id);
2124
+ if (ctx.state.marked.has(id)) {
2125
+ ctx.base.refs.set(id, value);
2126
+ }
2127
+ return value;
2128
+ }
2129
+ function assignIndexedValueCross(ctx, id, value) {
2130
+ guardIndexedValue(ctx.base, id);
2131
+ ctx.base.refs.set(id, value);
2132
+ return value;
2133
+ }
2134
+ function assignIndexedValue(ctx, id, value) {
2135
+ return ctx.mode === 1 ? assignIndexedValueVanilla(ctx, id, value) : assignIndexedValueCross(ctx, id, value);
2136
+ }
2137
+ function deserializeKnownValue(node, record, key) {
2138
+ if (Object.hasOwn(record, key)) {
2139
+ return record[key];
2140
+ }
2141
+ throw new SerovalMalformedNodeError(node);
2142
+ }
2143
+ function deserializeReference(ctx, node) {
2144
+ return assignIndexedValue(ctx, node.i, getReference(deserializeString(node.s)));
2145
+ }
2146
+ function deserializeArray(ctx, depth, node) {
2147
+ const items = node.a;
2148
+ const len = items.length;
2149
+ const result = assignIndexedValue(ctx, node.i, new Array(len));
2150
+ for (let i = 0, item;i < len; i++) {
2151
+ item = items[i];
2152
+ if (item) {
2153
+ result[i] = deserialize(ctx, depth, item);
2154
+ }
2155
+ }
2156
+ applyObjectFlag(result, node.o);
2157
+ return result;
2158
+ }
2159
+ function isValidKey(key) {
2160
+ switch (key) {
2161
+ case "constructor":
2162
+ case "__proto__":
2163
+ case "prototype":
2164
+ case "__defineGetter__":
2165
+ case "__defineSetter__":
2166
+ case "__lookupGetter__":
2167
+ case "__lookupSetter__":
2168
+ return false;
2169
+ default:
2170
+ return true;
2171
+ }
2172
+ }
2173
+ function isValidSymbol(symbol) {
2174
+ switch (symbol) {
2175
+ case SYM_ASYNC_ITERATOR:
2176
+ case SYM_IS_CONCAT_SPREADABLE:
2177
+ case SYM_TO_STRING_TAG:
2178
+ case SYM_ITERATOR:
2179
+ return true;
2180
+ default:
2181
+ return false;
2182
+ }
2183
+ }
2184
+ function assignStringProperty(object, key, value) {
2185
+ if (isValidKey(key)) {
2186
+ object[key] = value;
2187
+ } else {
2188
+ Object.defineProperty(object, key, {
2189
+ value,
2190
+ configurable: true,
2191
+ enumerable: true,
2192
+ writable: true
2193
+ });
2194
+ }
2195
+ }
2196
+ function assignProperty(ctx, depth, object, key, value) {
2197
+ if (typeof key === "string") {
2198
+ assignStringProperty(object, deserializeString(key), deserialize(ctx, depth, value));
2199
+ } else {
2200
+ const actual = deserialize(ctx, depth, key);
2201
+ switch (typeof actual) {
2202
+ case "string":
2203
+ assignStringProperty(object, actual, deserialize(ctx, depth, value));
2204
+ break;
2205
+ case "symbol":
2206
+ if (isValidSymbol(actual)) {
2207
+ object[actual] = deserialize(ctx, depth, value);
2208
+ }
2209
+ break;
2210
+ default:
2211
+ throw new SerovalMalformedNodeError(key);
2212
+ }
2213
+ }
2214
+ }
2215
+ function assignNodeType(ctx, id, type) {
2216
+ ctx.base.refs.types.set(id, type);
2217
+ }
2218
+ function validateNodeType(ctx, node, id, type) {
2219
+ if (ctx.base.refs.types.get(id) !== type) {
2220
+ throw new SerovalMalformedNodeError(node);
2221
+ }
2222
+ }
2223
+ function deserializeProperties(ctx, depth, node, result) {
2224
+ const keys = node.k;
2225
+ const len = keys.length;
2226
+ if (len > 0) {
2227
+ for (let i = 0, vals = node.v, len2 = keys.length;i < len2; i++) {
2228
+ assignProperty(ctx, depth, result, keys[i], vals[i]);
2229
+ }
2230
+ }
2231
+ return result;
2232
+ }
2233
+ function deserializeObject(ctx, depth, node) {
2234
+ const result = assignIndexedValue(ctx, node.i, node.t === 10 ? {} : /* @__PURE__ */ Object.create(null));
2235
+ deserializeProperties(ctx, depth, node.p, result);
2236
+ applyObjectFlag(result, node.o);
2237
+ return result;
2238
+ }
2239
+ function deserializeDate(ctx, node) {
2240
+ return assignIndexedValue(ctx, node.i, new Date(node.s));
2241
+ }
2242
+ function deserializeRegExp(ctx, node) {
2243
+ if (ctx.base.features & 32) {
2244
+ const source = deserializeString(node.c);
2245
+ if (source.length > MAX_REGEXP_SOURCE_LENGTH) {
2246
+ throw new SerovalMalformedNodeError(node);
2247
+ }
2248
+ return assignIndexedValue(ctx, node.i, new RegExp(source, node.m));
2249
+ }
2250
+ throw new SerovalUnsupportedNodeError(node);
2251
+ }
2252
+ function deserializeSet(ctx, depth, node) {
2253
+ const result = assignIndexedValue(ctx, node.i, /* @__PURE__ */ new Set);
2254
+ for (let i = 0, items = node.a, len = items.length;i < len; i++) {
2255
+ result.add(deserialize(ctx, depth, items[i]));
2256
+ }
2257
+ return result;
2258
+ }
2259
+ function deserializeMap(ctx, depth, node) {
2260
+ const result = assignIndexedValue(ctx, node.i, /* @__PURE__ */ new Map);
2261
+ for (let i = 0, keys = node.e.k, vals = node.e.v, len = keys.length;i < len; i++) {
2262
+ result.set(deserialize(ctx, depth, keys[i]), deserialize(ctx, depth, vals[i]));
2263
+ }
2264
+ return result;
2265
+ }
2266
+ function deserializeArrayBuffer(ctx, node) {
2267
+ if (node.s.length > MAX_BASE64_LENGTH) {
2268
+ throw new SerovalMalformedNodeError(node);
2269
+ }
2270
+ const result = assignIndexedValue(ctx, node.i, ARRAY_BUFFER_CONSTRUCTOR(deserializeString(node.s)));
2271
+ return result;
2272
+ }
2273
+ function deserializeTypedArray(ctx, depth, node) {
2274
+ var _a;
2275
+ const construct = getTypedArrayConstructor(node.c);
2276
+ const source = deserialize(ctx, depth, node.f);
2277
+ const offset = (_a = node.b) != null ? _a : 0;
2278
+ if (offset < 0 || offset > source.byteLength) {
2279
+ throw new SerovalMalformedNodeError(node);
2280
+ }
2281
+ const result = assignIndexedValue(ctx, node.i, new construct(source, offset, node.l));
2282
+ return result;
2283
+ }
2284
+ function deserializeDataView(ctx, depth, node) {
2285
+ var _a;
2286
+ const source = deserialize(ctx, depth, node.f);
2287
+ const offset = (_a = node.b) != null ? _a : 0;
2288
+ if (offset < 0 || offset > source.byteLength) {
2289
+ throw new SerovalMalformedNodeError(node);
2290
+ }
2291
+ const result = assignIndexedValue(ctx, node.i, new DataView(source, offset, node.l));
2292
+ return result;
2293
+ }
2294
+ function deserializeDictionary(ctx, depth, node, result) {
2295
+ if (node.p) {
2296
+ const fields = deserializeProperties(ctx, depth, node.p, {});
2297
+ Object.defineProperties(result, Object.getOwnPropertyDescriptors(fields));
2298
+ }
2299
+ return result;
2300
+ }
2301
+ function deserializeAggregateError(ctx, depth, node) {
2302
+ const result = assignIndexedValue(ctx, node.i, new AggregateError([], deserializeString(node.m)));
2303
+ return deserializeDictionary(ctx, depth, node, result);
2304
+ }
2305
+ function deserializeError(ctx, depth, node) {
2306
+ const construct = deserializeKnownValue(node, ERROR_CONSTRUCTOR, node.s);
2307
+ const result = assignIndexedValue(ctx, node.i, new construct(deserializeString(node.m)));
2308
+ return deserializeDictionary(ctx, depth, node, result);
2309
+ }
2310
+ function deserializePromise(ctx, depth, node) {
2311
+ const deferred = PROMISE_CONSTRUCTOR();
2312
+ const result = assignIndexedValue(ctx, node.i, deferred.p);
2313
+ const deserialized = deserialize(ctx, depth, node.f);
2314
+ if (node.s) {
2315
+ deferred.s(deserialized);
2316
+ } else {
2317
+ deferred.f(deserialized);
2318
+ }
2319
+ return result;
2320
+ }
2321
+ function deserializeBoxed(ctx, depth, node) {
2322
+ return assignIndexedValue(ctx, node.i, Object(deserialize(ctx, depth, node.f)));
2323
+ }
2324
+ function deserializePlugin(ctx, depth, node) {
2325
+ const currentPlugins = ctx.base.plugins;
2326
+ if (currentPlugins) {
2327
+ const tag = deserializeString(node.c);
2328
+ for (let i = 0, len = currentPlugins.length;i < len; i++) {
2329
+ const plugin = currentPlugins[i];
2330
+ if (plugin.tag === tag) {
2331
+ return assignIndexedValue(ctx, node.i, plugin.deserialize(node.s, new DeserializePluginContext(ctx, depth), {
2332
+ id: node.i
2333
+ }));
2334
+ }
2335
+ }
2336
+ }
2337
+ throw new SerovalMissingPluginError(node.c);
2338
+ }
2339
+ function deserializePromiseConstructor(ctx, node) {
2340
+ const value = assignIndexedValue(ctx, node.i, assignIndexedValue(ctx, node.s, PROMISE_CONSTRUCTOR()).p);
2341
+ assignNodeType(ctx, node.s, 22);
2342
+ return value;
2343
+ }
2344
+ function deserializePromiseResolve(ctx, depth, node) {
2345
+ const deferred = ctx.base.refs.get(node.i);
2346
+ if (deferred) {
2347
+ validateNodeType(ctx, node, node.i, 22);
2348
+ deferred.s(deserialize(ctx, depth, node.a[1]));
2349
+ return NIL;
2350
+ }
2351
+ throw new SerovalMissingInstanceError("Promise");
2352
+ }
2353
+ function deserializePromiseReject(ctx, depth, node) {
2354
+ const deferred = ctx.base.refs.get(node.i);
2355
+ if (deferred) {
2356
+ validateNodeType(ctx, node, node.i, 22);
2357
+ deferred.f(deserialize(ctx, depth, node.a[1]));
2358
+ return NIL;
2359
+ }
2360
+ throw new SerovalMissingInstanceError("Promise");
2361
+ }
2362
+ function deserializeIteratorFactoryInstance(ctx, depth, node) {
2363
+ deserialize(ctx, depth, node.a[0]);
2364
+ const source = deserialize(ctx, depth, node.a[1]);
2365
+ return sequenceToIterator(source);
2366
+ }
2367
+ function deserializeAsyncIteratorFactoryInstance(ctx, depth, node) {
2368
+ deserialize(ctx, depth, node.a[0]);
2369
+ const source = deserialize(ctx, depth, node.a[1]);
2370
+ return streamToAsyncIterable(source);
2371
+ }
2372
+ function deserializeStreamConstructor(ctx, depth, node) {
2373
+ const result = assignIndexedValue(ctx, node.i, createStream());
2374
+ assignNodeType(ctx, node.i, 31);
2375
+ const items = node.a;
2376
+ const len = items.length;
2377
+ if (len) {
2378
+ for (let i = 0;i < len; i++) {
2379
+ deserialize(ctx, depth, items[i]);
2380
+ }
2381
+ }
2382
+ return result;
2383
+ }
2384
+ function deserializeStreamNext(ctx, depth, node) {
2385
+ const deferred = ctx.base.refs.get(node.i);
2386
+ if (deferred) {
2387
+ validateNodeType(ctx, node, node.i, 31);
2388
+ deferred.next(deserialize(ctx, depth, node.f));
2389
+ return NIL;
2390
+ }
2391
+ throw new SerovalMissingInstanceError("Stream");
2392
+ }
2393
+ function deserializeStreamThrow(ctx, depth, node) {
2394
+ const deferred = ctx.base.refs.get(node.i);
2395
+ if (deferred) {
2396
+ validateNodeType(ctx, node, node.i, 31);
2397
+ deferred.throw(deserialize(ctx, depth, node.f));
2398
+ return NIL;
2399
+ }
2400
+ throw new SerovalMissingInstanceError("Stream");
2401
+ }
2402
+ function deserializeStreamReturn(ctx, depth, node) {
2403
+ const deferred = ctx.base.refs.get(node.i);
2404
+ if (deferred) {
2405
+ validateNodeType(ctx, node, node.i, 31);
2406
+ deferred.return(deserialize(ctx, depth, node.f));
2407
+ return NIL;
2408
+ }
2409
+ throw new SerovalMissingInstanceError("Stream");
2410
+ }
2411
+ function deserializeIteratorFactory(ctx, depth, node) {
2412
+ deserialize(ctx, depth, node.f);
2413
+ return NIL;
2414
+ }
2415
+ function deserializeAsyncIteratorFactory(ctx, depth, node) {
2416
+ deserialize(ctx, depth, node.a[1]);
2417
+ return NIL;
2418
+ }
2419
+ function deserializeSequence(ctx, depth, node) {
2420
+ const result = assignIndexedValue(ctx, node.i, createSequence([], node.s, node.l));
2421
+ for (let i = 0, len = node.a.length;i < len; i++) {
2422
+ result.v[i] = deserialize(ctx, depth, node.a[i]);
2423
+ }
2424
+ return result;
2425
+ }
2426
+ function deserialize(ctx, depth, node) {
2427
+ if (depth > ctx.base.depthLimit) {
2428
+ throw new SerovalDepthLimitError(ctx.base.depthLimit);
2429
+ }
2430
+ depth += 1;
2431
+ switch (node.t) {
2432
+ case 2:
2433
+ return deserializeKnownValue(node, CONSTANT_VAL, node.s);
2434
+ case 0:
2435
+ return Number(node.s);
2436
+ case 1:
2437
+ return deserializeString(String(node.s));
2438
+ case 3:
2439
+ if (String(node.s).length > MAX_BIGINT_LENGTH) {
2440
+ throw new SerovalMalformedNodeError(node);
2441
+ }
2442
+ return BigInt(node.s);
2443
+ case 4:
2444
+ return ctx.base.refs.get(node.i);
2445
+ case 18:
2446
+ return deserializeReference(ctx, node);
2447
+ case 9:
2448
+ return deserializeArray(ctx, depth, node);
2449
+ case 10:
2450
+ case 11:
2451
+ return deserializeObject(ctx, depth, node);
2452
+ case 5:
2453
+ return deserializeDate(ctx, node);
2454
+ case 6:
2455
+ return deserializeRegExp(ctx, node);
2456
+ case 7:
2457
+ return deserializeSet(ctx, depth, node);
2458
+ case 8:
2459
+ return deserializeMap(ctx, depth, node);
2460
+ case 19:
2461
+ return deserializeArrayBuffer(ctx, node);
2462
+ case 16:
2463
+ case 15:
2464
+ return deserializeTypedArray(ctx, depth, node);
2465
+ case 20:
2466
+ return deserializeDataView(ctx, depth, node);
2467
+ case 14:
2468
+ return deserializeAggregateError(ctx, depth, node);
2469
+ case 13:
2470
+ return deserializeError(ctx, depth, node);
2471
+ case 12:
2472
+ return deserializePromise(ctx, depth, node);
2473
+ case 17:
2474
+ return deserializeKnownValue(node, SYMBOL_REF, node.s);
2475
+ case 21:
2476
+ return deserializeBoxed(ctx, depth, node);
2477
+ case 25:
2478
+ return deserializePlugin(ctx, depth, node);
2479
+ case 22:
2480
+ return deserializePromiseConstructor(ctx, node);
2481
+ case 23:
2482
+ return deserializePromiseResolve(ctx, depth, node);
2483
+ case 24:
2484
+ return deserializePromiseReject(ctx, depth, node);
2485
+ case 28:
2486
+ return deserializeIteratorFactoryInstance(ctx, depth, node);
2487
+ case 30:
2488
+ return deserializeAsyncIteratorFactoryInstance(ctx, depth, node);
2489
+ case 31:
2490
+ return deserializeStreamConstructor(ctx, depth, node);
2491
+ case 32:
2492
+ return deserializeStreamNext(ctx, depth, node);
2493
+ case 33:
2494
+ return deserializeStreamThrow(ctx, depth, node);
2495
+ case 34:
2496
+ return deserializeStreamReturn(ctx, depth, node);
2497
+ case 27:
2498
+ return deserializeIteratorFactory(ctx, depth, node);
2499
+ case 29:
2500
+ return deserializeAsyncIteratorFactory(ctx, depth, node);
2501
+ case 35:
2502
+ return deserializeSequence(ctx, depth, node);
2503
+ default:
2504
+ throw new SerovalUnsupportedNodeError(node);
2505
+ }
2506
+ }
2507
+ function deserializeTop(ctx, node) {
2508
+ try {
2509
+ return deserialize(ctx, 0, node);
2510
+ } catch (error) {
2511
+ throw new SerovalDeserializationError(error);
2512
+ }
2513
+ }
2514
+ var REF_START_CHARS = "hjkmoquxzABCDEFGHIJKLNPQRTUVWXYZ$_";
2515
+ var REF_START_CHARS_LEN = REF_START_CHARS.length;
2516
+ var REF_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$_";
2517
+ var REF_CHARS_LEN = REF_CHARS.length;
2518
+ function fromCrossJSON(source, options) {
2519
+ const plugins = resolvePlugins(options.plugins);
2520
+ const ctx = createCrossDeserializerContext({
2521
+ plugins,
2522
+ refs: options.refs,
2523
+ features: options.features,
2524
+ disabledFeatures: options.disabledFeatures,
2525
+ depthLimit: options.depthLimit
2526
+ });
2527
+ return deserializeTop(ctx, source);
2528
+ }
2529
+
2530
+ // src/shared/deferred-ndjson.ts
2531
+ function makeAbortError(reason) {
2532
+ const message = reason instanceof Error ? reason.message || "The operation was aborted." : "aborted";
2533
+ const err = new Error(message);
2534
+ err.name = "AbortError";
2535
+ return err;
2536
+ }
2537
+ async function parseDeferredNdjson(stream, signal) {
2538
+ const reader = stream.getReader();
2539
+ const decoder = new TextDecoder;
2540
+ let buffer = "";
2541
+ let abortHandler;
2542
+ const cancelReader = (reason) => {
2543
+ reader.cancel(reason).catch(() => {});
2544
+ };
2545
+ if (signal?.aborted) {
2546
+ const err = makeAbortError(signal.reason);
2547
+ await reader.cancel(err).catch(() => {});
2548
+ try {
2549
+ reader.releaseLock();
2550
+ } catch {}
2551
+ return { syncData: {}, deferredPromises: {} };
2552
+ }
2553
+ if (signal !== undefined && !signal.aborted) {
2554
+ abortHandler = () => cancelReader(makeAbortError(signal.reason));
2555
+ signal.addEventListener("abort", abortHandler, { once: true });
2556
+ }
2557
+ const cleanupAbortHandler = () => {
2558
+ if (signal !== undefined && abortHandler !== undefined) {
2559
+ signal.removeEventListener("abort", abortHandler);
2560
+ abortHandler = undefined;
2561
+ }
2562
+ };
2563
+ async function readLine() {
2564
+ for (;; ) {
2565
+ const newlineIndex = buffer.indexOf(`
2566
+ `);
2567
+ if (newlineIndex >= 0) {
2568
+ const line = buffer.slice(0, newlineIndex).trim();
2569
+ buffer = buffer.slice(newlineIndex + 1);
2570
+ if (line.length > 0) {
2571
+ return line;
2572
+ }
2573
+ continue;
2574
+ }
2575
+ const { done, value } = await reader.read();
2576
+ if (done) {
2577
+ buffer += decoder.decode();
2578
+ const line = buffer.trim();
2579
+ buffer = "";
2580
+ return line.length > 0 ? line : undefined;
2581
+ }
2582
+ buffer += decoder.decode(value, { stream: true });
2583
+ }
2584
+ }
2585
+ const firstLine = await readLine();
2586
+ if (!firstLine) {
2587
+ cleanupAbortHandler();
2588
+ try {
2589
+ reader.releaseLock();
2590
+ } catch {}
2591
+ return { syncData: {}, deferredPromises: {} };
2592
+ }
2593
+ const node = JSON.parse(firstLine);
2594
+ const deserialized = fromCrossJSON(node, {});
2595
+ const syncData = {};
2596
+ const deferredPromises = {};
2597
+ const resolvers = {};
2598
+ const deferredKeys = Array.isArray(deserialized.__furinDeferredKeys) ? deserialized.__furinDeferredKeys.filter((key) => typeof key === "string") : [];
2599
+ for (const [key, value] of Object.entries(deserialized)) {
2600
+ if (key === "__furinDeferredKeys") {
2601
+ continue;
2602
+ }
2603
+ if (value instanceof Promise) {
2604
+ deferredPromises[key] = value;
2605
+ } else {
2606
+ syncData[key] = value;
2607
+ }
2608
+ }
2609
+ for (const key of deferredKeys) {
2610
+ if (!(key in deferredPromises)) {
2611
+ deferredPromises[key] = new Promise((resolve, reject) => {
2612
+ resolvers[key] = { resolve, reject };
2613
+ });
2614
+ }
2615
+ }
2616
+ if (deferredKeys.length === 0) {
2617
+ cleanupAbortHandler();
2618
+ try {
2619
+ reader.releaseLock();
2620
+ } catch {}
2621
+ return { syncData, deferredPromises };
2622
+ }
2623
+ const rejectAllPending = (reason) => {
2624
+ for (const key of Object.keys(resolvers)) {
2625
+ resolvers[key]?.reject(reason);
2626
+ delete resolvers[key];
2627
+ }
2628
+ cancelReader(reason);
2629
+ };
2630
+ if (signal !== undefined) {
2631
+ if (signal.aborted) {
2632
+ rejectAllPending(makeAbortError(signal.reason));
2633
+ return { syncData, deferredPromises };
2634
+ }
2635
+ cleanupAbortHandler();
2636
+ abortHandler = () => {
2637
+ rejectAllPending(makeAbortError(signal.reason));
2638
+ };
2639
+ signal.addEventListener("abort", abortHandler, { once: true });
2640
+ }
2641
+ readDeferredLines(readLine, resolvers).then(() => {
2642
+ for (const key of Object.keys(resolvers)) {
2643
+ const err = new Error(`[furin] deferred stream closed before "${key}" was resolved`);
2644
+ resolvers[key]?.reject(err);
2645
+ delete resolvers[key];
2646
+ }
2647
+ }).catch((err) => {
2648
+ for (const resolver of Object.values(resolvers)) {
2649
+ resolver.reject(err);
2650
+ }
2651
+ }).finally(() => {
2652
+ cleanupAbortHandler();
2653
+ try {
2654
+ reader.releaseLock();
2655
+ } catch {}
2656
+ });
2657
+ return { syncData, deferredPromises };
2658
+ }
2659
+ async function readDeferredLines(readLine, resolvers) {
2660
+ for (;; ) {
2661
+ const line = await readLine();
2662
+ if (!line) {
2663
+ return;
2664
+ }
2665
+ const entry = JSON.parse(line);
2666
+ if (typeof entry.key !== "string" || !entry.value) {
2667
+ continue;
2668
+ }
2669
+ const resolver = resolvers[entry.key];
2670
+ if (!resolver) {
2671
+ continue;
2672
+ }
2673
+ const value = fromCrossJSON(entry.value, {});
2674
+ if (entry.action === "reject") {
2675
+ resolver.reject(value);
2676
+ } else {
2677
+ resolver.resolve(value);
2678
+ }
2679
+ delete resolvers[entry.key];
2680
+ }
2681
+ }
2682
+
2683
+ // src/client/router/spa-response.ts
2684
+ import { createElement as createElement2 } from "react";
2685
+ function isFurinErrorPayload(value) {
2686
+ if (!value || typeof value !== "object") {
2687
+ return false;
2688
+ }
2689
+ const v = value;
2690
+ return typeof v.digest === "string" && typeof v.message === "string" && typeof v.status === "number";
2691
+ }
2692
+ function classifySpaResponse(status, data) {
2693
+ if (!data) {
2694
+ return { kind: "bail" };
2695
+ }
2696
+ if (isFurinErrorPayload(data.__furinError)) {
2697
+ return { kind: "error", error: data.__furinError };
2698
+ }
2699
+ if ((status >= 200 && status < 300 || status === 404) && data.__furinStatus === 404) {
2700
+ const notFound = data.__furinNotFound;
2701
+ return { kind: "not-found", error: notFound ?? {} };
2702
+ }
2703
+ if (status >= 200 && status < 300) {
2704
+ return { kind: "ok" };
2705
+ }
2706
+ return { kind: "bail" };
2707
+ }
2708
+ function pickDeepestNotFound(boundaries) {
2709
+ if (!boundaries) {
2710
+ return;
2711
+ }
2712
+ for (let i = boundaries.length - 1;i >= 0; i--) {
2713
+ const seg = boundaries[i];
2714
+ if (seg?.notFound) {
2715
+ return seg.notFound;
2716
+ }
2717
+ }
2718
+ return;
2719
+ }
2720
+ var DefaultClientNotFoundFallback = ({ error }) => createElement2(DefaultNotFoundScreen, { message: error.message });
2721
+ function buildNotFoundPageElement(boundaries, error) {
2722
+ const Fallback = pickDeepestNotFound(boundaries) ?? DefaultClientNotFoundFallback;
2723
+ return createElement2(Fallback, { error });
2724
+ }
2725
+ async function parsePageResponse(res, basePath) {
2726
+ let finalHref;
2727
+ if (res.redirected) {
2728
+ const final = new URL(res.url);
2729
+ finalHref = toLogical(final.pathname, basePath) + final.search;
2730
+ }
2731
+ const html = await res.text();
2732
+ const doc = new DOMParser().parseFromString(html, "text/html");
2733
+ const dataEl = doc.getElementById("__FURIN_DATA__");
2734
+ const data = dataEl ? JSON.parse(dataEl.textContent || "{}") : null;
2735
+ return { data, finalHref, title: doc.title };
2736
+ }
2737
+ function buildDataEndpoint(basePath, logicalHref, staticMode) {
2738
+ if (!staticMode) {
2739
+ return `${basePath}/_furin/data?path=${encodeURIComponent(logicalHref)}`;
2740
+ }
2741
+ const parsed = new URL(logicalHref, "http://x");
2742
+ const pathname = parsed.pathname.replace(TRAILING_SLASHES_RE, "");
2743
+ return `${basePath}${pathname}/__furin_data.ndjson`;
2744
+ }
2745
+ function detectStaticMode() {
2746
+ if (typeof document === "undefined") {
2747
+ return false;
2748
+ }
2749
+ const meta = document.querySelector('meta[name="furin-mode"]');
2750
+ return meta?.content === "static";
2751
+ }
2752
+
2753
+ // src/client/router/provider.tsx
2754
+ function setPrefetchCacheEntry(cache, href, entry, maxSize) {
2755
+ if (cache.has(href)) {
2756
+ cache.delete(href);
2757
+ }
2758
+ cache.set(href, entry);
2759
+ if (cache.size > maxSize) {
2760
+ const oldest = cache.keys().next().value;
2761
+ if (typeof oldest === "string") {
2762
+ cache.delete(oldest);
2763
+ }
2764
+ }
2765
+ }
2766
+ function RouterProvider({
2767
+ routes,
2768
+ root,
2769
+ initialMatch,
2770
+ initialData,
2771
+ initialDigest,
2772
+ initialNotFound,
2773
+ autoRefresh,
2774
+ basePath,
2775
+ defaultPreload,
2776
+ defaultPreloadDelay,
2777
+ defaultPreloadStaleTime,
2778
+ prefetchCacheSize
2779
+ }) {
2780
+ const [state, setState] = useState(() => ({
2781
+ match: initialMatch,
2782
+ data: initialData,
2783
+ notFound: initialNotFound
2784
+ }));
2785
+ const [isNavigating, setIsNavigating] = useState(false);
2786
+ const [currentHref, setCurrentHref] = useState(() => {
2787
+ if (typeof window === "undefined") {
2788
+ return "/";
2789
+ }
2790
+ return normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
2791
+ });
2792
+ const prefetchCache = useRef(new Map);
2793
+ const navVersion = useRef(0);
2794
+ const navAbortRef = useRef(null);
2795
+ const pendingScrollRef = useRef(null);
2796
+ const currentMatchRef = useRef(initialMatch);
2797
+ const staticModeRef = useRef(detectStaticMode());
2798
+ const rootBoundaries = useMemo(() => {
2799
+ for (const route of routes) {
2800
+ const depth0 = route.segmentBoundaries?.find((b) => b.depth === 0);
2801
+ if (depth0) {
2802
+ return [depth0];
2803
+ }
2804
+ }
2805
+ return;
2806
+ }, [routes]);
2807
+ const resolveNoMatchState = useCallback(async (physicalHref, signal) => {
2808
+ const res = await fetch(physicalHref, { signal });
2809
+ if (isStaleDeployResponse(res)) {
2810
+ window.location.href = physicalHref;
2811
+ return null;
2812
+ }
2813
+ const { data, finalHref, title } = await parsePageResponse(res, basePath);
2814
+ const kind = classifySpaResponse(res.status, data);
2815
+ if (kind.kind !== "not-found") {
2816
+ return null;
2817
+ }
2818
+ const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = data ?? {};
2819
+ return {
2820
+ match: currentMatchRef.current,
2821
+ data: cleanData,
2822
+ title,
2823
+ finalHref,
2824
+ notFound: kind.error,
2825
+ notFoundBoundaries: rootBoundaries
2826
+ };
2827
+ }, [basePath, rootBoundaries]);
2828
+ const fetchPageState = useCallback(async (rawLogicalHref, signal) => {
2829
+ const logicalHref = normalizeHref(rawLogicalHref);
2830
+ try {
2831
+ const physicalHref = basePath + logicalHref;
2832
+ const url = new URL(physicalHref, window.location.origin);
2833
+ const logicalPathname = toLogical(url.pathname, basePath);
2834
+ const match = routes.find((r) => r.regex.test(logicalPathname));
2835
+ if (!match) {
2836
+ return await resolveNoMatchState(physicalHref, signal);
2837
+ }
2838
+ const dataEndpoint = buildDataEndpoint(basePath, logicalHref, staticModeRef.current);
2839
+ const [res, loadedMod] = await Promise.all([fetch(dataEndpoint, { signal }), match.load()]);
2840
+ if (isStaleDeployResponse(res)) {
2841
+ window.location.href = physicalHref;
2842
+ return null;
2843
+ }
2844
+ const body = res.body ?? new ReadableStream({ start: (c) => c.close() });
2845
+ let parsed;
2846
+ try {
2847
+ parsed = await parseDeferredNdjson(body, signal);
2848
+ } catch (parseErr) {
2849
+ _log.warn({
2850
+ action: "navigate_server_error",
2851
+ href: physicalHref,
2852
+ status: res.status,
2853
+ error: String(parseErr)
2854
+ });
2855
+ return null;
2856
+ }
2857
+ const { syncData, deferredPromises } = parsed;
2858
+ const {
2859
+ __furinStatus,
2860
+ __furinNotFound,
2861
+ __furinRedirect,
2862
+ __furinError,
2863
+ __furinTitle,
2864
+ ...cleanSyncData
2865
+ } = syncData;
2866
+ const finalHref = typeof __furinRedirect === "string" ? __furinRedirect : undefined;
2867
+ const data = { ...cleanSyncData, ...deferredPromises };
2868
+ const title = typeof __furinTitle === "string" ? __furinTitle : "";
2869
+ const loadedMatch = {
2870
+ ...match,
2871
+ component: loadedMod.default.component,
2872
+ pageRoute: loadedMod.default._route,
2873
+ segmentBoundaries: loadedMod.segmentBoundaries ?? match.segmentBoundaries
2874
+ };
2875
+ if (__furinError) {
2876
+ return {
2877
+ match: loadedMatch,
2878
+ data: {},
2879
+ title,
2880
+ finalHref,
2881
+ error: __furinError
2882
+ };
2883
+ }
2884
+ if (!res.ok && res.status !== 404) {
2885
+ _log.warn({ action: "navigate_server_error", href: physicalHref, status: res.status });
2886
+ return null;
2887
+ }
2888
+ if (__furinStatus === 404) {
2889
+ return {
2890
+ match: loadedMatch,
2891
+ data,
2892
+ title,
2893
+ finalHref,
2894
+ notFound: __furinNotFound ?? {}
2895
+ };
2896
+ }
2897
+ if (finalHref) {
2898
+ return { match: null, data, title, finalHref };
2899
+ }
2900
+ return { match: loadedMatch, data, title, finalHref };
2901
+ } catch (err) {
2902
+ _log.error({ action: "navigate_failed", href: basePath + logicalHref, error: String(err) });
2903
+ return null;
2904
+ }
2905
+ }, [routes, basePath, resolveNoMatchState]);
2906
+ const invalidatePrefetch = useCallback((path, type) => {
2907
+ const normalizedPath = stripHashFromHref(path);
2908
+ if (type === "page") {
2909
+ for (const key of [...prefetchCache.current.keys()]) {
2910
+ if (stripHashFromHref(key) === normalizedPath) {
2911
+ prefetchCache.current.delete(key);
2912
+ }
2913
+ }
2914
+ return;
2915
+ }
2916
+ const prefix = normalizedPath === "/" || normalizedPath.endsWith("/") ? normalizedPath : `${normalizedPath}/`;
2917
+ for (const key of [...prefetchCache.current.keys()]) {
2918
+ const normalizedKey = stripHashFromHref(key);
2919
+ if (normalizedKey === normalizedPath || normalizedKey.startsWith(prefix)) {
2920
+ prefetchCache.current.delete(key);
2921
+ }
2922
+ }
2923
+ }, []);
2924
+ const prefetch = useCallback((href, opts) => {
2925
+ const staleTime = opts?.staleTime ?? defaultPreloadStaleTime;
2926
+ const existing = prefetchCache.current.get(href);
2927
+ if (existing && !shouldRefetch(existing)) {
2928
+ return;
2929
+ }
2930
+ setPrefetchCacheEntry(prefetchCache.current, href, {
2931
+ promise: fetchPageState(href, undefined),
2932
+ createdAt: Date.now(),
2933
+ staleTime
2934
+ }, prefetchCacheSize);
2935
+ }, [fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]);
2936
+ async function resolveRedirectState(redirectLogical, myVersion, signal) {
2937
+ const cached = prefetchCache.current.get(redirectLogical);
2938
+ const state2 = cached && !shouldRefetch(cached) ? await cached.promise : await fetchPageState(redirectLogical, signal);
2939
+ if (navVersion.current !== myVersion) {
2940
+ return null;
2941
+ }
2942
+ return state2;
2943
+ }
2944
+ const navigate = useCallback(async function navigateTo(rawLogicalHref, opts) {
2945
+ const logicalHref = normalizeHref(rawLogicalHref);
2946
+ const myVersion = ++navVersion.current;
2947
+ navAbortRef.current?.abort();
2948
+ const navAbort = new AbortController;
2949
+ navAbortRef.current = navAbort;
2950
+ const navSignal = navAbort.signal;
2951
+ setIsNavigating(true);
2952
+ try {
2953
+ const cached = prefetchCache.current.get(logicalHref);
2954
+ let newState = cached && !shouldRefetch(cached) ? await cached.promise : await fetchPageState(logicalHref, navSignal);
2955
+ if (navVersion.current !== myVersion) {
2956
+ return;
2957
+ }
2958
+ if (newState && (!cached || shouldRefetch(cached))) {
2959
+ setPrefetchCacheEntry(prefetchCache.current, logicalHref, {
2960
+ promise: Promise.resolve(newState),
2961
+ createdAt: Date.now(),
2962
+ staleTime: defaultPreloadStaleTime
2963
+ }, prefetchCacheSize);
2964
+ }
2965
+ if (!newState) {
2966
+ _log.warn({
2967
+ action: "navigate_fallback",
2968
+ href: logicalHref,
2969
+ reason: "prefetch_returned_null"
2970
+ });
2971
+ window.location.href = basePath + logicalHref;
2972
+ return;
2973
+ }
2974
+ let redirectLogical;
2975
+ if (newState.finalHref && !newState.match && !newState.notFound) {
2976
+ redirectLogical = normalizeHref(newState.finalHref);
2977
+ const redirectPhysical = basePath + redirectLogical;
2978
+ window.history.replaceState({
2979
+ ...history.state ?? {},
2980
+ _furinKey: getHistoryKey(history.state) ?? generateHistoryKey()
2981
+ }, "", redirectPhysical);
2982
+ setCurrentHref(redirectLogical);
2983
+ const redirectState = await resolveRedirectState(redirectLogical, myVersion, navSignal);
2984
+ if (!redirectState) {
2985
+ if (navVersion.current === myVersion) {
2986
+ window.location.href = redirectPhysical;
2987
+ }
2988
+ return;
2989
+ }
2990
+ newState = redirectState;
2991
+ }
2992
+ currentMatchRef.current = newState.match;
2993
+ setState(newState);
2994
+ if (newState.title) {
2995
+ document.title = newState.title;
2996
+ }
2997
+ const effectiveLogical = newState.finalHref ?? redirectLogical ?? logicalHref;
2998
+ const physicalEffective = basePath + effectiveLogical;
2999
+ if (opts?.replace) {
3000
+ window.history.replaceState({
3001
+ ...history.state ?? {},
3002
+ _furinKey: getHistoryKey(history.state) ?? generateHistoryKey()
3003
+ }, "", physicalEffective);
3004
+ } else {
3005
+ const currentKey = getHistoryKey(history.state);
3006
+ if (currentKey) {
3007
+ saveScrollPosition(currentKey);
3008
+ }
3009
+ window.history.pushState({ _furinKey: generateHistoryKey() }, "", physicalEffective);
3010
+ }
3011
+ const effectiveUrl = new URL(physicalEffective, window.location.origin);
3012
+ const logicalPath = normalizeHref(toLogical(effectiveUrl.pathname, basePath));
3013
+ setCurrentHref(logicalPath + effectiveUrl.search);
3014
+ if (opts?.resetScroll ?? true) {
3015
+ pendingScrollRef.current = { type: "reset", href: physicalEffective };
3016
+ }
3017
+ } finally {
3018
+ if (navVersion.current === myVersion) {
3019
+ setIsNavigating(false);
3020
+ }
3021
+ }
3022
+ }, [basePath, fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]);
3023
+ const refresh = useCallback(async (opts) => {
3024
+ const logicalPath = toLogical(window.location.pathname, basePath);
3025
+ const logicalHref = logicalPath + window.location.search;
3026
+ invalidatePrefetch(logicalHref, "page");
3027
+ await navigate(logicalHref, { replace: true, resetScroll: opts?.resetScroll ?? false });
3028
+ }, [navigate, invalidatePrefetch, basePath]);
3029
+ useEffect(() => {
3030
+ if (typeof window !== "undefined") {
3031
+ window.__FURIN_HMR_REFRESH__ = refresh;
3032
+ return () => {
3033
+ window.__FURIN_HMR_REFRESH__ = undefined;
3034
+ };
3035
+ }
3036
+ }, [refresh]);
3037
+ const handlePopState = useCallback(() => {
3038
+ const destKey = getHistoryKey(history.state);
3039
+ const logicalPath = normalizeHref(toLogical(window.location.pathname, basePath));
3040
+ const logicalHref = logicalPath + window.location.search;
3041
+ const myVersion = ++navVersion.current;
3042
+ navAbortRef.current?.abort();
3043
+ const navAbort = new AbortController;
3044
+ navAbortRef.current = navAbort;
3045
+ const navSignal = navAbort.signal;
3046
+ setIsNavigating(true);
3047
+ (async () => {
3048
+ try {
3049
+ const cached = prefetchCache.current.get(logicalHref);
3050
+ let newState;
3051
+ if (cached && !shouldRefetch(cached)) {
3052
+ newState = await cached.promise;
3053
+ } else {
3054
+ newState = await fetchPageState(logicalHref, navSignal);
3055
+ }
3056
+ if (navVersion.current !== myVersion) {
3057
+ return;
3058
+ }
3059
+ if (!newState) {
3060
+ _log.warn({
3061
+ action: "popstate_fallback",
3062
+ href: logicalHref,
3063
+ reason: "fetchPageState_returned_null"
3064
+ });
3065
+ window.location.reload();
3066
+ return;
3067
+ }
3068
+ let redirectLogical;
3069
+ if (newState.finalHref && !newState.match && !newState.notFound) {
3070
+ redirectLogical = normalizeHref(newState.finalHref);
3071
+ window.history.replaceState(history.state, "", basePath + redirectLogical);
3072
+ setCurrentHref(redirectLogical);
3073
+ const redirectState = await resolveRedirectState(redirectLogical, myVersion, navSignal);
3074
+ if (!redirectState) {
3075
+ if (navVersion.current === myVersion) {
3076
+ window.location.reload();
3077
+ }
3078
+ return;
3079
+ }
3080
+ newState = redirectState;
3081
+ }
3082
+ currentMatchRef.current = newState.match;
3083
+ setState(newState);
3084
+ if (newState.title) {
3085
+ document.title = newState.title;
3086
+ }
3087
+ const effectiveLogical = newState.finalHref ?? redirectLogical ?? logicalHref;
3088
+ if (newState.finalHref) {
3089
+ window.history.replaceState(history.state, "", basePath + effectiveLogical);
3090
+ }
3091
+ setCurrentHref(normalizeHref(effectiveLogical));
3092
+ if (destKey) {
3093
+ pendingScrollRef.current = { type: "restore", key: destKey };
3094
+ } else {
3095
+ window.scrollTo({ top: 0, behavior: "instant" });
3096
+ }
3097
+ } finally {
3098
+ if (navVersion.current === myVersion) {
3099
+ setIsNavigating(false);
3100
+ }
3101
+ }
3102
+ })();
3103
+ }, [fetchPageState, basePath]);
3104
+ useEffect(() => {
3105
+ history.scrollRestoration = "manual";
3106
+ if (!getHistoryKey(history.state)) {
3107
+ history.replaceState({ ...history.state ?? {}, _furinKey: generateHistoryKey() }, "");
3108
+ }
3109
+ }, []);
3110
+ useLayoutEffect(() => {
3111
+ const instruction = pendingScrollRef.current;
3112
+ if (!instruction) {
3113
+ return;
3114
+ }
3115
+ pendingScrollRef.current = null;
3116
+ if (instruction.type === "restore") {
3117
+ try {
3118
+ const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
3119
+ const positions = raw ? JSON.parse(raw) : {};
3120
+ const y = positions[instruction.key] ?? 0;
3121
+ window.scrollTo({ top: y, behavior: "instant" });
3122
+ } catch {
3123
+ window.scrollTo({ top: 0, behavior: "instant" });
3124
+ }
3125
+ return;
3126
+ }
3127
+ const destUrl = new URL(instruction.href, window.location.origin);
3128
+ if (destUrl.hash) {
3129
+ const id = decodeURIComponent(destUrl.hash.slice(1));
3130
+ const element = document.getElementById(id);
3131
+ if (element) {
3132
+ element.scrollIntoView({ behavior: "instant", block: "start" });
3133
+ }
3134
+ } else {
3135
+ window.scrollTo({ top: 0, behavior: "instant" });
3136
+ }
3137
+ }, [currentHref]);
3138
+ useEffect(() => {
3139
+ window.addEventListener("popstate", handlePopState);
3140
+ return () => window.removeEventListener("popstate", handlePopState);
3141
+ }, [handlePopState]);
3142
+ useEffect(() => {
3143
+ if (typeof window === "undefined") {
3144
+ return;
3145
+ }
3146
+ const handler = (e) => {
3147
+ if (e.defaultPrevented) {
3148
+ return;
3149
+ }
3150
+ const anchor = e.target.closest("a");
3151
+ if (!(anchor instanceof HTMLAnchorElement)) {
3152
+ return;
3153
+ }
3154
+ if (anchor.closest("a[data-furin-link]")) {
3155
+ return;
3156
+ }
3157
+ const logicalHref = shouldInterceptClick(anchor, e, basePath, window.location.origin, window.location.pathname);
3158
+ if (logicalHref === null) {
3159
+ return;
3160
+ }
3161
+ e.preventDefault();
3162
+ navigate(logicalHref, { resetScroll: !logicalHref.includes("#") });
3163
+ };
3164
+ document.addEventListener("click", handler);
3165
+ return () => document.removeEventListener("click", handler);
3166
+ }, [navigate, basePath]);
3167
+ useEffect(() => {
3168
+ if (typeof window === "undefined") {
3169
+ return;
3170
+ }
3171
+ const originalFetch = window.fetch;
3172
+ const wrapped = async (...args) => {
3173
+ const response = await originalFetch.apply(window, args);
3174
+ const invalidated = [];
3175
+ applyRevalidateHeader(response.headers, (path, type = "page") => {
3176
+ invalidatePrefetch(path, type);
3177
+ invalidated.push({ path, type });
3178
+ });
3179
+ if (autoRefresh && invalidated.length > 0) {
3180
+ const currentLogicalPath = normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
3181
+ if (shouldAutoRefreshPath(currentLogicalPath, invalidated)) {
3182
+ refresh(undefined);
3183
+ }
3184
+ }
3185
+ return response;
3186
+ };
3187
+ Object.assign(wrapped, originalFetch);
3188
+ window.fetch = wrapped;
3189
+ return () => {
3190
+ window.fetch = originalFetch;
3191
+ };
3192
+ }, [invalidatePrefetch, refresh, autoRefresh, basePath]);
3193
+ let pageElement;
3194
+ if (state.notFound || !state.match) {
3195
+ pageElement = buildNotFoundPageElement(state.notFoundBoundaries ?? state.match?.segmentBoundaries ?? rootBoundaries, state.notFound ?? {});
3196
+ } else {
3197
+ pageElement = buildPageElement(state.match, root, state.data, {
3198
+ onReset: () => {
3199
+ refresh(undefined).catch((err) => {
3200
+ _log.error({ action: "boundary_reset_failed", error: String(err) });
3201
+ });
3202
+ },
3203
+ resetKey: currentHref
3204
+ }, state.error);
3205
+ }
3206
+ return buildRouterTree({
3207
+ basePath,
3208
+ currentHref,
3209
+ navigate,
3210
+ prefetch,
3211
+ refresh,
3212
+ invalidatePrefetch,
3213
+ isNavigating,
3214
+ defaultPreload,
3215
+ defaultPreloadDelay,
3216
+ defaultPreloadStaleTime
3217
+ }, pageElement, {
3218
+ digest: initialDigest,
3219
+ onReset: () => {
3220
+ refresh(undefined).catch((err) => {
3221
+ _log.error({ action: "boundary_reset_failed", error: String(err) });
3222
+ });
3223
+ },
3224
+ resetKey: currentHref
3225
+ });
3226
+ }
3227
+ // src/client/link.tsx
3228
+ function computeLinkView({
3229
+ to,
3230
+ search,
3231
+ hash,
3232
+ children,
3233
+ activeProps,
3234
+ inactiveProps
3235
+ }, router2) {
3236
+ const logicalHref = buildHref(to, search, hash);
3237
+ const logicalHrefWithoutHash = buildHref(to, search, undefined);
3238
+ const isAbsolute = logicalHref.startsWith("http://") || logicalHref.startsWith("https://") || logicalHref.startsWith("//");
3239
+ const href = isAbsolute ? logicalHref : router2.basePath + logicalHref;
3240
+ const isActive = !isAbsolute && router2.currentHref === normalizeHref(logicalHrefWithoutHash);
3241
+ const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
3242
+ const extraProps = {
3243
+ ...inactiveProps && !isActive ? inactiveProps() : {},
3244
+ ...activeProps ? activeProps({ isActive }) : {}
3245
+ };
3246
+ return { logicalHref, href, isActive, resolvedChildren, extraProps };
3247
+ }
3248
+ function LinkInteractive({
3249
+ to,
3250
+ search,
3251
+ hash,
3252
+ preload,
3253
+ preloadDelay,
3254
+ preloadStaleTime,
3255
+ replace,
3256
+ disabled,
3257
+ resetScroll,
3258
+ activeProps,
3259
+ inactiveProps,
3260
+ onClick,
3261
+ onMouseEnter,
3262
+ onMouseLeave,
3263
+ onFocus,
3264
+ children,
3265
+ href: _href,
3266
+ ...anchorProps
3267
+ }) {
3268
+ const router2 = useRouter();
3269
+ const anchorRef = useRef2(null);
3270
+ const intentTimerRef = useRef2(null);
3271
+ const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ to, search, hash, children, activeProps, inactiveProps }, router2);
3272
+ const effectivePreload = preload ?? router2.defaultPreload;
3273
+ const effectiveDelay = preloadDelay ?? router2.defaultPreloadDelay;
3274
+ const effectiveStaleTime = preloadStaleTime ?? router2.defaultPreloadStaleTime;
3275
+ const { prefetch } = router2;
3276
+ const triggerPrefetch = useCallback2(() => {
3277
+ prefetch(logicalHref, { staleTime: effectiveStaleTime });
3278
+ }, [prefetch, logicalHref, effectiveStaleTime]);
3279
+ useEffect2(() => {
3280
+ if (effectivePreload === "render") {
3281
+ triggerPrefetch();
3282
+ }
3283
+ }, [effectivePreload, triggerPrefetch]);
3284
+ useEffect2(() => {
3285
+ if (effectivePreload !== "viewport" || !anchorRef.current) {
3286
+ return;
3287
+ }
3288
+ const observer = new IntersectionObserver(([entry]) => {
3289
+ if (entry?.isIntersecting) {
3290
+ triggerPrefetch();
3291
+ observer.disconnect();
3292
+ }
3293
+ }, { rootMargin: "200px" });
3294
+ observer.observe(anchorRef.current);
3295
+ return () => observer.disconnect();
3296
+ }, [effectivePreload, triggerPrefetch]);
3297
+ useEffect2(() => () => {
3298
+ if (intentTimerRef.current !== null) {
3299
+ clearTimeout(intentTimerRef.current);
3300
+ intentTimerRef.current = null;
3301
+ }
3302
+ }, []);
3303
+ const isInternal = (url) => {
3304
+ try {
3305
+ return new URL(url, window.location.origin).origin === window.location.origin;
3306
+ } catch {
3307
+ return false;
3308
+ }
3309
+ };
3310
+ const handleClick = (e) => {
3311
+ onClick?.(e);
3312
+ if (e.defaultPrevented) {
3313
+ return;
3314
+ }
3315
+ if (disabled) {
3316
+ e.preventDefault();
3317
+ return;
3318
+ }
3319
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
3320
+ return;
3321
+ }
3322
+ if (anchorProps.target && anchorProps.target !== "_self") {
3323
+ return;
3324
+ }
3325
+ if (!isInternal(href)) {
3326
+ return;
3327
+ }
3328
+ e.preventDefault();
3329
+ if (typeof window !== "undefined" && router2.navigate === CLIENT_FALLBACK_ROUTER.navigate) {
3330
+ window.location.href = href;
3331
+ return;
3332
+ }
3333
+ router2.navigate(logicalHref, { replace, resetScroll: resetScroll ?? true });
3334
+ };
3335
+ const handleMouseEnter = (e) => {
3336
+ onMouseEnter?.(e);
3337
+ if (!disabled && effectivePreload === "intent" && isInternal(href)) {
3338
+ intentTimerRef.current = setTimeout(triggerPrefetch, effectiveDelay);
3339
+ }
3340
+ };
3341
+ const handleMouseLeave = (e) => {
3342
+ onMouseLeave?.(e);
3343
+ if (intentTimerRef.current !== null) {
3344
+ clearTimeout(intentTimerRef.current);
3345
+ intentTimerRef.current = null;
3346
+ }
3347
+ };
3348
+ const handleFocus = (e) => {
3349
+ onFocus?.(e);
3350
+ if (!disabled && effectivePreload === "intent" && isInternal(href)) {
3351
+ triggerPrefetch();
3352
+ }
3353
+ };
3354
+ return createElement3("a", {
3355
+ ref: anchorRef,
3356
+ href,
3357
+ "data-furin-link": true,
3358
+ onClick: handleClick,
3359
+ onMouseEnter: handleMouseEnter,
3360
+ onMouseLeave: handleMouseLeave,
3361
+ onFocus: handleFocus,
3362
+ ...isActive ? { "data-status": "active" } : {},
3363
+ ...anchorProps,
3364
+ ...extraProps,
3365
+ ...disabled ? { "aria-disabled": true } : {}
3366
+ }, resolvedChildren);
3367
+ }
3368
+ var SSR_FALLBACK_ROUTER = {
3369
+ basePath: "",
3370
+ currentHref: "/",
3371
+ navigate: (_href, _opts) => Promise.resolve(),
3372
+ prefetch: (_href, _opts) => {},
3373
+ invalidatePrefetch: (_path, _type) => {},
3374
+ refresh: (_opts) => Promise.resolve(),
3375
+ isNavigating: false,
3376
+ defaultPreload: "intent",
3377
+ defaultPreloadDelay: 50,
3378
+ defaultPreloadStaleTime: 30000
3379
+ };
3380
+ function renderLinkElement(props, router2) {
3381
+ const { href, isActive, resolvedChildren, extraProps } = computeLinkView(props, router2);
3382
+ const {
3383
+ to: _to,
3384
+ search: _search,
3385
+ hash: _hash,
3386
+ children: _children,
3387
+ activeProps: _ap,
3388
+ inactiveProps: _ip,
3389
+ disabled,
3390
+ preload: _p,
3391
+ preloadDelay: _pd,
3392
+ preloadStaleTime: _ps,
3393
+ replace: _r,
3394
+ resetScroll: _rs,
3395
+ onClick: _oc,
3396
+ onMouseEnter: _ome,
3397
+ onMouseLeave: _oml,
3398
+ onFocus: _of,
3399
+ href: _href,
3400
+ ...anchorProps
3401
+ } = props;
3402
+ return createElement3("a", {
3403
+ href,
3404
+ "data-furin-link": true,
3405
+ ...isActive ? { "data-status": "active" } : {},
3406
+ ...anchorProps,
3407
+ ...extraProps,
3408
+ ...disabled ? { "aria-disabled": true } : {}
3409
+ }, resolvedChildren);
3410
+ }
3411
+ function Link(props) {
3412
+ if (typeof window === "undefined") {
3413
+ return createElement3(RouterContext.Consumer, {
3414
+ children: (routerCtx) => renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER)
3415
+ });
3416
+ }
3417
+ return createElement3(LinkInteractive, props);
3418
+ }
3419
+ export {
3420
+ useRouter,
3421
+ toLogical,
3422
+ stripHashFromHref,
3423
+ shouldRefetch,
3424
+ shouldInterceptClick,
3425
+ shouldAutoRefreshPath,
3426
+ saveScrollPosition,
3427
+ pickDeepestNotFound,
3428
+ parsePageResponse,
3429
+ normalizePath,
3430
+ normalizeHref,
3431
+ isStaleDeployResponse,
3432
+ getHistoryKey,
3433
+ generateHistoryKey,
3434
+ fromCrossJSON,
3435
+ detectStaticMode,
3436
+ classifySpaResponse,
3437
+ buildRouterTree,
3438
+ buildPageElement,
3439
+ buildNotFoundPageElement,
3440
+ buildHref,
3441
+ buildDataEndpoint,
3442
+ applyRevalidateHeader,
3443
+ TRAILING_SLASHES_RE,
3444
+ SSR_FALLBACK_ROUTER,
3445
+ SCROLL_STORAGE_KEY,
3446
+ RouterProvider,
3447
+ RouterContext,
3448
+ Link,
3449
+ CLIENT_FALLBACK_ROUTER
3450
+ };