@teyik0/furin 0.1.0-alpha.13 → 0.1.0-alpha.14

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 (58) hide show
  1. package/README.md +14 -232
  2. package/dist/await.d.ts +67 -0
  3. package/dist/build/index.js +2013 -191
  4. package/dist/cli/index.js +2007 -190
  5. package/dist/client.d.ts +33 -2
  6. package/dist/client.js +65 -1
  7. package/dist/deferred-ndjson.d.ts +32 -0
  8. package/dist/error.d.ts +14 -0
  9. package/dist/furin.d.ts +3 -0
  10. package/dist/furin.js +2684 -318
  11. package/dist/lang-detect.d.ts +5 -0
  12. package/dist/link.d.ts +1 -0
  13. package/dist/link.js +1453 -95
  14. package/dist/plugin/index.js +96 -25
  15. package/dist/plugin/transform-client.d.ts +2 -1
  16. package/dist/render/assemble.d.ts +32 -0
  17. package/dist/render/cache.d.ts +7 -0
  18. package/dist/render/element.d.ts +17 -1
  19. package/dist/render/index.d.ts +10 -1
  20. package/dist/render/index.ts +247 -44
  21. package/dist/render/loaders.d.ts +46 -3
  22. package/dist/render/shell.d.ts +16 -6
  23. package/dist/render/shell.ts +27 -12
  24. package/dist/router-provider.d.ts +86 -18
  25. package/dist/router.d.ts +63 -0
  26. package/dist/router.js +2768 -317
  27. package/dist/router.ts +543 -54
  28. package/dist/server-error.d.ts +12 -0
  29. package/dist/utils.d.ts +7 -0
  30. package/package.json +8 -7
  31. package/src/adapter/bun.ts +3 -3
  32. package/src/adapter/static.ts +73 -31
  33. package/src/await.tsx +175 -0
  34. package/src/build/client.ts +4 -8
  35. package/src/build/hydrate.ts +67 -1
  36. package/src/build/route-types.ts +5 -1
  37. package/src/build/scan-server.ts +6 -23
  38. package/src/client.ts +58 -1
  39. package/src/deferred-ndjson.ts +212 -0
  40. package/src/dev-page-plugin.ts +2 -0
  41. package/src/error.ts +18 -1
  42. package/src/furin.ts +12 -2
  43. package/src/lang-detect.ts +46 -0
  44. package/src/link.tsx +16 -3
  45. package/src/plugin/index.ts +7 -8
  46. package/src/plugin/transform-client.ts +108 -39
  47. package/src/render/assemble.ts +67 -0
  48. package/src/render/boundaries.tsx +23 -5
  49. package/src/render/cache.ts +7 -0
  50. package/src/render/default-screens.tsx +4 -11
  51. package/src/render/element.tsx +26 -3
  52. package/src/render/index.ts +247 -44
  53. package/src/render/loaders.ts +221 -18
  54. package/src/render/shell.ts +27 -12
  55. package/src/router-provider.tsx +414 -122
  56. package/src/router.ts +543 -54
  57. package/src/server-error.ts +47 -0
  58. package/src/utils.ts +31 -0
@@ -263,7 +263,7 @@ function getBtoa() {
263
263
  };
264
264
  }
265
265
  }
266
- var btoa = /* @__PURE__ */ getBtoa();
266
+ var btoa2 = /* @__PURE__ */ getBtoa();
267
267
 
268
268
  class SourceMap {
269
269
  constructor(properties) {
@@ -284,7 +284,7 @@ class SourceMap {
284
284
  return JSON.stringify(this);
285
285
  }
286
286
  toUrl() {
287
- return "data:application/json;charset=utf-8;base64," + btoa(this.toString());
287
+ return "data:application/json;charset=utf-8;base64," + btoa2(this.toString());
288
288
  }
289
289
  }
290
290
  function guessIndent(code) {
@@ -1151,16 +1151,41 @@ class MagicString {
1151
1151
 
1152
1152
  // src/plugin/transform-client.ts
1153
1153
  import { parse } from "yuku-parser";
1154
- var bunTranspiler = new Bun.Transpiler({
1155
- loader: "tsx",
1156
- tsconfig: {
1157
- compilerOptions: {
1158
- jsx: "react",
1159
- jsxFactory: "React.createElement",
1160
- jsxFragmentFactory: "React.Fragment"
1161
- }
1154
+
1155
+ // src/lang-detect.ts
1156
+ function detectLangFromPath(filePath) {
1157
+ if (filePath.endsWith(".d.ts")) {
1158
+ return "dts";
1162
1159
  }
1163
- });
1160
+ const ext = filePath.split(".").pop()?.toLowerCase();
1161
+ switch (ext) {
1162
+ case "ts":
1163
+ return "ts";
1164
+ case "tsx":
1165
+ return "tsx";
1166
+ case "jsx":
1167
+ return "jsx";
1168
+ default:
1169
+ return "js";
1170
+ }
1171
+ }
1172
+ var TS_WRAPPER_TYPES = new Set([
1173
+ "TSAsExpression",
1174
+ "TSSatisfiesExpression",
1175
+ "TSTypeAssertion",
1176
+ "TSNonNullExpression",
1177
+ "TSInstantiationExpression",
1178
+ "ParenthesizedExpression"
1179
+ ]);
1180
+ function unwrapTSExpression(node) {
1181
+ let current = node;
1182
+ while (current && typeof current === "object" && TS_WRAPPER_TYPES.has(current.type) && current.expression && typeof current.expression === "object") {
1183
+ current = current.expression;
1184
+ }
1185
+ return current;
1186
+ }
1187
+
1188
+ // src/plugin/transform-client.ts
1164
1189
  var SERVER_ONLY_PROPERTIES = new Set(["loader", "query", "params", "staticParams"]);
1165
1190
  function walk(node, visitor) {
1166
1191
  if (!node || typeof node !== "object") {
@@ -1244,6 +1269,45 @@ function removeServerProperties(s, source, obj) {
1244
1269
  }
1245
1270
  return true;
1246
1271
  }
1272
+ var TYPE_SCOPE_NODES = new Set([
1273
+ "TSTypeAnnotation",
1274
+ "TSTypeParameterDeclaration",
1275
+ "TSTypeParameterInstantiation",
1276
+ "TSInterfaceDeclaration",
1277
+ "TSTypeAliasDeclaration",
1278
+ "TSTypePredicate",
1279
+ "TSClassImplements"
1280
+ ]);
1281
+ function markTypeDescendants(node, excluded) {
1282
+ if (!node || typeof node !== "object") {
1283
+ return;
1284
+ }
1285
+ if (Array.isArray(node)) {
1286
+ for (const item of node) {
1287
+ markTypeDescendants(item, excluded);
1288
+ }
1289
+ return;
1290
+ }
1291
+ const n2 = node;
1292
+ if (n2.type === "Identifier" || n2.type === "JSXIdentifier") {
1293
+ excluded.add(n2);
1294
+ }
1295
+ for (const key of Object.keys(n2)) {
1296
+ if (key === "type" || key === "start" || key === "end") {
1297
+ continue;
1298
+ }
1299
+ markTypeDescendants(n2[key], excluded);
1300
+ }
1301
+ }
1302
+ function excludeTypePositionIdentifiers(node, excluded) {
1303
+ if (TYPE_SCOPE_NODES.has(node.type)) {
1304
+ markTypeDescendants(node, excluded);
1305
+ return;
1306
+ }
1307
+ if (node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSTypeAssertion") {
1308
+ markTypeDescendants(node.typeAnnotation, excluded);
1309
+ }
1310
+ }
1247
1311
  function collectReferencedNames(program) {
1248
1312
  const refs = new Set;
1249
1313
  const excluded = new Set;
@@ -1258,6 +1322,13 @@ function collectReferencedNames(program) {
1258
1322
  if (node.type === "MemberExpression" && !node.computed) {
1259
1323
  excluded.add(node.property);
1260
1324
  }
1325
+ if (node.type === "JSXAttribute") {
1326
+ excluded.add(node.name);
1327
+ }
1328
+ if (node.type === "JSXMemberExpression") {
1329
+ excluded.add(node.property);
1330
+ }
1331
+ excludeTypePositionIdentifiers(node, excluded);
1261
1332
  });
1262
1333
  }
1263
1334
  for (const stmt of program.body ?? []) {
@@ -1268,7 +1339,7 @@ function collectReferencedNames(program) {
1268
1339
  if (excluded.has(node)) {
1269
1340
  return;
1270
1341
  }
1271
- if (node.type === "Identifier" && typeof node.name === "string") {
1342
+ if ((node.type === "Identifier" || node.type === "JSXIdentifier") && typeof node.name === "string") {
1272
1343
  refs.add(node.name);
1273
1344
  }
1274
1345
  });
@@ -1299,9 +1370,9 @@ function removeUnusedSpecifiers(s, code, decl, refs) {
1299
1370
  s.remove(removeStart, removeEnd);
1300
1371
  }
1301
1372
  }
1302
- function deadCodeElimination(s) {
1373
+ function deadCodeElimination(s, lang) {
1303
1374
  const code = s.toString();
1304
- const { program, diagnostics } = parse(code, { sourceType: "module" });
1375
+ const { program, diagnostics } = parse(code, { sourceType: "module", lang });
1305
1376
  const firstError = diagnostics.find((d) => d.severity === "error");
1306
1377
  if (firstError) {
1307
1378
  console.error("[furin] DCE: failed to parse transformed output:", firstError.message);
@@ -1342,7 +1413,7 @@ function removeServerExports(s, source, program) {
1342
1413
  if (!isTargetCall(call)) {
1343
1414
  return;
1344
1415
  }
1345
- const arg = call.arguments[0];
1416
+ const arg = call.arguments[0] ? unwrapTSExpression(call.arguments[0]) : undefined;
1346
1417
  if (!arg || arg.type !== "ObjectExpression") {
1347
1418
  return;
1348
1419
  }
@@ -1353,16 +1424,19 @@ function removeServerExports(s, source, program) {
1353
1424
  return removedServerCode;
1354
1425
  }
1355
1426
  function transformForClient(code, filename) {
1356
- const plainJs = bunTranspiler.transformSync(code);
1357
- const { program, diagnostics } = parse(plainJs, { sourceType: "module" });
1427
+ const lang = detectLangFromPath(filename);
1428
+ if (lang === "dts") {
1429
+ return { code, map: null, removedServerCode: false };
1430
+ }
1431
+ const { program, diagnostics } = parse(code, { sourceType: "module", lang });
1358
1432
  const firstError = diagnostics.find((d) => d.severity === "error");
1359
1433
  if (firstError) {
1360
1434
  throw new Error(`Failed to parse ${filename}: ${firstError.message}`);
1361
1435
  }
1362
- let s = new MagicString(plainJs);
1363
- const removedServerCode = removeServerExports(s, plainJs, program);
1436
+ let s = new MagicString(code);
1437
+ const removedServerCode = removeServerExports(s, code, program);
1364
1438
  if (removedServerCode) {
1365
- s = deadCodeElimination(s);
1439
+ s = deadCodeElimination(s, lang);
1366
1440
  }
1367
1441
  return {
1368
1442
  code: s.toString(),
@@ -1397,7 +1471,13 @@ function safeJson(value) {
1397
1471
  return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1398
1472
  }
1399
1473
  function renderAttrs(obj) {
1400
- return Object.entries(obj).filter(([, v]) => v !== undefined).map(([k, v]) => `${k}="${escapeHtml(String(v))}"`).join(" ");
1474
+ const parts = [];
1475
+ for (const [k, v] of Object.entries(obj)) {
1476
+ if (v !== undefined) {
1477
+ parts.push(`${k}="${escapeHtml(String(v))}"`);
1478
+ }
1479
+ }
1480
+ return parts.join(" ");
1401
1481
  }
1402
1482
  function buildMetaParts(meta) {
1403
1483
  const parts = [];
@@ -1470,13 +1550,15 @@ function generateIndexHtml() {
1470
1550
  </html>
1471
1551
  `;
1472
1552
  }
1473
- function generateProdIndexHtml(entryChunk, cssChunks, buildId, faviconHref) {
1553
+ function generateProdIndexHtml(entryChunk, cssChunks, buildId, faviconHref, staticMode) {
1474
1554
  const cssLinks = cssChunks.map((c) => ` <link rel="stylesheet" crossorigin href="${c}">`).join(`
1475
1555
  `);
1476
1556
  const scriptTag = `<script type="module" crossorigin src="${entryChunk}"></script>`;
1477
1557
  const buildIdMeta = buildId ? ` <meta name="furin-build-id" content="${escapeHtml(buildId)}">
1478
1558
  ` : "";
1479
1559
  const faviconLink = faviconHref ? ` <link rel="icon" href="${escapeHtml(faviconHref)}">
1560
+ ` : "";
1561
+ const modeMeta = staticMode ? ` <meta name="furin-mode" content="static">
1480
1562
  ` : "";
1481
1563
  return `<!DOCTYPE html>
1482
1564
  <html lang="en">
@@ -1484,7 +1566,7 @@ function generateProdIndexHtml(entryChunk, cssChunks, buildId, faviconHref) {
1484
1566
  <meta charset="UTF-8">
1485
1567
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1486
1568
  ${THEME_INIT_SCRIPT}
1487
- ${buildIdMeta}${faviconLink}${cssLinks ? `${cssLinks}
1569
+ ${buildIdMeta}${modeMeta}${faviconLink}${cssLinks ? `${cssLinks}
1488
1570
  ` : ""} <!--ssr-head-->
1489
1571
  </head>
1490
1572
  <body>
@@ -1508,7 +1590,12 @@ function schemaToTypeString(schema) {
1508
1590
  }
1509
1591
  const s = schema;
1510
1592
  if (s.anyOf && Array.isArray(s.anyOf)) {
1511
- const parts = s.anyOf.map(schemaToTypeString).filter((t) => t !== "null");
1593
+ const parts = [];
1594
+ for (const item of s.anyOf) {
1595
+ const t = schemaToTypeString(item);
1596
+ if (t !== "null")
1597
+ parts.push(t);
1598
+ }
1512
1599
  return parts.join(" | ") || "unknown";
1513
1600
  }
1514
1601
  switch (s.type) {
@@ -1616,6 +1703,8 @@ import { createElement } from "react";
1616
1703
  import { initLogger, log } from "evlog";
1617
1704
  import { createHttpLogDrain } from "evlog/http";
1618
1705
  import { RouterProvider } from "@teyik0/furin/link";
1706
+ import { fromCrossJSON } from "@teyik0/furin/link";
1707
+ import type { SerovalNode } from "seroval";
1619
1708
  import { route as root } from "${rootLayout.replace(/\\/g, "/")}";${conventionImportsBlock}
1620
1709
 
1621
1710
  initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });
@@ -1637,6 +1726,70 @@ const _match = routes.find((r) => r.regex.test(pathname));
1637
1726
  // former does not \u2014 so the two cases fork on _match below.
1638
1727
  const dataEl = document.getElementById("__FURIN_DATA__");
1639
1728
  const loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
1729
+
1730
+ // \u2500\u2500 Deferred data hydration \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1731
+ // window.__FURIN_DEFERRED__ is injected by the server when a loader returns
1732
+ // defer(). It carries:
1733
+ // - _chunks: raw CrossJSON chunks keyed by field name (from late <script> tags)
1734
+ // We deserialise each chunk with fromCrossJSON and create a Promise so <Await>
1735
+ // components receive a proper resolved Promise instead of the raw CrossJSON node.
1736
+ // Sync loader fields live exclusively in __FURIN_DATA__ (read above).
1737
+ interface FurinDeferredRegistry {
1738
+ _chunks: Record<string, { a: 0 | 1; v: SerovalNode }>;
1739
+ _deferredKeys: string[];
1740
+ _resolvers: Record<string, {
1741
+ promise: Promise<unknown>;
1742
+ reject: (reason: unknown) => void;
1743
+ resolve: (value: unknown) => void;
1744
+ }>;
1745
+ getPromise: (key: string) => Promise<unknown>;
1746
+ reject: (key: string, chunk: SerovalNode) => void;
1747
+ resolve: (key: string, chunk: SerovalNode) => void;
1748
+ }
1749
+ const __deferred = (window as unknown as { __FURIN_DEFERRED__?: FurinDeferredRegistry })
1750
+ .__FURIN_DEFERRED__;
1751
+ const deferredData: Record<string, Promise<unknown>> = {};
1752
+ if (__deferred && __deferred._chunks) {
1753
+ // Patch resolve/reject so any chunks that arrive AFTER this entry has run
1754
+ // settle immediately. The previous version stored late chunks in _chunks
1755
+ // when no resolver was registered yet, but the drain loop below only runs
1756
+ // ONCE at hydrate time \u2014 so any chunk landing after the drain would stay
1757
+ // orphaned and the corresponding Await would hang forever. Eagerly creating
1758
+ // the resolver via getPromise() fixes the race.
1759
+ __deferred.resolve = (key: string, chunk: SerovalNode) => {
1760
+ __deferred.getPromise(key);
1761
+ __deferred._resolvers[key].resolve(fromCrossJSON(chunk, {}));
1762
+ };
1763
+ __deferred.reject = (key: string, chunk: SerovalNode) => {
1764
+ __deferred.getPromise(key);
1765
+ __deferred._resolvers[key].reject(fromCrossJSON(chunk, {}));
1766
+ };
1767
+ for (const key of Object.keys(__deferred._chunks)) {
1768
+ const entry = __deferred._chunks[key] as { a: 0 | 1; v: SerovalNode };
1769
+ const p = __deferred.getPromise(key) as Promise<unknown>;
1770
+ const resolver = __deferred._resolvers[key];
1771
+ const value = fromCrossJSON(entry.v, {});
1772
+ if (entry.a === 0) {
1773
+ resolver.resolve(value);
1774
+ } else {
1775
+ resolver.reject(value);
1776
+ }
1777
+ deferredData[key] = p;
1778
+ }
1779
+ for (const key of __deferred._deferredKeys ?? []) {
1780
+ if (!(key in deferredData)) {
1781
+ deferredData[key] = __deferred.getPromise(key) as Promise<unknown>;
1782
+ }
1783
+ }
1784
+ // Keys that have a resolver (getPromise was called by <Await>) but no
1785
+ // chunk yet (the late <script> hasn't arrived) still need a Promise entry
1786
+ // so the hydration data record is complete.
1787
+ for (const key of Object.keys(__deferred._resolvers ?? {})) {
1788
+ if (!(key in deferredData)) {
1789
+ deferredData[key] = __deferred.getPromise(key) as Promise<unknown>;
1790
+ }
1791
+ }
1792
+ }
1640
1793
  const rootEl = document.getElementById("root") as HTMLElement;
1641
1794
 
1642
1795
  // Eagerly load only the current page module for initial hydration.
@@ -1655,7 +1808,7 @@ const rootEl = document.getElementById("root") as HTMLElement;
1655
1808
  routes,
1656
1809
  root,
1657
1810
  initialMatch: match,
1658
- initialData: loaderData,
1811
+ initialData: { ...loaderData, ...deferredData },
1659
1812
  initialDigest: loaderData.__furinError?.digest,
1660
1813
  initialNotFound: isNotFound ? (loaderData.__furinNotFound ?? loaderData) : undefined,${routerProviderDefaults}
1661
1814
  } as any);
@@ -1801,7 +1954,6 @@ function buildTargetManifest(rootDir, buildRoot, target, serverEntry) {
1801
1954
 
1802
1955
  // src/build/client.ts
1803
1956
  var TS_FILE_FILTER = /\.(tsx|ts)$/;
1804
- var REACT_IMPORT_RE = /import\s+React\b/;
1805
1957
  async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, basePath }) {
1806
1958
  const clientDir = join4(outDir, "client");
1807
1959
  if (!existsSync4(outDir)) {
@@ -1825,12 +1977,7 @@ async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, ba
1825
1977
  const code = await Bun.file(path).text();
1826
1978
  try {
1827
1979
  const result2 = transformForClient(code, path);
1828
- let transformed = result2.code;
1829
- if (transformed.includes("React.createElement") && !REACT_IMPORT_RE.test(transformed)) {
1830
- transformed = `import React from "react";
1831
- ${transformed}`;
1832
- }
1833
- transformed = transformed.replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH)).replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH));
1980
+ const transformed = result2.code.replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH)).replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH));
1834
1981
  return {
1835
1982
  contents: transformed,
1836
1983
  loader: path.endsWith(".tsx") ? "tsx" : "ts"
@@ -2111,12 +2258,12 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
2111
2258
  }
2112
2259
  fingerprintPaths.add(path);
2113
2260
  }
2114
- const fileParts = await Promise.all([...fingerprintPaths].sort().map(async (path) => {
2261
+ const fileParts = await Promise.all([...fingerprintPaths].toSorted().map(async (path) => {
2115
2262
  const content = existsSync7(path) ? await Bun.file(path).text() : "";
2116
2263
  return `${toPosixPath(path)}:${content}`;
2117
2264
  }));
2118
2265
  const routeParts = routes.map((route) => JSON.stringify({ mode: route.mode, path: toPosixPath(route.path), pattern: route.pattern })).sort();
2119
- return [entryChunk, ...[...cssChunks].sort(), ...routeParts, ...fileParts].join(`
2266
+ return [entryChunk, ...[...cssChunks].toSorted(), ...routeParts, ...fileParts].join(`
2120
2267
  `);
2121
2268
  }
2122
2269
  function buildCompileMetadata(root, routes) {
@@ -2157,7 +2304,7 @@ async function buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, opt
2157
2304
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
2158
2305
  targetManifest.buildId = buildId;
2159
2306
  const clientDir = join8(targetDir, "client");
2160
- writeFileSync6(join8(clientDir, "index.html"), generateProdIndexHtml(entryChunk, cssChunks, buildId));
2307
+ writeFileSync6(join8(clientDir, "index.html"), generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false));
2161
2308
  const routeManifest = routes.map((r) => ({ pattern: r.pattern, path: r.path, mode: r.mode }));
2162
2309
  const publicDir = existsSync7(join8(rootDir, "public")) ? join8(rootDir, "public") : undefined;
2163
2310
  const targetPublicDir = publicDir ? join8(targetDir, "public") : undefined;
@@ -2271,6 +2418,1045 @@ function assembleHTML(template, headData, reactHtml, data) {
2271
2418
  import { createElement as createElement3 } from "react";
2272
2419
  import { renderToReadableStream } from "react-dom/server";
2273
2420
 
2421
+ // ../../node_modules/.bun/seroval@1.5.4/node_modules/seroval/dist/esm/development/index.mjs
2422
+ var ALL_ENABLED = 1 | 2 | 4 | 8 | 16 | 32;
2423
+ var SYM_ASYNC_ITERATOR = Symbol.asyncIterator;
2424
+ var SYM_HAS_INSTANCE = Symbol.hasInstance;
2425
+ var SYM_IS_CONCAT_SPREADABLE = Symbol.isConcatSpreadable;
2426
+ var SYM_ITERATOR = Symbol.iterator;
2427
+ var SYM_MATCH = Symbol.match;
2428
+ var SYM_MATCH_ALL = Symbol.matchAll;
2429
+ var SYM_REPLACE = Symbol.replace;
2430
+ var SYM_SEARCH = Symbol.search;
2431
+ var SYM_SPECIES = Symbol.species;
2432
+ var SYM_SPLIT = Symbol.split;
2433
+ var SYM_TO_PRIMITIVE = Symbol.toPrimitive;
2434
+ var SYM_TO_STRING_TAG = Symbol.toStringTag;
2435
+ var SYM_UNSCOPABLES = Symbol.unscopables;
2436
+ var INV_SYMBOL_REF = {
2437
+ [SYM_ASYNC_ITERATOR]: 0,
2438
+ [SYM_HAS_INSTANCE]: 1,
2439
+ [SYM_IS_CONCAT_SPREADABLE]: 2,
2440
+ [SYM_ITERATOR]: 3,
2441
+ [SYM_MATCH]: 4,
2442
+ [SYM_MATCH_ALL]: 5,
2443
+ [SYM_REPLACE]: 6,
2444
+ [SYM_SEARCH]: 7,
2445
+ [SYM_SPECIES]: 8,
2446
+ [SYM_SPLIT]: 9,
2447
+ [SYM_TO_PRIMITIVE]: 10,
2448
+ [SYM_TO_STRING_TAG]: 11,
2449
+ [SYM_UNSCOPABLES]: 12
2450
+ };
2451
+ var NIL = undefined;
2452
+ var CONSTANT_VAL = {
2453
+ [2]: true,
2454
+ [3]: false,
2455
+ [1]: NIL,
2456
+ [0]: null,
2457
+ [4]: -0,
2458
+ [5]: Number.POSITIVE_INFINITY,
2459
+ [6]: Number.NEGATIVE_INFINITY,
2460
+ [7]: Number.NaN
2461
+ };
2462
+ var ERROR_CONSTRUCTOR_STRING = {
2463
+ [0]: "Error",
2464
+ [1]: "EvalError",
2465
+ [2]: "RangeError",
2466
+ [3]: "ReferenceError",
2467
+ [4]: "SyntaxError",
2468
+ [5]: "TypeError",
2469
+ [6]: "URIError"
2470
+ };
2471
+ function createSerovalNode(t, i, s, c, m, p, e, a, f, b, o, l) {
2472
+ return {
2473
+ t,
2474
+ i,
2475
+ s,
2476
+ c,
2477
+ m,
2478
+ p,
2479
+ e,
2480
+ a,
2481
+ f,
2482
+ b,
2483
+ o,
2484
+ l
2485
+ };
2486
+ }
2487
+ function createConstantNode(value) {
2488
+ return createSerovalNode(2, NIL, value, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2489
+ }
2490
+ var TRUE_NODE = /* @__PURE__ */ createConstantNode(2);
2491
+ var FALSE_NODE = /* @__PURE__ */ createConstantNode(3);
2492
+ var UNDEFINED_NODE = /* @__PURE__ */ createConstantNode(1);
2493
+ var NULL_NODE = /* @__PURE__ */ createConstantNode(0);
2494
+ var NEG_ZERO_NODE = /* @__PURE__ */ createConstantNode(4);
2495
+ var INFINITY_NODE = /* @__PURE__ */ createConstantNode(5);
2496
+ var NEG_INFINITY_NODE = /* @__PURE__ */ createConstantNode(6);
2497
+ var NAN_NODE = /* @__PURE__ */ createConstantNode(7);
2498
+ function serializeChar(str) {
2499
+ switch (str) {
2500
+ case '"':
2501
+ return "\\\"";
2502
+ case "\\":
2503
+ return "\\\\";
2504
+ case `
2505
+ `:
2506
+ return "\\n";
2507
+ case "\r":
2508
+ return "\\r";
2509
+ case "\b":
2510
+ return "\\b";
2511
+ case "\t":
2512
+ return "\\t";
2513
+ case "\f":
2514
+ return "\\f";
2515
+ case "<":
2516
+ return "\\x3C";
2517
+ case "\u2028":
2518
+ return "\\u2028";
2519
+ case "\u2029":
2520
+ return "\\u2029";
2521
+ default:
2522
+ return NIL;
2523
+ }
2524
+ }
2525
+ function serializeString(str) {
2526
+ let result = "";
2527
+ let lastPos = 0;
2528
+ let replacement;
2529
+ for (let i = 0, len = str.length;i < len; i++) {
2530
+ replacement = serializeChar(str[i]);
2531
+ if (replacement) {
2532
+ result += str.slice(lastPos, i) + replacement;
2533
+ lastPos = i + 1;
2534
+ }
2535
+ }
2536
+ if (lastPos === 0) {
2537
+ result = str;
2538
+ } else {
2539
+ result += str.slice(lastPos);
2540
+ }
2541
+ return result;
2542
+ }
2543
+ var REFERENCES_KEY = "__SEROVAL_REFS__";
2544
+ var GLOBAL_CONTEXT_REFERENCES = "$R";
2545
+ var GLOBAL_CONTEXT_R = `self.${GLOBAL_CONTEXT_REFERENCES}`;
2546
+ var REFERENCE = /* @__PURE__ */ new Map;
2547
+ var INV_REFERENCE = /* @__PURE__ */ new Map;
2548
+ function hasReferenceID(value) {
2549
+ return REFERENCE.has(value);
2550
+ }
2551
+ function getReferenceID(value) {
2552
+ if (hasReferenceID(value)) {
2553
+ return REFERENCE.get(value);
2554
+ }
2555
+ throw new SerovalMissingReferenceError(value);
2556
+ }
2557
+ if (typeof globalThis !== "undefined") {
2558
+ Object.defineProperty(globalThis, REFERENCES_KEY, {
2559
+ value: INV_REFERENCE,
2560
+ configurable: true,
2561
+ writable: false,
2562
+ enumerable: false
2563
+ });
2564
+ } else if (typeof window !== "undefined") {
2565
+ Object.defineProperty(window, REFERENCES_KEY, {
2566
+ value: INV_REFERENCE,
2567
+ configurable: true,
2568
+ writable: false,
2569
+ enumerable: false
2570
+ });
2571
+ } else if (typeof self !== "undefined") {
2572
+ Object.defineProperty(self, REFERENCES_KEY, {
2573
+ value: INV_REFERENCE,
2574
+ configurable: true,
2575
+ writable: false,
2576
+ enumerable: false
2577
+ });
2578
+ } else if (typeof global !== "undefined") {
2579
+ Object.defineProperty(global, REFERENCES_KEY, {
2580
+ value: INV_REFERENCE,
2581
+ configurable: true,
2582
+ writable: false,
2583
+ enumerable: false
2584
+ });
2585
+ }
2586
+ function getErrorConstructor(error) {
2587
+ if (error instanceof EvalError) {
2588
+ return 1;
2589
+ }
2590
+ if (error instanceof RangeError) {
2591
+ return 2;
2592
+ }
2593
+ if (error instanceof ReferenceError) {
2594
+ return 3;
2595
+ }
2596
+ if (error instanceof SyntaxError) {
2597
+ return 4;
2598
+ }
2599
+ if (error instanceof TypeError) {
2600
+ return 5;
2601
+ }
2602
+ if (error instanceof URIError) {
2603
+ return 6;
2604
+ }
2605
+ return 0;
2606
+ }
2607
+ function getInitialErrorOptions(error) {
2608
+ const construct = ERROR_CONSTRUCTOR_STRING[getErrorConstructor(error)];
2609
+ if (error.name !== construct) {
2610
+ return { name: error.name };
2611
+ }
2612
+ if (error.constructor.name !== construct) {
2613
+ return { name: error.constructor.name };
2614
+ }
2615
+ return {};
2616
+ }
2617
+ function getErrorOptions(error, features) {
2618
+ let options = getInitialErrorOptions(error);
2619
+ const names = Object.getOwnPropertyNames(error);
2620
+ for (let i = 0, len = names.length, name;i < len; i++) {
2621
+ name = names[i];
2622
+ if (name !== "name" && name !== "message") {
2623
+ if (name === "stack") {
2624
+ if (features & 4) {
2625
+ options = options || {};
2626
+ options[name] = error[name];
2627
+ }
2628
+ } else {
2629
+ options = options || {};
2630
+ options[name] = error[name];
2631
+ }
2632
+ }
2633
+ }
2634
+ return options;
2635
+ }
2636
+ function getObjectFlag(obj) {
2637
+ if (Object.isFrozen(obj)) {
2638
+ return 3;
2639
+ }
2640
+ if (Object.isSealed(obj)) {
2641
+ return 2;
2642
+ }
2643
+ if (Object.isExtensible(obj)) {
2644
+ return 0;
2645
+ }
2646
+ return 1;
2647
+ }
2648
+ function createNumberNode(value) {
2649
+ switch (value) {
2650
+ case Number.POSITIVE_INFINITY:
2651
+ return INFINITY_NODE;
2652
+ case Number.NEGATIVE_INFINITY:
2653
+ return NEG_INFINITY_NODE;
2654
+ }
2655
+ if (value !== value) {
2656
+ return NAN_NODE;
2657
+ }
2658
+ if (Object.is(value, -0)) {
2659
+ return NEG_ZERO_NODE;
2660
+ }
2661
+ return createSerovalNode(0, NIL, value, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2662
+ }
2663
+ function createStringNode(value) {
2664
+ return createSerovalNode(1, NIL, serializeString(value), NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2665
+ }
2666
+ function createBigIntNode(current) {
2667
+ return createSerovalNode(3, NIL, "" + current, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2668
+ }
2669
+ function createIndexedValueNode(id) {
2670
+ return createSerovalNode(4, id, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2671
+ }
2672
+ function createDateNode(id, current) {
2673
+ const timestamp = current.valueOf();
2674
+ return createSerovalNode(5, id, timestamp !== timestamp ? "" : current.toISOString(), NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2675
+ }
2676
+ function createRegExpNode(id, current) {
2677
+ return createSerovalNode(6, id, NIL, serializeString(current.source), current.flags, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2678
+ }
2679
+ function createWKSymbolNode(id, current) {
2680
+ return createSerovalNode(17, id, INV_SYMBOL_REF[current], NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2681
+ }
2682
+ function createReferenceNode(id, ref) {
2683
+ return createSerovalNode(18, id, serializeString(getReferenceID(ref)), NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2684
+ }
2685
+ function createPluginNode(id, tag, value) {
2686
+ return createSerovalNode(25, id, value, serializeString(tag), NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2687
+ }
2688
+ function createArrayNode(id, current, parsedItems) {
2689
+ return createSerovalNode(9, id, NIL, NIL, NIL, NIL, NIL, parsedItems, NIL, NIL, getObjectFlag(current), NIL);
2690
+ }
2691
+ function createBoxedNode(id, boxed) {
2692
+ return createSerovalNode(21, id, NIL, NIL, NIL, NIL, NIL, NIL, boxed, NIL, NIL, NIL);
2693
+ }
2694
+ function createTypedArrayNode(id, current, buffer) {
2695
+ return createSerovalNode(15, id, NIL, current.constructor.name, NIL, NIL, NIL, NIL, buffer, current.byteOffset, NIL, current.length);
2696
+ }
2697
+ function createBigIntTypedArrayNode(id, current, buffer) {
2698
+ return createSerovalNode(16, id, NIL, current.constructor.name, NIL, NIL, NIL, NIL, buffer, current.byteOffset, NIL, current.byteLength);
2699
+ }
2700
+ function createDataViewNode(id, current, buffer) {
2701
+ return createSerovalNode(20, id, NIL, NIL, NIL, NIL, NIL, NIL, buffer, current.byteOffset, NIL, current.byteLength);
2702
+ }
2703
+ function createErrorNode(id, current, options) {
2704
+ return createSerovalNode(13, id, getErrorConstructor(current), NIL, serializeString(current.message), options, NIL, NIL, NIL, NIL, NIL, NIL);
2705
+ }
2706
+ function createAggregateErrorNode(id, current, options) {
2707
+ return createSerovalNode(14, id, getErrorConstructor(current), NIL, serializeString(current.message), options, NIL, NIL, NIL, NIL, NIL, NIL);
2708
+ }
2709
+ function createSetNode(id, items) {
2710
+ return createSerovalNode(7, id, NIL, NIL, NIL, NIL, NIL, items, NIL, NIL, NIL, NIL);
2711
+ }
2712
+ function createIteratorFactoryInstanceNode(factory, items) {
2713
+ return createSerovalNode(28, NIL, NIL, NIL, NIL, NIL, NIL, [factory, items], NIL, NIL, NIL, NIL);
2714
+ }
2715
+ function createAsyncIteratorFactoryInstanceNode(factory, items) {
2716
+ return createSerovalNode(30, NIL, NIL, NIL, NIL, NIL, NIL, [factory, items], NIL, NIL, NIL, NIL);
2717
+ }
2718
+ function createStreamConstructorNode(id, factory, sequence) {
2719
+ return createSerovalNode(31, id, NIL, NIL, NIL, NIL, NIL, sequence, factory, NIL, NIL, NIL);
2720
+ }
2721
+ function createStreamNextNode(id, parsed) {
2722
+ return createSerovalNode(32, id, NIL, NIL, NIL, NIL, NIL, NIL, parsed, NIL, NIL, NIL);
2723
+ }
2724
+ function createStreamThrowNode(id, parsed) {
2725
+ return createSerovalNode(33, id, NIL, NIL, NIL, NIL, NIL, NIL, parsed, NIL, NIL, NIL);
2726
+ }
2727
+ function createStreamReturnNode(id, parsed) {
2728
+ return createSerovalNode(34, id, NIL, NIL, NIL, NIL, NIL, NIL, parsed, NIL, NIL, NIL);
2729
+ }
2730
+ function createSequenceNode(id, sequence, throwAt, doneAt) {
2731
+ return createSerovalNode(35, id, throwAt, NIL, NIL, NIL, NIL, sequence, NIL, NIL, NIL, doneAt);
2732
+ }
2733
+ var { toString: objectToString } = Object.prototype;
2734
+ function getErrorMessageDev(type, cause) {
2735
+ if (cause instanceof Error) {
2736
+ return `Seroval caught an error during the ${type} process.
2737
+
2738
+ ${cause.name}
2739
+ ${cause.message}
2740
+
2741
+ - For more information, please check the "cause" property of this error.
2742
+ - If you believe this is an error in Seroval, please submit an issue at https://github.com/lxsmnsyc/seroval/issues/new`;
2743
+ }
2744
+ return `Seroval caught an error during the ${type} process.
2745
+
2746
+ "${objectToString.call(cause)}"
2747
+
2748
+ For more information, please check the "cause" property of this error.`;
2749
+ }
2750
+ var getErrorMessage = (type, cause) => getErrorMessageDev(type, cause);
2751
+ var SerovalError = class extends Error {
2752
+ constructor(type, cause) {
2753
+ super(getErrorMessage(type, cause));
2754
+ this.cause = cause;
2755
+ }
2756
+ };
2757
+ var SerovalParserError = class extends SerovalError {
2758
+ constructor(cause) {
2759
+ super("parsing", cause);
2760
+ }
2761
+ };
2762
+ var SerovalUnsupportedTypeError = class extends Error {
2763
+ constructor(value) {
2764
+ super(`The value ${objectToString.call(value)} of type "${typeof value}" cannot be parsed/serialized.
2765
+
2766
+ There are few workarounds for this problem:
2767
+ - Transform the value in a way that it can be serialized.
2768
+ - If the reference is present on multiple runtimes (isomorphic), you can use the Reference API to map the references.`);
2769
+ this.value = value;
2770
+ }
2771
+ };
2772
+ var SerovalMissingReferenceError = class extends Error {
2773
+ constructor(value) {
2774
+ super('Missing reference for the value "' + objectToString.call(value) + '" of type "' + typeof value + '"');
2775
+ this.value = value;
2776
+ }
2777
+ };
2778
+ var OpaqueReference = class {
2779
+ constructor(value, replacement) {
2780
+ this.value = value;
2781
+ this.replacement = replacement;
2782
+ }
2783
+ };
2784
+ var PROMISE_CONSTRUCTOR = () => {
2785
+ const resolver = {
2786
+ p: 0,
2787
+ s: 0,
2788
+ f: 0
2789
+ };
2790
+ resolver.p = new Promise((resolve2, reject) => {
2791
+ resolver.s = resolve2;
2792
+ resolver.f = reject;
2793
+ });
2794
+ return resolver;
2795
+ };
2796
+ var STREAM_CONSTRUCTOR = () => {
2797
+ const buffer = [];
2798
+ const listeners = [];
2799
+ let alive = true;
2800
+ let success = false;
2801
+ let count = 0;
2802
+ const flush = (value, mode, x) => {
2803
+ for (x = 0;x < count; x++) {
2804
+ if (listeners[x]) {
2805
+ listeners[x][mode](value);
2806
+ }
2807
+ }
2808
+ };
2809
+ const up = (listener, x, z, current) => {
2810
+ for (x = 0, z = buffer.length;x < z; x++) {
2811
+ current = buffer[x];
2812
+ if (!alive && x === z - 1) {
2813
+ listener[success ? "return" : "throw"](current);
2814
+ } else {
2815
+ listener.next(current);
2816
+ }
2817
+ }
2818
+ };
2819
+ const on = (listener, temp) => {
2820
+ if (alive) {
2821
+ temp = count++;
2822
+ listeners[temp] = listener;
2823
+ }
2824
+ up(listener);
2825
+ return () => {
2826
+ if (alive) {
2827
+ listeners[temp] = listeners[count];
2828
+ listeners[count--] = undefined;
2829
+ }
2830
+ };
2831
+ };
2832
+ return {
2833
+ __SEROVAL_STREAM__: true,
2834
+ on: (listener) => on(listener),
2835
+ next: (value) => {
2836
+ if (alive) {
2837
+ buffer.push(value);
2838
+ flush(value, "next");
2839
+ }
2840
+ },
2841
+ throw: (value) => {
2842
+ if (alive) {
2843
+ buffer.push(value);
2844
+ flush(value, "throw");
2845
+ alive = false;
2846
+ success = false;
2847
+ listeners.length = 0;
2848
+ }
2849
+ },
2850
+ return: (value) => {
2851
+ if (alive) {
2852
+ buffer.push(value);
2853
+ flush(value, "return");
2854
+ alive = false;
2855
+ success = true;
2856
+ listeners.length = 0;
2857
+ }
2858
+ }
2859
+ };
2860
+ };
2861
+ var ITERATOR_CONSTRUCTOR = (symbol) => (sequence) => () => {
2862
+ let index = 0;
2863
+ const instance = {
2864
+ [symbol]: () => instance,
2865
+ next: () => {
2866
+ if (index > sequence.d) {
2867
+ return {
2868
+ done: true,
2869
+ value: undefined
2870
+ };
2871
+ }
2872
+ const currentIndex = index++;
2873
+ const data = sequence.v[currentIndex];
2874
+ if (currentIndex === sequence.t) {
2875
+ throw data;
2876
+ }
2877
+ return {
2878
+ done: currentIndex === sequence.d,
2879
+ value: data
2880
+ };
2881
+ }
2882
+ };
2883
+ return instance;
2884
+ };
2885
+ var ASYNC_ITERATOR_CONSTRUCTOR = (symbol, createPromise) => (stream) => () => {
2886
+ let count = 0;
2887
+ let doneAt = -1;
2888
+ let isThrow = false;
2889
+ const buffer = [];
2890
+ const pending = [];
2891
+ const finalize = (i = 0, len = pending.length) => {
2892
+ for (;i < len; i++) {
2893
+ pending[i].s({
2894
+ done: true,
2895
+ value: undefined
2896
+ });
2897
+ }
2898
+ };
2899
+ stream.on({
2900
+ next: (value) => {
2901
+ const temp = pending.shift();
2902
+ if (temp) {
2903
+ temp.s({ done: false, value });
2904
+ }
2905
+ buffer.push(value);
2906
+ },
2907
+ throw: (value) => {
2908
+ const temp = pending.shift();
2909
+ if (temp) {
2910
+ temp.f(value);
2911
+ }
2912
+ finalize();
2913
+ doneAt = buffer.length;
2914
+ isThrow = true;
2915
+ buffer.push(value);
2916
+ },
2917
+ return: (value) => {
2918
+ const temp = pending.shift();
2919
+ if (temp) {
2920
+ temp.s({ done: true, value });
2921
+ }
2922
+ finalize();
2923
+ doneAt = buffer.length;
2924
+ buffer.push(value);
2925
+ }
2926
+ });
2927
+ const instance = {
2928
+ [symbol]: () => instance,
2929
+ next: () => {
2930
+ if (doneAt === -1) {
2931
+ const index2 = count++;
2932
+ if (index2 >= buffer.length) {
2933
+ const temp = createPromise();
2934
+ pending.push(temp);
2935
+ return temp.p;
2936
+ }
2937
+ return {
2938
+ done: false,
2939
+ value: buffer[index2]
2940
+ };
2941
+ }
2942
+ if (count > doneAt) {
2943
+ return {
2944
+ done: true,
2945
+ value: undefined
2946
+ };
2947
+ }
2948
+ const index = count++;
2949
+ const value = buffer[index];
2950
+ if (index !== doneAt) {
2951
+ return {
2952
+ done: false,
2953
+ value
2954
+ };
2955
+ }
2956
+ if (isThrow) {
2957
+ throw value;
2958
+ }
2959
+ return {
2960
+ done: true,
2961
+ value
2962
+ };
2963
+ }
2964
+ };
2965
+ return instance;
2966
+ };
2967
+ function isSequence(value) {
2968
+ return "__SEROVAL_SEQUENCE__" in value;
2969
+ }
2970
+ function createSequence(values, throwAt, doneAt) {
2971
+ return {
2972
+ __SEROVAL_SEQUENCE__: true,
2973
+ v: values,
2974
+ t: throwAt,
2975
+ d: doneAt
2976
+ };
2977
+ }
2978
+ function createSequenceFromIterable(source) {
2979
+ const values = [];
2980
+ let throwsAt = -1;
2981
+ let doneAt = -1;
2982
+ const iterator = source[SYM_ITERATOR]();
2983
+ while (true) {
2984
+ try {
2985
+ const value = iterator.next();
2986
+ values.push(value.value);
2987
+ if (value.done) {
2988
+ doneAt = values.length - 1;
2989
+ break;
2990
+ }
2991
+ } catch (error) {
2992
+ throwsAt = values.length;
2993
+ values.push(error);
2994
+ }
2995
+ }
2996
+ return createSequence(values, throwsAt, doneAt);
2997
+ }
2998
+ var createIterator = ITERATOR_CONSTRUCTOR(SYM_ITERATOR);
2999
+ var ITERATOR = {};
3000
+ var ASYNC_ITERATOR = {};
3001
+ var SPECIAL_REFS = {
3002
+ [0]: {},
3003
+ [1]: {},
3004
+ [2]: {},
3005
+ [3]: {},
3006
+ [4]: {},
3007
+ [5]: {}
3008
+ };
3009
+ function isStream(value) {
3010
+ return "__SEROVAL_STREAM__" in value;
3011
+ }
3012
+ function createStream() {
3013
+ return STREAM_CONSTRUCTOR();
3014
+ }
3015
+ function createStreamFromAsyncIterable(iterable) {
3016
+ const stream = createStream();
3017
+ const iterator = iterable[SYM_ASYNC_ITERATOR]();
3018
+ async function push() {
3019
+ try {
3020
+ const value = await iterator.next();
3021
+ if (value.done) {
3022
+ stream.return(value.value);
3023
+ } else {
3024
+ stream.next(value.value);
3025
+ await push();
3026
+ }
3027
+ } catch (error) {
3028
+ stream.throw(error);
3029
+ }
3030
+ }
3031
+ push().catch(() => {});
3032
+ return stream;
3033
+ }
3034
+ var createAsyncIterable = ASYNC_ITERATOR_CONSTRUCTOR(SYM_ASYNC_ITERATOR, PROMISE_CONSTRUCTOR);
3035
+ async function promiseToResult(current) {
3036
+ try {
3037
+ return [1, await current];
3038
+ } catch (e) {
3039
+ return [0, e];
3040
+ }
3041
+ }
3042
+ function createBaseParserContext(mode, options) {
3043
+ return {
3044
+ plugins: options.plugins,
3045
+ mode,
3046
+ marked: /* @__PURE__ */ new Set,
3047
+ features: ALL_ENABLED ^ (options.disabledFeatures || 0),
3048
+ refs: options.refs || /* @__PURE__ */ new Map,
3049
+ depthLimit: options.depthLimit || 1000
3050
+ };
3051
+ }
3052
+ function markParserRef(ctx, id) {
3053
+ ctx.marked.add(id);
3054
+ }
3055
+ function createIndexForValue(ctx, current) {
3056
+ const id = ctx.refs.size;
3057
+ ctx.refs.set(current, id);
3058
+ return id;
3059
+ }
3060
+ function getNodeForIndexedValue(ctx, current) {
3061
+ const registeredId = ctx.refs.get(current);
3062
+ if (registeredId != null) {
3063
+ markParserRef(ctx, registeredId);
3064
+ return {
3065
+ type: 1,
3066
+ value: createIndexedValueNode(registeredId)
3067
+ };
3068
+ }
3069
+ return {
3070
+ type: 0,
3071
+ value: createIndexForValue(ctx, current)
3072
+ };
3073
+ }
3074
+ function getReferenceNode(ctx, current) {
3075
+ const indexed = getNodeForIndexedValue(ctx, current);
3076
+ if (indexed.type === 1) {
3077
+ return indexed;
3078
+ }
3079
+ if (hasReferenceID(current)) {
3080
+ return {
3081
+ type: 2,
3082
+ value: createReferenceNode(indexed.value, current)
3083
+ };
3084
+ }
3085
+ return indexed;
3086
+ }
3087
+ function parseWellKnownSymbol(ctx, current) {
3088
+ const ref = getReferenceNode(ctx, current);
3089
+ if (ref.type !== 0) {
3090
+ return ref.value;
3091
+ }
3092
+ if (current in INV_SYMBOL_REF) {
3093
+ return createWKSymbolNode(ref.value, current);
3094
+ }
3095
+ throw new SerovalUnsupportedTypeError(current);
3096
+ }
3097
+ function parseSpecialReference(ctx, ref) {
3098
+ const result = getNodeForIndexedValue(ctx, SPECIAL_REFS[ref]);
3099
+ if (result.type === 1) {
3100
+ return result.value;
3101
+ }
3102
+ return createSerovalNode(26, result.value, ref, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
3103
+ }
3104
+ function parseIteratorFactory(ctx) {
3105
+ const result = getNodeForIndexedValue(ctx, ITERATOR);
3106
+ if (result.type === 1) {
3107
+ return result.value;
3108
+ }
3109
+ return createSerovalNode(27, result.value, NIL, NIL, NIL, NIL, NIL, NIL, parseWellKnownSymbol(ctx, SYM_ITERATOR), NIL, NIL, NIL);
3110
+ }
3111
+ function parseAsyncIteratorFactory(ctx) {
3112
+ const result = getNodeForIndexedValue(ctx, ASYNC_ITERATOR);
3113
+ if (result.type === 1) {
3114
+ return result.value;
3115
+ }
3116
+ return createSerovalNode(29, result.value, NIL, NIL, NIL, NIL, NIL, [
3117
+ parseSpecialReference(ctx, 1),
3118
+ parseWellKnownSymbol(ctx, SYM_ASYNC_ITERATOR)
3119
+ ], NIL, NIL, NIL, NIL);
3120
+ }
3121
+ function createObjectNode(id, current, empty, record) {
3122
+ return createSerovalNode(empty ? 11 : 10, id, NIL, NIL, NIL, record, NIL, NIL, NIL, NIL, getObjectFlag(current), NIL);
3123
+ }
3124
+ function createMapNode(ctx, id, k, v) {
3125
+ return createSerovalNode(8, id, NIL, NIL, NIL, NIL, { k, v }, NIL, parseSpecialReference(ctx, 0), NIL, NIL, NIL);
3126
+ }
3127
+ function createArrayBufferNode(ctx, id, current) {
3128
+ const bytes = new Uint8Array(current);
3129
+ let result = "";
3130
+ for (let i = 0, len = bytes.length;i < len; i++) {
3131
+ result += String.fromCharCode(bytes[i]);
3132
+ }
3133
+ return createSerovalNode(19, id, serializeString(btoa(result)), NIL, NIL, NIL, NIL, NIL, parseSpecialReference(ctx, 5), NIL, NIL, NIL);
3134
+ }
3135
+ function createAsyncParserContext(mode, options) {
3136
+ return {
3137
+ base: createBaseParserContext(mode, options),
3138
+ child: undefined
3139
+ };
3140
+ }
3141
+ var AsyncParsePluginContext = class {
3142
+ constructor(_p, depth) {
3143
+ this._p = _p;
3144
+ this.depth = depth;
3145
+ }
3146
+ parse(current) {
3147
+ return parseAsync(this._p, this.depth, current);
3148
+ }
3149
+ };
3150
+ async function parseItems(ctx, depth, current) {
3151
+ const nodes = [];
3152
+ for (let i = 0, len = current.length;i < len; i++) {
3153
+ if (i in current) {
3154
+ nodes[i] = await parseAsync(ctx, depth, current[i]);
3155
+ } else {
3156
+ nodes[i] = 0;
3157
+ }
3158
+ }
3159
+ return nodes;
3160
+ }
3161
+ async function parseArray(ctx, depth, id, current) {
3162
+ return createArrayNode(id, current, await parseItems(ctx, depth, current));
3163
+ }
3164
+ async function parseProperties(ctx, depth, properties) {
3165
+ const entries = Object.entries(properties);
3166
+ const keyNodes = [];
3167
+ const valueNodes = [];
3168
+ for (let i = 0, len = entries.length;i < len; i++) {
3169
+ keyNodes.push(serializeString(entries[i][0]));
3170
+ valueNodes.push(await parseAsync(ctx, depth, entries[i][1]));
3171
+ }
3172
+ if (SYM_ITERATOR in properties) {
3173
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ITERATOR));
3174
+ valueNodes.push(createIteratorFactoryInstanceNode(parseIteratorFactory(ctx.base), await parseAsync(ctx, depth, createSequenceFromIterable(properties))));
3175
+ }
3176
+ if (SYM_ASYNC_ITERATOR in properties) {
3177
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ASYNC_ITERATOR));
3178
+ valueNodes.push(createAsyncIteratorFactoryInstanceNode(parseAsyncIteratorFactory(ctx.base), await parseAsync(ctx, depth, createStreamFromAsyncIterable(properties))));
3179
+ }
3180
+ if (SYM_TO_STRING_TAG in properties) {
3181
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_TO_STRING_TAG));
3182
+ valueNodes.push(createStringNode(properties[SYM_TO_STRING_TAG]));
3183
+ }
3184
+ if (SYM_IS_CONCAT_SPREADABLE in properties) {
3185
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_IS_CONCAT_SPREADABLE));
3186
+ valueNodes.push(properties[SYM_IS_CONCAT_SPREADABLE] ? TRUE_NODE : FALSE_NODE);
3187
+ }
3188
+ return {
3189
+ k: keyNodes,
3190
+ v: valueNodes
3191
+ };
3192
+ }
3193
+ async function parsePlainObject(ctx, depth, id, current, empty) {
3194
+ return createObjectNode(id, current, empty, await parseProperties(ctx, depth, current));
3195
+ }
3196
+ async function parseBoxed(ctx, depth, id, current) {
3197
+ return createBoxedNode(id, await parseAsync(ctx, depth, current.valueOf()));
3198
+ }
3199
+ async function parseTypedArray(ctx, depth, id, current) {
3200
+ return createTypedArrayNode(id, current, await parseAsync(ctx, depth, current.buffer));
3201
+ }
3202
+ async function parseBigIntTypedArray(ctx, depth, id, current) {
3203
+ return createBigIntTypedArrayNode(id, current, await parseAsync(ctx, depth, current.buffer));
3204
+ }
3205
+ async function parseDataView(ctx, depth, id, current) {
3206
+ return createDataViewNode(id, current, await parseAsync(ctx, depth, current.buffer));
3207
+ }
3208
+ async function parseError(ctx, depth, id, current) {
3209
+ const options = getErrorOptions(current, ctx.base.features);
3210
+ return createErrorNode(id, current, options ? await parseProperties(ctx, depth, options) : NIL);
3211
+ }
3212
+ async function parseAggregateError(ctx, depth, id, current) {
3213
+ const options = getErrorOptions(current, ctx.base.features);
3214
+ return createAggregateErrorNode(id, current, options ? await parseProperties(ctx, depth, options) : NIL);
3215
+ }
3216
+ async function parseMap(ctx, depth, id, current) {
3217
+ const keyNodes = [];
3218
+ const valueNodes = [];
3219
+ for (const [key, value] of current.entries()) {
3220
+ keyNodes.push(await parseAsync(ctx, depth, key));
3221
+ valueNodes.push(await parseAsync(ctx, depth, value));
3222
+ }
3223
+ return createMapNode(ctx.base, id, keyNodes, valueNodes);
3224
+ }
3225
+ async function parseSet(ctx, depth, id, current) {
3226
+ const items = [];
3227
+ for (const item of current.keys()) {
3228
+ items.push(await parseAsync(ctx, depth, item));
3229
+ }
3230
+ return createSetNode(id, items);
3231
+ }
3232
+ async function parsePlugin(ctx, depth, id, current) {
3233
+ const currentPlugins = ctx.base.plugins;
3234
+ if (currentPlugins) {
3235
+ for (let i = 0, len = currentPlugins.length;i < len; i++) {
3236
+ const plugin = currentPlugins[i];
3237
+ if (plugin.parse.async && plugin.test(current)) {
3238
+ return createPluginNode(id, plugin.tag, await plugin.parse.async(current, new AsyncParsePluginContext(ctx, depth), {
3239
+ id
3240
+ }));
3241
+ }
3242
+ }
3243
+ }
3244
+ return NIL;
3245
+ }
3246
+ async function parsePromise(ctx, depth, id, current) {
3247
+ const [status, result] = await promiseToResult(current);
3248
+ return createSerovalNode(12, id, status, NIL, NIL, NIL, NIL, NIL, await parseAsync(ctx, depth, result), NIL, NIL, NIL);
3249
+ }
3250
+ function parseStreamHandle(depth, id, current, resolve2, reject) {
3251
+ const sequence = [];
3252
+ const cleanup = current.on({
3253
+ next: (value) => {
3254
+ markParserRef(this.base, id);
3255
+ parseAsync(this, depth, value).then((data) => {
3256
+ sequence.push(createStreamNextNode(id, data));
3257
+ }, (data) => {
3258
+ reject(data);
3259
+ cleanup();
3260
+ });
3261
+ },
3262
+ throw: (value) => {
3263
+ markParserRef(this.base, id);
3264
+ parseAsync(this, depth, value).then((data) => {
3265
+ sequence.push(createStreamThrowNode(id, data));
3266
+ resolve2(sequence);
3267
+ cleanup();
3268
+ }, (data) => {
3269
+ reject(data);
3270
+ cleanup();
3271
+ });
3272
+ },
3273
+ return: (value) => {
3274
+ markParserRef(this.base, id);
3275
+ parseAsync(this, depth, value).then((data) => {
3276
+ sequence.push(createStreamReturnNode(id, data));
3277
+ resolve2(sequence);
3278
+ cleanup();
3279
+ }, (data) => {
3280
+ reject(data);
3281
+ cleanup();
3282
+ });
3283
+ }
3284
+ });
3285
+ }
3286
+ async function parseStream(ctx, depth, id, current) {
3287
+ return createStreamConstructorNode(id, parseSpecialReference(ctx.base, 4), await new Promise(parseStreamHandle.bind(ctx, depth, id, current)));
3288
+ }
3289
+ async function parseSequence(ctx, depth, id, current) {
3290
+ const nodes = [];
3291
+ for (let i = 0, len = current.v.length;i < len; i++) {
3292
+ nodes[i] = await parseAsync(ctx, depth, current.v[i]);
3293
+ }
3294
+ return createSequenceNode(id, nodes, current.t, current.d);
3295
+ }
3296
+ async function parseObjectAsync(ctx, depth, id, current) {
3297
+ if (Array.isArray(current)) {
3298
+ return parseArray(ctx, depth, id, current);
3299
+ }
3300
+ if (isStream(current)) {
3301
+ return parseStream(ctx, depth, id, current);
3302
+ }
3303
+ if (isSequence(current)) {
3304
+ return parseSequence(ctx, depth, id, current);
3305
+ }
3306
+ const currentClass = current.constructor;
3307
+ if (currentClass === OpaqueReference) {
3308
+ return parseAsync(ctx, depth, current.replacement);
3309
+ }
3310
+ const parsed = await parsePlugin(ctx, depth, id, current);
3311
+ if (parsed) {
3312
+ return parsed;
3313
+ }
3314
+ switch (currentClass) {
3315
+ case Object:
3316
+ return parsePlainObject(ctx, depth, id, current, false);
3317
+ case NIL:
3318
+ return parsePlainObject(ctx, depth, id, current, true);
3319
+ case Date:
3320
+ return createDateNode(id, current);
3321
+ case Error:
3322
+ case EvalError:
3323
+ case RangeError:
3324
+ case ReferenceError:
3325
+ case SyntaxError:
3326
+ case TypeError:
3327
+ case URIError:
3328
+ return parseError(ctx, depth, id, current);
3329
+ case Number:
3330
+ case Boolean:
3331
+ case String:
3332
+ case BigInt:
3333
+ return parseBoxed(ctx, depth, id, current);
3334
+ case ArrayBuffer:
3335
+ return createArrayBufferNode(ctx.base, id, current);
3336
+ case Int8Array:
3337
+ case Int16Array:
3338
+ case Int32Array:
3339
+ case Uint8Array:
3340
+ case Uint16Array:
3341
+ case Uint32Array:
3342
+ case Uint8ClampedArray:
3343
+ case Float32Array:
3344
+ case Float64Array:
3345
+ return parseTypedArray(ctx, depth, id, current);
3346
+ case DataView:
3347
+ return parseDataView(ctx, depth, id, current);
3348
+ case Map:
3349
+ return parseMap(ctx, depth, id, current);
3350
+ case Set:
3351
+ return parseSet(ctx, depth, id, current);
3352
+ default:
3353
+ break;
3354
+ }
3355
+ if (currentClass === Promise || current instanceof Promise) {
3356
+ return parsePromise(ctx, depth, id, current);
3357
+ }
3358
+ const currentFeatures = ctx.base.features;
3359
+ if (currentFeatures & 32 && currentClass === RegExp) {
3360
+ return createRegExpNode(id, current);
3361
+ }
3362
+ if (currentFeatures & 16) {
3363
+ switch (currentClass) {
3364
+ case BigInt64Array:
3365
+ case BigUint64Array:
3366
+ return parseBigIntTypedArray(ctx, depth, id, current);
3367
+ default:
3368
+ break;
3369
+ }
3370
+ }
3371
+ if (currentFeatures & 1 && typeof AggregateError !== "undefined" && (currentClass === AggregateError || current instanceof AggregateError)) {
3372
+ return parseAggregateError(ctx, depth, id, current);
3373
+ }
3374
+ if (current instanceof Error) {
3375
+ return parseError(ctx, depth, id, current);
3376
+ }
3377
+ if (SYM_ITERATOR in current || SYM_ASYNC_ITERATOR in current) {
3378
+ return parsePlainObject(ctx, depth, id, current, !!currentClass);
3379
+ }
3380
+ throw new SerovalUnsupportedTypeError(current);
3381
+ }
3382
+ async function parseFunctionAsync(ctx, depth, current) {
3383
+ const ref = getReferenceNode(ctx.base, current);
3384
+ if (ref.type !== 0) {
3385
+ return ref.value;
3386
+ }
3387
+ const plugin = await parsePlugin(ctx, depth, ref.value, current);
3388
+ if (plugin) {
3389
+ return plugin;
3390
+ }
3391
+ throw new SerovalUnsupportedTypeError(current);
3392
+ }
3393
+ async function parseAsync(ctx, depth, current) {
3394
+ switch (typeof current) {
3395
+ case "boolean":
3396
+ return current ? TRUE_NODE : FALSE_NODE;
3397
+ case "undefined":
3398
+ return UNDEFINED_NODE;
3399
+ case "string":
3400
+ return createStringNode(current);
3401
+ case "number":
3402
+ return createNumberNode(current);
3403
+ case "bigint":
3404
+ return createBigIntNode(current);
3405
+ case "object": {
3406
+ if (current) {
3407
+ const ref = getReferenceNode(ctx.base, current);
3408
+ return ref.type === 0 ? await parseObjectAsync(ctx, depth + 1, ref.value, current) : ref.value;
3409
+ }
3410
+ return NULL_NODE;
3411
+ }
3412
+ case "symbol":
3413
+ return parseWellKnownSymbol(ctx.base, current);
3414
+ case "function":
3415
+ return parseFunctionAsync(ctx, depth, current);
3416
+ default:
3417
+ throw new SerovalUnsupportedTypeError(current);
3418
+ }
3419
+ }
3420
+ async function parseTopAsync(ctx, current) {
3421
+ try {
3422
+ return await parseAsync(ctx, 0, current);
3423
+ } catch (error) {
3424
+ throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
3425
+ }
3426
+ }
3427
+ function dedupePlugins(deduped, plugins) {
3428
+ for (let i = 0, len = plugins.length;i < len; i++) {
3429
+ const current = plugins[i];
3430
+ if (!deduped.has(current)) {
3431
+ deduped.add(current);
3432
+ if (current.extends) {
3433
+ dedupePlugins(deduped, current.extends);
3434
+ }
3435
+ }
3436
+ }
3437
+ }
3438
+ function resolvePlugins(plugins) {
3439
+ if (plugins) {
3440
+ const deduped = /* @__PURE__ */ new Set;
3441
+ dedupePlugins(deduped, plugins);
3442
+ return [...deduped];
3443
+ }
3444
+ return;
3445
+ }
3446
+ var REF_START_CHARS = "hjkmoquxzABCDEFGHIJKLNPQRTUVWXYZ$_";
3447
+ var REF_START_CHARS_LEN = REF_START_CHARS.length;
3448
+ var REF_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$_";
3449
+ var REF_CHARS_LEN = REF_CHARS.length;
3450
+ async function toCrossJSONAsync(source, options = {}) {
3451
+ const plugins = resolvePlugins(options.plugins);
3452
+ const ctx = createAsyncParserContext(2, {
3453
+ plugins,
3454
+ disabledFeatures: options.disabledFeatures,
3455
+ refs: options.refs
3456
+ });
3457
+ return await parseTopAsync(ctx, source);
3458
+ }
3459
+
2274
3460
  // src/not-found.ts
2275
3461
  var NOT_FOUND_BRAND = "FURIN_NOT_FOUND";
2276
3462
 
@@ -2286,7 +3472,7 @@ function isNotFoundError(err) {
2286
3472
  return err instanceof FurinNotFoundError || typeof err === "object" && err !== null && err.__furinBrand === NOT_FOUND_BRAND;
2287
3473
  }
2288
3474
 
2289
- // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/utils.mjs
3475
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/utils.mjs
2290
3476
  function formatDuration(ms) {
2291
3477
  if (ms < 1000)
2292
3478
  return `${Math.round(ms)}ms`;
@@ -2374,6 +3560,21 @@ function getCssLevelColor(level) {
2374
3560
  function escapeFormatString(str) {
2375
3561
  return str.replace(/%/g, "%%");
2376
3562
  }
3563
+ var SENSITIVE_HEADERS = [
3564
+ "authorization",
3565
+ "cookie",
3566
+ "set-cookie",
3567
+ "x-api-key",
3568
+ "x-auth-token",
3569
+ "proxy-authorization"
3570
+ ];
3571
+ function filterSafeHeaders(headers) {
3572
+ const safeHeaders = {};
3573
+ for (const [key, value] of Object.entries(headers))
3574
+ if (!SENSITIVE_HEADERS.includes(key.toLowerCase()))
3575
+ safeHeaders[key] = value;
3576
+ return safeHeaders;
3577
+ }
2377
3578
  var patternCache = /* @__PURE__ */ new Map;
2378
3579
  function matchesPattern(path, pattern) {
2379
3580
  let regex = patternCache.get(pattern);
@@ -2385,7 +3586,25 @@ function matchesPattern(path, pattern) {
2385
3586
  return regex.test(path);
2386
3587
  }
2387
3588
 
2388
- // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/audit-DQoBo7Dl.mjs
3589
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/headers-CU-QqnYg.mjs
3590
+ function extractSafeHeaders(headers) {
3591
+ const raw = {};
3592
+ headers.forEach((value, key) => {
3593
+ raw[key] = value;
3594
+ });
3595
+ return filterSafeHeaders(raw);
3596
+ }
3597
+ function extractSafeNodeHeaders(headers) {
3598
+ const raw = {};
3599
+ for (const [key, value] of Object.entries(headers)) {
3600
+ if (value === undefined)
3601
+ continue;
3602
+ raw[key] = Array.isArray(value) ? value.join(", ") : value;
3603
+ }
3604
+ return filterSafeHeaders(raw);
3605
+ }
3606
+
3607
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/audit-pV5aLGP0.mjs
2389
3608
  var DEFAULT_REPLACEMENT = "[REDACTED]";
2390
3609
  var builtinPatterns = {
2391
3610
  creditCard: {
@@ -2526,15 +3745,126 @@ function applyMaskersToTree(obj, maskers) {
2526
3745
  else if (typeof val === "object")
2527
3746
  applyMaskersToTree(val, maskers);
2528
3747
  }
2529
- }
3748
+ }
3749
+ }
3750
+ function applyMaskers(value, maskers) {
3751
+ let result = value;
3752
+ for (const [pattern, mask] of maskers) {
3753
+ pattern.lastIndex = 0;
3754
+ result = result.replace(pattern, mask);
3755
+ }
3756
+ return result;
3757
+ }
3758
+ function logPluginError(name, hook, err) {
3759
+ console.error(`[evlog/${name}] ${hook} failed:`, err);
3760
+ }
3761
+ function createPluginRunner(plugins = []) {
3762
+ const byName = /* @__PURE__ */ new Map;
3763
+ for (const plugin of plugins)
3764
+ byName.set(plugin.name, plugin);
3765
+ const list = Array.from(byName.values());
3766
+ return {
3767
+ plugins: list,
3768
+ hasEnrich: list.some((p) => typeof p.enrich === "function"),
3769
+ hasDrain: list.some((p) => typeof p.drain === "function"),
3770
+ hasKeep: list.some((p) => typeof p.keep === "function"),
3771
+ hasRequestLifecycle: list.some((p) => typeof p.onRequestStart === "function" || typeof p.onRequestFinish === "function"),
3772
+ hasClientLog: list.some((p) => typeof p.onClientLog === "function"),
3773
+ hasExtendLogger: list.some((p) => typeof p.extendLogger === "function"),
3774
+ applyExtendLogger(logger) {
3775
+ for (const plugin of list) {
3776
+ if (!plugin.extendLogger)
3777
+ continue;
3778
+ try {
3779
+ plugin.extendLogger(logger);
3780
+ } catch (err) {
3781
+ logPluginError(plugin.name, "extendLogger", err);
3782
+ }
3783
+ }
3784
+ },
3785
+ runOnRequestStart(ctx) {
3786
+ for (const plugin of list) {
3787
+ if (!plugin.onRequestStart)
3788
+ continue;
3789
+ try {
3790
+ plugin.onRequestStart(ctx);
3791
+ } catch (err) {
3792
+ logPluginError(plugin.name, "onRequestStart", err);
3793
+ }
3794
+ }
3795
+ },
3796
+ runOnRequestFinish(ctx) {
3797
+ for (const plugin of list) {
3798
+ if (!plugin.onRequestFinish)
3799
+ continue;
3800
+ try {
3801
+ plugin.onRequestFinish(ctx);
3802
+ } catch (err) {
3803
+ logPluginError(plugin.name, "onRequestFinish", err);
3804
+ }
3805
+ }
3806
+ },
3807
+ async runEnrich(ctx) {
3808
+ for (const plugin of list) {
3809
+ if (!plugin.enrich)
3810
+ continue;
3811
+ try {
3812
+ await plugin.enrich(ctx);
3813
+ } catch (err) {
3814
+ logPluginError(plugin.name, "enrich", err);
3815
+ }
3816
+ }
3817
+ },
3818
+ async runDrain(ctx) {
3819
+ const drains = list.filter((p) => typeof p.drain === "function");
3820
+ if (drains.length === 0)
3821
+ return;
3822
+ await Promise.allSettled(drains.map(async (plugin) => {
3823
+ try {
3824
+ await plugin.drain(ctx);
3825
+ } catch (err) {
3826
+ logPluginError(plugin.name, "drain", err);
3827
+ }
3828
+ }));
3829
+ },
3830
+ async runKeep(ctx) {
3831
+ for (const plugin of list) {
3832
+ if (!plugin.keep)
3833
+ continue;
3834
+ try {
3835
+ await plugin.keep(ctx);
3836
+ } catch (err) {
3837
+ logPluginError(plugin.name, "keep", err);
3838
+ }
3839
+ }
3840
+ },
3841
+ runOnClientLog(ctx) {
3842
+ for (const plugin of list) {
3843
+ if (!plugin.onClientLog)
3844
+ continue;
3845
+ try {
3846
+ plugin.onClientLog(ctx);
3847
+ } catch (err) {
3848
+ logPluginError(plugin.name, "onClientLog", err);
3849
+ }
3850
+ }
3851
+ },
3852
+ async runSetup(ctx) {
3853
+ for (const plugin of list) {
3854
+ if (!plugin.setup)
3855
+ continue;
3856
+ try {
3857
+ await plugin.setup(ctx);
3858
+ } catch (err) {
3859
+ logPluginError(plugin.name, "setup", err);
3860
+ }
3861
+ }
3862
+ }
3863
+ };
2530
3864
  }
2531
- function applyMaskers(value, maskers) {
2532
- let result = value;
2533
- for (const [pattern, mask] of maskers) {
2534
- pattern.lastIndex = 0;
2535
- result = result.replace(pattern, mask);
2536
- }
2537
- return result;
3865
+ var emptyRunner = createPluginRunner([]);
3866
+ function getEmptyPluginRunner() {
3867
+ return emptyRunner;
2538
3868
  }
2539
3869
  function isPlainObject(val) {
2540
3870
  return val !== null && typeof val === "object" && !Array.isArray(val);
@@ -2574,6 +3904,7 @@ var globalRedact;
2574
3904
  var globalEnabled = true;
2575
3905
  var globalSilent = false;
2576
3906
  var globalMinLevel = "debug";
3907
+ var globalPluginRunner = getEmptyPluginRunner();
2577
3908
  function initLogger(config = {}) {
2578
3909
  globalEnabled = config.enabled ?? true;
2579
3910
  const detected = detectEnvironment();
@@ -2591,9 +3922,22 @@ function initLogger(config = {}) {
2591
3922
  globalRedact = resolveRedactConfig(config.redact ?? !isDev());
2592
3923
  globalSilent = config.silent ?? false;
2593
3924
  globalMinLevel = config.minLevel ?? "debug";
2594
- if (globalSilent && !globalDrain && !config._suppressDrainWarning)
3925
+ globalPluginRunner = config.plugins?.length ? createPluginRunner(config.plugins) : getEmptyPluginRunner();
3926
+ if (globalPluginRunner.plugins.length > 0)
3927
+ globalPluginRunner.runSetup({ env: { ...globalEnv } });
3928
+ const hasAnyDrain = !!globalDrain || globalPluginRunner.hasDrain;
3929
+ if (globalSilent && !hasAnyDrain && !config._suppressDrainWarning)
2595
3930
  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).");
2596
3931
  }
3932
+ function getGlobalPluginRunner() {
3933
+ return globalPluginRunner;
3934
+ }
3935
+ function isEnabled() {
3936
+ return globalEnabled;
3937
+ }
3938
+ function getGlobalDrain() {
3939
+ return globalDrain;
3940
+ }
2597
3941
  function shouldSample(level) {
2598
3942
  const { rates } = globalSampling;
2599
3943
  if (!rates)
@@ -2661,12 +4005,20 @@ function emitWideEvent(level, event, options = {}) {
2661
4005
  console[getConsoleMethod(level)](JSON.stringify(formatted));
2662
4006
  else
2663
4007
  console[getConsoleMethod(level)](formatted);
2664
- if (globalDrain && !deferDrain) {
2665
- const drainPromise = Promise.resolve(globalDrain({ event: formatted })).catch((err) => {
2666
- console.error("[evlog] drain failed:", err);
2667
- });
2668
- if (waitUntil)
2669
- waitUntil(drainPromise);
4008
+ if (!deferDrain) {
4009
+ const drainPromises = [];
4010
+ if (globalDrain)
4011
+ drainPromises.push((async () => {
4012
+ try {
4013
+ await globalDrain({ event: formatted });
4014
+ } catch (err) {
4015
+ console.error("[evlog] drain failed:", err);
4016
+ }
4017
+ })());
4018
+ if (globalPluginRunner.hasDrain)
4019
+ drainPromises.push(globalPluginRunner.runDrain({ event: formatted }));
4020
+ if (drainPromises.length > 0 && waitUntil)
4021
+ waitUntil(Promise.all(drainPromises));
2670
4022
  }
2671
4023
  return formatted;
2672
4024
  }
@@ -3035,6 +4387,7 @@ function createLogger(initialContext = {}, internalOptions) {
3035
4387
  };
3036
4388
  const errRecord = err;
3037
4389
  for (const k of [
4390
+ "code",
3038
4391
  "status",
3039
4392
  "statusText",
3040
4393
  "statusCode",
@@ -3117,6 +4470,20 @@ function createLogger(initialContext = {}, internalOptions) {
3117
4470
  }
3118
4471
  };
3119
4472
  }
4473
+ function createRequestLogger(options = {}, internalOptions) {
4474
+ const { method, path, requestId, waitUntil: optionsWaitUntil } = options;
4475
+ const initial = {};
4476
+ if (method !== undefined)
4477
+ initial.method = method;
4478
+ if (path !== undefined)
4479
+ initial.path = path;
4480
+ if (requestId !== undefined)
4481
+ initial.requestId = requestId;
4482
+ return createLogger(initial, {
4483
+ ...internalOptions,
4484
+ waitUntil: internalOptions?.waitUntil ?? optionsWaitUntil
4485
+ });
4486
+ }
3120
4487
  if (typeof __EVLOG_CONFIG__ !== "undefined")
3121
4488
  initLogger(__EVLOG_CONFIG__);
3122
4489
  function stableStringify(value) {
@@ -3191,6 +4558,16 @@ function finalizeAudit(event) {
3191
4558
  return;
3192
4559
  event.audit = decorateAudit(a, String(event.timestamp));
3193
4560
  }
4561
+
4562
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/errors-BQgyQ9xe.mjs
4563
+ function extractErrorStatus(error) {
4564
+ if (error === null || typeof error !== "object")
4565
+ return 500;
4566
+ const raw = error.status ?? error.statusCode;
4567
+ const status = Number(raw);
4568
+ return Number.isFinite(status) ? status : 500;
4569
+ }
4570
+
3194
4571
  // src/router-provider.tsx
3195
4572
  import {
3196
4573
  createContext,
@@ -3210,12 +4587,29 @@ import { Component, Fragment } from "react";
3210
4587
  // src/error.ts
3211
4588
  function getPublicErrorMessage(error) {
3212
4589
  const branded = error;
3213
- if (branded?.__furinBrand === "FURIN_NOT_FOUND") {
4590
+ if (branded?.__furinBrand === "FURIN_NOT_FOUND" || branded?.__furinBrand === "FURIN_SERVER_ERROR") {
3214
4591
  return error.message;
3215
4592
  }
3216
4593
  return "Something went wrong";
3217
4594
  }
3218
4595
 
4596
+ // src/server-error.ts
4597
+ var SERVER_ERROR_BRAND = "FURIN_SERVER_ERROR";
4598
+
4599
+ class FurinServerError extends Error {
4600
+ __furinBrand = SERVER_ERROR_BRAND;
4601
+ digest;
4602
+ status;
4603
+ constructor(args) {
4604
+ super(args.message);
4605
+ this.status = args.status;
4606
+ this.digest = args.digest;
4607
+ }
4608
+ }
4609
+ function isFurinServerError(err) {
4610
+ return err instanceof FurinServerError || typeof err === "object" && err !== null && err.__furinBrand === SERVER_ERROR_BRAND;
4611
+ }
4612
+
3219
4613
  // src/link.tsx
3220
4614
  import { createElement, useCallback, useEffect, useRef } from "react";
3221
4615
  function computeLinkView({
@@ -3265,9 +4659,10 @@ function LinkInteractive({
3265
4659
  const effectivePreload = preload ?? router.defaultPreload;
3266
4660
  const effectiveDelay = preloadDelay ?? router.defaultPreloadDelay;
3267
4661
  const effectiveStaleTime = preloadStaleTime ?? router.defaultPreloadStaleTime;
4662
+ const { prefetch } = router;
3268
4663
  const triggerPrefetch = useCallback(() => {
3269
- router.prefetch(logicalHref, { staleTime: effectiveStaleTime });
3270
- }, [router, logicalHref, effectiveStaleTime]);
4664
+ prefetch(logicalHref, { staleTime: effectiveStaleTime });
4665
+ }, [prefetch, logicalHref, effectiveStaleTime]);
3271
4666
  useEffect(() => {
3272
4667
  if (effectivePreload === "render") {
3273
4668
  triggerPrefetch();
@@ -3318,6 +4713,10 @@ function LinkInteractive({
3318
4713
  return;
3319
4714
  }
3320
4715
  e.preventDefault();
4716
+ if (typeof window !== "undefined" && router.navigate === SSR_FALLBACK_ROUTER.navigate) {
4717
+ window.location.href = href;
4718
+ return;
4719
+ }
3321
4720
  router.navigate(logicalHref, { replace, resetScroll: resetScroll ?? true });
3322
4721
  };
3323
4722
  const handleMouseEnter = (e) => {
@@ -3480,11 +4879,6 @@ var BADGE_STYLE = {
3480
4879
  marginBottom: "16px",
3481
4880
  padding: "12px 36px"
3482
4881
  };
3483
- var NOT_FOUND_BADGE_STYLE = {
3484
- ...BADGE_STYLE,
3485
- border: 0,
3486
- padding: 0
3487
- };
3488
4882
  var HEADING_STYLE = {
3489
4883
  color: COLOR_TEXT,
3490
4884
  fontFamily: FONT_SANS,
@@ -3572,7 +4966,7 @@ function ScreenFrame({ badge, children }) {
3572
4966
  style: PAGE_STYLE,
3573
4967
  children: [
3574
4968
  /* @__PURE__ */ jsxDEV("style", {
3575
- dangerouslySetInnerHTML: { __html: RESET_CSS }
4969
+ children: RESET_CSS
3576
4970
  }, undefined, false, undefined, this),
3577
4971
  /* @__PURE__ */ jsxDEV("div", {
3578
4972
  style: FRAME_STYLE,
@@ -3653,7 +5047,7 @@ function DefaultErrorScreen({ message, digest, reset }) {
3653
5047
  function DefaultNotFoundScreen({ message }) {
3654
5048
  return /* @__PURE__ */ jsxDEV(ScreenFrame, {
3655
5049
  badge: /* @__PURE__ */ jsxDEV("div", {
3656
- style: NOT_FOUND_BADGE_STYLE,
5050
+ style: BADGE_STYLE,
3657
5051
  children: "404 \u2014 NOT FOUND"
3658
5052
  }, undefined, false, undefined, this),
3659
5053
  children: [
@@ -3719,6 +5113,7 @@ var DefaultErrorFallback = ({ error, reset }) => /* @__PURE__ */ jsxDEV2(Default
3719
5113
  message: error.message,
3720
5114
  reset
3721
5115
  }, undefined, false, undefined, this);
5116
+ var DEFAULT_ERROR_STATUS = 500;
3722
5117
  var DefaultNotFoundFallback = ({ error }) => /* @__PURE__ */ jsxDEV2(DefaultNotFoundScreen, {
3723
5118
  message: error.message
3724
5119
  }, undefined, false, undefined, this);
@@ -3750,10 +5145,12 @@ class FurinErrorBoundary extends Component {
3750
5145
  throw error;
3751
5146
  }
3752
5147
  const Fallback = this.props.fallback ?? DefaultErrorFallback;
3753
- const finalDigest = digest ?? this.props.digest ?? computeErrorDigest(error);
5148
+ const serverDigest = isFurinServerError(error) ? error.digest : undefined;
5149
+ const finalDigest = serverDigest ?? digest ?? this.props.digest ?? computeErrorDigest(error);
3754
5150
  const message = this.props.fallback ? error.message : getPublicErrorMessage(error);
5151
+ const status = isFurinServerError(error) ? error.status : DEFAULT_ERROR_STATUS;
3755
5152
  return /* @__PURE__ */ jsxDEV2(Fallback, {
3756
- error: { message, digest: finalDigest },
5153
+ error: { message, digest: finalDigest, status },
3757
5154
  reset: typeof window === "undefined" ? SERVER_RESET_NOOP : this.reset
3758
5155
  }, undefined, false, undefined, this);
3759
5156
  }
@@ -3842,23 +5239,378 @@ function normalizeHref(href) {
3842
5239
  return pathname + url.search + url.hash;
3843
5240
  }
3844
5241
 
5242
+ // src/utils.ts
5243
+ function isFurinPage(value) {
5244
+ return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
5245
+ }
5246
+ function isFurinRoute(value) {
5247
+ return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_ROUTE";
5248
+ }
5249
+ function collectRouteChainFromRoute(route) {
5250
+ const chain = [];
5251
+ let current = route;
5252
+ while (current) {
5253
+ chain.unshift(current);
5254
+ current = current.parent;
5255
+ }
5256
+ return chain;
5257
+ }
5258
+ function hasCycle(route) {
5259
+ const visited = new Set;
5260
+ let current = route;
5261
+ while (current) {
5262
+ if (visited.has(current)) {
5263
+ return true;
5264
+ }
5265
+ visited.add(current);
5266
+ current = current.parent;
5267
+ }
5268
+ return false;
5269
+ }
5270
+ async function mapWithConcurrency(items, concurrency, fn) {
5271
+ if (items.length === 0) {
5272
+ return [];
5273
+ }
5274
+ const results = new Array(items.length);
5275
+ let cursor = 0;
5276
+ const workerCount = Math.min(Math.max(concurrency, 1), items.length);
5277
+ await Promise.all(Array.from({ length: workerCount }, async () => {
5278
+ while (true) {
5279
+ const index = cursor++;
5280
+ if (index >= items.length) {
5281
+ return;
5282
+ }
5283
+ results[index] = await fn(items[index], index);
5284
+ }
5285
+ }));
5286
+ return results;
5287
+ }
5288
+ function validateRouteChain(chain, root, pagePath) {
5289
+ const hasRoot = chain.some((r) => r === root);
5290
+ if (!hasRoot) {
5291
+ const location = pagePath ? `in ${pagePath}` : "";
5292
+ throw new Error(`[furin] Page ${location} must inherit from root route. ` + 'Add: import { route } from "./root"; and use route.page() or set parent: route');
5293
+ }
5294
+ for (const route of chain) {
5295
+ if (hasCycle(route)) {
5296
+ throw new Error("[furin] Cycle detected in route chain. A route cannot be its own ancestor.");
5297
+ }
5298
+ }
5299
+ }
5300
+
3845
5301
  // src/render/cache.ts
3846
5302
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
3847
5303
 
3848
5304
  // src/context-logger.ts
3849
5305
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
3850
5306
 
3851
- // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/elysia/index.mjs
5307
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/routes-CnIgYWf8.mjs
5308
+ function shouldLog(path, include, exclude) {
5309
+ if (exclude && exclude.length > 0) {
5310
+ if (exclude.some((pattern) => matchesPattern(path, pattern)))
5311
+ return false;
5312
+ }
5313
+ if (!include || include.length === 0)
5314
+ return true;
5315
+ return include.some((pattern) => matchesPattern(path, pattern));
5316
+ }
5317
+ function getServiceForPath(path, routes) {
5318
+ if (!routes)
5319
+ return;
5320
+ for (const [pattern, config] of Object.entries(routes))
5321
+ if (matchesPattern(path, pattern))
5322
+ return config.service;
5323
+ }
5324
+
5325
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/fork-8u_zFOJq.mjs
5326
+ var noopResult = {
5327
+ logger: {
5328
+ set() {},
5329
+ error() {},
5330
+ info() {},
5331
+ warn() {},
5332
+ emit() {
5333
+ return null;
5334
+ },
5335
+ getContext() {
5336
+ return {};
5337
+ }
5338
+ },
5339
+ finish: () => Promise.resolve(null),
5340
+ skipped: true
5341
+ };
5342
+ var runnerCache = /* @__PURE__ */ new WeakMap;
5343
+ function resolveMiddlewarePluginRunner(options) {
5344
+ const global2 = getGlobalPluginRunner();
5345
+ const local = options.plugins;
5346
+ if (!local || local.length === 0)
5347
+ return global2;
5348
+ const cached = runnerCache.get(local);
5349
+ if (cached && cached.global === global2)
5350
+ return cached.merged;
5351
+ const merged = /* @__PURE__ */ new Map;
5352
+ for (const plugin of global2.plugins)
5353
+ merged.set(plugin.name, plugin);
5354
+ for (const plugin of local)
5355
+ merged.set(plugin.name, plugin);
5356
+ if (merged.size === 0)
5357
+ return getEmptyPluginRunner();
5358
+ const runner = createPluginRunner(Array.from(merged.values()));
5359
+ runnerCache.set(local, {
5360
+ global: global2,
5361
+ merged: runner
5362
+ });
5363
+ return runner;
5364
+ }
5365
+ async function runEnrichAndDrain(emittedEvent, options, requestInfo, responseStatus, plugins) {
5366
+ const runner = plugins ?? resolveMiddlewarePluginRunner(options);
5367
+ const resolvedRedact = resolveRedactConfig(options.redact);
5368
+ if (resolvedRedact)
5369
+ redactEvent(emittedEvent, resolvedRedact);
5370
+ if (options.enrich || runner.hasEnrich) {
5371
+ const enrichCtx = {
5372
+ event: emittedEvent,
5373
+ request: requestInfo,
5374
+ headers: options.headers,
5375
+ response: { status: responseStatus }
5376
+ };
5377
+ if (options.enrich)
5378
+ try {
5379
+ await options.enrich(enrichCtx);
5380
+ } catch (err) {
5381
+ console.error("[evlog] enrich failed:", err);
5382
+ }
5383
+ if (runner.hasEnrich)
5384
+ await runner.runEnrich(enrichCtx);
5385
+ }
5386
+ const drain = options.drain ?? getGlobalDrain();
5387
+ const hasUserDrain = !!drain;
5388
+ const hasPluginDrain = runner.hasDrain;
5389
+ if (hasUserDrain || hasPluginDrain) {
5390
+ const drainCtx = {
5391
+ event: emittedEvent,
5392
+ request: requestInfo,
5393
+ headers: options.headers
5394
+ };
5395
+ const tasks = [];
5396
+ if (hasUserDrain)
5397
+ tasks.push((async () => {
5398
+ try {
5399
+ await drain(drainCtx);
5400
+ } catch (err) {
5401
+ console.error("[evlog] drain failed:", err);
5402
+ }
5403
+ })());
5404
+ if (hasPluginDrain)
5405
+ tasks.push(runner.runDrain(drainCtx));
5406
+ await Promise.all(tasks);
5407
+ }
5408
+ }
5409
+ function createMiddlewareLogger(options) {
5410
+ if (!isEnabled())
5411
+ return noopResult;
5412
+ const { method, path, requestId, include, exclude, routes, keep } = options;
5413
+ if (!shouldLog(path, include, exclude))
5414
+ return noopResult;
5415
+ const resolvedRequestId = requestId || crypto.randomUUID();
5416
+ const logger = createRequestLogger({
5417
+ method,
5418
+ path,
5419
+ requestId: resolvedRequestId
5420
+ }, { _deferDrain: true });
5421
+ const routeService = getServiceForPath(path, routes);
5422
+ if (routeService)
5423
+ logger.set({ service: routeService });
5424
+ const pluginRunner = resolveMiddlewarePluginRunner(options);
5425
+ if (pluginRunner.hasExtendLogger)
5426
+ pluginRunner.applyExtendLogger(logger);
5427
+ const startTime = Date.now();
5428
+ const requestInfo = {
5429
+ method,
5430
+ path,
5431
+ requestId: resolvedRequestId
5432
+ };
5433
+ if (pluginRunner.hasRequestLifecycle)
5434
+ pluginRunner.runOnRequestStart({
5435
+ logger,
5436
+ request: requestInfo,
5437
+ headers: options.headers
5438
+ });
5439
+ const finish = async (opts) => {
5440
+ const { status, error } = opts ?? {};
5441
+ if (error) {
5442
+ logger.error(error);
5443
+ const errorStatus = extractErrorStatus(error);
5444
+ logger.set({ status: errorStatus });
5445
+ } else if (status !== undefined)
5446
+ logger.set({ status });
5447
+ const durationMs = Date.now() - startTime;
5448
+ const resolvedStatus = error ? extractErrorStatus(error) : status ?? logger.getContext().status;
5449
+ const tailCtx = {
5450
+ status: resolvedStatus,
5451
+ duration: durationMs,
5452
+ path,
5453
+ method,
5454
+ context: logger.getContext(),
5455
+ shouldKeep: false
5456
+ };
5457
+ if (keep)
5458
+ await keep(tailCtx);
5459
+ if (pluginRunner.hasKeep)
5460
+ await pluginRunner.runKeep(tailCtx);
5461
+ const forceKeep = tailCtx.shouldKeep || shouldKeep(tailCtx);
5462
+ const emittedEvent = logger.emit({ _forceKeep: forceKeep });
5463
+ if (emittedEvent && (options.enrich || options.drain || pluginRunner.hasEnrich || pluginRunner.hasDrain || getGlobalDrain()))
5464
+ await runEnrichAndDrain(emittedEvent, options, requestInfo, resolvedStatus, pluginRunner);
5465
+ if (pluginRunner.hasRequestLifecycle)
5466
+ pluginRunner.runOnRequestFinish({
5467
+ logger,
5468
+ request: requestInfo,
5469
+ headers: options.headers,
5470
+ event: emittedEvent,
5471
+ status: resolvedStatus,
5472
+ durationMs,
5473
+ error
5474
+ });
5475
+ return emittedEvent;
5476
+ };
5477
+ return {
5478
+ logger,
5479
+ finish,
5480
+ skipped: false
5481
+ };
5482
+ }
5483
+ function attachForkToLogger(storage, parent, middlewareOptions, lifecycle) {
5484
+ const log = parent;
5485
+ log.fork = (label, fn) => {
5486
+ forkBackgroundLogger({
5487
+ storage,
5488
+ parent,
5489
+ middlewareOptions,
5490
+ label,
5491
+ fn,
5492
+ lifecycle
5493
+ });
5494
+ };
5495
+ }
5496
+ function forkBackgroundLogger(options) {
5497
+ const { storage, parent, middlewareOptions, label, fn, lifecycle } = options;
5498
+ const parentCtx = parent.getContext();
5499
+ const parentRequestId = parentCtx.requestId;
5500
+ if (typeof parentRequestId !== "string" || parentRequestId.length === 0)
5501
+ throw new Error("[evlog] log.fork() requires the parent logger to have a requestId. Ensure the request was created by evlog middleware.");
5502
+ const method = String(parentCtx.method ?? middlewareOptions.method);
5503
+ const path = String(parentCtx.path ?? middlewareOptions.path);
5504
+ const child = createRequestLogger({
5505
+ method,
5506
+ path,
5507
+ requestId: crypto.randomUUID()
5508
+ }, { _deferDrain: true });
5509
+ child.set({
5510
+ operation: label,
5511
+ _parentRequestId: parentRequestId
5512
+ });
5513
+ const childRequestInfo = {
5514
+ method,
5515
+ path,
5516
+ requestId: child.getContext().requestId
5517
+ };
5518
+ storage.run(child, () => {
5519
+ lifecycle?.onChildEnter?.(child);
5520
+ Promise.resolve().then(() => fn()).then(async () => {
5521
+ const emittedEvent = child.emit();
5522
+ const ctxStatus = child.getContext().status;
5523
+ const status = emittedEvent?.status ?? (typeof ctxStatus === "number" ? ctxStatus : undefined);
5524
+ if (emittedEvent && (middlewareOptions.enrich || middlewareOptions.drain || getGlobalDrain()))
5525
+ await runEnrichAndDrain(emittedEvent, middlewareOptions, childRequestInfo, status);
5526
+ }).catch(async (err) => {
5527
+ const error = err instanceof Error ? err : new Error(String(err));
5528
+ child.error(error);
5529
+ child.set({ status: extractErrorStatus(error) });
5530
+ const emittedEvent = child.emit();
5531
+ const status = extractErrorStatus(error);
5532
+ if (emittedEvent && (middlewareOptions.enrich || middlewareOptions.drain || getGlobalDrain()))
5533
+ await runEnrichAndDrain(emittedEvent, middlewareOptions, childRequestInfo, status);
5534
+ }).finally(() => {
5535
+ lifecycle?.onChildExit?.(child);
5536
+ });
5537
+ });
5538
+ }
5539
+
5540
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/integration-DTZtjSqh.mjs
5541
+ function normalizeHeaders(headers) {
5542
+ if (!headers)
5543
+ return;
5544
+ if (typeof headers.forEach === "function" && typeof headers.get === "function")
5545
+ return extractSafeHeaders(headers);
5546
+ return extractSafeNodeHeaders(headers);
5547
+ }
5548
+ function defineFrameworkIntegration(spec) {
5549
+ return { start(ctx, options = {}) {
5550
+ const extracted = spec.extractRequest(ctx);
5551
+ const headers = normalizeHeaders(extracted.headers);
5552
+ const middlewareOptions = {
5553
+ method: extracted.method,
5554
+ path: extracted.path,
5555
+ requestId: extracted.requestId || crypto.randomUUID(),
5556
+ headers,
5557
+ ...options
5558
+ };
5559
+ const result = createMiddlewareLogger(middlewareOptions);
5560
+ if (!result.skipped) {
5561
+ if (spec.storage)
5562
+ attachForkToLogger(spec.storage, result.logger, middlewareOptions, spec.forkLifecycle);
5563
+ spec.attachLogger(ctx, result.logger);
5564
+ }
5565
+ const { storage } = spec;
5566
+ const runWith = async (fn) => {
5567
+ if (!storage || result.skipped)
5568
+ return await fn();
5569
+ return await storage.run(result.logger, fn);
5570
+ };
5571
+ return {
5572
+ ...result,
5573
+ middlewareOptions,
5574
+ runWith
5575
+ };
5576
+ } };
5577
+ }
5578
+
5579
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/elysia/index.mjs
3852
5580
  import { AsyncLocalStorage } from "async_hooks";
3853
5581
  import { Elysia } from "elysia";
3854
5582
  var storage = new AsyncLocalStorage;
3855
5583
  var activeLoggers = /* @__PURE__ */ new WeakSet;
3856
- function useLogger2() {
5584
+ function useLogger() {
3857
5585
  const logger = storage.getStore();
3858
5586
  if (!logger || !activeLoggers.has(logger))
3859
5587
  throw new Error("[evlog] useLogger() was called outside of an evlog plugin context. Make sure app.use(evlog()) is registered before your routes.");
3860
5588
  return logger;
3861
5589
  }
5590
+ var integration = defineFrameworkIntegration({
5591
+ name: "elysia",
5592
+ extractRequest: ({ request, path, headers }) => ({
5593
+ method: request.method,
5594
+ path,
5595
+ headers,
5596
+ requestId: headers["x-request-id"]
5597
+ }),
5598
+ attachLogger: ({ request, path, headers }, logger) => {
5599
+ attachForkToLogger(storage, logger, {
5600
+ method: request.method,
5601
+ path,
5602
+ requestId: headers["x-request-id"]
5603
+ }, {
5604
+ onChildEnter: (child) => {
5605
+ activeLoggers.add(child);
5606
+ },
5607
+ onChildExit: (child) => {
5608
+ activeLoggers.delete(child);
5609
+ }
5610
+ });
5611
+ activeLoggers.add(logger);
5612
+ }
5613
+ });
3862
5614
 
3863
5615
  // src/context-logger.ts
3864
5616
  var noopLogger2 = {
@@ -3871,9 +5623,9 @@ var noopLogger2 = {
3871
5623
  fork: (_label, fn) => fn()
3872
5624
  };
3873
5625
  var syntheticRenderStorage = new AsyncLocalStorage2;
3874
- function useLogger3() {
5626
+ function useLogger2() {
3875
5627
  try {
3876
- return useLogger2();
5628
+ return useLogger();
3877
5629
  } catch {
3878
5630
  return syntheticRenderStorage.getStore() ?? noopLogger2;
3879
5631
  }
@@ -4100,16 +5852,42 @@ function errorMessageOf(err) {
4100
5852
  return "";
4101
5853
  }
4102
5854
  var SERVER_RESET_NOOP2 = () => {};
4103
- function buildErrorElement(component, error, digest) {
5855
+ function buildErrorElement(component, error, digest, messageOverride, status) {
4104
5856
  const ErrorView = component ?? DefaultErrorComponent;
4105
- const message = component ? errorMessageOf(error) : "An unexpected error occurred.";
5857
+ let message;
5858
+ if (component) {
5859
+ message = messageOverride ?? errorMessageOf(error);
5860
+ } else {
5861
+ message = "An unexpected error occurred.";
5862
+ }
4106
5863
  return /* @__PURE__ */ jsxDEV4(ErrorView, {
4107
- error: { message, digest },
5864
+ error: { message, digest, status },
4108
5865
  reset: SERVER_RESET_NOOP2
4109
5866
  }, undefined, false, undefined, this);
4110
5867
  }
4111
5868
 
5869
+ // src/client.ts
5870
+ var DEFERRED_BRAND = "__isDeferred";
5871
+ function isDeferred(v) {
5872
+ return typeof v === "object" && v !== null && Object.hasOwn(v, DEFERRED_BRAND) && v[DEFERRED_BRAND] === true;
5873
+ }
5874
+
4112
5875
  // src/render/loaders.ts
5876
+ var REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
5877
+ function isHttpRedirect(res) {
5878
+ return REDIRECT_STATUSES.has(res.status) && res.headers.has("location");
5879
+ }
5880
+ async function readResponseMessage(res) {
5881
+ if (res.body === null) {
5882
+ return res.statusText;
5883
+ }
5884
+ try {
5885
+ const body = await res.text();
5886
+ return body || res.statusText;
5887
+ } catch {
5888
+ return res.statusText;
5889
+ }
5890
+ }
4113
5891
  function createLoaderCtx(ctx, accumulatedParentPromise) {
4114
5892
  const cache = new Map;
4115
5893
  return new Proxy(ctx, {
@@ -4132,9 +5910,40 @@ function createLoaderCtx(ctx, accumulatedParentPromise) {
4132
5910
  }
4133
5911
  });
4134
5912
  }
4135
- async function runLoaders(route, ctx, _rootLayout) {
5913
+ function splitDeferredResult(pageResult, routeChainData) {
5914
+ const syncData = {};
5915
+ const deferredPromises = {};
5916
+ for (const [key, value] of Object.entries(routeChainData)) {
5917
+ syncData[key] = value;
5918
+ }
5919
+ for (const [key, value] of Object.entries(pageResult)) {
5920
+ if (key === "__isDeferred") {
5921
+ continue;
5922
+ }
5923
+ if (isPromiseLike(value)) {
5924
+ deferredPromises[key] = Promise.resolve(value);
5925
+ } else {
5926
+ syncData[key] = value;
5927
+ }
5928
+ }
5929
+ return {
5930
+ syncData,
5931
+ deferredPromises: Object.keys(deferredPromises).length > 0 ? deferredPromises : undefined
5932
+ };
5933
+ }
5934
+ function isPromiseLike(value) {
5935
+ return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
5936
+ }
5937
+ function assertNoDeferredInRouteLoaders(routeResults) {
5938
+ for (const result of routeResults) {
5939
+ if (isDeferred(result)) {
5940
+ throw new Error("[furin] defer() is only supported in a page loader (route.page({ loader })). A route/layout loader returned a deferred object; move the deferred fields to the page loader, or `await` them in the route loader and return resolved values.");
5941
+ }
5942
+ }
5943
+ }
5944
+ async function runLoaders(route, ctx) {
4136
5945
  try {
4137
- const ctxRecord = { ...ctx, log: useLogger3() };
5946
+ const ctxRecord = { ...ctx, log: useLogger2() };
4138
5947
  const loaderMap = new Map;
4139
5948
  let accumulatedParentPromise = Promise.resolve({});
4140
5949
  for (const r of route.routeChain) {
@@ -4153,22 +5962,47 @@ async function runLoaders(route, ctx, _rootLayout) {
4153
5962
  const pageCtx = createLoaderCtx(ctxRecord, accumulatedParentPromise);
4154
5963
  const pagePromise = route.page?.loader ? Promise.resolve(route.page.loader(pageCtx)).then((r) => r ?? {}) : Promise.resolve({});
4155
5964
  const results = await Promise.all([...loaderMap.values(), pagePromise]);
4156
- const data = Object.assign({}, ...results);
5965
+ const merged = Object.assign({}, ...results);
4157
5966
  const headers = {};
4158
5967
  Object.assign(headers, ctx.set.headers);
4159
- return { type: "data", data, headers };
5968
+ const routeOnlyResults = results.slice(0, loaderMap.size);
5969
+ const pageResult = results[loaderMap.size];
5970
+ assertNoDeferredInRouteLoaders(routeOnlyResults);
5971
+ const routeCtx = { params: ctx.params, query: ctx.query, path: ctx.path };
5972
+ if (isDeferred(pageResult)) {
5973
+ const routeMerged = Object.assign({}, ...routeOnlyResults);
5974
+ const { syncData, deferredPromises } = splitDeferredResult(pageResult, routeMerged);
5975
+ return { type: "data", syncData: { ...syncData, ...routeCtx }, deferredPromises, headers };
5976
+ }
5977
+ return {
5978
+ type: "data",
5979
+ syncData: { ...merged, ...routeCtx },
5980
+ deferredPromises: undefined,
5981
+ headers
5982
+ };
4160
5983
  } catch (err) {
5984
+ const headers = {};
5985
+ Object.assign(headers, ctx.set.headers);
4161
5986
  if (isNotFoundError(err)) {
4162
- const headers2 = {};
4163
- Object.assign(headers2, ctx.set.headers);
4164
- return { type: "not-found", error: err, headers: headers2 };
5987
+ return { type: "not-found", error: err, headers };
4165
5988
  }
4166
5989
  if (err instanceof Response) {
4167
- return { type: "redirect", response: err };
5990
+ if (isHttpRedirect(err)) {
5991
+ return { type: "redirect", response: err };
5992
+ }
5993
+ const isMalformedRedirect = REDIRECT_STATUSES.has(err.status);
5994
+ const status = isMalformedRedirect ? 500 : err.status;
5995
+ const body = await readResponseMessage(err);
5996
+ const message = body || "Something went wrong";
5997
+ return { type: "error", error: err, status, message, headers };
4168
5998
  }
4169
- const headers = {};
4170
- Object.assign(headers, ctx.set.headers);
4171
- return { type: "error", error: err, headers };
5999
+ return {
6000
+ type: "error",
6001
+ error: err,
6002
+ status: 500,
6003
+ message: "Something went wrong",
6004
+ headers
6005
+ };
4172
6006
  }
4173
6007
  }
4174
6008
 
@@ -4216,9 +6050,14 @@ var IS_DEV = true;
4216
6050
  function withSSRRouterContext(element, contextValue) {
4217
6051
  return createElement3(RouterContext.Provider, { value: contextValue }, element);
4218
6052
  }
6053
+ function assertDeferredModeAllowed(route, deferredPromises) {
6054
+ if (deferredPromises !== undefined && route.mode !== "ssr") {
6055
+ throw new Error(`[furin] page "${route.pattern}" returned defer() but the route is rendered in "${route.mode}" mode. ` + "defer() streams data progressively and is only supported in SSR. " + "Return the data directly (await it inside the loader) or switch the route to SSR mode.");
6056
+ }
6057
+ }
4219
6058
  async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomputedLoaderResult) {
4220
6059
  const loaderStart = Date.now();
4221
- const loaderResult = precomputedLoaderResult ?? await runLoaders(route, ctx, root.route);
6060
+ const loaderResult = precomputedLoaderResult ?? await runLoaders(route, ctx);
4222
6061
  const loader_ms = Date.now() - loaderStart;
4223
6062
  if (loaderResult.type === "redirect") {
4224
6063
  return loaderResult.response;
@@ -4229,10 +6068,13 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
4229
6068
  const isNotFound = loaderResult.type === "not-found";
4230
6069
  const isError = loaderResult.type === "error";
4231
6070
  const isFallback = isNotFound || isError;
4232
- const data = isFallback ? {} : loaderResult.data;
6071
+ const syncData = isFallback ? {} : loaderResult.syncData;
6072
+ const deferredPromises = !isFallback && loaderResult.type === "data" ? loaderResult.deferredPromises : undefined;
6073
+ assertDeferredModeAllowed(route, deferredPromises);
4233
6074
  const headers = loaderResult.headers;
4234
6075
  const componentProps = {
4235
- ...data,
6076
+ ...syncData,
6077
+ ...deferredPromises ?? {},
4236
6078
  params: ctx.params,
4237
6079
  query: ctx.query,
4238
6080
  path: ctx.path
@@ -4250,8 +6092,8 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
4250
6092
  notFoundError = { message: loaderResult.error.message, data: loaderResult.error.data };
4251
6093
  } else if (loaderResult.type === "error") {
4252
6094
  errorDigest = computeErrorDigest(loaderResult.error);
4253
- element = buildErrorElement(route.error ?? root.error, loaderResult.error, errorDigest);
4254
- status = 500;
6095
+ element = buildErrorElement(route.error ?? root.error, loaderResult.error, errorDigest, loaderResult.message, loaderResult.status);
6096
+ status = loaderResult.status;
4255
6097
  } else {
4256
6098
  element = buildElement(route, componentProps, root.route);
4257
6099
  }
@@ -4270,12 +6112,14 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
4270
6112
  element = withSSRRouterContext(element, ssrContext);
4271
6113
  return {
4272
6114
  componentProps,
6115
+ deferredPromises,
4273
6116
  element,
4274
6117
  errorDigest,
4275
6118
  headData,
4276
6119
  headers,
4277
6120
  loader_ms,
4278
6121
  notFoundError,
6122
+ syncData,
4279
6123
  ssrContext,
4280
6124
  status,
4281
6125
  template
@@ -4298,7 +6142,7 @@ function renderForPath(route, params, root, origin, mode, basePath) {
4298
6142
  if (prepared instanceof Response) {
4299
6143
  return prepared;
4300
6144
  }
4301
- useLogger3().set({
6145
+ useLogger2().set({
4302
6146
  furin: {
4303
6147
  render: mode,
4304
6148
  route: route.pattern,
@@ -4307,17 +6151,27 @@ function renderForPath(route, params, root, origin, mode, basePath) {
4307
6151
  ...prepared.errorDigest ? { digest: prepared.errorDigest } : {}
4308
6152
  }
4309
6153
  });
4310
- const { componentProps, element, headData, headers, status, template } = prepared;
6154
+ const { deferredPromises, element, headData, headers, status, syncData, template } = prepared;
4311
6155
  const stream = await renderToReadableStream(element);
4312
6156
  await stream.allReady;
4313
6157
  const reactHtml = await streamToString(stream);
4314
6158
  return {
4315
- html: assembleHTML(template, headData, reactHtml, componentProps),
6159
+ html: assembleHTML(template, headData, reactHtml, syncData),
4316
6160
  headers,
6161
+ ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
4317
6162
  status
4318
6163
  };
4319
6164
  }, { route: route.pattern, render: mode });
4320
6165
  }
6166
+ async function serializeLoaderDataNdjson(syncData, deferredPromises) {
6167
+ const payload = {
6168
+ ...syncData,
6169
+ ...deferredPromises ?? {}
6170
+ };
6171
+ const serialized = await toCrossJSONAsync(payload);
6172
+ return `${JSON.stringify(serialized)}
6173
+ `;
6174
+ }
4321
6175
  async function prerenderSSG(route, params, root, origin, basePath) {
4322
6176
  const resolvedPath = resolvePath(route.pattern, params);
4323
6177
  const cached = getSSGCache(resolvedPath);
@@ -4329,7 +6183,12 @@ async function prerenderSSG(route, params, root, origin, basePath) {
4329
6183
  return renderResult;
4330
6184
  }
4331
6185
  const result = renderResult;
4332
- const entry = { html: result.html, cachedAt: Date.now(), status: result.status };
6186
+ const entry = {
6187
+ cachedAt: Date.now(),
6188
+ html: result.html,
6189
+ ndjson: result.ndjson,
6190
+ status: result.status
6191
+ };
4333
6192
  setSSGCache(resolvedPath, entry);
4334
6193
  return entry;
4335
6194
  }
@@ -4339,12 +6198,12 @@ var pendingRevalidations = new Set;
4339
6198
  var STATIC_CONCURRENCY = 4;
4340
6199
  var DYNAMIC_SEGMENT_RE = /\/:[^/]+|\/\*/;
4341
6200
  var TRAILING_SLASHES_RE = /\/+$/;
4342
- function pathToOutputFile(urlPath, outDir) {
6201
+ function pathToOutputFile(urlPath, outDir, fileName) {
4343
6202
  const normalizedOutDir = resolve2(outDir);
4344
6203
  if (urlPath === "/" || urlPath === "") {
4345
- return join9(normalizedOutDir, "index.html");
6204
+ return join9(normalizedOutDir, fileName);
4346
6205
  }
4347
- const resolved = resolve2(normalizedOutDir, urlPath.slice(1), "index.html");
6206
+ const resolved = resolve2(normalizedOutDir, urlPath.slice(1), fileName);
4348
6207
  if (!resolved.startsWith(`${normalizedOutDir}${sep}`)) {
4349
6208
  throw new Error(`[furin] static: unsafe output path detected for URL "${urlPath}" \u2014 path traversal via ".." is not allowed.`);
4350
6209
  }
@@ -4352,17 +6211,19 @@ function pathToOutputFile(urlPath, outDir) {
4352
6211
  }
4353
6212
  async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath) {
4354
6213
  const urlPath = resolvePath(route.pattern, params);
4355
- const outputFile = pathToOutputFile(urlPath, outDir);
6214
+ const htmlOutputFile = pathToOutputFile(urlPath, outDir, "index.html");
6215
+ const dataOutputFile = pathToOutputFile(urlPath, outDir, "__furin_data.ndjson");
4356
6216
  try {
4357
6217
  const entry = await prerenderSSG(route, params, root, "http://localhost", basePath);
4358
6218
  if (entry instanceof Response) {
4359
6219
  console.warn(`[furin] static: route "${route.pattern}" loader returned a redirect \u2014 skipping.`);
4360
6220
  return;
4361
6221
  }
4362
- ensureDir(dirname3(outputFile));
4363
- writeFileSync7(outputFile, entry.html);
6222
+ ensureDir(dirname3(htmlOutputFile));
6223
+ writeFileSync7(htmlOutputFile, entry.html);
6224
+ writeFileSync7(dataOutputFile, entry.ndjson);
4364
6225
  renderedRoutes.push(urlPath);
4365
- console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(outputFile)}`);
6226
+ console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)}`);
4366
6227
  } catch (err) {
4367
6228
  console.error(`[furin] static: prerender failed for "${route.pattern}" (params: ${JSON.stringify(params)}):`, err);
4368
6229
  skippedRoutes.push(urlPath);
@@ -4389,24 +6250,38 @@ function collectSsgRoutes(routes, onSSR, skippedRoutes) {
4389
6250
  }
4390
6251
  async function buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath) {
4391
6252
  const tasks = [];
4392
- for (const route of ssgRoutes) {
6253
+ const staticParamsResults = await mapWithConcurrency(ssgRoutes, STATIC_CONCURRENCY, async (route) => {
4393
6254
  if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
4394
- tasks.push(() => prerenderAndWrite(route, {}, root, outDir, renderedRoutes, skippedRoutes, basePath));
4395
- continue;
6255
+ return { route, paramSets: [{}] };
4396
6256
  }
4397
6257
  if (!route.page.staticParams) {
4398
6258
  console.warn(`[furin] static: skipping dynamic route "${route.pattern}" \u2014 no staticParams() defined.`);
4399
6259
  skippedRoutes.push(route.pattern);
4400
- continue;
6260
+ return { route, paramSets: null };
4401
6261
  }
4402
6262
  try {
4403
6263
  const paramSets = await route.page.staticParams() ?? [];
4404
- for (const params of paramSets) {
4405
- tasks.push(() => prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath));
4406
- }
6264
+ return { route, paramSets };
4407
6265
  } catch (err) {
4408
- console.error(`[furin] static: staticParams() failed for "${route.pattern}":`, err);
4409
- skippedRoutes.push(route.pattern);
6266
+ return { error: err, paramSets: null, route };
6267
+ }
6268
+ });
6269
+ for (const result of staticParamsResults) {
6270
+ if ("error" in result) {
6271
+ console.error(`[furin] static: staticParams() failed for "${result.route.pattern}":`, result.error);
6272
+ skippedRoutes.push(result.route.pattern);
6273
+ continue;
6274
+ }
6275
+ if (result.paramSets === null) {
6276
+ continue;
6277
+ }
6278
+ if (!Array.isArray(result.paramSets)) {
6279
+ console.error(`[furin] static: staticParams() for "${result.route.pattern}" returned a non-array value; skipping route.`);
6280
+ skippedRoutes.push(result.route.pattern);
6281
+ continue;
6282
+ }
6283
+ for (const params of result.paramSets) {
6284
+ tasks.push(() => prerenderAndWrite(result.route, params, root, outDir, renderedRoutes, skippedRoutes, basePath));
4410
6285
  }
4411
6286
  }
4412
6287
  return tasks;
@@ -4466,7 +6341,7 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
4466
6341
  });
4467
6342
  const publicFavicon = join9(rootDir, "public", "favicon.ico");
4468
6343
  const faviconHref = existsSync8(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
4469
- const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref);
6344
+ const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref, true);
4470
6345
  setProductionTemplateContent(shellHtml);
4471
6346
  const publicSrcDir = join9(rootDir, "public");
4472
6347
  if (existsSync8(publicSrcDir)) {
@@ -4532,47 +6407,6 @@ function getCompileContext() {
4532
6407
  return _compileCtx;
4533
6408
  }
4534
6409
 
4535
- // src/utils.ts
4536
- function isFurinPage(value) {
4537
- return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
4538
- }
4539
- function isFurinRoute(value) {
4540
- return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_ROUTE";
4541
- }
4542
- function collectRouteChainFromRoute(route) {
4543
- const chain = [];
4544
- let current = route;
4545
- while (current) {
4546
- chain.unshift(current);
4547
- current = current.parent;
4548
- }
4549
- return chain;
4550
- }
4551
- function hasCycle(route) {
4552
- const visited = new Set;
4553
- let current = route;
4554
- while (current) {
4555
- if (visited.has(current)) {
4556
- return true;
4557
- }
4558
- visited.add(current);
4559
- current = current.parent;
4560
- }
4561
- return false;
4562
- }
4563
- function validateRouteChain(chain, root, pagePath) {
4564
- const hasRoot = chain.some((r) => r === root);
4565
- if (!hasRoot) {
4566
- const location = pagePath ? `in ${pagePath}` : "";
4567
- throw new Error(`[furin] Page ${location} must inherit from root route. ` + 'Add: import { route } from "./root"; and use route.page() or set parent: route');
4568
- }
4569
- for (const route of chain) {
4570
- if (hasCycle(route)) {
4571
- throw new Error("[furin] Cycle detected in route chain. A route cannot be its own ancestor.");
4572
- }
4573
- }
4574
- }
4575
-
4576
6410
  // src/router.ts
4577
6411
  async function scanPages(pagesDir) {
4578
6412
  const root = await scanRootLayout(pagesDir);
@@ -4593,8 +6427,10 @@ async function scanRootLayout(pagesDir) {
4593
6427
  if (!rootExport.layout) {
4594
6428
  throw new Error("[furin] root.tsx: createRoute() has no layout.");
4595
6429
  }
4596
- const notFoundEntry = await loadConventionComponent(pagesDir, "not-found");
4597
- const errorEntry = await loadConventionComponent(pagesDir, "error");
6430
+ const [notFoundEntry, errorEntry] = await Promise.all([
6431
+ loadConventionComponent(pagesDir, "not-found"),
6432
+ loadConventionComponent(pagesDir, "error")
6433
+ ]);
4598
6434
  return {
4599
6435
  path: rootPath,
4600
6436
  route: rootExport,
@@ -4637,9 +6473,11 @@ async function scanPageFiles(pagesDir, root) {
4637
6473
  if (fileName.startsWith("_") || fileName === "root" || isConventionFileName(fileName)) {
4638
6474
  continue;
4639
6475
  }
4640
- const notFound = await resolveNearestConvention(absolutePath, pagesDir, "not-found", notFoundCache, root.notFound);
4641
- const errorComponent = await resolveNearestConvention(absolutePath, pagesDir, "error", errorCache, root.error);
4642
- const segmentBoundaries = await collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache);
6476
+ const [notFound, errorComponent, segmentBoundaries] = await Promise.all([
6477
+ resolveNearestConvention(absolutePath, pagesDir, "not-found", notFoundCache, root.notFound),
6478
+ resolveNearestConvention(absolutePath, pagesDir, "error", errorCache, root.error),
6479
+ collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache)
6480
+ ]);
4643
6481
  if (IS_DEV) {
4644
6482
  const devRoute = await buildDevRoute(absolutePath, relativePath, root);
4645
6483
  devRoute.notFound = notFound;
@@ -4684,14 +6522,16 @@ async function collectSegmentBoundaries(pageAbsolutePath, pagesDir, notFoundCach
4684
6522
  const boundaries = [];
4685
6523
  for (let depth = 0;depth < dirs.length; depth++) {
4686
6524
  const dir = dirs[depth];
4687
- if (!errorCache.has(dir)) {
4688
- errorCache.set(dir, await loadConventionComponent(dir, "error"));
4689
- }
4690
- if (!notFoundCache.has(dir)) {
4691
- notFoundCache.set(dir, await loadConventionComponent(dir, "not-found"));
4692
- }
4693
- const errorEntry = errorCache.get(dir);
4694
- const notFoundEntry = notFoundCache.get(dir);
6525
+ const [errorEntry, notFoundEntry] = await Promise.all([
6526
+ errorCache.has(dir) ? Promise.resolve(errorCache.get(dir)) : loadConventionComponent(dir, "error").then((r) => {
6527
+ errorCache.set(dir, r);
6528
+ return r;
6529
+ }),
6530
+ notFoundCache.has(dir) ? Promise.resolve(notFoundCache.get(dir)) : loadConventionComponent(dir, "not-found").then((r) => {
6531
+ notFoundCache.set(dir, r);
6532
+ return r;
6533
+ })
6534
+ ]);
4695
6535
  if (errorEntry || notFoundEntry) {
4696
6536
  boundaries.push({
4697
6537
  path: dir,
@@ -4748,18 +6588,22 @@ async function buildDevRoute(absolutePath, relativePath, root) {
4748
6588
  };
4749
6589
  }
4750
6590
  var TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
6591
+ var DIR_SCAN_CONCURRENCY = 8;
4751
6592
  async function collectPageFilePaths(dir) {
4752
6593
  const files = [];
4753
6594
  const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
4754
- for (const entry of entries) {
6595
+ const resolved = await mapWithConcurrency(entries, DIR_SCAN_CONCURRENCY, async (entry) => {
4755
6596
  const absolutePath = join10(dir, entry.name);
4756
6597
  if (entry.isDirectory()) {
4757
- files.push(...await collectPageFilePaths(absolutePath));
4758
- continue;
6598
+ return await collectPageFilePaths(absolutePath);
4759
6599
  }
4760
6600
  if (entry.isFile()) {
4761
- files.push(absolutePath);
6601
+ return [absolutePath];
4762
6602
  }
6603
+ return [];
6604
+ });
6605
+ for (const chunk of resolved) {
6606
+ files.push(...chunk);
4763
6607
  }
4764
6608
  return files;
4765
6609
  }
@@ -4804,35 +6648,13 @@ function filePathToPattern(path) {
4804
6648
  // src/build/scan-server.ts
4805
6649
  import { readFileSync as readFileSync4 } from "fs";
4806
6650
  import { parse as parse3 } from "yuku-parser";
4807
- function detectLangFromPath(filePath) {
4808
- if (filePath.endsWith(".d.ts")) {
4809
- return "dts";
4810
- }
4811
- const ext = filePath.split(".").pop()?.toLowerCase();
4812
- switch (ext) {
4813
- case "ts":
4814
- return "ts";
4815
- case "tsx":
4816
- return "tsx";
4817
- case "jsx":
4818
- return "jsx";
4819
- default:
4820
- return "js";
4821
- }
4822
- }
4823
6651
  function scanFurinInstances(serverEntryPath) {
4824
6652
  const code = readFileSync4(serverEntryPath, "utf8");
4825
- let lang = detectLangFromPath(serverEntryPath);
6653
+ const lang = detectLangFromPath(serverEntryPath);
4826
6654
  if (lang === "dts") {
4827
6655
  return [];
4828
6656
  }
4829
- let parseInput = code;
4830
- if (lang === "ts" || lang === "tsx") {
4831
- const transpiler = new Bun.Transpiler({ loader: lang });
4832
- parseInput = transpiler.transformSync(code);
4833
- lang = "js";
4834
- }
4835
- const { program, diagnostics } = parse3(parseInput, { sourceType: "module", lang });
6657
+ const { program, diagnostics } = parse3(code, { sourceType: "module", lang });
4836
6658
  const firstError = diagnostics.find((d) => d.severity === "error");
4837
6659
  if (firstError) {
4838
6660
  console.error("[furin] scan-server: parse error:", firstError.message, "in", serverEntryPath);
@@ -4850,7 +6672,7 @@ function checkFurinCall(node, out) {
4850
6672
  if (!(isFurinCall && Array.isArray(args)) || args.length === 0) {
4851
6673
  return;
4852
6674
  }
4853
- const firstArg = args[0];
6675
+ const firstArg = unwrapTSExpression(args[0]);
4854
6676
  if (firstArg?.type !== "ObjectExpression") {
4855
6677
  return;
4856
6678
  }