@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
package/dist/furin.js CHANGED
@@ -15,7 +15,7 @@ var __export = (target, all) => {
15
15
  };
16
16
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
17
17
 
18
- // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/utils.mjs
18
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/utils.mjs
19
19
  function formatDuration(ms) {
20
20
  if (ms < 1000)
21
21
  return `${Math.round(ms)}ms`;
@@ -132,7 +132,28 @@ var init_utils = __esm(() => {
132
132
  patternCache = /* @__PURE__ */ new Map;
133
133
  });
134
134
 
135
- // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/audit-DQoBo7Dl.mjs
135
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/headers-CU-QqnYg.mjs
136
+ function extractSafeHeaders(headers) {
137
+ const raw = {};
138
+ headers.forEach((value, key) => {
139
+ raw[key] = value;
140
+ });
141
+ return filterSafeHeaders(raw);
142
+ }
143
+ function extractSafeNodeHeaders(headers) {
144
+ const raw = {};
145
+ for (const [key, value] of Object.entries(headers)) {
146
+ if (value === undefined)
147
+ continue;
148
+ raw[key] = Array.isArray(value) ? value.join(", ") : value;
149
+ }
150
+ return filterSafeHeaders(raw);
151
+ }
152
+ var init_headers_CU_QqnYg = __esm(() => {
153
+ init_utils();
154
+ });
155
+
156
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/audit-pV5aLGP0.mjs
136
157
  function resolveRedactConfig(input) {
137
158
  if (input === undefined || input === false)
138
159
  return;
@@ -235,6 +256,116 @@ function applyMaskers(value, maskers) {
235
256
  }
236
257
  return result;
237
258
  }
259
+ function logPluginError(name, hook, err) {
260
+ console.error(`[evlog/${name}] ${hook} failed:`, err);
261
+ }
262
+ function createPluginRunner(plugins = []) {
263
+ const byName = /* @__PURE__ */ new Map;
264
+ for (const plugin of plugins)
265
+ byName.set(plugin.name, plugin);
266
+ const list = Array.from(byName.values());
267
+ return {
268
+ plugins: list,
269
+ hasEnrich: list.some((p) => typeof p.enrich === "function"),
270
+ hasDrain: list.some((p) => typeof p.drain === "function"),
271
+ hasKeep: list.some((p) => typeof p.keep === "function"),
272
+ hasRequestLifecycle: list.some((p) => typeof p.onRequestStart === "function" || typeof p.onRequestFinish === "function"),
273
+ hasClientLog: list.some((p) => typeof p.onClientLog === "function"),
274
+ hasExtendLogger: list.some((p) => typeof p.extendLogger === "function"),
275
+ applyExtendLogger(logger) {
276
+ for (const plugin of list) {
277
+ if (!plugin.extendLogger)
278
+ continue;
279
+ try {
280
+ plugin.extendLogger(logger);
281
+ } catch (err) {
282
+ logPluginError(plugin.name, "extendLogger", err);
283
+ }
284
+ }
285
+ },
286
+ runOnRequestStart(ctx) {
287
+ for (const plugin of list) {
288
+ if (!plugin.onRequestStart)
289
+ continue;
290
+ try {
291
+ plugin.onRequestStart(ctx);
292
+ } catch (err) {
293
+ logPluginError(plugin.name, "onRequestStart", err);
294
+ }
295
+ }
296
+ },
297
+ runOnRequestFinish(ctx) {
298
+ for (const plugin of list) {
299
+ if (!plugin.onRequestFinish)
300
+ continue;
301
+ try {
302
+ plugin.onRequestFinish(ctx);
303
+ } catch (err) {
304
+ logPluginError(plugin.name, "onRequestFinish", err);
305
+ }
306
+ }
307
+ },
308
+ async runEnrich(ctx) {
309
+ for (const plugin of list) {
310
+ if (!plugin.enrich)
311
+ continue;
312
+ try {
313
+ await plugin.enrich(ctx);
314
+ } catch (err) {
315
+ logPluginError(plugin.name, "enrich", err);
316
+ }
317
+ }
318
+ },
319
+ async runDrain(ctx) {
320
+ const drains = list.filter((p) => typeof p.drain === "function");
321
+ if (drains.length === 0)
322
+ return;
323
+ await Promise.allSettled(drains.map(async (plugin) => {
324
+ try {
325
+ await plugin.drain(ctx);
326
+ } catch (err) {
327
+ logPluginError(plugin.name, "drain", err);
328
+ }
329
+ }));
330
+ },
331
+ async runKeep(ctx) {
332
+ for (const plugin of list) {
333
+ if (!plugin.keep)
334
+ continue;
335
+ try {
336
+ await plugin.keep(ctx);
337
+ } catch (err) {
338
+ logPluginError(plugin.name, "keep", err);
339
+ }
340
+ }
341
+ },
342
+ runOnClientLog(ctx) {
343
+ for (const plugin of list) {
344
+ if (!plugin.onClientLog)
345
+ continue;
346
+ try {
347
+ plugin.onClientLog(ctx);
348
+ } catch (err) {
349
+ logPluginError(plugin.name, "onClientLog", err);
350
+ }
351
+ }
352
+ },
353
+ async runSetup(ctx) {
354
+ for (const plugin of list) {
355
+ if (!plugin.setup)
356
+ continue;
357
+ try {
358
+ await plugin.setup(ctx);
359
+ } catch (err) {
360
+ logPluginError(plugin.name, "setup", err);
361
+ }
362
+ }
363
+ }
364
+ };
365
+ }
366
+ function getEmptyPluginRunner() {
367
+ return emptyRunner;
368
+ }
238
369
  function isPlainObject(val) {
239
370
  return val !== null && typeof val === "object" && !Array.isArray(val);
240
371
  }
@@ -276,9 +407,16 @@ function initLogger(config = {}) {
276
407
  globalRedact = resolveRedactConfig(config.redact ?? !isDev());
277
408
  globalSilent = config.silent ?? false;
278
409
  globalMinLevel = config.minLevel ?? "debug";
279
- if (globalSilent && !globalDrain && !config._suppressDrainWarning)
410
+ globalPluginRunner = config.plugins?.length ? createPluginRunner(config.plugins) : getEmptyPluginRunner();
411
+ if (globalPluginRunner.plugins.length > 0)
412
+ globalPluginRunner.runSetup({ env: { ...globalEnv } });
413
+ const hasAnyDrain = !!globalDrain || globalPluginRunner.hasDrain;
414
+ if (globalSilent && !hasAnyDrain && !config._suppressDrainWarning)
280
415
  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).");
281
416
  }
417
+ function getGlobalPluginRunner() {
418
+ return globalPluginRunner;
419
+ }
282
420
  function isEnabled() {
283
421
  return globalEnabled;
284
422
  }
@@ -352,12 +490,20 @@ function emitWideEvent(level, event, options = {}) {
352
490
  console[getConsoleMethod(level)](JSON.stringify(formatted));
353
491
  else
354
492
  console[getConsoleMethod(level)](formatted);
355
- if (globalDrain && !deferDrain) {
356
- const drainPromise = Promise.resolve(globalDrain({ event: formatted })).catch((err) => {
357
- console.error("[evlog] drain failed:", err);
358
- });
359
- if (waitUntil)
360
- waitUntil(drainPromise);
493
+ if (!deferDrain) {
494
+ const drainPromises = [];
495
+ if (globalDrain)
496
+ drainPromises.push((async () => {
497
+ try {
498
+ await globalDrain({ event: formatted });
499
+ } catch (err) {
500
+ console.error("[evlog] drain failed:", err);
501
+ }
502
+ })());
503
+ if (globalPluginRunner.hasDrain)
504
+ drainPromises.push(globalPluginRunner.runDrain({ event: formatted }));
505
+ if (drainPromises.length > 0 && waitUntil)
506
+ waitUntil(Promise.all(drainPromises));
361
507
  }
362
508
  return formatted;
363
509
  }
@@ -707,6 +853,7 @@ function createLogger(initialContext = {}, internalOptions) {
707
853
  };
708
854
  const errRecord = err;
709
855
  for (const k of [
856
+ "code",
710
857
  "status",
711
858
  "statusText",
712
859
  "statusCode",
@@ -875,8 +1022,8 @@ function finalizeAudit(event) {
875
1022
  return;
876
1023
  event.audit = decorateAudit(a, String(event.timestamp));
877
1024
  }
878
- var DEFAULT_REPLACEMENT = "[REDACTED]", builtinPatterns, _tsDate, POST_EMIT_FORK_HINT = "For intentional background work tied to this request, use log.fork('label', fn) when your integration supports it (see https://evlog.dev).", globalEnv, globalPretty, globalSampling, globalStringify = true, globalDrain, globalRedact, globalEnabled = true, globalSilent = false, globalMinLevel = "debug", _log, noopLogger;
879
- var init_audit_DQoBo7Dl = __esm(() => {
1025
+ var DEFAULT_REPLACEMENT = "[REDACTED]", builtinPatterns, emptyRunner, _tsDate, POST_EMIT_FORK_HINT = "For intentional background work tied to this request, use log.fork('label', fn) when your integration supports it (see https://evlog.dev).", globalEnv, globalPretty, globalSampling, globalStringify = true, globalDrain, globalRedact, globalEnabled = true, globalSilent = false, globalMinLevel = "debug", globalPluginRunner, _log, noopLogger;
1026
+ var init_audit_pV5aLGP0 = __esm(() => {
880
1027
  init_utils();
881
1028
  builtinPatterns = {
882
1029
  creditCard: {
@@ -925,6 +1072,7 @@ var init_audit_DQoBo7Dl = __esm(() => {
925
1072
  }
926
1073
  }
927
1074
  };
1075
+ emptyRunner = createPluginRunner([]);
928
1076
  _tsDate = /* @__PURE__ */ new Date;
929
1077
  globalEnv = {
930
1078
  service: "app",
@@ -932,6 +1080,7 @@ var init_audit_DQoBo7Dl = __esm(() => {
932
1080
  };
933
1081
  globalPretty = isDev();
934
1082
  globalSampling = {};
1083
+ globalPluginRunner = getEmptyPluginRunner();
935
1084
  _log = {
936
1085
  info: createLogMethod("info"),
937
1086
  error: createLogMethod("error"),
@@ -955,12 +1104,7 @@ var init_audit_DQoBo7Dl = __esm(() => {
955
1104
  initLogger(__EVLOG_CONFIG__);
956
1105
  });
957
1106
 
958
- // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/index.mjs
959
- var init_dist = __esm(() => {
960
- init_audit_DQoBo7Dl();
961
- });
962
-
963
- // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/errors-BJRXUfMg.mjs
1107
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/errors-BQgyQ9xe.mjs
964
1108
  function extractErrorStatus(error) {
965
1109
  if (error === null || typeof error !== "object")
966
1110
  return 500;
@@ -968,9 +1112,14 @@ function extractErrorStatus(error) {
968
1112
  const status = Number(raw);
969
1113
  return Number.isFinite(status) ? status : 500;
970
1114
  }
971
- var init_errors_BJRXUfMg = () => {};
1115
+ var init_errors_BQgyQ9xe = () => {};
972
1116
 
973
- // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/routes-CGPmbzCZ.mjs
1117
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/index.mjs
1118
+ var init_dist = __esm(() => {
1119
+ init_audit_pV5aLGP0();
1120
+ });
1121
+
1122
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/routes-CnIgYWf8.mjs
974
1123
  function shouldLog(path, include, exclude) {
975
1124
  if (exclude && exclude.length > 0) {
976
1125
  if (exclude.some((pattern) => matchesPattern(path, pattern)))
@@ -987,40 +1136,75 @@ function getServiceForPath(path, routes) {
987
1136
  if (matchesPattern(path, pattern))
988
1137
  return config.service;
989
1138
  }
990
- var init_routes_CGPmbzCZ = __esm(() => {
1139
+ var init_routes_CnIgYWf8 = __esm(() => {
991
1140
  init_utils();
992
1141
  });
993
1142
 
994
- // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/middleware-oAccqyPp.mjs
995
- async function runEnrichAndDrain(emittedEvent, options, requestInfo, responseStatus) {
1143
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/fork-8u_zFOJq.mjs
1144
+ function resolveMiddlewarePluginRunner(options) {
1145
+ const global2 = getGlobalPluginRunner();
1146
+ const local = options.plugins;
1147
+ if (!local || local.length === 0)
1148
+ return global2;
1149
+ const cached = runnerCache.get(local);
1150
+ if (cached && cached.global === global2)
1151
+ return cached.merged;
1152
+ const merged = /* @__PURE__ */ new Map;
1153
+ for (const plugin of global2.plugins)
1154
+ merged.set(plugin.name, plugin);
1155
+ for (const plugin of local)
1156
+ merged.set(plugin.name, plugin);
1157
+ if (merged.size === 0)
1158
+ return getEmptyPluginRunner();
1159
+ const runner = createPluginRunner(Array.from(merged.values()));
1160
+ runnerCache.set(local, {
1161
+ global: global2,
1162
+ merged: runner
1163
+ });
1164
+ return runner;
1165
+ }
1166
+ async function runEnrichAndDrain(emittedEvent, options, requestInfo, responseStatus, plugins) {
1167
+ const runner = plugins ?? resolveMiddlewarePluginRunner(options);
996
1168
  const resolvedRedact = resolveRedactConfig(options.redact);
997
1169
  if (resolvedRedact)
998
1170
  redactEvent(emittedEvent, resolvedRedact);
999
- if (options.enrich) {
1171
+ if (options.enrich || runner.hasEnrich) {
1000
1172
  const enrichCtx = {
1001
1173
  event: emittedEvent,
1002
1174
  request: requestInfo,
1003
1175
  headers: options.headers,
1004
1176
  response: { status: responseStatus }
1005
1177
  };
1006
- try {
1007
- await options.enrich(enrichCtx);
1008
- } catch (err) {
1009
- console.error("[evlog] enrich failed:", err);
1010
- }
1178
+ if (options.enrich)
1179
+ try {
1180
+ await options.enrich(enrichCtx);
1181
+ } catch (err) {
1182
+ console.error("[evlog] enrich failed:", err);
1183
+ }
1184
+ if (runner.hasEnrich)
1185
+ await runner.runEnrich(enrichCtx);
1011
1186
  }
1012
1187
  const drain = options.drain ?? getGlobalDrain();
1013
- if (drain) {
1188
+ const hasUserDrain = !!drain;
1189
+ const hasPluginDrain = runner.hasDrain;
1190
+ if (hasUserDrain || hasPluginDrain) {
1014
1191
  const drainCtx = {
1015
1192
  event: emittedEvent,
1016
1193
  request: requestInfo,
1017
1194
  headers: options.headers
1018
1195
  };
1019
- try {
1020
- await drain(drainCtx);
1021
- } catch (err) {
1022
- console.error("[evlog] drain failed:", err);
1023
- }
1196
+ const tasks = [];
1197
+ if (hasUserDrain)
1198
+ tasks.push((async () => {
1199
+ try {
1200
+ await drain(drainCtx);
1201
+ } catch (err) {
1202
+ console.error("[evlog] drain failed:", err);
1203
+ }
1204
+ })());
1205
+ if (hasPluginDrain)
1206
+ tasks.push(runner.runDrain(drainCtx));
1207
+ await Promise.all(tasks);
1024
1208
  }
1025
1209
  }
1026
1210
  function createMiddlewareLogger(options) {
@@ -1038,12 +1222,21 @@ function createMiddlewareLogger(options) {
1038
1222
  const routeService = getServiceForPath(path, routes);
1039
1223
  if (routeService)
1040
1224
  logger.set({ service: routeService });
1225
+ const pluginRunner = resolveMiddlewarePluginRunner(options);
1226
+ if (pluginRunner.hasExtendLogger)
1227
+ pluginRunner.applyExtendLogger(logger);
1041
1228
  const startTime = Date.now();
1042
1229
  const requestInfo = {
1043
1230
  method,
1044
1231
  path,
1045
1232
  requestId: resolvedRequestId
1046
1233
  };
1234
+ if (pluginRunner.hasRequestLifecycle)
1235
+ pluginRunner.runOnRequestStart({
1236
+ logger,
1237
+ request: requestInfo,
1238
+ headers: options.headers
1239
+ });
1047
1240
  const finish = async (opts) => {
1048
1241
  const { status, error } = opts ?? {};
1049
1242
  if (error) {
@@ -1064,10 +1257,22 @@ function createMiddlewareLogger(options) {
1064
1257
  };
1065
1258
  if (keep)
1066
1259
  await keep(tailCtx);
1260
+ if (pluginRunner.hasKeep)
1261
+ await pluginRunner.runKeep(tailCtx);
1067
1262
  const forceKeep = tailCtx.shouldKeep || shouldKeep(tailCtx);
1068
1263
  const emittedEvent = logger.emit({ _forceKeep: forceKeep });
1069
- if (emittedEvent && (options.enrich || options.drain || getGlobalDrain()))
1070
- await runEnrichAndDrain(emittedEvent, options, requestInfo, resolvedStatus);
1264
+ if (emittedEvent && (options.enrich || options.drain || pluginRunner.hasEnrich || pluginRunner.hasDrain || getGlobalDrain()))
1265
+ await runEnrichAndDrain(emittedEvent, options, requestInfo, resolvedStatus, pluginRunner);
1266
+ if (pluginRunner.hasRequestLifecycle)
1267
+ pluginRunner.runOnRequestFinish({
1268
+ logger,
1269
+ request: requestInfo,
1270
+ headers: options.headers,
1271
+ event: emittedEvent,
1272
+ status: resolvedStatus,
1273
+ durationMs,
1274
+ error
1275
+ });
1071
1276
  return emittedEvent;
1072
1277
  };
1073
1278
  return {
@@ -1076,30 +1281,6 @@ function createMiddlewareLogger(options) {
1076
1281
  skipped: false
1077
1282
  };
1078
1283
  }
1079
- var noopResult;
1080
- var init_middleware_oAccqyPp = __esm(() => {
1081
- init_audit_DQoBo7Dl();
1082
- init_errors_BJRXUfMg();
1083
- init_routes_CGPmbzCZ();
1084
- noopResult = {
1085
- logger: {
1086
- set() {},
1087
- error() {},
1088
- info() {},
1089
- warn() {},
1090
- emit() {
1091
- return null;
1092
- },
1093
- getContext() {
1094
- return {};
1095
- }
1096
- },
1097
- finish: () => Promise.resolve(null),
1098
- skipped: true
1099
- };
1100
- });
1101
-
1102
- // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/fork-D1j1Fuzy.mjs
1103
1284
  function attachForkToLogger(storage, parent, middlewareOptions, lifecycle) {
1104
1285
  const log = parent;
1105
1286
  log.fork = (label, fn) => {
@@ -1156,16 +1337,77 @@ function forkBackgroundLogger(options) {
1156
1337
  });
1157
1338
  });
1158
1339
  }
1159
- var init_fork_D1j1Fuzy = __esm(() => {
1160
- init_audit_DQoBo7Dl();
1161
- init_errors_BJRXUfMg();
1162
- init_middleware_oAccqyPp();
1340
+ var noopResult, runnerCache;
1341
+ var init_fork_8u_zFOJq = __esm(() => {
1342
+ init_audit_pV5aLGP0();
1343
+ init_errors_BQgyQ9xe();
1344
+ init_routes_CnIgYWf8();
1345
+ noopResult = {
1346
+ logger: {
1347
+ set() {},
1348
+ error() {},
1349
+ info() {},
1350
+ warn() {},
1351
+ emit() {
1352
+ return null;
1353
+ },
1354
+ getContext() {
1355
+ return {};
1356
+ }
1357
+ },
1358
+ finish: () => Promise.resolve(null),
1359
+ skipped: true
1360
+ };
1361
+ runnerCache = /* @__PURE__ */ new WeakMap;
1362
+ });
1363
+
1364
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/integration-DTZtjSqh.mjs
1365
+ function normalizeHeaders(headers) {
1366
+ if (!headers)
1367
+ return;
1368
+ if (typeof headers.forEach === "function" && typeof headers.get === "function")
1369
+ return extractSafeHeaders(headers);
1370
+ return extractSafeNodeHeaders(headers);
1371
+ }
1372
+ function defineFrameworkIntegration(spec) {
1373
+ return { start(ctx, options = {}) {
1374
+ const extracted = spec.extractRequest(ctx);
1375
+ const headers = normalizeHeaders(extracted.headers);
1376
+ const middlewareOptions = {
1377
+ method: extracted.method,
1378
+ path: extracted.path,
1379
+ requestId: extracted.requestId || crypto.randomUUID(),
1380
+ headers,
1381
+ ...options
1382
+ };
1383
+ const result = createMiddlewareLogger(middlewareOptions);
1384
+ if (!result.skipped) {
1385
+ if (spec.storage)
1386
+ attachForkToLogger(spec.storage, result.logger, middlewareOptions, spec.forkLifecycle);
1387
+ spec.attachLogger(ctx, result.logger);
1388
+ }
1389
+ const { storage } = spec;
1390
+ const runWith = async (fn) => {
1391
+ if (!storage || result.skipped)
1392
+ return await fn();
1393
+ return await storage.run(result.logger, fn);
1394
+ };
1395
+ return {
1396
+ ...result,
1397
+ middlewareOptions,
1398
+ runWith
1399
+ };
1400
+ } };
1401
+ }
1402
+ var init_integration_DTZtjSqh = __esm(() => {
1403
+ init_headers_CU_QqnYg();
1404
+ init_fork_8u_zFOJq();
1163
1405
  });
1164
1406
 
1165
- // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/elysia/index.mjs
1407
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/elysia/index.mjs
1166
1408
  import { AsyncLocalStorage } from "async_hooks";
1167
1409
  import { Elysia } from "elysia";
1168
- function useLogger2() {
1410
+ function useLogger() {
1169
1411
  const logger = storage.getStore();
1170
1412
  if (!logger || !activeLoggers.has(logger))
1171
1413
  throw new Error("[evlog] useLogger() was called outside of an evlog plugin context. Make sure app.use(evlog()) is registered before your routes.");
@@ -1175,25 +1417,12 @@ function evlog(options = {}) {
1175
1417
  const emitted = /* @__PURE__ */ new WeakSet;
1176
1418
  const requestState = /* @__PURE__ */ new WeakMap;
1177
1419
  return new Elysia({ name: "evlog" }).derive({ as: "global" }, ({ request, path, headers }) => {
1178
- const middlewareOpts = {
1179
- method: request.method,
1420
+ const ctx = {
1421
+ request,
1180
1422
  path,
1181
- requestId: headers["x-request-id"] || crypto.randomUUID(),
1182
- headers: filterSafeHeaders(headers),
1183
- ...options
1423
+ headers
1184
1424
  };
1185
- const { logger, finish, skipped } = createMiddlewareLogger(middlewareOpts);
1186
- if (!skipped) {
1187
- attachForkToLogger(storage, logger, middlewareOpts, {
1188
- onChildEnter: (child) => {
1189
- activeLoggers.add(child);
1190
- },
1191
- onChildExit: (child) => {
1192
- activeLoggers.delete(child);
1193
- }
1194
- });
1195
- activeLoggers.add(logger);
1196
- }
1425
+ const { logger, finish, skipped } = integration.start(ctx, options);
1197
1426
  storage.enterWith(logger);
1198
1427
  requestState.set(request, {
1199
1428
  finish,
@@ -1221,13 +1450,36 @@ function evlog(options = {}) {
1221
1450
  storage.enterWith(undefined);
1222
1451
  });
1223
1452
  }
1224
- var storage, activeLoggers;
1453
+ var storage, activeLoggers, integration;
1225
1454
  var init_elysia = __esm(() => {
1226
- init_utils();
1227
- init_middleware_oAccqyPp();
1228
- init_fork_D1j1Fuzy();
1455
+ init_fork_8u_zFOJq();
1456
+ init_integration_DTZtjSqh();
1229
1457
  storage = new AsyncLocalStorage;
1230
1458
  activeLoggers = /* @__PURE__ */ new WeakSet;
1459
+ integration = defineFrameworkIntegration({
1460
+ name: "elysia",
1461
+ extractRequest: ({ request, path, headers }) => ({
1462
+ method: request.method,
1463
+ path,
1464
+ headers,
1465
+ requestId: headers["x-request-id"]
1466
+ }),
1467
+ attachLogger: ({ request, path, headers }, logger) => {
1468
+ attachForkToLogger(storage, logger, {
1469
+ method: request.method,
1470
+ path,
1471
+ requestId: headers["x-request-id"]
1472
+ }, {
1473
+ onChildEnter: (child) => {
1474
+ activeLoggers.add(child);
1475
+ },
1476
+ onChildExit: (child) => {
1477
+ activeLoggers.delete(child);
1478
+ }
1479
+ });
1480
+ activeLoggers.add(logger);
1481
+ }
1482
+ });
1231
1483
  });
1232
1484
 
1233
1485
  // src/internal.ts
@@ -1238,9 +1490,9 @@ var _compileCtx = null;
1238
1490
 
1239
1491
  // src/context-logger.ts
1240
1492
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
1241
- function useLogger3() {
1493
+ function useLogger2() {
1242
1494
  try {
1243
- return useLogger2();
1495
+ return useLogger();
1244
1496
  } catch {
1245
1497
  return syntheticRenderStorage.getStore() ?? noopLogger2;
1246
1498
  }
@@ -1471,91 +1723,1564 @@ var init_cache = __esm(() => {
1471
1723
  registerCacheInvalidator(ssgRouteCache);
1472
1724
  });
1473
1725
 
1474
- // src/not-found.ts
1475
- function notFound(options) {
1476
- throw new FurinNotFoundError(options);
1726
+ // ../../node_modules/.bun/seroval@1.5.4/node_modules/seroval/dist/esm/development/index.mjs
1727
+ function createSerovalNode(t, i, s, c, m, p, e, a, f, b, o, l) {
1728
+ return {
1729
+ t,
1730
+ i,
1731
+ s,
1732
+ c,
1733
+ m,
1734
+ p,
1735
+ e,
1736
+ a,
1737
+ f,
1738
+ b,
1739
+ o,
1740
+ l
1741
+ };
1477
1742
  }
1478
- function isNotFoundError(err) {
1479
- return err instanceof FurinNotFoundError || typeof err === "object" && err !== null && err.__furinBrand === NOT_FOUND_BRAND;
1743
+ function createConstantNode(value) {
1744
+ return createSerovalNode(2, NIL, value, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
1745
+ }
1746
+ function serializeChar(str) {
1747
+ switch (str) {
1748
+ case '"':
1749
+ return "\\\"";
1750
+ case "\\":
1751
+ return "\\\\";
1752
+ case `
1753
+ `:
1754
+ return "\\n";
1755
+ case "\r":
1756
+ return "\\r";
1757
+ case "\b":
1758
+ return "\\b";
1759
+ case "\t":
1760
+ return "\\t";
1761
+ case "\f":
1762
+ return "\\f";
1763
+ case "<":
1764
+ return "\\x3C";
1765
+ case "\u2028":
1766
+ return "\\u2028";
1767
+ case "\u2029":
1768
+ return "\\u2029";
1769
+ default:
1770
+ return NIL;
1771
+ }
1480
1772
  }
1481
- var NOT_FOUND_BRAND = "FURIN_NOT_FOUND", FurinNotFoundError;
1482
- var init_not_found = __esm(() => {
1483
- FurinNotFoundError = class FurinNotFoundError extends Error {
1484
- __furinBrand = NOT_FOUND_BRAND;
1485
- data;
1486
- constructor(options) {
1487
- super(options?.message ?? "");
1488
- this.data = options?.data;
1773
+ function serializeString(str) {
1774
+ let result = "";
1775
+ let lastPos = 0;
1776
+ let replacement;
1777
+ for (let i = 0, len = str.length;i < len; i++) {
1778
+ replacement = serializeChar(str[i]);
1779
+ if (replacement) {
1780
+ result += str.slice(lastPos, i) + replacement;
1781
+ lastPos = i + 1;
1489
1782
  }
1490
- };
1491
- });
1492
-
1493
- // src/error.ts
1494
- function getPublicErrorMessage(error) {
1495
- const branded = error;
1496
- if (branded?.__furinBrand === "FURIN_NOT_FOUND") {
1497
- return error.message;
1498
1783
  }
1499
- return "Something went wrong";
1784
+ if (lastPos === 0) {
1785
+ result = str;
1786
+ } else {
1787
+ result += str.slice(lastPos);
1788
+ }
1789
+ return result;
1500
1790
  }
1501
-
1502
- // src/link.tsx
1503
- import { createElement, useCallback, useEffect, useRef } from "react";
1504
- function computeLinkView({
1505
- to,
1506
- search,
1507
- hash,
1508
- children,
1509
- activeProps,
1510
- inactiveProps
1511
- }, router) {
1512
- const logicalHref = buildHref(to, search, hash);
1513
- const logicalHrefWithoutHash = buildHref(to, search, undefined);
1514
- const isAbsolute = logicalHref.startsWith("http://") || logicalHref.startsWith("https://") || logicalHref.startsWith("//");
1515
- const href = isAbsolute ? logicalHref : router.basePath + logicalHref;
1516
- const isActive = !isAbsolute && router.currentHref === normalizeHref(logicalHrefWithoutHash);
1517
- const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
1518
- const extraProps = {
1519
- ...inactiveProps && !isActive ? inactiveProps() : {},
1520
- ...activeProps ? activeProps({ isActive }) : {}
1521
- };
1522
- return { logicalHref, href, isActive, resolvedChildren, extraProps };
1791
+ function hasReferenceID(value) {
1792
+ return REFERENCE.has(value);
1523
1793
  }
1524
- function LinkInteractive({
1525
- to,
1526
- search,
1527
- hash,
1528
- preload,
1529
- preloadDelay,
1530
- preloadStaleTime,
1531
- replace,
1532
- disabled,
1533
- resetScroll,
1534
- activeProps,
1535
- inactiveProps,
1536
- onClick,
1537
- onMouseEnter,
1538
- onMouseLeave,
1539
- onFocus,
1540
- children,
1541
- href: _href,
1542
- ...anchorProps
1543
- }) {
1544
- const router = useRouter();
1545
- const anchorRef = useRef(null);
1546
- const intentTimerRef = useRef(null);
1547
- const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ to, search, hash, children, activeProps, inactiveProps }, router);
1548
- const effectivePreload = preload ?? router.defaultPreload;
1549
- const effectiveDelay = preloadDelay ?? router.defaultPreloadDelay;
1550
- const effectiveStaleTime = preloadStaleTime ?? router.defaultPreloadStaleTime;
1551
- const triggerPrefetch = useCallback(() => {
1552
- router.prefetch(logicalHref, { staleTime: effectiveStaleTime });
1553
- }, [router, logicalHref, effectiveStaleTime]);
1554
- useEffect(() => {
1555
- if (effectivePreload === "render") {
1556
- triggerPrefetch();
1794
+ function getReferenceID(value) {
1795
+ if (hasReferenceID(value)) {
1796
+ return REFERENCE.get(value);
1797
+ }
1798
+ throw new SerovalMissingReferenceError(value);
1799
+ }
1800
+ function getErrorConstructor(error) {
1801
+ if (error instanceof EvalError) {
1802
+ return 1;
1803
+ }
1804
+ if (error instanceof RangeError) {
1805
+ return 2;
1806
+ }
1807
+ if (error instanceof ReferenceError) {
1808
+ return 3;
1809
+ }
1810
+ if (error instanceof SyntaxError) {
1811
+ return 4;
1812
+ }
1813
+ if (error instanceof TypeError) {
1814
+ return 5;
1815
+ }
1816
+ if (error instanceof URIError) {
1817
+ return 6;
1818
+ }
1819
+ return 0;
1820
+ }
1821
+ function getInitialErrorOptions(error) {
1822
+ const construct = ERROR_CONSTRUCTOR_STRING[getErrorConstructor(error)];
1823
+ if (error.name !== construct) {
1824
+ return { name: error.name };
1825
+ }
1826
+ if (error.constructor.name !== construct) {
1827
+ return { name: error.constructor.name };
1828
+ }
1829
+ return {};
1830
+ }
1831
+ function getErrorOptions(error, features) {
1832
+ let options = getInitialErrorOptions(error);
1833
+ const names = Object.getOwnPropertyNames(error);
1834
+ for (let i = 0, len = names.length, name;i < len; i++) {
1835
+ name = names[i];
1836
+ if (name !== "name" && name !== "message") {
1837
+ if (name === "stack") {
1838
+ if (features & 4) {
1839
+ options = options || {};
1840
+ options[name] = error[name];
1841
+ }
1842
+ } else {
1843
+ options = options || {};
1844
+ options[name] = error[name];
1845
+ }
1557
1846
  }
1558
- }, [effectivePreload, triggerPrefetch]);
1847
+ }
1848
+ return options;
1849
+ }
1850
+ function getObjectFlag(obj) {
1851
+ if (Object.isFrozen(obj)) {
1852
+ return 3;
1853
+ }
1854
+ if (Object.isSealed(obj)) {
1855
+ return 2;
1856
+ }
1857
+ if (Object.isExtensible(obj)) {
1858
+ return 0;
1859
+ }
1860
+ return 1;
1861
+ }
1862
+ function createNumberNode(value) {
1863
+ switch (value) {
1864
+ case Number.POSITIVE_INFINITY:
1865
+ return INFINITY_NODE;
1866
+ case Number.NEGATIVE_INFINITY:
1867
+ return NEG_INFINITY_NODE;
1868
+ }
1869
+ if (value !== value) {
1870
+ return NAN_NODE;
1871
+ }
1872
+ if (Object.is(value, -0)) {
1873
+ return NEG_ZERO_NODE;
1874
+ }
1875
+ return createSerovalNode(0, NIL, value, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
1876
+ }
1877
+ function createStringNode(value) {
1878
+ return createSerovalNode(1, NIL, serializeString(value), NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
1879
+ }
1880
+ function createBigIntNode(current) {
1881
+ return createSerovalNode(3, NIL, "" + current, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
1882
+ }
1883
+ function createIndexedValueNode(id) {
1884
+ return createSerovalNode(4, id, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
1885
+ }
1886
+ function createDateNode(id, current) {
1887
+ const timestamp = current.valueOf();
1888
+ return createSerovalNode(5, id, timestamp !== timestamp ? "" : current.toISOString(), NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
1889
+ }
1890
+ function createRegExpNode(id, current) {
1891
+ return createSerovalNode(6, id, NIL, serializeString(current.source), current.flags, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
1892
+ }
1893
+ function createWKSymbolNode(id, current) {
1894
+ return createSerovalNode(17, id, INV_SYMBOL_REF[current], NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
1895
+ }
1896
+ function createReferenceNode(id, ref) {
1897
+ return createSerovalNode(18, id, serializeString(getReferenceID(ref)), NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
1898
+ }
1899
+ function createPluginNode(id, tag, value) {
1900
+ return createSerovalNode(25, id, value, serializeString(tag), NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
1901
+ }
1902
+ function createArrayNode(id, current, parsedItems) {
1903
+ return createSerovalNode(9, id, NIL, NIL, NIL, NIL, NIL, parsedItems, NIL, NIL, getObjectFlag(current), NIL);
1904
+ }
1905
+ function createBoxedNode(id, boxed) {
1906
+ return createSerovalNode(21, id, NIL, NIL, NIL, NIL, NIL, NIL, boxed, NIL, NIL, NIL);
1907
+ }
1908
+ function createTypedArrayNode(id, current, buffer) {
1909
+ return createSerovalNode(15, id, NIL, current.constructor.name, NIL, NIL, NIL, NIL, buffer, current.byteOffset, NIL, current.length);
1910
+ }
1911
+ function createBigIntTypedArrayNode(id, current, buffer) {
1912
+ return createSerovalNode(16, id, NIL, current.constructor.name, NIL, NIL, NIL, NIL, buffer, current.byteOffset, NIL, current.byteLength);
1913
+ }
1914
+ function createDataViewNode(id, current, buffer) {
1915
+ return createSerovalNode(20, id, NIL, NIL, NIL, NIL, NIL, NIL, buffer, current.byteOffset, NIL, current.byteLength);
1916
+ }
1917
+ function createErrorNode(id, current, options) {
1918
+ return createSerovalNode(13, id, getErrorConstructor(current), NIL, serializeString(current.message), options, NIL, NIL, NIL, NIL, NIL, NIL);
1919
+ }
1920
+ function createAggregateErrorNode(id, current, options) {
1921
+ return createSerovalNode(14, id, getErrorConstructor(current), NIL, serializeString(current.message), options, NIL, NIL, NIL, NIL, NIL, NIL);
1922
+ }
1923
+ function createSetNode(id, items) {
1924
+ return createSerovalNode(7, id, NIL, NIL, NIL, NIL, NIL, items, NIL, NIL, NIL, NIL);
1925
+ }
1926
+ function createIteratorFactoryInstanceNode(factory, items) {
1927
+ return createSerovalNode(28, NIL, NIL, NIL, NIL, NIL, NIL, [factory, items], NIL, NIL, NIL, NIL);
1928
+ }
1929
+ function createAsyncIteratorFactoryInstanceNode(factory, items) {
1930
+ return createSerovalNode(30, NIL, NIL, NIL, NIL, NIL, NIL, [factory, items], NIL, NIL, NIL, NIL);
1931
+ }
1932
+ function createStreamConstructorNode(id, factory, sequence) {
1933
+ return createSerovalNode(31, id, NIL, NIL, NIL, NIL, NIL, sequence, factory, NIL, NIL, NIL);
1934
+ }
1935
+ function createStreamNextNode(id, parsed) {
1936
+ return createSerovalNode(32, id, NIL, NIL, NIL, NIL, NIL, NIL, parsed, NIL, NIL, NIL);
1937
+ }
1938
+ function createStreamThrowNode(id, parsed) {
1939
+ return createSerovalNode(33, id, NIL, NIL, NIL, NIL, NIL, NIL, parsed, NIL, NIL, NIL);
1940
+ }
1941
+ function createStreamReturnNode(id, parsed) {
1942
+ return createSerovalNode(34, id, NIL, NIL, NIL, NIL, NIL, NIL, parsed, NIL, NIL, NIL);
1943
+ }
1944
+ function createSequenceNode(id, sequence, throwAt, doneAt) {
1945
+ return createSerovalNode(35, id, throwAt, NIL, NIL, NIL, NIL, sequence, NIL, NIL, NIL, doneAt);
1946
+ }
1947
+ function getErrorMessageDev(type, cause) {
1948
+ if (cause instanceof Error) {
1949
+ return `Seroval caught an error during the ${type} process.
1950
+
1951
+ ${cause.name}
1952
+ ${cause.message}
1953
+
1954
+ - For more information, please check the "cause" property of this error.
1955
+ - If you believe this is an error in Seroval, please submit an issue at https://github.com/lxsmnsyc/seroval/issues/new`;
1956
+ }
1957
+ return `Seroval caught an error during the ${type} process.
1958
+
1959
+ "${objectToString.call(cause)}"
1960
+
1961
+ For more information, please check the "cause" property of this error.`;
1962
+ }
1963
+ function isSequence(value) {
1964
+ return "__SEROVAL_SEQUENCE__" in value;
1965
+ }
1966
+ function createSequence(values, throwAt, doneAt) {
1967
+ return {
1968
+ __SEROVAL_SEQUENCE__: true,
1969
+ v: values,
1970
+ t: throwAt,
1971
+ d: doneAt
1972
+ };
1973
+ }
1974
+ function createSequenceFromIterable(source) {
1975
+ const values = [];
1976
+ let throwsAt = -1;
1977
+ let doneAt = -1;
1978
+ const iterator = source[SYM_ITERATOR]();
1979
+ while (true) {
1980
+ try {
1981
+ const value = iterator.next();
1982
+ values.push(value.value);
1983
+ if (value.done) {
1984
+ doneAt = values.length - 1;
1985
+ break;
1986
+ }
1987
+ } catch (error) {
1988
+ throwsAt = values.length;
1989
+ values.push(error);
1990
+ }
1991
+ }
1992
+ return createSequence(values, throwsAt, doneAt);
1993
+ }
1994
+ function isStream(value) {
1995
+ return "__SEROVAL_STREAM__" in value;
1996
+ }
1997
+ function createStream() {
1998
+ return STREAM_CONSTRUCTOR();
1999
+ }
2000
+ function createStreamFromAsyncIterable(iterable) {
2001
+ const stream = createStream();
2002
+ const iterator = iterable[SYM_ASYNC_ITERATOR]();
2003
+ async function push() {
2004
+ try {
2005
+ const value = await iterator.next();
2006
+ if (value.done) {
2007
+ stream.return(value.value);
2008
+ } else {
2009
+ stream.next(value.value);
2010
+ await push();
2011
+ }
2012
+ } catch (error) {
2013
+ stream.throw(error);
2014
+ }
2015
+ }
2016
+ push().catch(() => {});
2017
+ return stream;
2018
+ }
2019
+ async function promiseToResult(current) {
2020
+ try {
2021
+ return [1, await current];
2022
+ } catch (e) {
2023
+ return [0, e];
2024
+ }
2025
+ }
2026
+ function createBaseParserContext(mode, options) {
2027
+ return {
2028
+ plugins: options.plugins,
2029
+ mode,
2030
+ marked: /* @__PURE__ */ new Set,
2031
+ features: ALL_ENABLED ^ (options.disabledFeatures || 0),
2032
+ refs: options.refs || /* @__PURE__ */ new Map,
2033
+ depthLimit: options.depthLimit || 1000
2034
+ };
2035
+ }
2036
+ function markParserRef(ctx, id) {
2037
+ ctx.marked.add(id);
2038
+ }
2039
+ function createIndexForValue(ctx, current) {
2040
+ const id = ctx.refs.size;
2041
+ ctx.refs.set(current, id);
2042
+ return id;
2043
+ }
2044
+ function getNodeForIndexedValue(ctx, current) {
2045
+ const registeredId = ctx.refs.get(current);
2046
+ if (registeredId != null) {
2047
+ markParserRef(ctx, registeredId);
2048
+ return {
2049
+ type: 1,
2050
+ value: createIndexedValueNode(registeredId)
2051
+ };
2052
+ }
2053
+ return {
2054
+ type: 0,
2055
+ value: createIndexForValue(ctx, current)
2056
+ };
2057
+ }
2058
+ function getReferenceNode(ctx, current) {
2059
+ const indexed = getNodeForIndexedValue(ctx, current);
2060
+ if (indexed.type === 1) {
2061
+ return indexed;
2062
+ }
2063
+ if (hasReferenceID(current)) {
2064
+ return {
2065
+ type: 2,
2066
+ value: createReferenceNode(indexed.value, current)
2067
+ };
2068
+ }
2069
+ return indexed;
2070
+ }
2071
+ function parseWellKnownSymbol(ctx, current) {
2072
+ const ref = getReferenceNode(ctx, current);
2073
+ if (ref.type !== 0) {
2074
+ return ref.value;
2075
+ }
2076
+ if (current in INV_SYMBOL_REF) {
2077
+ return createWKSymbolNode(ref.value, current);
2078
+ }
2079
+ throw new SerovalUnsupportedTypeError(current);
2080
+ }
2081
+ function parseSpecialReference(ctx, ref) {
2082
+ const result = getNodeForIndexedValue(ctx, SPECIAL_REFS[ref]);
2083
+ if (result.type === 1) {
2084
+ return result.value;
2085
+ }
2086
+ return createSerovalNode(26, result.value, ref, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
2087
+ }
2088
+ function parseIteratorFactory(ctx) {
2089
+ const result = getNodeForIndexedValue(ctx, ITERATOR);
2090
+ if (result.type === 1) {
2091
+ return result.value;
2092
+ }
2093
+ return createSerovalNode(27, result.value, NIL, NIL, NIL, NIL, NIL, NIL, parseWellKnownSymbol(ctx, SYM_ITERATOR), NIL, NIL, NIL);
2094
+ }
2095
+ function parseAsyncIteratorFactory(ctx) {
2096
+ const result = getNodeForIndexedValue(ctx, ASYNC_ITERATOR);
2097
+ if (result.type === 1) {
2098
+ return result.value;
2099
+ }
2100
+ return createSerovalNode(29, result.value, NIL, NIL, NIL, NIL, NIL, [
2101
+ parseSpecialReference(ctx, 1),
2102
+ parseWellKnownSymbol(ctx, SYM_ASYNC_ITERATOR)
2103
+ ], NIL, NIL, NIL, NIL);
2104
+ }
2105
+ function createObjectNode(id, current, empty, record) {
2106
+ return createSerovalNode(empty ? 11 : 10, id, NIL, NIL, NIL, record, NIL, NIL, NIL, NIL, getObjectFlag(current), NIL);
2107
+ }
2108
+ function createMapNode(ctx, id, k, v) {
2109
+ return createSerovalNode(8, id, NIL, NIL, NIL, NIL, { k, v }, NIL, parseSpecialReference(ctx, 0), NIL, NIL, NIL);
2110
+ }
2111
+ function createPromiseConstructorNode(ctx, id, resolver) {
2112
+ return createSerovalNode(22, id, resolver, NIL, NIL, NIL, NIL, NIL, parseSpecialReference(ctx, 1), NIL, NIL, NIL);
2113
+ }
2114
+ function createArrayBufferNode(ctx, id, current) {
2115
+ const bytes = new Uint8Array(current);
2116
+ let result = "";
2117
+ for (let i = 0, len = bytes.length;i < len; i++) {
2118
+ result += String.fromCharCode(bytes[i]);
2119
+ }
2120
+ return createSerovalNode(19, id, serializeString(btoa(result)), NIL, NIL, NIL, NIL, NIL, parseSpecialReference(ctx, 5), NIL, NIL, NIL);
2121
+ }
2122
+ function createAsyncParserContext(mode, options) {
2123
+ return {
2124
+ base: createBaseParserContext(mode, options),
2125
+ child: undefined
2126
+ };
2127
+ }
2128
+ async function parseItems(ctx, depth, current) {
2129
+ const nodes = [];
2130
+ for (let i = 0, len = current.length;i < len; i++) {
2131
+ if (i in current) {
2132
+ nodes[i] = await parseAsync(ctx, depth, current[i]);
2133
+ } else {
2134
+ nodes[i] = 0;
2135
+ }
2136
+ }
2137
+ return nodes;
2138
+ }
2139
+ async function parseArray(ctx, depth, id, current) {
2140
+ return createArrayNode(id, current, await parseItems(ctx, depth, current));
2141
+ }
2142
+ async function parseProperties(ctx, depth, properties) {
2143
+ const entries = Object.entries(properties);
2144
+ const keyNodes = [];
2145
+ const valueNodes = [];
2146
+ for (let i = 0, len = entries.length;i < len; i++) {
2147
+ keyNodes.push(serializeString(entries[i][0]));
2148
+ valueNodes.push(await parseAsync(ctx, depth, entries[i][1]));
2149
+ }
2150
+ if (SYM_ITERATOR in properties) {
2151
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ITERATOR));
2152
+ valueNodes.push(createIteratorFactoryInstanceNode(parseIteratorFactory(ctx.base), await parseAsync(ctx, depth, createSequenceFromIterable(properties))));
2153
+ }
2154
+ if (SYM_ASYNC_ITERATOR in properties) {
2155
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ASYNC_ITERATOR));
2156
+ valueNodes.push(createAsyncIteratorFactoryInstanceNode(parseAsyncIteratorFactory(ctx.base), await parseAsync(ctx, depth, createStreamFromAsyncIterable(properties))));
2157
+ }
2158
+ if (SYM_TO_STRING_TAG in properties) {
2159
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_TO_STRING_TAG));
2160
+ valueNodes.push(createStringNode(properties[SYM_TO_STRING_TAG]));
2161
+ }
2162
+ if (SYM_IS_CONCAT_SPREADABLE in properties) {
2163
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_IS_CONCAT_SPREADABLE));
2164
+ valueNodes.push(properties[SYM_IS_CONCAT_SPREADABLE] ? TRUE_NODE : FALSE_NODE);
2165
+ }
2166
+ return {
2167
+ k: keyNodes,
2168
+ v: valueNodes
2169
+ };
2170
+ }
2171
+ async function parsePlainObject(ctx, depth, id, current, empty) {
2172
+ return createObjectNode(id, current, empty, await parseProperties(ctx, depth, current));
2173
+ }
2174
+ async function parseBoxed(ctx, depth, id, current) {
2175
+ return createBoxedNode(id, await parseAsync(ctx, depth, current.valueOf()));
2176
+ }
2177
+ async function parseTypedArray(ctx, depth, id, current) {
2178
+ return createTypedArrayNode(id, current, await parseAsync(ctx, depth, current.buffer));
2179
+ }
2180
+ async function parseBigIntTypedArray(ctx, depth, id, current) {
2181
+ return createBigIntTypedArrayNode(id, current, await parseAsync(ctx, depth, current.buffer));
2182
+ }
2183
+ async function parseDataView(ctx, depth, id, current) {
2184
+ return createDataViewNode(id, current, await parseAsync(ctx, depth, current.buffer));
2185
+ }
2186
+ async function parseError(ctx, depth, id, current) {
2187
+ const options = getErrorOptions(current, ctx.base.features);
2188
+ return createErrorNode(id, current, options ? await parseProperties(ctx, depth, options) : NIL);
2189
+ }
2190
+ async function parseAggregateError(ctx, depth, id, current) {
2191
+ const options = getErrorOptions(current, ctx.base.features);
2192
+ return createAggregateErrorNode(id, current, options ? await parseProperties(ctx, depth, options) : NIL);
2193
+ }
2194
+ async function parseMap(ctx, depth, id, current) {
2195
+ const keyNodes = [];
2196
+ const valueNodes = [];
2197
+ for (const [key, value] of current.entries()) {
2198
+ keyNodes.push(await parseAsync(ctx, depth, key));
2199
+ valueNodes.push(await parseAsync(ctx, depth, value));
2200
+ }
2201
+ return createMapNode(ctx.base, id, keyNodes, valueNodes);
2202
+ }
2203
+ async function parseSet(ctx, depth, id, current) {
2204
+ const items = [];
2205
+ for (const item of current.keys()) {
2206
+ items.push(await parseAsync(ctx, depth, item));
2207
+ }
2208
+ return createSetNode(id, items);
2209
+ }
2210
+ async function parsePlugin(ctx, depth, id, current) {
2211
+ const currentPlugins = ctx.base.plugins;
2212
+ if (currentPlugins) {
2213
+ for (let i = 0, len = currentPlugins.length;i < len; i++) {
2214
+ const plugin = currentPlugins[i];
2215
+ if (plugin.parse.async && plugin.test(current)) {
2216
+ return createPluginNode(id, plugin.tag, await plugin.parse.async(current, new AsyncParsePluginContext(ctx, depth), {
2217
+ id
2218
+ }));
2219
+ }
2220
+ }
2221
+ }
2222
+ return NIL;
2223
+ }
2224
+ async function parsePromise(ctx, depth, id, current) {
2225
+ const [status, result] = await promiseToResult(current);
2226
+ return createSerovalNode(12, id, status, NIL, NIL, NIL, NIL, NIL, await parseAsync(ctx, depth, result), NIL, NIL, NIL);
2227
+ }
2228
+ function parseStreamHandle(depth, id, current, resolve, reject) {
2229
+ const sequence = [];
2230
+ const cleanup = current.on({
2231
+ next: (value) => {
2232
+ markParserRef(this.base, id);
2233
+ parseAsync(this, depth, value).then((data) => {
2234
+ sequence.push(createStreamNextNode(id, data));
2235
+ }, (data) => {
2236
+ reject(data);
2237
+ cleanup();
2238
+ });
2239
+ },
2240
+ throw: (value) => {
2241
+ markParserRef(this.base, id);
2242
+ parseAsync(this, depth, value).then((data) => {
2243
+ sequence.push(createStreamThrowNode(id, data));
2244
+ resolve(sequence);
2245
+ cleanup();
2246
+ }, (data) => {
2247
+ reject(data);
2248
+ cleanup();
2249
+ });
2250
+ },
2251
+ return: (value) => {
2252
+ markParserRef(this.base, id);
2253
+ parseAsync(this, depth, value).then((data) => {
2254
+ sequence.push(createStreamReturnNode(id, data));
2255
+ resolve(sequence);
2256
+ cleanup();
2257
+ }, (data) => {
2258
+ reject(data);
2259
+ cleanup();
2260
+ });
2261
+ }
2262
+ });
2263
+ }
2264
+ async function parseStream(ctx, depth, id, current) {
2265
+ return createStreamConstructorNode(id, parseSpecialReference(ctx.base, 4), await new Promise(parseStreamHandle.bind(ctx, depth, id, current)));
2266
+ }
2267
+ async function parseSequence(ctx, depth, id, current) {
2268
+ const nodes = [];
2269
+ for (let i = 0, len = current.v.length;i < len; i++) {
2270
+ nodes[i] = await parseAsync(ctx, depth, current.v[i]);
2271
+ }
2272
+ return createSequenceNode(id, nodes, current.t, current.d);
2273
+ }
2274
+ async function parseObjectAsync(ctx, depth, id, current) {
2275
+ if (Array.isArray(current)) {
2276
+ return parseArray(ctx, depth, id, current);
2277
+ }
2278
+ if (isStream(current)) {
2279
+ return parseStream(ctx, depth, id, current);
2280
+ }
2281
+ if (isSequence(current)) {
2282
+ return parseSequence(ctx, depth, id, current);
2283
+ }
2284
+ const currentClass = current.constructor;
2285
+ if (currentClass === OpaqueReference) {
2286
+ return parseAsync(ctx, depth, current.replacement);
2287
+ }
2288
+ const parsed = await parsePlugin(ctx, depth, id, current);
2289
+ if (parsed) {
2290
+ return parsed;
2291
+ }
2292
+ switch (currentClass) {
2293
+ case Object:
2294
+ return parsePlainObject(ctx, depth, id, current, false);
2295
+ case NIL:
2296
+ return parsePlainObject(ctx, depth, id, current, true);
2297
+ case Date:
2298
+ return createDateNode(id, current);
2299
+ case Error:
2300
+ case EvalError:
2301
+ case RangeError:
2302
+ case ReferenceError:
2303
+ case SyntaxError:
2304
+ case TypeError:
2305
+ case URIError:
2306
+ return parseError(ctx, depth, id, current);
2307
+ case Number:
2308
+ case Boolean:
2309
+ case String:
2310
+ case BigInt:
2311
+ return parseBoxed(ctx, depth, id, current);
2312
+ case ArrayBuffer:
2313
+ return createArrayBufferNode(ctx.base, id, current);
2314
+ case Int8Array:
2315
+ case Int16Array:
2316
+ case Int32Array:
2317
+ case Uint8Array:
2318
+ case Uint16Array:
2319
+ case Uint32Array:
2320
+ case Uint8ClampedArray:
2321
+ case Float32Array:
2322
+ case Float64Array:
2323
+ return parseTypedArray(ctx, depth, id, current);
2324
+ case DataView:
2325
+ return parseDataView(ctx, depth, id, current);
2326
+ case Map:
2327
+ return parseMap(ctx, depth, id, current);
2328
+ case Set:
2329
+ return parseSet(ctx, depth, id, current);
2330
+ default:
2331
+ break;
2332
+ }
2333
+ if (currentClass === Promise || current instanceof Promise) {
2334
+ return parsePromise(ctx, depth, id, current);
2335
+ }
2336
+ const currentFeatures = ctx.base.features;
2337
+ if (currentFeatures & 32 && currentClass === RegExp) {
2338
+ return createRegExpNode(id, current);
2339
+ }
2340
+ if (currentFeatures & 16) {
2341
+ switch (currentClass) {
2342
+ case BigInt64Array:
2343
+ case BigUint64Array:
2344
+ return parseBigIntTypedArray(ctx, depth, id, current);
2345
+ default:
2346
+ break;
2347
+ }
2348
+ }
2349
+ if (currentFeatures & 1 && typeof AggregateError !== "undefined" && (currentClass === AggregateError || current instanceof AggregateError)) {
2350
+ return parseAggregateError(ctx, depth, id, current);
2351
+ }
2352
+ if (current instanceof Error) {
2353
+ return parseError(ctx, depth, id, current);
2354
+ }
2355
+ if (SYM_ITERATOR in current || SYM_ASYNC_ITERATOR in current) {
2356
+ return parsePlainObject(ctx, depth, id, current, !!currentClass);
2357
+ }
2358
+ throw new SerovalUnsupportedTypeError(current);
2359
+ }
2360
+ async function parseFunctionAsync(ctx, depth, current) {
2361
+ const ref = getReferenceNode(ctx.base, current);
2362
+ if (ref.type !== 0) {
2363
+ return ref.value;
2364
+ }
2365
+ const plugin = await parsePlugin(ctx, depth, ref.value, current);
2366
+ if (plugin) {
2367
+ return plugin;
2368
+ }
2369
+ throw new SerovalUnsupportedTypeError(current);
2370
+ }
2371
+ async function parseAsync(ctx, depth, current) {
2372
+ switch (typeof current) {
2373
+ case "boolean":
2374
+ return current ? TRUE_NODE : FALSE_NODE;
2375
+ case "undefined":
2376
+ return UNDEFINED_NODE;
2377
+ case "string":
2378
+ return createStringNode(current);
2379
+ case "number":
2380
+ return createNumberNode(current);
2381
+ case "bigint":
2382
+ return createBigIntNode(current);
2383
+ case "object": {
2384
+ if (current) {
2385
+ const ref = getReferenceNode(ctx.base, current);
2386
+ return ref.type === 0 ? await parseObjectAsync(ctx, depth + 1, ref.value, current) : ref.value;
2387
+ }
2388
+ return NULL_NODE;
2389
+ }
2390
+ case "symbol":
2391
+ return parseWellKnownSymbol(ctx.base, current);
2392
+ case "function":
2393
+ return parseFunctionAsync(ctx, depth, current);
2394
+ default:
2395
+ throw new SerovalUnsupportedTypeError(current);
2396
+ }
2397
+ }
2398
+ async function parseTopAsync(ctx, current) {
2399
+ try {
2400
+ return await parseAsync(ctx, 0, current);
2401
+ } catch (error) {
2402
+ throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
2403
+ }
2404
+ }
2405
+ function dedupePlugins(deduped, plugins) {
2406
+ for (let i = 0, len = plugins.length;i < len; i++) {
2407
+ const current = plugins[i];
2408
+ if (!deduped.has(current)) {
2409
+ deduped.add(current);
2410
+ if (current.extends) {
2411
+ dedupePlugins(deduped, current.extends);
2412
+ }
2413
+ }
2414
+ }
2415
+ }
2416
+ function resolvePlugins(plugins) {
2417
+ if (plugins) {
2418
+ const deduped = /* @__PURE__ */ new Set;
2419
+ dedupePlugins(deduped, plugins);
2420
+ return [...deduped];
2421
+ }
2422
+ return;
2423
+ }
2424
+ function createSyncParserContext(mode, options) {
2425
+ return {
2426
+ type: 1,
2427
+ base: createBaseParserContext(mode, options),
2428
+ child: NIL
2429
+ };
2430
+ }
2431
+ function parseItems2(ctx, depth, current) {
2432
+ const nodes = [];
2433
+ for (let i = 0, len = current.length;i < len; i++) {
2434
+ if (i in current) {
2435
+ nodes[i] = parseSOS(ctx, depth, current[i]);
2436
+ } else {
2437
+ nodes[i] = 0;
2438
+ }
2439
+ }
2440
+ return nodes;
2441
+ }
2442
+ function parseArray2(ctx, depth, id, current) {
2443
+ return createArrayNode(id, current, parseItems2(ctx, depth, current));
2444
+ }
2445
+ function parseProperties2(ctx, depth, properties) {
2446
+ const entries = Object.entries(properties);
2447
+ const keyNodes = [];
2448
+ const valueNodes = [];
2449
+ for (let i = 0, len = entries.length;i < len; i++) {
2450
+ keyNodes.push(serializeString(entries[i][0]));
2451
+ valueNodes.push(parseSOS(ctx, depth, entries[i][1]));
2452
+ }
2453
+ if (SYM_ITERATOR in properties) {
2454
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ITERATOR));
2455
+ valueNodes.push(createIteratorFactoryInstanceNode(parseIteratorFactory(ctx.base), parseSOS(ctx, depth, createSequenceFromIterable(properties))));
2456
+ }
2457
+ if (SYM_ASYNC_ITERATOR in properties) {
2458
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ASYNC_ITERATOR));
2459
+ valueNodes.push(createAsyncIteratorFactoryInstanceNode(parseAsyncIteratorFactory(ctx.base), parseSOS(ctx, depth, ctx.type === 1 ? createStream() : createStreamFromAsyncIterable(properties))));
2460
+ }
2461
+ if (SYM_TO_STRING_TAG in properties) {
2462
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_TO_STRING_TAG));
2463
+ valueNodes.push(createStringNode(properties[SYM_TO_STRING_TAG]));
2464
+ }
2465
+ if (SYM_IS_CONCAT_SPREADABLE in properties) {
2466
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_IS_CONCAT_SPREADABLE));
2467
+ valueNodes.push(properties[SYM_IS_CONCAT_SPREADABLE] ? TRUE_NODE : FALSE_NODE);
2468
+ }
2469
+ return {
2470
+ k: keyNodes,
2471
+ v: valueNodes
2472
+ };
2473
+ }
2474
+ function parsePlainObject2(ctx, depth, id, current, empty) {
2475
+ return createObjectNode(id, current, empty, parseProperties2(ctx, depth, current));
2476
+ }
2477
+ function parseBoxed2(ctx, depth, id, current) {
2478
+ return createBoxedNode(id, parseSOS(ctx, depth, current.valueOf()));
2479
+ }
2480
+ function parseTypedArray2(ctx, depth, id, current) {
2481
+ return createTypedArrayNode(id, current, parseSOS(ctx, depth, current.buffer));
2482
+ }
2483
+ function parseBigIntTypedArray2(ctx, depth, id, current) {
2484
+ return createBigIntTypedArrayNode(id, current, parseSOS(ctx, depth, current.buffer));
2485
+ }
2486
+ function parseDataView2(ctx, depth, id, current) {
2487
+ return createDataViewNode(id, current, parseSOS(ctx, depth, current.buffer));
2488
+ }
2489
+ function parseError2(ctx, depth, id, current) {
2490
+ const options = getErrorOptions(current, ctx.base.features);
2491
+ return createErrorNode(id, current, options ? parseProperties2(ctx, depth, options) : NIL);
2492
+ }
2493
+ function parseAggregateError2(ctx, depth, id, current) {
2494
+ const options = getErrorOptions(current, ctx.base.features);
2495
+ return createAggregateErrorNode(id, current, options ? parseProperties2(ctx, depth, options) : NIL);
2496
+ }
2497
+ function parseMap2(ctx, depth, id, current) {
2498
+ const keyNodes = [];
2499
+ const valueNodes = [];
2500
+ for (const [key, value] of current.entries()) {
2501
+ keyNodes.push(parseSOS(ctx, depth, key));
2502
+ valueNodes.push(parseSOS(ctx, depth, value));
2503
+ }
2504
+ return createMapNode(ctx.base, id, keyNodes, valueNodes);
2505
+ }
2506
+ function parseSet2(ctx, depth, id, current) {
2507
+ const items = [];
2508
+ for (const item of current.keys()) {
2509
+ items.push(parseSOS(ctx, depth, item));
2510
+ }
2511
+ return createSetNode(id, items);
2512
+ }
2513
+ function parseStream2(ctx, depth, id, current) {
2514
+ const result = createStreamConstructorNode(id, parseSpecialReference(ctx.base, 4), []);
2515
+ if (ctx.type === 1) {
2516
+ return result;
2517
+ }
2518
+ pushPendingState(ctx);
2519
+ current.on({
2520
+ next: (value) => {
2521
+ if (ctx.state.alive) {
2522
+ const parsed = parseWithError(ctx, depth, value);
2523
+ if (parsed) {
2524
+ onParse(ctx, createStreamNextNode(id, parsed));
2525
+ }
2526
+ }
2527
+ },
2528
+ throw: (value) => {
2529
+ if (ctx.state.alive) {
2530
+ const parsed = parseWithError(ctx, depth, value);
2531
+ if (parsed) {
2532
+ onParse(ctx, createStreamThrowNode(id, parsed));
2533
+ }
2534
+ }
2535
+ popPendingState(ctx);
2536
+ },
2537
+ return: (value) => {
2538
+ if (ctx.state.alive) {
2539
+ const parsed = parseWithError(ctx, depth, value);
2540
+ if (parsed) {
2541
+ onParse(ctx, createStreamReturnNode(id, parsed));
2542
+ }
2543
+ }
2544
+ popPendingState(ctx);
2545
+ }
2546
+ });
2547
+ return result;
2548
+ }
2549
+ function handlePromiseSuccess(id, depth, data) {
2550
+ if (this.state.alive) {
2551
+ const parsed = parseWithError(this, depth, data);
2552
+ if (parsed) {
2553
+ onParse(this, createSerovalNode(23, id, NIL, NIL, NIL, NIL, NIL, [
2554
+ parseSpecialReference(this.base, 2),
2555
+ parsed
2556
+ ], NIL, NIL, NIL, NIL));
2557
+ }
2558
+ popPendingState(this);
2559
+ }
2560
+ }
2561
+ function handlePromiseFailure(id, depth, data) {
2562
+ if (this.state.alive) {
2563
+ const parsed = parseWithError(this, depth, data);
2564
+ if (parsed) {
2565
+ onParse(this, createSerovalNode(24, id, NIL, NIL, NIL, NIL, NIL, [
2566
+ parseSpecialReference(this.base, 3),
2567
+ parsed
2568
+ ], NIL, NIL, NIL, NIL));
2569
+ }
2570
+ }
2571
+ popPendingState(this);
2572
+ }
2573
+ function parsePromise2(ctx, depth, id, current) {
2574
+ const resolver = createIndexForValue(ctx.base, {});
2575
+ if (ctx.type === 2) {
2576
+ pushPendingState(ctx);
2577
+ current.then(handlePromiseSuccess.bind(ctx, resolver, depth), handlePromiseFailure.bind(ctx, resolver, depth));
2578
+ }
2579
+ return createPromiseConstructorNode(ctx.base, id, resolver);
2580
+ }
2581
+ function parsePluginSync(ctx, depth, id, current, currentPlugins) {
2582
+ for (let i = 0, len = currentPlugins.length;i < len; i++) {
2583
+ const plugin = currentPlugins[i];
2584
+ if (plugin.parse.sync && plugin.test(current)) {
2585
+ return createPluginNode(id, plugin.tag, plugin.parse.sync(current, new SyncParsePluginContext(ctx, depth), {
2586
+ id
2587
+ }));
2588
+ }
2589
+ }
2590
+ return NIL;
2591
+ }
2592
+ function parsePluginStream(ctx, depth, id, current, currentPlugins) {
2593
+ for (let i = 0, len = currentPlugins.length;i < len; i++) {
2594
+ const plugin = currentPlugins[i];
2595
+ if (plugin.parse.stream && plugin.test(current)) {
2596
+ return createPluginNode(id, plugin.tag, plugin.parse.stream(current, new StreamParsePluginContext(ctx, depth), {
2597
+ id
2598
+ }));
2599
+ }
2600
+ }
2601
+ return NIL;
2602
+ }
2603
+ function parsePlugin2(ctx, depth, id, current) {
2604
+ const currentPlugins = ctx.base.plugins;
2605
+ if (currentPlugins) {
2606
+ return ctx.type === 1 ? parsePluginSync(ctx, depth, id, current, currentPlugins) : parsePluginStream(ctx, depth, id, current, currentPlugins);
2607
+ }
2608
+ return NIL;
2609
+ }
2610
+ function parseSequence2(ctx, depth, id, current) {
2611
+ const nodes = [];
2612
+ for (let i = 0, len = current.v.length;i < len; i++) {
2613
+ nodes[i] = parseSOS(ctx, depth, current.v[i]);
2614
+ }
2615
+ return createSequenceNode(id, nodes, current.t, current.d);
2616
+ }
2617
+ function parseObjectPhase2(ctx, depth, id, current, currentClass) {
2618
+ switch (currentClass) {
2619
+ case Object:
2620
+ return parsePlainObject2(ctx, depth, id, current, false);
2621
+ case NIL:
2622
+ return parsePlainObject2(ctx, depth, id, current, true);
2623
+ case Date:
2624
+ return createDateNode(id, current);
2625
+ case Error:
2626
+ case EvalError:
2627
+ case RangeError:
2628
+ case ReferenceError:
2629
+ case SyntaxError:
2630
+ case TypeError:
2631
+ case URIError:
2632
+ return parseError2(ctx, depth, id, current);
2633
+ case Number:
2634
+ case Boolean:
2635
+ case String:
2636
+ case BigInt:
2637
+ return parseBoxed2(ctx, depth, id, current);
2638
+ case ArrayBuffer:
2639
+ return createArrayBufferNode(ctx.base, id, current);
2640
+ case Int8Array:
2641
+ case Int16Array:
2642
+ case Int32Array:
2643
+ case Uint8Array:
2644
+ case Uint16Array:
2645
+ case Uint32Array:
2646
+ case Uint8ClampedArray:
2647
+ case Float32Array:
2648
+ case Float64Array:
2649
+ return parseTypedArray2(ctx, depth, id, current);
2650
+ case DataView:
2651
+ return parseDataView2(ctx, depth, id, current);
2652
+ case Map:
2653
+ return parseMap2(ctx, depth, id, current);
2654
+ case Set:
2655
+ return parseSet2(ctx, depth, id, current);
2656
+ default:
2657
+ break;
2658
+ }
2659
+ if (currentClass === Promise || current instanceof Promise) {
2660
+ return parsePromise2(ctx, depth, id, current);
2661
+ }
2662
+ const currentFeatures = ctx.base.features;
2663
+ if (currentFeatures & 32 && currentClass === RegExp) {
2664
+ return createRegExpNode(id, current);
2665
+ }
2666
+ if (currentFeatures & 16) {
2667
+ switch (currentClass) {
2668
+ case BigInt64Array:
2669
+ case BigUint64Array:
2670
+ return parseBigIntTypedArray2(ctx, depth, id, current);
2671
+ default:
2672
+ break;
2673
+ }
2674
+ }
2675
+ if (currentFeatures & 1 && typeof AggregateError !== "undefined" && (currentClass === AggregateError || current instanceof AggregateError)) {
2676
+ return parseAggregateError2(ctx, depth, id, current);
2677
+ }
2678
+ if (current instanceof Error) {
2679
+ return parseError2(ctx, depth, id, current);
2680
+ }
2681
+ if (SYM_ITERATOR in current || SYM_ASYNC_ITERATOR in current) {
2682
+ return parsePlainObject2(ctx, depth, id, current, !!currentClass);
2683
+ }
2684
+ throw new SerovalUnsupportedTypeError(current);
2685
+ }
2686
+ function parseObject(ctx, depth, id, current) {
2687
+ if (Array.isArray(current)) {
2688
+ return parseArray2(ctx, depth, id, current);
2689
+ }
2690
+ if (isStream(current)) {
2691
+ return parseStream2(ctx, depth, id, current);
2692
+ }
2693
+ if (isSequence(current)) {
2694
+ return parseSequence2(ctx, depth, id, current);
2695
+ }
2696
+ const currentClass = current.constructor;
2697
+ if (currentClass === OpaqueReference) {
2698
+ return parseSOS(ctx, depth, current.replacement);
2699
+ }
2700
+ const parsed = parsePlugin2(ctx, depth, id, current);
2701
+ if (parsed) {
2702
+ return parsed;
2703
+ }
2704
+ return parseObjectPhase2(ctx, depth, id, current, currentClass);
2705
+ }
2706
+ function parseFunction(ctx, depth, current) {
2707
+ const ref = getReferenceNode(ctx.base, current);
2708
+ if (ref.type !== 0) {
2709
+ return ref.value;
2710
+ }
2711
+ const plugin = parsePlugin2(ctx, depth, ref.value, current);
2712
+ if (plugin) {
2713
+ return plugin;
2714
+ }
2715
+ throw new SerovalUnsupportedTypeError(current);
2716
+ }
2717
+ function parseSOS(ctx, depth, current) {
2718
+ if (depth >= ctx.base.depthLimit) {
2719
+ throw new SerovalDepthLimitError(ctx.base.depthLimit);
2720
+ }
2721
+ switch (typeof current) {
2722
+ case "boolean":
2723
+ return current ? TRUE_NODE : FALSE_NODE;
2724
+ case "undefined":
2725
+ return UNDEFINED_NODE;
2726
+ case "string":
2727
+ return createStringNode(current);
2728
+ case "number":
2729
+ return createNumberNode(current);
2730
+ case "bigint":
2731
+ return createBigIntNode(current);
2732
+ case "object": {
2733
+ if (current) {
2734
+ const ref = getReferenceNode(ctx.base, current);
2735
+ return ref.type === 0 ? parseObject(ctx, depth + 1, ref.value, current) : ref.value;
2736
+ }
2737
+ return NULL_NODE;
2738
+ }
2739
+ case "symbol":
2740
+ return parseWellKnownSymbol(ctx.base, current);
2741
+ case "function": {
2742
+ return parseFunction(ctx, depth, current);
2743
+ }
2744
+ default:
2745
+ throw new SerovalUnsupportedTypeError(current);
2746
+ }
2747
+ }
2748
+ function parseTop(ctx, current) {
2749
+ try {
2750
+ return parseSOS(ctx, 0, current);
2751
+ } catch (error) {
2752
+ throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
2753
+ }
2754
+ }
2755
+ function onParse(ctx, node) {
2756
+ if (ctx.state.initial) {
2757
+ ctx.state.buffer.push(node);
2758
+ } else {
2759
+ onParseInternal(ctx, node, false);
2760
+ }
2761
+ }
2762
+ function onError(ctx, error) {
2763
+ if (ctx.state.onError) {
2764
+ ctx.state.onError(error);
2765
+ } else {
2766
+ throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
2767
+ }
2768
+ }
2769
+ function onDone(ctx) {
2770
+ if (ctx.state.onDone) {
2771
+ ctx.state.onDone();
2772
+ }
2773
+ }
2774
+ function onParseInternal(ctx, node, initial) {
2775
+ try {
2776
+ ctx.state.onParse(node, initial);
2777
+ } catch (error) {
2778
+ onError(ctx, error);
2779
+ }
2780
+ }
2781
+ function pushPendingState(ctx) {
2782
+ ctx.state.pending++;
2783
+ }
2784
+ function popPendingState(ctx) {
2785
+ if (--ctx.state.pending <= 0) {
2786
+ onDone(ctx);
2787
+ }
2788
+ }
2789
+ function parseWithError(ctx, depth, current) {
2790
+ try {
2791
+ return parseSOS(ctx, depth, current);
2792
+ } catch (err) {
2793
+ onError(ctx, err);
2794
+ return NIL;
2795
+ }
2796
+ }
2797
+ function toCrossJSON(source, options = {}) {
2798
+ const plugins = resolvePlugins(options.plugins);
2799
+ const ctx = createSyncParserContext(2, {
2800
+ plugins,
2801
+ disabledFeatures: options.disabledFeatures,
2802
+ refs: options.refs
2803
+ });
2804
+ return parseTop(ctx, source);
2805
+ }
2806
+ async function toCrossJSONAsync(source, options = {}) {
2807
+ const plugins = resolvePlugins(options.plugins);
2808
+ const ctx = createAsyncParserContext(2, {
2809
+ plugins,
2810
+ disabledFeatures: options.disabledFeatures,
2811
+ refs: options.refs
2812
+ });
2813
+ return await parseTopAsync(ctx, source);
2814
+ }
2815
+ var ALL_ENABLED, SYM_ASYNC_ITERATOR, SYM_HAS_INSTANCE, SYM_IS_CONCAT_SPREADABLE, SYM_ITERATOR, SYM_MATCH, SYM_MATCH_ALL, SYM_REPLACE, SYM_SEARCH, SYM_SPECIES, SYM_SPLIT, SYM_TO_PRIMITIVE, SYM_TO_STRING_TAG, SYM_UNSCOPABLES, INV_SYMBOL_REF, NIL = undefined, CONSTANT_VAL, ERROR_CONSTRUCTOR_STRING, TRUE_NODE, FALSE_NODE, UNDEFINED_NODE, NULL_NODE, NEG_ZERO_NODE, INFINITY_NODE, NEG_INFINITY_NODE, NAN_NODE, REFERENCES_KEY = "__SEROVAL_REFS__", GLOBAL_CONTEXT_REFERENCES = "$R", GLOBAL_CONTEXT_R, REFERENCE, INV_REFERENCE, objectToString, getErrorMessage = (type, cause) => getErrorMessageDev(type, cause), SerovalError, SerovalParserError, SerovalUnsupportedTypeError, SerovalMissingReferenceError, SerovalDepthLimitError, OpaqueReference = class {
2816
+ constructor(value, replacement) {
2817
+ this.value = value;
2818
+ this.replacement = replacement;
2819
+ }
2820
+ }, PROMISE_CONSTRUCTOR = () => {
2821
+ const resolver = {
2822
+ p: 0,
2823
+ s: 0,
2824
+ f: 0
2825
+ };
2826
+ resolver.p = new Promise((resolve, reject) => {
2827
+ resolver.s = resolve;
2828
+ resolver.f = reject;
2829
+ });
2830
+ return resolver;
2831
+ }, STREAM_CONSTRUCTOR = () => {
2832
+ const buffer = [];
2833
+ const listeners = [];
2834
+ let alive = true;
2835
+ let success = false;
2836
+ let count = 0;
2837
+ const flush = (value, mode, x) => {
2838
+ for (x = 0;x < count; x++) {
2839
+ if (listeners[x]) {
2840
+ listeners[x][mode](value);
2841
+ }
2842
+ }
2843
+ };
2844
+ const up = (listener, x, z, current) => {
2845
+ for (x = 0, z = buffer.length;x < z; x++) {
2846
+ current = buffer[x];
2847
+ if (!alive && x === z - 1) {
2848
+ listener[success ? "return" : "throw"](current);
2849
+ } else {
2850
+ listener.next(current);
2851
+ }
2852
+ }
2853
+ };
2854
+ const on = (listener, temp) => {
2855
+ if (alive) {
2856
+ temp = count++;
2857
+ listeners[temp] = listener;
2858
+ }
2859
+ up(listener);
2860
+ return () => {
2861
+ if (alive) {
2862
+ listeners[temp] = listeners[count];
2863
+ listeners[count--] = undefined;
2864
+ }
2865
+ };
2866
+ };
2867
+ return {
2868
+ __SEROVAL_STREAM__: true,
2869
+ on: (listener) => on(listener),
2870
+ next: (value) => {
2871
+ if (alive) {
2872
+ buffer.push(value);
2873
+ flush(value, "next");
2874
+ }
2875
+ },
2876
+ throw: (value) => {
2877
+ if (alive) {
2878
+ buffer.push(value);
2879
+ flush(value, "throw");
2880
+ alive = false;
2881
+ success = false;
2882
+ listeners.length = 0;
2883
+ }
2884
+ },
2885
+ return: (value) => {
2886
+ if (alive) {
2887
+ buffer.push(value);
2888
+ flush(value, "return");
2889
+ alive = false;
2890
+ success = true;
2891
+ listeners.length = 0;
2892
+ }
2893
+ }
2894
+ };
2895
+ }, ITERATOR_CONSTRUCTOR = (symbol) => (sequence) => () => {
2896
+ let index = 0;
2897
+ const instance = {
2898
+ [symbol]: () => instance,
2899
+ next: () => {
2900
+ if (index > sequence.d) {
2901
+ return {
2902
+ done: true,
2903
+ value: undefined
2904
+ };
2905
+ }
2906
+ const currentIndex = index++;
2907
+ const data = sequence.v[currentIndex];
2908
+ if (currentIndex === sequence.t) {
2909
+ throw data;
2910
+ }
2911
+ return {
2912
+ done: currentIndex === sequence.d,
2913
+ value: data
2914
+ };
2915
+ }
2916
+ };
2917
+ return instance;
2918
+ }, ASYNC_ITERATOR_CONSTRUCTOR = (symbol, createPromise) => (stream) => () => {
2919
+ let count = 0;
2920
+ let doneAt = -1;
2921
+ let isThrow = false;
2922
+ const buffer = [];
2923
+ const pending = [];
2924
+ const finalize = (i = 0, len = pending.length) => {
2925
+ for (;i < len; i++) {
2926
+ pending[i].s({
2927
+ done: true,
2928
+ value: undefined
2929
+ });
2930
+ }
2931
+ };
2932
+ stream.on({
2933
+ next: (value) => {
2934
+ const temp = pending.shift();
2935
+ if (temp) {
2936
+ temp.s({ done: false, value });
2937
+ }
2938
+ buffer.push(value);
2939
+ },
2940
+ throw: (value) => {
2941
+ const temp = pending.shift();
2942
+ if (temp) {
2943
+ temp.f(value);
2944
+ }
2945
+ finalize();
2946
+ doneAt = buffer.length;
2947
+ isThrow = true;
2948
+ buffer.push(value);
2949
+ },
2950
+ return: (value) => {
2951
+ const temp = pending.shift();
2952
+ if (temp) {
2953
+ temp.s({ done: true, value });
2954
+ }
2955
+ finalize();
2956
+ doneAt = buffer.length;
2957
+ buffer.push(value);
2958
+ }
2959
+ });
2960
+ const instance = {
2961
+ [symbol]: () => instance,
2962
+ next: () => {
2963
+ if (doneAt === -1) {
2964
+ const index2 = count++;
2965
+ if (index2 >= buffer.length) {
2966
+ const temp = createPromise();
2967
+ pending.push(temp);
2968
+ return temp.p;
2969
+ }
2970
+ return {
2971
+ done: false,
2972
+ value: buffer[index2]
2973
+ };
2974
+ }
2975
+ if (count > doneAt) {
2976
+ return {
2977
+ done: true,
2978
+ value: undefined
2979
+ };
2980
+ }
2981
+ const index = count++;
2982
+ const value = buffer[index];
2983
+ if (index !== doneAt) {
2984
+ return {
2985
+ done: false,
2986
+ value
2987
+ };
2988
+ }
2989
+ if (isThrow) {
2990
+ throw value;
2991
+ }
2992
+ return {
2993
+ done: true,
2994
+ value
2995
+ };
2996
+ }
2997
+ };
2998
+ return instance;
2999
+ }, createIterator, ITERATOR, ASYNC_ITERATOR, SPECIAL_REFS, createAsyncIterable, AsyncParsePluginContext = class {
3000
+ constructor(_p, depth) {
3001
+ this._p = _p;
3002
+ this.depth = depth;
3003
+ }
3004
+ parse(current) {
3005
+ return parseAsync(this._p, this.depth, current);
3006
+ }
3007
+ }, REF_START_CHARS = "hjkmoquxzABCDEFGHIJKLNPQRTUVWXYZ$_", REF_START_CHARS_LEN, REF_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$_", REF_CHARS_LEN, SyncParsePluginContext = class {
3008
+ constructor(_p, depth) {
3009
+ this._p = _p;
3010
+ this.depth = depth;
3011
+ }
3012
+ parse(current) {
3013
+ return parseSOS(this._p, this.depth, current);
3014
+ }
3015
+ }, StreamParsePluginContext = class {
3016
+ constructor(_p, depth) {
3017
+ this._p = _p;
3018
+ this.depth = depth;
3019
+ }
3020
+ parse(current) {
3021
+ return parseSOS(this._p, this.depth, current);
3022
+ }
3023
+ parseWithError(current) {
3024
+ return parseWithError(this._p, this.depth, current);
3025
+ }
3026
+ isAlive() {
3027
+ return this._p.state.alive;
3028
+ }
3029
+ pushPendingState() {
3030
+ pushPendingState(this._p);
3031
+ }
3032
+ popPendingState() {
3033
+ popPendingState(this._p);
3034
+ }
3035
+ onParse(node) {
3036
+ onParse(this._p, node);
3037
+ }
3038
+ onError(error) {
3039
+ onError(this._p, error);
3040
+ }
3041
+ };
3042
+ var init_development = __esm(() => {
3043
+ ALL_ENABLED = 1 | 2 | 4 | 8 | 16 | 32;
3044
+ SYM_ASYNC_ITERATOR = Symbol.asyncIterator;
3045
+ SYM_HAS_INSTANCE = Symbol.hasInstance;
3046
+ SYM_IS_CONCAT_SPREADABLE = Symbol.isConcatSpreadable;
3047
+ SYM_ITERATOR = Symbol.iterator;
3048
+ SYM_MATCH = Symbol.match;
3049
+ SYM_MATCH_ALL = Symbol.matchAll;
3050
+ SYM_REPLACE = Symbol.replace;
3051
+ SYM_SEARCH = Symbol.search;
3052
+ SYM_SPECIES = Symbol.species;
3053
+ SYM_SPLIT = Symbol.split;
3054
+ SYM_TO_PRIMITIVE = Symbol.toPrimitive;
3055
+ SYM_TO_STRING_TAG = Symbol.toStringTag;
3056
+ SYM_UNSCOPABLES = Symbol.unscopables;
3057
+ INV_SYMBOL_REF = {
3058
+ [SYM_ASYNC_ITERATOR]: 0,
3059
+ [SYM_HAS_INSTANCE]: 1,
3060
+ [SYM_IS_CONCAT_SPREADABLE]: 2,
3061
+ [SYM_ITERATOR]: 3,
3062
+ [SYM_MATCH]: 4,
3063
+ [SYM_MATCH_ALL]: 5,
3064
+ [SYM_REPLACE]: 6,
3065
+ [SYM_SEARCH]: 7,
3066
+ [SYM_SPECIES]: 8,
3067
+ [SYM_SPLIT]: 9,
3068
+ [SYM_TO_PRIMITIVE]: 10,
3069
+ [SYM_TO_STRING_TAG]: 11,
3070
+ [SYM_UNSCOPABLES]: 12
3071
+ };
3072
+ CONSTANT_VAL = {
3073
+ [2]: true,
3074
+ [3]: false,
3075
+ [1]: NIL,
3076
+ [0]: null,
3077
+ [4]: -0,
3078
+ [5]: Number.POSITIVE_INFINITY,
3079
+ [6]: Number.NEGATIVE_INFINITY,
3080
+ [7]: Number.NaN
3081
+ };
3082
+ ERROR_CONSTRUCTOR_STRING = {
3083
+ [0]: "Error",
3084
+ [1]: "EvalError",
3085
+ [2]: "RangeError",
3086
+ [3]: "ReferenceError",
3087
+ [4]: "SyntaxError",
3088
+ [5]: "TypeError",
3089
+ [6]: "URIError"
3090
+ };
3091
+ TRUE_NODE = /* @__PURE__ */ createConstantNode(2);
3092
+ FALSE_NODE = /* @__PURE__ */ createConstantNode(3);
3093
+ UNDEFINED_NODE = /* @__PURE__ */ createConstantNode(1);
3094
+ NULL_NODE = /* @__PURE__ */ createConstantNode(0);
3095
+ NEG_ZERO_NODE = /* @__PURE__ */ createConstantNode(4);
3096
+ INFINITY_NODE = /* @__PURE__ */ createConstantNode(5);
3097
+ NEG_INFINITY_NODE = /* @__PURE__ */ createConstantNode(6);
3098
+ NAN_NODE = /* @__PURE__ */ createConstantNode(7);
3099
+ GLOBAL_CONTEXT_R = `self.${GLOBAL_CONTEXT_REFERENCES}`;
3100
+ REFERENCE = /* @__PURE__ */ new Map;
3101
+ INV_REFERENCE = /* @__PURE__ */ new Map;
3102
+ if (typeof globalThis !== "undefined") {
3103
+ Object.defineProperty(globalThis, REFERENCES_KEY, {
3104
+ value: INV_REFERENCE,
3105
+ configurable: true,
3106
+ writable: false,
3107
+ enumerable: false
3108
+ });
3109
+ } else if (typeof window !== "undefined") {
3110
+ Object.defineProperty(window, REFERENCES_KEY, {
3111
+ value: INV_REFERENCE,
3112
+ configurable: true,
3113
+ writable: false,
3114
+ enumerable: false
3115
+ });
3116
+ } else if (typeof self !== "undefined") {
3117
+ Object.defineProperty(self, REFERENCES_KEY, {
3118
+ value: INV_REFERENCE,
3119
+ configurable: true,
3120
+ writable: false,
3121
+ enumerable: false
3122
+ });
3123
+ } else if (typeof global !== "undefined") {
3124
+ Object.defineProperty(global, REFERENCES_KEY, {
3125
+ value: INV_REFERENCE,
3126
+ configurable: true,
3127
+ writable: false,
3128
+ enumerable: false
3129
+ });
3130
+ }
3131
+ ({ toString: objectToString } = Object.prototype);
3132
+ SerovalError = class extends Error {
3133
+ constructor(type, cause) {
3134
+ super(getErrorMessage(type, cause));
3135
+ this.cause = cause;
3136
+ }
3137
+ };
3138
+ SerovalParserError = class extends SerovalError {
3139
+ constructor(cause) {
3140
+ super("parsing", cause);
3141
+ }
3142
+ };
3143
+ SerovalUnsupportedTypeError = class extends Error {
3144
+ constructor(value) {
3145
+ super(`The value ${objectToString.call(value)} of type "${typeof value}" cannot be parsed/serialized.
3146
+
3147
+ There are few workarounds for this problem:
3148
+ - Transform the value in a way that it can be serialized.
3149
+ - If the reference is present on multiple runtimes (isomorphic), you can use the Reference API to map the references.`);
3150
+ this.value = value;
3151
+ }
3152
+ };
3153
+ SerovalMissingReferenceError = class extends Error {
3154
+ constructor(value) {
3155
+ super('Missing reference for the value "' + objectToString.call(value) + '" of type "' + typeof value + '"');
3156
+ this.value = value;
3157
+ }
3158
+ };
3159
+ SerovalDepthLimitError = class extends Error {
3160
+ constructor(limit) {
3161
+ super("Depth limit of " + limit + " reached");
3162
+ }
3163
+ };
3164
+ createIterator = ITERATOR_CONSTRUCTOR(SYM_ITERATOR);
3165
+ ITERATOR = {};
3166
+ ASYNC_ITERATOR = {};
3167
+ SPECIAL_REFS = {
3168
+ [0]: {},
3169
+ [1]: {},
3170
+ [2]: {},
3171
+ [3]: {},
3172
+ [4]: {},
3173
+ [5]: {}
3174
+ };
3175
+ createAsyncIterable = ASYNC_ITERATOR_CONSTRUCTOR(SYM_ASYNC_ITERATOR, PROMISE_CONSTRUCTOR);
3176
+ REF_START_CHARS_LEN = REF_START_CHARS.length;
3177
+ REF_CHARS_LEN = REF_CHARS.length;
3178
+ });
3179
+
3180
+ // src/not-found.ts
3181
+ function notFound(options) {
3182
+ throw new FurinNotFoundError(options);
3183
+ }
3184
+ function isNotFoundError(err) {
3185
+ return err instanceof FurinNotFoundError || typeof err === "object" && err !== null && err.__furinBrand === NOT_FOUND_BRAND;
3186
+ }
3187
+ var NOT_FOUND_BRAND = "FURIN_NOT_FOUND", FurinNotFoundError;
3188
+ var init_not_found = __esm(() => {
3189
+ FurinNotFoundError = class FurinNotFoundError extends Error {
3190
+ __furinBrand = NOT_FOUND_BRAND;
3191
+ data;
3192
+ constructor(options) {
3193
+ super(options?.message ?? "");
3194
+ this.data = options?.data;
3195
+ }
3196
+ };
3197
+ });
3198
+
3199
+ // src/error.ts
3200
+ function getPublicErrorMessage(error) {
3201
+ const branded = error;
3202
+ if (branded?.__furinBrand === "FURIN_NOT_FOUND" || branded?.__furinBrand === "FURIN_SERVER_ERROR") {
3203
+ return error.message;
3204
+ }
3205
+ return "Something went wrong";
3206
+ }
3207
+
3208
+ // src/server-error.ts
3209
+ function isFurinServerError(err) {
3210
+ return err instanceof FurinServerError || typeof err === "object" && err !== null && err.__furinBrand === SERVER_ERROR_BRAND;
3211
+ }
3212
+ var SERVER_ERROR_BRAND = "FURIN_SERVER_ERROR", FurinServerError;
3213
+ var init_server_error = __esm(() => {
3214
+ FurinServerError = class FurinServerError extends Error {
3215
+ __furinBrand = SERVER_ERROR_BRAND;
3216
+ digest;
3217
+ status;
3218
+ constructor(args) {
3219
+ super(args.message);
3220
+ this.status = args.status;
3221
+ this.digest = args.digest;
3222
+ }
3223
+ };
3224
+ });
3225
+
3226
+ // src/link.tsx
3227
+ import { createElement, useCallback, useEffect, useRef } from "react";
3228
+ function computeLinkView({
3229
+ to,
3230
+ search,
3231
+ hash,
3232
+ children,
3233
+ activeProps,
3234
+ inactiveProps
3235
+ }, router) {
3236
+ const logicalHref = buildHref(to, search, hash);
3237
+ const logicalHrefWithoutHash = buildHref(to, search, undefined);
3238
+ const isAbsolute = logicalHref.startsWith("http://") || logicalHref.startsWith("https://") || logicalHref.startsWith("//");
3239
+ const href = isAbsolute ? logicalHref : router.basePath + logicalHref;
3240
+ const isActive = !isAbsolute && router.currentHref === normalizeHref(logicalHrefWithoutHash);
3241
+ const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
3242
+ const extraProps = {
3243
+ ...inactiveProps && !isActive ? inactiveProps() : {},
3244
+ ...activeProps ? activeProps({ isActive }) : {}
3245
+ };
3246
+ return { logicalHref, href, isActive, resolvedChildren, extraProps };
3247
+ }
3248
+ function LinkInteractive({
3249
+ to,
3250
+ search,
3251
+ hash,
3252
+ preload,
3253
+ preloadDelay,
3254
+ preloadStaleTime,
3255
+ replace,
3256
+ disabled,
3257
+ resetScroll,
3258
+ activeProps,
3259
+ inactiveProps,
3260
+ onClick,
3261
+ onMouseEnter,
3262
+ onMouseLeave,
3263
+ onFocus,
3264
+ children,
3265
+ href: _href,
3266
+ ...anchorProps
3267
+ }) {
3268
+ const router = useRouter();
3269
+ const anchorRef = useRef(null);
3270
+ const intentTimerRef = useRef(null);
3271
+ const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ to, search, hash, children, activeProps, inactiveProps }, router);
3272
+ const effectivePreload = preload ?? router.defaultPreload;
3273
+ const effectiveDelay = preloadDelay ?? router.defaultPreloadDelay;
3274
+ const effectiveStaleTime = preloadStaleTime ?? router.defaultPreloadStaleTime;
3275
+ const { prefetch } = router;
3276
+ const triggerPrefetch = useCallback(() => {
3277
+ prefetch(logicalHref, { staleTime: effectiveStaleTime });
3278
+ }, [prefetch, logicalHref, effectiveStaleTime]);
3279
+ useEffect(() => {
3280
+ if (effectivePreload === "render") {
3281
+ triggerPrefetch();
3282
+ }
3283
+ }, [effectivePreload, triggerPrefetch]);
1559
3284
  useEffect(() => {
1560
3285
  if (effectivePreload !== "viewport" || !anchorRef.current) {
1561
3286
  return;
@@ -1601,6 +3326,10 @@ function LinkInteractive({
1601
3326
  return;
1602
3327
  }
1603
3328
  e.preventDefault();
3329
+ if (typeof window !== "undefined" && router.navigate === SSR_FALLBACK_ROUTER.navigate) {
3330
+ window.location.href = href;
3331
+ return;
3332
+ }
1604
3333
  router.navigate(logicalHref, { replace, resetScroll: resetScroll ?? true });
1605
3334
  };
1606
3335
  const handleMouseEnter = (e) => {
@@ -1678,6 +3407,7 @@ function Link(props) {
1678
3407
  var SSR_FALLBACK_ROUTER;
1679
3408
  var init_link = __esm(() => {
1680
3409
  init_router_provider();
3410
+ init_development();
1681
3411
  init_router_provider();
1682
3412
  SSR_FALLBACK_ROUTER = {
1683
3413
  basePath: "",
@@ -1715,7 +3445,7 @@ function ScreenFrame({ badge, children }) {
1715
3445
  style: PAGE_STYLE,
1716
3446
  children: [
1717
3447
  /* @__PURE__ */ jsxDEV("style", {
1718
- dangerouslySetInnerHTML: { __html: RESET_CSS }
3448
+ children: RESET_CSS
1719
3449
  }, undefined, false, undefined, this),
1720
3450
  /* @__PURE__ */ jsxDEV("div", {
1721
3451
  style: FRAME_STYLE,
@@ -1796,7 +3526,7 @@ function DefaultErrorScreen({ message, digest, reset }) {
1796
3526
  function DefaultNotFoundScreen({ message }) {
1797
3527
  return /* @__PURE__ */ jsxDEV(ScreenFrame, {
1798
3528
  badge: /* @__PURE__ */ jsxDEV("div", {
1799
- style: NOT_FOUND_BADGE_STYLE,
3529
+ style: BADGE_STYLE,
1800
3530
  children: "404 \u2014 NOT FOUND"
1801
3531
  }, undefined, false, undefined, this),
1802
3532
  children: [
@@ -1819,7 +3549,7 @@ function DefaultNotFoundScreen({ message }) {
1819
3549
  ]
1820
3550
  }, undefined, true, undefined, this);
1821
3551
  }
1822
- var FONT_SANS = '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif', FONT_MONO = 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace', COLOR_BG = "#000000", COLOR_TEXT = "#ffffff", COLOR_TEXT_DIM = "rgba(255, 255, 255, 0.7)", COLOR_TEXT_MUTED = "rgba(255, 255, 255, 0.45)", COLOR_GRID = "rgba(255, 255, 255, 0.04)", COLOR_BRACKET = "rgba(255, 255, 255, 0.55)", COLOR_DANGER_DIM = "rgba(239, 68, 68, 0.6)", PAGE_STYLE, FRAME_STYLE, BRACKET_BASE, CARD_STYLE, BADGE_STYLE, NOT_FOUND_BADGE_STYLE, HEADING_STYLE, CODE_BOX_STYLE, CODE_LABEL_STYLE, DESCRIPTION_WRAPPER_STYLE, ACTIONS_STYLE, BUTTON_BASE, BUTTON_PRIMARY, BUTTON_SECONDARY, DIVIDER_STYLE, RESET_CSS;
3552
+ var FONT_SANS = '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif', FONT_MONO = 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace', COLOR_BG = "#000000", COLOR_TEXT = "#ffffff", COLOR_TEXT_DIM = "rgba(255, 255, 255, 0.7)", COLOR_TEXT_MUTED = "rgba(255, 255, 255, 0.45)", COLOR_GRID = "rgba(255, 255, 255, 0.04)", COLOR_BRACKET = "rgba(255, 255, 255, 0.55)", COLOR_DANGER_DIM = "rgba(239, 68, 68, 0.6)", PAGE_STYLE, FRAME_STYLE, BRACKET_BASE, CARD_STYLE, BADGE_STYLE, HEADING_STYLE, CODE_BOX_STYLE, CODE_LABEL_STYLE, DESCRIPTION_WRAPPER_STYLE, ACTIONS_STYLE, BUTTON_BASE, BUTTON_PRIMARY, BUTTON_SECONDARY, DIVIDER_STYLE, RESET_CSS;
1823
3553
  var init_default_screens = __esm(() => {
1824
3554
  init_link();
1825
3555
  PAGE_STYLE = {
@@ -1871,11 +3601,6 @@ var init_default_screens = __esm(() => {
1871
3601
  marginBottom: "16px",
1872
3602
  padding: "12px 36px"
1873
3603
  };
1874
- NOT_FOUND_BADGE_STYLE = {
1875
- ...BADGE_STYLE,
1876
- border: 0,
1877
- padding: 0
1878
- };
1879
3604
  HEADING_STYLE = {
1880
3605
  color: COLOR_TEXT,
1881
3606
  fontFamily: FONT_SANS,
@@ -2002,11 +3727,12 @@ var DefaultErrorFallback = ({ error, reset }) => /* @__PURE__ */ jsxDEV2(Default
2002
3727
  digest: error.digest,
2003
3728
  message: error.message,
2004
3729
  reset
2005
- }, undefined, false, undefined, this), DefaultNotFoundFallback = ({ error }) => /* @__PURE__ */ jsxDEV2(DefaultNotFoundScreen, {
3730
+ }, undefined, false, undefined, this), DEFAULT_ERROR_STATUS = 500, DefaultNotFoundFallback = ({ error }) => /* @__PURE__ */ jsxDEV2(DefaultNotFoundScreen, {
2006
3731
  message: error.message
2007
3732
  }, undefined, false, undefined, this), SERVER_RESET_NOOP = () => {}, FurinErrorBoundary, FurinNotFoundBoundary;
2008
3733
  var init_boundaries = __esm(() => {
2009
3734
  init_not_found();
3735
+ init_server_error();
2010
3736
  init_default_screens();
2011
3737
  FurinErrorBoundary = class FurinErrorBoundary extends Component {
2012
3738
  state = {
@@ -2034,10 +3760,12 @@ var init_boundaries = __esm(() => {
2034
3760
  throw error;
2035
3761
  }
2036
3762
  const Fallback = this.props.fallback ?? DefaultErrorFallback;
2037
- const finalDigest = digest ?? this.props.digest ?? computeErrorDigest(error);
3763
+ const serverDigest = isFurinServerError(error) ? error.digest : undefined;
3764
+ const finalDigest = serverDigest ?? digest ?? this.props.digest ?? computeErrorDigest(error);
2038
3765
  const message = this.props.fallback ? error.message : getPublicErrorMessage(error);
3766
+ const status = isFurinServerError(error) ? error.status : DEFAULT_ERROR_STATUS;
2039
3767
  return /* @__PURE__ */ jsxDEV2(Fallback, {
2040
- error: { message, digest: finalDigest },
3768
+ error: { message, digest: finalDigest, status },
2041
3769
  reset: typeof window === "undefined" ? SERVER_RESET_NOOP : this.reset
2042
3770
  }, undefined, false, undefined, this);
2043
3771
  }
@@ -2127,18 +3855,77 @@ function useRouter() {
2127
3855
  defaultPreloadStaleTime: 30000
2128
3856
  };
2129
3857
  }
2130
- function normalizeHref(href) {
2131
- const url = new URL(href, "http://localhost");
2132
- let pathname = url.pathname;
2133
- if (pathname !== "/") {
2134
- pathname = pathname.replace(/\/+$/g, "");
3858
+ function normalizeHref(href) {
3859
+ const url = new URL(href, "http://localhost");
3860
+ let pathname = url.pathname;
3861
+ if (pathname !== "/") {
3862
+ pathname = pathname.replace(/\/+$/g, "");
3863
+ }
3864
+ return pathname + url.search + url.hash;
3865
+ }
3866
+ var RouterContext;
3867
+ var init_router_provider = __esm(() => {
3868
+ RouterContext = createContext(null);
3869
+ });
3870
+
3871
+ // src/utils.ts
3872
+ function isFurinPage(value) {
3873
+ return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
3874
+ }
3875
+ function isFurinRoute(value) {
3876
+ return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_ROUTE";
3877
+ }
3878
+ function collectRouteChainFromRoute(route) {
3879
+ const chain = [];
3880
+ let current = route;
3881
+ while (current) {
3882
+ chain.unshift(current);
3883
+ current = current.parent;
3884
+ }
3885
+ return chain;
3886
+ }
3887
+ function hasCycle(route) {
3888
+ const visited = new Set;
3889
+ let current = route;
3890
+ while (current) {
3891
+ if (visited.has(current)) {
3892
+ return true;
3893
+ }
3894
+ visited.add(current);
3895
+ current = current.parent;
3896
+ }
3897
+ return false;
3898
+ }
3899
+ async function mapWithConcurrency(items, concurrency, fn) {
3900
+ if (items.length === 0) {
3901
+ return [];
3902
+ }
3903
+ const results = new Array(items.length);
3904
+ let cursor = 0;
3905
+ const workerCount = Math.min(Math.max(concurrency, 1), items.length);
3906
+ await Promise.all(Array.from({ length: workerCount }, async () => {
3907
+ while (true) {
3908
+ const index = cursor++;
3909
+ if (index >= items.length) {
3910
+ return;
3911
+ }
3912
+ results[index] = await fn(items[index], index);
3913
+ }
3914
+ }));
3915
+ return results;
3916
+ }
3917
+ function validateRouteChain(chain, root, pagePath) {
3918
+ const hasRoot = chain.some((r) => r === root);
3919
+ if (!hasRoot) {
3920
+ const location = pagePath ? `in ${pagePath}` : "";
3921
+ throw new Error(`[furin] Page ${location} must inherit from root route. ` + 'Add: import { route } from "./root"; and use route.page() or set parent: route');
3922
+ }
3923
+ for (const route of chain) {
3924
+ if (hasCycle(route)) {
3925
+ throw new Error("[furin] Cycle detected in route chain. A route cannot be its own ancestor.");
3926
+ }
2135
3927
  }
2136
- return pathname + url.search + url.hash;
2137
3928
  }
2138
- var RouterContext;
2139
- var init_router_provider = __esm(() => {
2140
- RouterContext = createContext(null);
2141
- });
2142
3929
 
2143
3930
  // src/render/shell.ts
2144
3931
  function extractTitle(meta) {
@@ -2162,7 +3949,13 @@ function safeJson(value) {
2162
3949
  return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
2163
3950
  }
2164
3951
  function renderAttrs(obj) {
2165
- return Object.entries(obj).filter(([, v]) => v !== undefined).map(([k, v]) => `${k}="${escapeHtml(String(v))}"`).join(" ");
3952
+ const parts = [];
3953
+ for (const [k, v] of Object.entries(obj)) {
3954
+ if (v !== undefined) {
3955
+ parts.push(`${k}="${escapeHtml(String(v))}"`);
3956
+ }
3957
+ }
3958
+ return parts.join(" ");
2166
3959
  }
2167
3960
  function buildMetaParts(meta) {
2168
3961
  const parts = [];
@@ -2240,6 +4033,34 @@ var init_shell = __esm(() => {
2240
4033
  });
2241
4034
 
2242
4035
  // src/render/assemble.ts
4036
+ function buildDeferredScript(deferredKeys) {
4037
+ const keysJson = safeJson(deferredKeys);
4038
+ return `<script id="${FURIN_DEFERRED_GLOBAL}">
4039
+ window.${FURIN_DEFERRED_GLOBAL} = {
4040
+ _deferredKeys: ${keysJson},
4041
+ _chunks: {},
4042
+ _resolvers: {},
4043
+ resolve(key, chunk) {
4044
+ this._chunks[key] = { a: 0, v: chunk };
4045
+ },
4046
+ reject(key, chunk) {
4047
+ this._chunks[key] = { a: 1, v: chunk };
4048
+ },
4049
+ getPromise(key) {
4050
+ if (!this._resolvers[key]) {
4051
+ var res, rej;
4052
+ var p = new Promise(function(resolve, reject) { res = resolve; rej = reject; });
4053
+ this._resolvers[key] = { resolve: res, reject: rej, promise: p };
4054
+ }
4055
+ return this._resolvers[key].promise;
4056
+ }
4057
+ };
4058
+ </script>`;
4059
+ }
4060
+ function buildDeferredResolution(key, chunk, action) {
4061
+ const chunkJson = safeJson(chunk);
4062
+ return `<script>window.${FURIN_DEFERRED_GLOBAL}.${action}(${safeJson(key)},${chunkJson})</script>`;
4063
+ }
2243
4064
  function resolvePath(pattern, params) {
2244
4065
  let path = pattern;
2245
4066
  for (const [key, val] of Object.entries(params ?? {})) {
@@ -2275,6 +4096,7 @@ function assembleHTML(template, headData, reactHtml, data) {
2275
4096
  }
2276
4097
  return headPre + headData + bodyPre + reactHtml + injectedBodyPost;
2277
4098
  }
4099
+ var FURIN_DEFERRED_GLOBAL = "__FURIN_DEFERRED__";
2278
4100
  var init_assemble = __esm(() => {
2279
4101
  init_shell();
2280
4102
  });
@@ -2345,11 +4167,16 @@ function errorMessageOf(err) {
2345
4167
  }
2346
4168
  return "";
2347
4169
  }
2348
- function buildErrorElement(component, error, digest) {
4170
+ function buildErrorElement(component, error, digest, messageOverride, status) {
2349
4171
  const ErrorView = component ?? DefaultErrorComponent;
2350
- const message = component ? errorMessageOf(error) : "An unexpected error occurred.";
4172
+ let message;
4173
+ if (component) {
4174
+ message = messageOverride ?? errorMessageOf(error);
4175
+ } else {
4176
+ message = "An unexpected error occurred.";
4177
+ }
2351
4178
  return /* @__PURE__ */ jsxDEV4(ErrorView, {
2352
- error: { message, digest },
4179
+ error: { message, digest, status },
2353
4180
  reset: SERVER_RESET_NOOP2
2354
4181
  }, undefined, false, undefined, this);
2355
4182
  }
@@ -2365,7 +4192,85 @@ var init_element = __esm(() => {
2365
4192
  init_default_screens();
2366
4193
  });
2367
4194
 
4195
+ // src/await.tsx
4196
+ import { Component as Component2, createContext as createContext2, createElement as createElement3, use } from "react";
4197
+ function useAsyncError() {
4198
+ return use(AsyncErrorContext);
4199
+ }
4200
+ function useAsyncValue() {
4201
+ const ctx = use(AwaitValueContext);
4202
+ if (!ctx) {
4203
+ throw new Error("useAsyncValue must be used inside <Await> children");
4204
+ }
4205
+ return use(ctx.promise);
4206
+ }
4207
+ function Await({ resolve, errorElement, children }) {
4208
+ return createElement3(AsyncErrorBoundary, { errorElement, resolve }, createElement3(AwaitInner, { resolve, children }));
4209
+ }
4210
+ function AwaitInner({ resolve, children }) {
4211
+ const value = use(resolve);
4212
+ return createElement3(AwaitValueContext.Provider, { value: { promise: resolve } }, children ? children(value) : null);
4213
+ }
4214
+ var AsyncErrorContext, AwaitValueContext, AsyncErrorBoundary;
4215
+ var init_await = __esm(() => {
4216
+ AsyncErrorContext = createContext2(undefined);
4217
+ AwaitValueContext = createContext2(undefined);
4218
+ AsyncErrorBoundary = class AsyncErrorBoundary extends Component2 {
4219
+ constructor(props) {
4220
+ super(props);
4221
+ this.state = { hasError: false, error: undefined, resolve: props.resolve };
4222
+ }
4223
+ static getDerivedStateFromProps(props, state) {
4224
+ if (props.resolve !== state.resolve) {
4225
+ return { hasError: false, error: undefined, resolve: props.resolve };
4226
+ }
4227
+ return null;
4228
+ }
4229
+ static getDerivedStateFromError(error) {
4230
+ return { hasError: true, error };
4231
+ }
4232
+ render() {
4233
+ const { hasError, error } = this.state;
4234
+ const { children, errorElement } = this.props;
4235
+ if (hasError) {
4236
+ if (errorElement === undefined) {
4237
+ throw error;
4238
+ }
4239
+ return createElement3(AsyncErrorContext.Provider, { value: error }, errorElement);
4240
+ }
4241
+ return children;
4242
+ }
4243
+ };
4244
+ });
4245
+
4246
+ // src/client.ts
4247
+ function defer(data) {
4248
+ if (Object.hasOwn(data, DEFERRED_BRAND)) {
4249
+ throw new Error(`[furin] defer() received an object with a reserved key "${DEFERRED_BRAND}". Rename this field to avoid conflicts with the deferred-data runtime.`);
4250
+ }
4251
+ return { ...data, [DEFERRED_BRAND]: true };
4252
+ }
4253
+ function isDeferred(v) {
4254
+ return typeof v === "object" && v !== null && Object.hasOwn(v, DEFERRED_BRAND) && v[DEFERRED_BRAND] === true;
4255
+ }
4256
+ var DEFERRED_BRAND = "__isDeferred";
4257
+ var init_client = () => {};
4258
+
2368
4259
  // src/render/loaders.ts
4260
+ function isHttpRedirect(res) {
4261
+ return REDIRECT_STATUSES.has(res.status) && res.headers.has("location");
4262
+ }
4263
+ async function readResponseMessage(res) {
4264
+ if (res.body === null) {
4265
+ return res.statusText;
4266
+ }
4267
+ try {
4268
+ const body = await res.text();
4269
+ return body || res.statusText;
4270
+ } catch {
4271
+ return res.statusText;
4272
+ }
4273
+ }
2369
4274
  function createLoaderCtx(ctx, accumulatedParentPromise) {
2370
4275
  const cache = new Map;
2371
4276
  return new Proxy(ctx, {
@@ -2388,9 +4293,57 @@ function createLoaderCtx(ctx, accumulatedParentPromise) {
2388
4293
  }
2389
4294
  });
2390
4295
  }
2391
- async function runLoaders(route, ctx, _rootLayout) {
4296
+ function splitDeferredResult(pageResult, routeChainData) {
4297
+ const syncData = {};
4298
+ const deferredPromises = {};
4299
+ for (const [key, value] of Object.entries(routeChainData)) {
4300
+ syncData[key] = value;
4301
+ }
4302
+ for (const [key, value] of Object.entries(pageResult)) {
4303
+ if (key === "__isDeferred") {
4304
+ continue;
4305
+ }
4306
+ if (isPromiseLike(value)) {
4307
+ deferredPromises[key] = Promise.resolve(value);
4308
+ } else {
4309
+ syncData[key] = value;
4310
+ }
4311
+ }
4312
+ return {
4313
+ syncData,
4314
+ deferredPromises: Object.keys(deferredPromises).length > 0 ? deferredPromises : undefined
4315
+ };
4316
+ }
4317
+ function isPromiseLike(value) {
4318
+ return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
4319
+ }
4320
+ async function serializeDeferredRejection(err) {
4321
+ if (isNotFoundError(err)) {
4322
+ const wrapped = new Error(err.message);
4323
+ Object.assign(wrapped, { __furinBrand: "FURIN_NOT_FOUND", data: err.data });
4324
+ return wrapped;
4325
+ }
4326
+ if (err instanceof Response) {
4327
+ const body = await readResponseMessage(err);
4328
+ const wrapped = new Error(body || err.statusText || "Something went wrong");
4329
+ Object.assign(wrapped, { __furinStatus: err.status });
4330
+ return wrapped;
4331
+ }
4332
+ if (err instanceof Error) {
4333
+ return err;
4334
+ }
4335
+ return new Error(String(err));
4336
+ }
4337
+ function assertNoDeferredInRouteLoaders(routeResults) {
4338
+ for (const result of routeResults) {
4339
+ if (isDeferred(result)) {
4340
+ 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.");
4341
+ }
4342
+ }
4343
+ }
4344
+ async function runLoaders(route, ctx) {
2392
4345
  try {
2393
- const ctxRecord = { ...ctx, log: useLogger3() };
4346
+ const ctxRecord = { ...ctx, log: useLogger2() };
2394
4347
  const loaderMap = new Map;
2395
4348
  let accumulatedParentPromise = Promise.resolve({});
2396
4349
  for (const r of route.routeChain) {
@@ -2409,27 +4362,55 @@ async function runLoaders(route, ctx, _rootLayout) {
2409
4362
  const pageCtx = createLoaderCtx(ctxRecord, accumulatedParentPromise);
2410
4363
  const pagePromise = route.page?.loader ? Promise.resolve(route.page.loader(pageCtx)).then((r) => r ?? {}) : Promise.resolve({});
2411
4364
  const results = await Promise.all([...loaderMap.values(), pagePromise]);
2412
- const data = Object.assign({}, ...results);
4365
+ const merged = Object.assign({}, ...results);
2413
4366
  const headers = {};
2414
4367
  Object.assign(headers, ctx.set.headers);
2415
- return { type: "data", data, headers };
4368
+ const routeOnlyResults = results.slice(0, loaderMap.size);
4369
+ const pageResult = results[loaderMap.size];
4370
+ assertNoDeferredInRouteLoaders(routeOnlyResults);
4371
+ const routeCtx = { params: ctx.params, query: ctx.query, path: ctx.path };
4372
+ if (isDeferred(pageResult)) {
4373
+ const routeMerged = Object.assign({}, ...routeOnlyResults);
4374
+ const { syncData, deferredPromises } = splitDeferredResult(pageResult, routeMerged);
4375
+ return { type: "data", syncData: { ...syncData, ...routeCtx }, deferredPromises, headers };
4376
+ }
4377
+ return {
4378
+ type: "data",
4379
+ syncData: { ...merged, ...routeCtx },
4380
+ deferredPromises: undefined,
4381
+ headers
4382
+ };
2416
4383
  } catch (err) {
4384
+ const headers = {};
4385
+ Object.assign(headers, ctx.set.headers);
2417
4386
  if (isNotFoundError(err)) {
2418
- const headers2 = {};
2419
- Object.assign(headers2, ctx.set.headers);
2420
- return { type: "not-found", error: err, headers: headers2 };
4387
+ return { type: "not-found", error: err, headers };
2421
4388
  }
2422
4389
  if (err instanceof Response) {
2423
- return { type: "redirect", response: err };
4390
+ if (isHttpRedirect(err)) {
4391
+ return { type: "redirect", response: err };
4392
+ }
4393
+ const isMalformedRedirect = REDIRECT_STATUSES.has(err.status);
4394
+ const status = isMalformedRedirect ? 500 : err.status;
4395
+ const body = await readResponseMessage(err);
4396
+ const message = body || "Something went wrong";
4397
+ return { type: "error", error: err, status, message, headers };
2424
4398
  }
2425
- const headers = {};
2426
- Object.assign(headers, ctx.set.headers);
2427
- return { type: "error", error: err, headers };
4399
+ return {
4400
+ type: "error",
4401
+ error: err,
4402
+ status: 500,
4403
+ message: "Something went wrong",
4404
+ headers
4405
+ };
2428
4406
  }
2429
4407
  }
4408
+ var REDIRECT_STATUSES;
2430
4409
  var init_loaders = __esm(() => {
4410
+ init_client();
2431
4411
  init_context_logger();
2432
4412
  init_not_found();
4413
+ REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
2433
4414
  });
2434
4415
 
2435
4416
  // src/render/template.ts
@@ -2475,14 +4456,19 @@ var init_template = () => {};
2475
4456
  var IS_DEV = true;
2476
4457
 
2477
4458
  // src/render/index.ts
2478
- import { createElement as createElement3 } from "react";
4459
+ import { createElement as createElement4 } from "react";
2479
4460
  import { renderToReadableStream } from "react-dom/server";
2480
4461
  function withSSRRouterContext(element, contextValue) {
2481
- return createElement3(RouterContext.Provider, { value: contextValue }, element);
4462
+ return createElement4(RouterContext.Provider, { value: contextValue }, element);
4463
+ }
4464
+ function assertDeferredModeAllowed(route, deferredPromises) {
4465
+ if (deferredPromises !== undefined && route.mode !== "ssr") {
4466
+ 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.");
4467
+ }
2482
4468
  }
2483
4469
  async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomputedLoaderResult) {
2484
4470
  const loaderStart = Date.now();
2485
- const loaderResult = precomputedLoaderResult ?? await runLoaders(route, ctx, root.route);
4471
+ const loaderResult = precomputedLoaderResult ?? await runLoaders(route, ctx);
2486
4472
  const loader_ms = Date.now() - loaderStart;
2487
4473
  if (loaderResult.type === "redirect") {
2488
4474
  return loaderResult.response;
@@ -2493,10 +4479,13 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
2493
4479
  const isNotFound = loaderResult.type === "not-found";
2494
4480
  const isError = loaderResult.type === "error";
2495
4481
  const isFallback = isNotFound || isError;
2496
- const data = isFallback ? {} : loaderResult.data;
4482
+ const syncData = isFallback ? {} : loaderResult.syncData;
4483
+ const deferredPromises = !isFallback && loaderResult.type === "data" ? loaderResult.deferredPromises : undefined;
4484
+ assertDeferredModeAllowed(route, deferredPromises);
2497
4485
  const headers = loaderResult.headers;
2498
4486
  const componentProps = {
2499
- ...data,
4487
+ ...syncData,
4488
+ ...deferredPromises ?? {},
2500
4489
  params: ctx.params,
2501
4490
  query: ctx.query,
2502
4491
  path: ctx.path
@@ -2514,8 +4503,8 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
2514
4503
  notFoundError = { message: loaderResult.error.message, data: loaderResult.error.data };
2515
4504
  } else if (loaderResult.type === "error") {
2516
4505
  errorDigest = computeErrorDigest(loaderResult.error);
2517
- element = buildErrorElement(route.error ?? root.error, loaderResult.error, errorDigest);
2518
- status = 500;
4506
+ element = buildErrorElement(route.error ?? root.error, loaderResult.error, errorDigest, loaderResult.message, loaderResult.status);
4507
+ status = loaderResult.status;
2519
4508
  } else {
2520
4509
  element = buildElement(route, componentProps, root.route);
2521
4510
  }
@@ -2534,12 +4523,14 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
2534
4523
  element = withSSRRouterContext(element, ssrContext);
2535
4524
  return {
2536
4525
  componentProps,
4526
+ deferredPromises,
2537
4527
  element,
2538
4528
  errorDigest,
2539
4529
  headData,
2540
4530
  headers,
2541
4531
  loader_ms,
2542
4532
  notFoundError,
4533
+ syncData,
2543
4534
  ssrContext,
2544
4535
  status,
2545
4536
  template
@@ -2562,7 +4553,7 @@ function renderForPath(route, params, root, origin, mode, basePath) {
2562
4553
  if (prepared instanceof Response) {
2563
4554
  return prepared;
2564
4555
  }
2565
- useLogger3().set({
4556
+ useLogger2().set({
2566
4557
  furin: {
2567
4558
  render: mode,
2568
4559
  route: route.pattern,
@@ -2571,17 +4562,27 @@ function renderForPath(route, params, root, origin, mode, basePath) {
2571
4562
  ...prepared.errorDigest ? { digest: prepared.errorDigest } : {}
2572
4563
  }
2573
4564
  });
2574
- const { componentProps, element, headData, headers, status, template } = prepared;
4565
+ const { deferredPromises, element, headData, headers, status, syncData, template } = prepared;
2575
4566
  const stream = await renderToReadableStream(element);
2576
4567
  await stream.allReady;
2577
4568
  const reactHtml = await streamToString(stream);
2578
4569
  return {
2579
- html: assembleHTML(template, headData, reactHtml, componentProps),
4570
+ html: assembleHTML(template, headData, reactHtml, syncData),
2580
4571
  headers,
4572
+ ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
2581
4573
  status
2582
4574
  };
2583
4575
  }, { route: route.pattern, render: mode });
2584
4576
  }
4577
+ async function serializeLoaderDataNdjson(syncData, deferredPromises) {
4578
+ const payload = {
4579
+ ...syncData,
4580
+ ...deferredPromises ?? {}
4581
+ };
4582
+ const serialized = await toCrossJSONAsync(payload);
4583
+ return `${JSON.stringify(serialized)}
4584
+ `;
4585
+ }
2585
4586
  async function prerenderSSG(route, params, root, origin, basePath) {
2586
4587
  const resolvedPath = resolvePath(route.pattern, params);
2587
4588
  const cached = getSSGCache(resolvedPath);
@@ -2593,7 +4594,12 @@ async function prerenderSSG(route, params, root, origin, basePath) {
2593
4594
  return renderResult;
2594
4595
  }
2595
4596
  const result = renderResult;
2596
- const entry = { html: result.html, cachedAt: Date.now(), status: result.status };
4597
+ const entry = {
4598
+ cachedAt: Date.now(),
4599
+ html: result.html,
4600
+ ndjson: result.ndjson,
4601
+ status: result.status
4602
+ };
2597
4603
  setSSGCache(resolvedPath, entry);
2598
4604
  return entry;
2599
4605
  }
@@ -2602,7 +4608,7 @@ async function renderSSR(route, ctx, root, precomputedLoaderResult) {
2602
4608
  if (prepared instanceof Response) {
2603
4609
  return prepared;
2604
4610
  }
2605
- useLogger3().set({
4611
+ useLogger2().set({
2606
4612
  furin: {
2607
4613
  render: route.mode,
2608
4614
  route: route.pattern,
@@ -2610,7 +4616,7 @@ async function renderSSR(route, ctx, root, precomputedLoaderResult) {
2610
4616
  ...prepared.errorDigest ? { digest: prepared.errorDigest } : {}
2611
4617
  }
2612
4618
  });
2613
- const { componentProps, element, headData, headers, template } = prepared;
4619
+ const { deferredPromises, element, headData, headers, syncData, template } = prepared;
2614
4620
  const { headPre, bodyPre, bodyPost } = splitTemplate(template);
2615
4621
  let reactStream;
2616
4622
  let status = prepared.status;
@@ -2622,18 +4628,18 @@ async function renderSSR(route, ctx, root, precomputedLoaderResult) {
2622
4628
  shellErrored = true;
2623
4629
  status = 500;
2624
4630
  finalDigest = computeErrorDigest(shellError);
2625
- useLogger3().set({
4631
+ useLogger2().set({
2626
4632
  furin: { render: route.mode, route: route.pattern, digest: finalDigest, phase: "shell" }
2627
4633
  });
2628
4634
  try {
2629
- reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(route.error ?? root.error, shellError, finalDigest), prepared.ssrContext));
4635
+ reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(route.error ?? root.error, shellError, finalDigest, undefined, 500), prepared.ssrContext));
2630
4636
  } catch {
2631
- reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(undefined, shellError, finalDigest), prepared.ssrContext));
4637
+ reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(undefined, shellError, finalDigest, undefined, 500), prepared.ssrContext));
2632
4638
  }
2633
4639
  }
2634
- const dataPayload = shellErrored ? {} : { ...componentProps };
4640
+ const dataPayload = shellErrored ? {} : { ...syncData };
2635
4641
  if (finalDigest) {
2636
- dataPayload.__furinError = { digest: finalDigest };
4642
+ dataPayload.__furinError = { digest: finalDigest, status };
2637
4643
  }
2638
4644
  if (status === 404 && !shellErrored) {
2639
4645
  dataPayload.__furinStatus = 404;
@@ -2641,12 +4647,18 @@ async function renderSSR(route, ctx, root, precomputedLoaderResult) {
2641
4647
  dataPayload.__furinNotFound = prepared.notFoundError;
2642
4648
  }
2643
4649
  }
4650
+ if (dataPayload.__furinError !== undefined && dataPayload.__furinNotFound !== undefined) {
4651
+ throw new Error("[furin] internal invariant violated: __furinError and __furinNotFound were both set on the same SSR payload. Open a bug \u2014 these signals are mutually exclusive.");
4652
+ }
4653
+ const hasDeferred = !shellErrored && deferredPromises !== undefined;
4654
+ const deferredKeys = hasDeferred ? Object.keys(deferredPromises) : [];
4655
+ const deferredSetupScript = hasDeferred ? buildDeferredScript(deferredKeys) : "";
2644
4656
  const dataScript = `<script id="__FURIN_DATA__" type="application/json">${safeJson(dataPayload)}</script>`;
2645
4657
  const { readable, writable } = new TransformStream;
2646
4658
  const writer = writable.getWriter();
2647
4659
  const enc = new TextEncoder;
2648
4660
  (async () => {
2649
- await writer.write(enc.encode(headPre + headData + bodyPre));
4661
+ await writer.write(enc.encode(headPre + headData + deferredSetupScript + bodyPre));
2650
4662
  const reader = reactStream.getReader();
2651
4663
  for (;; ) {
2652
4664
  const { done, value } = await reader.read();
@@ -2655,7 +4667,22 @@ async function renderSSR(route, ctx, root, precomputedLoaderResult) {
2655
4667
  }
2656
4668
  await writer.write(value);
2657
4669
  }
2658
- await writer.write(enc.encode(dataScript + bodyPost));
4670
+ const [earlyBodyPost, finalBodyPost] = hasDeferred ? splitBeforeBodyClose(bodyPost) : ["", bodyPost];
4671
+ await writer.write(enc.encode(dataScript + earlyBodyPost));
4672
+ if (hasDeferred) {
4673
+ await Promise.all(Object.entries(deferredPromises).map(async ([key, promise]) => {
4674
+ try {
4675
+ const resolvedValue = await promise;
4676
+ const chunk = toCrossJSON(resolvedValue);
4677
+ await writer.write(enc.encode(buildDeferredResolution(key, chunk, "resolve")));
4678
+ } catch (err) {
4679
+ const normalized = await serializeDeferredRejection(err);
4680
+ const chunk = toCrossJSON(normalized);
4681
+ await writer.write(enc.encode(buildDeferredResolution(key, chunk, "reject")));
4682
+ }
4683
+ }));
4684
+ }
4685
+ await writer.write(enc.encode(finalBodyPost));
2659
4686
  await writer.close();
2660
4687
  })().catch((err) => writer.abort(err));
2661
4688
  return new Response(readable, {
@@ -2667,6 +4694,13 @@ async function renderSSR(route, ctx, root, precomputedLoaderResult) {
2667
4694
  }
2668
4695
  });
2669
4696
  }
4697
+ function splitBeforeBodyClose(bodyPost) {
4698
+ const index = bodyPost.toLowerCase().lastIndexOf("</body>");
4699
+ if (index === -1) {
4700
+ return [bodyPost, ""];
4701
+ }
4702
+ return [bodyPost.slice(0, index), bodyPost.slice(index)];
4703
+ }
2670
4704
  async function renderRootNotFound(root, request) {
2671
4705
  const prodTemplate = getProductionTemplate();
2672
4706
  let template;
@@ -2676,7 +4710,7 @@ async function renderRootNotFound(root, request) {
2676
4710
  try {
2677
4711
  template = await getDevTemplate(new URL(request.url).origin);
2678
4712
  } catch (devTemplateErr) {
2679
- useLogger3().set({
4713
+ useLogger2().set({
2680
4714
  furin: {
2681
4715
  render: "not-found",
2682
4716
  action: "dev_template_fallback",
@@ -2701,7 +4735,7 @@ async function renderRootNotFound(root, request) {
2701
4735
  defaultPreloadDelay: 50,
2702
4736
  defaultPreloadStaleTime: 30000
2703
4737
  };
2704
- useLogger3().set({
4738
+ useLogger2().set({
2705
4739
  furin: {
2706
4740
  render: "not-found",
2707
4741
  action: "catch_all",
@@ -2743,7 +4777,7 @@ function serveISRCacheHit(cached, ctx, route, params, cacheKey, revalidate, root
2743
4777
  if (etag) {
2744
4778
  ctx.set.headers.etag = etag;
2745
4779
  }
2746
- useLogger3().set({
4780
+ useLogger2().set({
2747
4781
  furin: { render: "isr", route: route.pattern, cache: isFresh ? "hit" : "stale" }
2748
4782
  });
2749
4783
  return cached.html;
@@ -2765,7 +4799,7 @@ async function renderISRNon200(prepared, route, ctx, root, errorDigest, renderSt
2765
4799
  } catch (shellError) {
2766
4800
  finalStatus = 500;
2767
4801
  finalDigest = computeErrorDigest(shellError);
2768
- useLogger3().set({
4802
+ useLogger2().set({
2769
4803
  furin: {
2770
4804
  render: "isr",
2771
4805
  route: route.pattern,
@@ -2774,23 +4808,23 @@ async function renderISRNon200(prepared, route, ctx, root, errorDigest, renderSt
2774
4808
  phase: "shell"
2775
4809
  }
2776
4810
  });
2777
- fallbackProps.__furinError = { digest: finalDigest };
4811
+ fallbackProps.__furinError = { digest: finalDigest, status: finalStatus };
2778
4812
  fallbackProps.__furinStatus = 500;
2779
4813
  try {
2780
- reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(route.error ?? root.error, shellError, finalDigest), prepared.ssrContext));
4814
+ reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(route.error ?? root.error, shellError, finalDigest, undefined, 500), prepared.ssrContext));
2781
4815
  } catch {
2782
- reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(undefined, shellError, finalDigest), prepared.ssrContext));
4816
+ reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(undefined, shellError, finalDigest, undefined, 500), prepared.ssrContext));
2783
4817
  }
2784
4818
  }
2785
4819
  if (!fallbackProps.__furinError && errorDigest) {
2786
- fallbackProps.__furinError = { digest: errorDigest };
4820
+ fallbackProps.__furinError = { digest: errorDigest, status };
2787
4821
  }
2788
4822
  await reactStream.allReady;
2789
4823
  const reactHtml = await streamToString(reactStream);
2790
4824
  const html = assembleHTML(template, headData, reactHtml, fallbackProps);
2791
4825
  const generatedAt = Date.now();
2792
4826
  const renderMs = generatedAt - renderStart;
2793
- useLogger3().set({
4827
+ useLogger2().set({
2794
4828
  furin: {
2795
4829
  render: "isr",
2796
4830
  route: route.pattern,
@@ -2822,16 +4856,16 @@ async function handleISR(route, ctx, root, buildId = "") {
2822
4856
  if (prepared instanceof Response) {
2823
4857
  return prepared;
2824
4858
  }
2825
- const { componentProps, element, headData, template, status, errorDigest } = prepared;
4859
+ const { element, headData, syncData, template, status, errorDigest } = prepared;
2826
4860
  if (status !== 200) {
2827
4861
  return renderISRNon200(prepared, route, ctx, root, errorDigest, renderStart, buildId);
2828
4862
  }
2829
4863
  const stream = await renderToReadableStream(element);
2830
4864
  await stream.allReady;
2831
4865
  const reactHtml = await streamToString(stream);
2832
- const html = assembleHTML(template, headData, reactHtml, componentProps);
4866
+ const html = assembleHTML(template, headData, reactHtml, syncData);
2833
4867
  const generatedAt = Date.now();
2834
- useLogger3().set({
4868
+ useLogger2().set({
2835
4869
  furin: {
2836
4870
  render: "isr",
2837
4871
  route: route.pattern,
@@ -2859,12 +4893,31 @@ async function warmSSGCache(routes, root, origin) {
2859
4893
  }
2860
4894
  });
2861
4895
  warmupLogger.emit();
2862
- const tasks = [];
2863
- for (const route of targets) {
2864
- let paramSets;
4896
+ const staticParamsResults = await mapWithConcurrency(targets, SSG_WARM_CONCURRENCY, async (route) => {
2865
4897
  try {
2866
- paramSets = await route.page.staticParams?.() ?? [];
4898
+ const paramSets = await route.page.staticParams?.() ?? [];
4899
+ return { route, paramSets };
2867
4900
  } catch (err) {
4901
+ return { error: err, route };
4902
+ }
4903
+ });
4904
+ const tasks = [];
4905
+ for (const result of staticParamsResults) {
4906
+ if ("error" in result) {
4907
+ const errorLogger = createLogger({});
4908
+ errorLogger.set({
4909
+ furin: {
4910
+ render: "ssg",
4911
+ action: "warmup_failed",
4912
+ route: result.route.pattern
4913
+ }
4914
+ });
4915
+ errorLogger.error(result.error instanceof Error ? result.error : new Error(String(result.error)));
4916
+ errorLogger.emit();
4917
+ continue;
4918
+ }
4919
+ const { route, paramSets } = result;
4920
+ if (!Array.isArray(paramSets)) {
2868
4921
  const errorLogger = createLogger({});
2869
4922
  errorLogger.set({
2870
4923
  furin: {
@@ -2873,7 +4926,7 @@ async function warmSSGCache(routes, root, origin) {
2873
4926
  route: route.pattern
2874
4927
  }
2875
4928
  });
2876
- errorLogger.error(err instanceof Error ? err : new Error(String(err)));
4929
+ errorLogger.error(new Error(`staticParams() for "${route.pattern}" returned a non-array value`));
2877
4930
  errorLogger.emit();
2878
4931
  continue;
2879
4932
  }
@@ -2948,6 +5001,7 @@ function revalidateInBackground(route, params, cacheKey, revalidate, root, origi
2948
5001
  }
2949
5002
  var SSG_WARM_CONCURRENCY = 4, pendingRevalidations;
2950
5003
  var init_render = __esm(() => {
5004
+ init_development();
2951
5005
  init_not_found();
2952
5006
  init_router_provider();
2953
5007
  init_assemble();
@@ -3087,47 +5141,6 @@ var init_dev_cache = __esm(() => {
3087
5141
  registerCacheInvalidator(devSSGLoaderCache);
3088
5142
  });
3089
5143
 
3090
- // src/utils.ts
3091
- function isFurinPage(value) {
3092
- return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
3093
- }
3094
- function isFurinRoute(value) {
3095
- return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_ROUTE";
3096
- }
3097
- function collectRouteChainFromRoute(route) {
3098
- const chain = [];
3099
- let current = route;
3100
- while (current) {
3101
- chain.unshift(current);
3102
- current = current.parent;
3103
- }
3104
- return chain;
3105
- }
3106
- function hasCycle(route) {
3107
- const visited = new Set;
3108
- let current = route;
3109
- while (current) {
3110
- if (visited.has(current)) {
3111
- return true;
3112
- }
3113
- visited.add(current);
3114
- current = current.parent;
3115
- }
3116
- return false;
3117
- }
3118
- function validateRouteChain(chain, root, pagePath) {
3119
- const hasRoot = chain.some((r) => r === root);
3120
- if (!hasRoot) {
3121
- const location = pagePath ? `in ${pagePath}` : "";
3122
- throw new Error(`[furin] Page ${location} must inherit from root route. ` + 'Add: import { route } from "./root"; and use route.page() or set parent: route');
3123
- }
3124
- for (const route of chain) {
3125
- if (hasCycle(route)) {
3126
- throw new Error("[furin] Cycle detected in route chain. A route cannot be its own ancestor.");
3127
- }
3128
- }
3129
- }
3130
-
3131
5144
  // src/router.ts
3132
5145
  var exports_router = {};
3133
5146
  __export(exports_router, {
@@ -3135,11 +5148,15 @@ __export(exports_router, {
3135
5148
  scanPages: () => scanPages,
3136
5149
  resolveMode: () => resolveMode,
3137
5150
  refreshLayoutChain: () => refreshLayoutChain,
5151
+ rebuildDevRoute: () => rebuildDevRoute,
3138
5152
  queryDefaultRedirectHook: () => queryDefaultRedirectHook,
5153
+ parseDataEndpointPath: () => parseDataEndpointPath,
3139
5154
  mergeRouteSchemas: () => mergeRouteSchemas,
3140
5155
  loadProdRoutes: () => loadProdRoutes,
3141
5156
  filePathToPattern: () => filePathToPattern,
5157
+ detectQueryDefaultRedirect: () => detectQueryDefaultRedirect,
3142
5158
  createRoutePlugin: () => createRoutePlugin,
5159
+ createDataEndpoint: () => createDataEndpoint,
3143
5160
  computeRouteDependencies: () => computeRouteDependencies
3144
5161
  });
3145
5162
  import { existsSync } from "fs";
@@ -3222,8 +5239,10 @@ async function scanRootLayout(pagesDir) {
3222
5239
  if (!rootExport.layout) {
3223
5240
  throw new Error("[furin] root.tsx: createRoute() has no layout.");
3224
5241
  }
3225
- const notFoundEntry = await loadConventionComponent(pagesDir, "not-found");
3226
- const errorEntry = await loadConventionComponent(pagesDir, "error");
5242
+ const [notFoundEntry, errorEntry] = await Promise.all([
5243
+ loadConventionComponent(pagesDir, "not-found"),
5244
+ loadConventionComponent(pagesDir, "error")
5245
+ ]);
3227
5246
  return {
3228
5247
  path: rootPath,
3229
5248
  route: rootExport,
@@ -3264,9 +5283,11 @@ async function scanPageFiles(pagesDir, root) {
3264
5283
  if (fileName.startsWith("_") || fileName === "root" || isConventionFileName(fileName)) {
3265
5284
  continue;
3266
5285
  }
3267
- const notFound2 = await resolveNearestConvention(absolutePath, pagesDir, "not-found", notFoundCache, root.notFound);
3268
- const errorComponent = await resolveNearestConvention(absolutePath, pagesDir, "error", errorCache, root.error);
3269
- const segmentBoundaries = await collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache);
5286
+ const [notFound2, errorComponent, segmentBoundaries] = await Promise.all([
5287
+ resolveNearestConvention(absolutePath, pagesDir, "not-found", notFoundCache, root.notFound),
5288
+ resolveNearestConvention(absolutePath, pagesDir, "error", errorCache, root.error),
5289
+ collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache)
5290
+ ]);
3270
5291
  if (IS_DEV) {
3271
5292
  const devRoute = await buildDevRoute(absolutePath, relativePath, root);
3272
5293
  devRoute.notFound = notFound2;
@@ -3311,14 +5332,16 @@ async function collectSegmentBoundaries(pageAbsolutePath, pagesDir, notFoundCach
3311
5332
  const boundaries = [];
3312
5333
  for (let depth = 0;depth < dirs.length; depth++) {
3313
5334
  const dir = dirs[depth];
3314
- if (!errorCache.has(dir)) {
3315
- errorCache.set(dir, await loadConventionComponent(dir, "error"));
3316
- }
3317
- if (!notFoundCache.has(dir)) {
3318
- notFoundCache.set(dir, await loadConventionComponent(dir, "not-found"));
3319
- }
3320
- const errorEntry = errorCache.get(dir);
3321
- const notFoundEntry = notFoundCache.get(dir);
5335
+ const [errorEntry, notFoundEntry] = await Promise.all([
5336
+ errorCache.has(dir) ? Promise.resolve(errorCache.get(dir)) : loadConventionComponent(dir, "error").then((r) => {
5337
+ errorCache.set(dir, r);
5338
+ return r;
5339
+ }),
5340
+ notFoundCache.has(dir) ? Promise.resolve(notFoundCache.get(dir)) : loadConventionComponent(dir, "not-found").then((r) => {
5341
+ notFoundCache.set(dir, r);
5342
+ return r;
5343
+ })
5344
+ ]);
3322
5345
  if (errorEntry || notFoundEntry) {
3323
5346
  boundaries.push({
3324
5347
  path: dir,
@@ -3374,8 +5397,7 @@ async function buildDevRoute(absolutePath, relativePath, root) {
3374
5397
  segmentBoundaries: []
3375
5398
  };
3376
5399
  }
3377
- function queryDefaultRedirectHook({ request, query, status, set }) {
3378
- const resolvedQuery = query;
5400
+ function detectQueryDefaultRedirect(request, resolvedQuery) {
3379
5401
  const queryKeys = Object.keys(resolvedQuery);
3380
5402
  if (queryKeys.length === 0) {
3381
5403
  return;
@@ -3397,7 +5419,29 @@ function queryDefaultRedirectHook({ request, query, status, set }) {
3397
5419
  url.searchParams.set(k, String(v));
3398
5420
  }
3399
5421
  }
3400
- set.headers.location = url.pathname + url.search;
5422
+ return url.pathname + url.search;
5423
+ }
5424
+ function parseDataEndpointPath(rawPath) {
5425
+ if (rawPath.includes("://") || rawPath.startsWith("//")) {
5426
+ return;
5427
+ }
5428
+ let url;
5429
+ try {
5430
+ url = new URL(rawPath, "http://localhost");
5431
+ } catch {
5432
+ return;
5433
+ }
5434
+ if (url.origin !== "http://localhost") {
5435
+ return;
5436
+ }
5437
+ return { url, pathname: url.pathname };
5438
+ }
5439
+ function queryDefaultRedirectHook({ request, query, status, set }) {
5440
+ const location = detectQueryDefaultRedirect(request, query);
5441
+ if (!location) {
5442
+ return;
5443
+ }
5444
+ set.headers.location = location;
3401
5445
  return status("Found");
3402
5446
  }
3403
5447
  function collectIntermediateLayoutDirs(pagePath, rootPath) {
@@ -3454,12 +5498,12 @@ async function refreshLayoutChain(chain, pagePath, rootPath, importFn) {
3454
5498
  const ctx = getCompileContext();
3455
5499
  const timestamp = Date.now();
3456
5500
  const layoutDirs = collectIntermediateLayoutDirs(pagePath, rootPath);
5501
+ const freshMods = await Promise.all(layoutDirs.map((layoutDir) => importFreshLayoutRouteModule(layoutDir, timestamp, resolveImport, ctx)));
3457
5502
  let chainIdx = 1;
3458
- for (const layoutDir of layoutDirs) {
5503
+ for (const freshMod of freshMods) {
3459
5504
  if (chainIdx >= chain.length) {
3460
5505
  break;
3461
5506
  }
3462
- const freshMod = await importFreshLayoutRouteModule(layoutDir, timestamp, resolveImport, ctx);
3463
5507
  if (!freshMod) {
3464
5508
  continue;
3465
5509
  }
@@ -3467,6 +5511,14 @@ async function refreshLayoutChain(chain, pagePath, rootPath, importFn) {
3467
5511
  chainIdx++;
3468
5512
  }
3469
5513
  }
5514
+ function rebuildDevRoute(base, page, chain) {
5515
+ return {
5516
+ ...base,
5517
+ page,
5518
+ routeChain: chain,
5519
+ mode: resolveMode(page, chain)
5520
+ };
5521
+ }
3470
5522
  async function handleDevRequest(route, ctx, root) {
3471
5523
  try {
3472
5524
  let currentRoot = root;
@@ -3484,7 +5536,7 @@ async function handleDevRequest(route, ctx, root) {
3484
5536
  chain[0].layout = currentRoot.route.layout;
3485
5537
  chain[0].loader = currentRoot.route.loader;
3486
5538
  }
3487
- const refreshedRoute = { ...route, page, routeChain: chain };
5539
+ const refreshedRoute = rebuildDevRoute(route, page, chain);
3488
5540
  if (refreshedRoute.mode === "isr") {
3489
5541
  return renderDevISRWithLoaderCache(refreshedRoute, ctx, currentRoot);
3490
5542
  }
@@ -3504,19 +5556,20 @@ async function renderDevISRWithLoaderCache(route, ctx, root) {
3504
5556
  if (cached && isDevLoaderCacheValid(cached)) {
3505
5557
  const precomputed = {
3506
5558
  type: "data",
3507
- data: cached.loaderData,
5559
+ syncData: cached.loaderData,
5560
+ deferredPromises: undefined,
3508
5561
  headers: cached.headers
3509
5562
  };
3510
5563
  return renderSSR(route, ctx, root, precomputed);
3511
5564
  }
3512
- const result = await runLoaders(route, ctx, root.route);
5565
+ const result = await runLoaders(route, ctx);
3513
5566
  if (result.type === "data") {
3514
5567
  const revalidate = route.page._route.revalidate ?? 60;
3515
5568
  const entry = {
3516
5569
  dependencies: computeRouteDependencies(route.path, root.path),
3517
5570
  generatedAt: Date.now(),
3518
5571
  headers: result.headers,
3519
- loaderData: result.data,
5572
+ loaderData: result.syncData,
3520
5573
  mode: "isr",
3521
5574
  revalidate
3522
5575
  };
@@ -3530,18 +5583,19 @@ async function renderDevSSGWithLoaderCache(route, ctx, root) {
3530
5583
  if (cached && isDevLoaderCacheValid(cached)) {
3531
5584
  const precomputed = {
3532
5585
  type: "data",
3533
- data: cached.loaderData,
5586
+ syncData: cached.loaderData,
5587
+ deferredPromises: undefined,
3534
5588
  headers: cached.headers
3535
5589
  };
3536
5590
  return renderSSR(route, ctx, root, precomputed);
3537
5591
  }
3538
- const result = await runLoaders(route, ctx, root.route);
5592
+ const result = await runLoaders(route, ctx);
3539
5593
  if (result.type === "data") {
3540
5594
  const entry = {
3541
5595
  dependencies: computeRouteDependencies(route.path, root.path),
3542
5596
  generatedAt: Date.now(),
3543
5597
  headers: result.headers,
3544
- loaderData: result.data,
5598
+ loaderData: result.syncData,
3545
5599
  mode: "ssg",
3546
5600
  revalidate: Number.POSITIVE_INFINITY
3547
5601
  };
@@ -3581,7 +5635,7 @@ async function handleSSGRequest(route, ctx, root, buildId) {
3581
5635
  return entry.html;
3582
5636
  }
3583
5637
  function mergeRouteSchemas(routeChain, key) {
3584
- const schemas = routeChain.map((r) => r[key]).filter(Boolean);
5638
+ const schemas = routeChain.flatMap((r) => r[key] ? [r[key]] : []);
3585
5639
  if (schemas.length === 0) {
3586
5640
  return;
3587
5641
  }
@@ -3628,15 +5682,18 @@ function createRoutePlugin(route, root, buildId = "") {
3628
5682
  async function collectPageFilePaths(dir) {
3629
5683
  const files = [];
3630
5684
  const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
3631
- for (const entry of entries) {
5685
+ const resolved = await mapWithConcurrency(entries, DIR_SCAN_CONCURRENCY, async (entry) => {
3632
5686
  const absolutePath = join(dir, entry.name);
3633
5687
  if (entry.isDirectory()) {
3634
- files.push(...await collectPageFilePaths(absolutePath));
3635
- continue;
5688
+ return await collectPageFilePaths(absolutePath);
3636
5689
  }
3637
5690
  if (entry.isFile()) {
3638
- files.push(absolutePath);
5691
+ return [absolutePath];
3639
5692
  }
5693
+ return [];
5694
+ });
5695
+ for (const chunk of resolved) {
5696
+ files.push(...chunk);
3640
5697
  }
3641
5698
  return files;
3642
5699
  }
@@ -3677,14 +5734,246 @@ function filePathToPattern(path) {
3677
5734
  }
3678
5735
  return `/${segments.join("/")}`;
3679
5736
  }
3680
- var CONVENTION_FILE_NAMES, SOURCE_MODULE_EXTENSIONS, TOBJECT_STRUCTURAL_KEYS;
5737
+ function escapeRegExpChar(ch) {
5738
+ return REGEX_META_CHARS_RE.test(ch) ? `\\${ch}` : ch;
5739
+ }
5740
+ function routeSpecificity(pattern) {
5741
+ let score = 0;
5742
+ for (const segment of pattern.split("/")) {
5743
+ if (segment.length === 0) {
5744
+ continue;
5745
+ }
5746
+ if (segment === "*") {
5747
+ score += 1;
5748
+ } else if (segment.startsWith(":")) {
5749
+ score += 2;
5750
+ } else {
5751
+ score += 3;
5752
+ }
5753
+ }
5754
+ return score;
5755
+ }
5756
+ function buildRouteRegex(pattern) {
5757
+ const paramNames = [];
5758
+ let source = "";
5759
+ let i = 0;
5760
+ while (i < pattern.length) {
5761
+ if (pattern[i] === ":") {
5762
+ const start = ++i;
5763
+ while (i < pattern.length && pattern[i] !== "/") {
5764
+ i++;
5765
+ }
5766
+ paramNames.push(pattern.slice(start, i));
5767
+ source += "([^/]+)";
5768
+ } else if (pattern[i] === "*") {
5769
+ paramNames.push("*");
5770
+ source += "(.*)";
5771
+ i++;
5772
+ } else {
5773
+ const ch = pattern[i];
5774
+ if (ch !== undefined) {
5775
+ source += escapeRegExpChar(ch);
5776
+ }
5777
+ i++;
5778
+ }
5779
+ }
5780
+ return { regex: new RegExp(`^${source}$`), paramNames };
5781
+ }
5782
+ function applySchemaDefaults(schema, values) {
5783
+ if (!schema || typeof schema !== "object") {
5784
+ return values;
5785
+ }
5786
+ const s = schema;
5787
+ if (s.type !== "object" || !s.properties || typeof s.properties !== "object") {
5788
+ return values;
5789
+ }
5790
+ const result = { ...values };
5791
+ const properties = s.properties;
5792
+ for (const [key, propSchema] of Object.entries(properties)) {
5793
+ if (!(key in result) && propSchema && typeof propSchema === "object" && "default" in propSchema) {
5794
+ result[key] = propSchema.default;
5795
+ }
5796
+ }
5797
+ return result;
5798
+ }
5799
+ function createDataEndpoint(routes) {
5800
+ const plugin = new Elysia2;
5801
+ plugin.get("/_furin/data", async (ctx) => {
5802
+ const rawPath = ctx.query.path;
5803
+ if (!rawPath || typeof rawPath !== "string") {
5804
+ return new Response("Missing required query param: path", { status: 400 });
5805
+ }
5806
+ const parsed = parseDataEndpointPath(rawPath);
5807
+ if (!parsed) {
5808
+ return new Response("Invalid path", { status: 400 });
5809
+ }
5810
+ const { url, pathname } = parsed;
5811
+ const wideEventLog = useLogger2();
5812
+ wideEventLog.set({ path: rawPath });
5813
+ const matched = routes.reduce((acc, route) => {
5814
+ const { regex, paramNames } = buildRouteRegex(route.pattern);
5815
+ const m = regex.exec(pathname);
5816
+ if (!m) {
5817
+ return acc;
5818
+ }
5819
+ const score = routeSpecificity(route.pattern);
5820
+ if (acc && acc.score >= score) {
5821
+ return acc;
5822
+ }
5823
+ const params = {};
5824
+ for (let i = 0;i < paramNames.length; i++) {
5825
+ const name = paramNames[i];
5826
+ if (name !== undefined) {
5827
+ params[name] = m[i + 1] ?? "";
5828
+ }
5829
+ }
5830
+ return { route, params, score };
5831
+ }, null);
5832
+ if (!matched) {
5833
+ return new Response("Route not found", { status: 404 });
5834
+ }
5835
+ wideEventLog.set({ routePattern: matched.route.pattern });
5836
+ const syntheticRequest = new Request(new URL(pathname + url.search, ctx.request.url));
5837
+ const syntheticSet = { headers: {}, status: 200 };
5838
+ const syntheticCtx = {
5839
+ request: syntheticRequest,
5840
+ params: matched.params,
5841
+ query: Object.fromEntries(url.searchParams),
5842
+ set: syntheticSet,
5843
+ headers: ctx.headers,
5844
+ cookie: ctx.cookie,
5845
+ path: pathname,
5846
+ redirect: (location, status) => new Response(null, { status: status ?? 302, headers: { location } }),
5847
+ status: (code) => new Response(null, { status: code })
5848
+ };
5849
+ const mergedParams = mergeRouteSchemas(matched.route.routeChain, "params");
5850
+ const mergedQuery = mergeRouteSchemas(matched.route.routeChain, "query");
5851
+ syntheticCtx.params = applySchemaDefaults(mergedParams, syntheticCtx.params);
5852
+ syntheticCtx.query = applySchemaDefaults(mergedQuery, syntheticCtx.query);
5853
+ if (mergedQuery) {
5854
+ const redirectLocation = detectQueryDefaultRedirect(syntheticRequest, syntheticCtx.query);
5855
+ if (redirectLocation) {
5856
+ const serialized2 = await toCrossJSONAsync({ __furinRedirect: redirectLocation });
5857
+ return new Response(`${JSON.stringify(serialized2)}
5858
+ `, {
5859
+ headers: { "content-type": "application/x-ndjson" }
5860
+ });
5861
+ }
5862
+ }
5863
+ const result = await runLoaders(matched.route, syntheticCtx);
5864
+ if (result.type === "redirect") {
5865
+ const redirectUrl = new URL(result.response.headers.get("location") ?? "/", ctx.request.url);
5866
+ const serialized2 = await toCrossJSONAsync({
5867
+ __furinRedirect: redirectUrl.pathname + redirectUrl.search
5868
+ });
5869
+ return new Response(`${JSON.stringify(serialized2)}
5870
+ `, {
5871
+ headers: { "content-type": "application/x-ndjson" }
5872
+ });
5873
+ }
5874
+ if (result.type === "not-found") {
5875
+ const serialized2 = await toCrossJSONAsync({
5876
+ __furinStatus: 404,
5877
+ __furinNotFound: { message: result.error.message, data: result.error.data }
5878
+ });
5879
+ return new Response(`${JSON.stringify(serialized2)}
5880
+ `, {
5881
+ status: 200,
5882
+ headers: { "content-type": "application/x-ndjson" }
5883
+ });
5884
+ }
5885
+ if (result.type === "error") {
5886
+ const digest = computeErrorDigest(result.error);
5887
+ const serialized2 = await toCrossJSONAsync({
5888
+ __furinError: {
5889
+ digest,
5890
+ message: result.message,
5891
+ status: result.status
5892
+ }
5893
+ });
5894
+ return new Response(`${JSON.stringify(serialized2)}
5895
+ `, {
5896
+ status: result.status,
5897
+ headers: { "content-type": "application/x-ndjson" }
5898
+ });
5899
+ }
5900
+ const syncDataWithTitle = withResolvedTitle(matched.route, result.syncData);
5901
+ if (result.deferredPromises) {
5902
+ return new Response(createDeferredNdjsonStream(syncDataWithTitle, result.deferredPromises), {
5903
+ headers: {
5904
+ "content-type": "application/x-ndjson",
5905
+ ...result.headers
5906
+ }
5907
+ });
5908
+ }
5909
+ const serialized = await toCrossJSONAsync(syncDataWithTitle);
5910
+ return new Response(`${JSON.stringify(serialized)}
5911
+ `, {
5912
+ headers: {
5913
+ "content-type": "application/x-ndjson",
5914
+ ...result.headers
5915
+ }
5916
+ });
5917
+ }, {
5918
+ query: t.Object({ path: t.Optional(t.String()) })
5919
+ });
5920
+ return plugin;
5921
+ }
5922
+ function withResolvedTitle(route, syncData) {
5923
+ const head = route.page.head;
5924
+ if (!head) {
5925
+ return syncData;
5926
+ }
5927
+ let title;
5928
+ try {
5929
+ title = extractTitle(head(syncData).meta);
5930
+ } catch {
5931
+ return syncData;
5932
+ }
5933
+ if (title === undefined) {
5934
+ return syncData;
5935
+ }
5936
+ return { ...syncData, __furinTitle: title };
5937
+ }
5938
+ function createDeferredNdjsonStream(syncData, deferredPromises) {
5939
+ const enc = new TextEncoder;
5940
+ const entries = Object.entries(deferredPromises);
5941
+ return new ReadableStream({
5942
+ async start(controller) {
5943
+ const initial = toCrossJSON({
5944
+ ...syncData,
5945
+ __furinDeferredKeys: entries.map(([key]) => key)
5946
+ });
5947
+ controller.enqueue(enc.encode(`${JSON.stringify(initial)}
5948
+ `));
5949
+ await Promise.all(entries.map(async ([key, promise]) => {
5950
+ try {
5951
+ const value = await promise;
5952
+ controller.enqueue(enc.encode(`${JSON.stringify({ key, action: "resolve", value: toCrossJSON(value) })}
5953
+ `));
5954
+ } catch (err) {
5955
+ const normalized = await serializeDeferredRejection(err);
5956
+ const value = toCrossJSON(normalized);
5957
+ controller.enqueue(enc.encode(`${JSON.stringify({ key, action: "reject", value })}
5958
+ `));
5959
+ }
5960
+ }));
5961
+ controller.close();
5962
+ }
5963
+ });
5964
+ }
5965
+ var CONVENTION_FILE_NAMES, SOURCE_MODULE_EXTENSIONS, TOBJECT_STRUCTURAL_KEYS, DIR_SCAN_CONCURRENCY = 8, REGEX_META_CHARS_RE;
3681
5966
  var init_router = __esm(() => {
5967
+ init_development();
5968
+ init_context_logger();
3682
5969
  init_assemble();
3683
5970
  init_dev_cache();
3684
5971
  init_render();
5972
+ init_shell();
3685
5973
  CONVENTION_FILE_NAMES = ["not-found", "error"];
3686
5974
  SOURCE_MODULE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
3687
5975
  TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
5976
+ REGEX_META_CHARS_RE = /[.*+?^${}()|[\]\\]/;
3688
5977
  });
3689
5978
 
3690
5979
  // src/dev-page-plugin.ts
@@ -3940,7 +6229,12 @@ function schemaToTypeString(schema) {
3940
6229
  }
3941
6230
  const s = schema;
3942
6231
  if (s.anyOf && Array.isArray(s.anyOf)) {
3943
- const parts = s.anyOf.map(schemaToTypeString).filter((t2) => t2 !== "null");
6232
+ const parts = [];
6233
+ for (const item of s.anyOf) {
6234
+ const t2 = schemaToTypeString(item);
6235
+ if (t2 !== "null")
6236
+ parts.push(t2);
6237
+ }
3944
6238
  return parts.join(" | ") || "unknown";
3945
6239
  }
3946
6240
  switch (s.type) {
@@ -4056,6 +6350,8 @@ import { createElement } from "react";
4056
6350
  import { initLogger, log } from "evlog";
4057
6351
  import { createHttpLogDrain } from "evlog/http";
4058
6352
  import { RouterProvider } from "@teyik0/furin/link";
6353
+ import { fromCrossJSON } from "@teyik0/furin/link";
6354
+ import type { SerovalNode } from "seroval";
4059
6355
  import { route as root } from "${rootLayout.replace(/\\/g, "/")}";${conventionImportsBlock}
4060
6356
 
4061
6357
  initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });
@@ -4077,6 +6373,70 @@ const _match = routes.find((r) => r.regex.test(pathname));
4077
6373
  // former does not \u2014 so the two cases fork on _match below.
4078
6374
  const dataEl = document.getElementById("__FURIN_DATA__");
4079
6375
  const loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
6376
+
6377
+ // \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
6378
+ // window.__FURIN_DEFERRED__ is injected by the server when a loader returns
6379
+ // defer(). It carries:
6380
+ // - _chunks: raw CrossJSON chunks keyed by field name (from late <script> tags)
6381
+ // We deserialise each chunk with fromCrossJSON and create a Promise so <Await>
6382
+ // components receive a proper resolved Promise instead of the raw CrossJSON node.
6383
+ // Sync loader fields live exclusively in __FURIN_DATA__ (read above).
6384
+ interface FurinDeferredRegistry {
6385
+ _chunks: Record<string, { a: 0 | 1; v: SerovalNode }>;
6386
+ _deferredKeys: string[];
6387
+ _resolvers: Record<string, {
6388
+ promise: Promise<unknown>;
6389
+ reject: (reason: unknown) => void;
6390
+ resolve: (value: unknown) => void;
6391
+ }>;
6392
+ getPromise: (key: string) => Promise<unknown>;
6393
+ reject: (key: string, chunk: SerovalNode) => void;
6394
+ resolve: (key: string, chunk: SerovalNode) => void;
6395
+ }
6396
+ const __deferred = (window as unknown as { __FURIN_DEFERRED__?: FurinDeferredRegistry })
6397
+ .__FURIN_DEFERRED__;
6398
+ const deferredData: Record<string, Promise<unknown>> = {};
6399
+ if (__deferred && __deferred._chunks) {
6400
+ // Patch resolve/reject so any chunks that arrive AFTER this entry has run
6401
+ // settle immediately. The previous version stored late chunks in _chunks
6402
+ // when no resolver was registered yet, but the drain loop below only runs
6403
+ // ONCE at hydrate time \u2014 so any chunk landing after the drain would stay
6404
+ // orphaned and the corresponding Await would hang forever. Eagerly creating
6405
+ // the resolver via getPromise() fixes the race.
6406
+ __deferred.resolve = (key: string, chunk: SerovalNode) => {
6407
+ __deferred.getPromise(key);
6408
+ __deferred._resolvers[key].resolve(fromCrossJSON(chunk, {}));
6409
+ };
6410
+ __deferred.reject = (key: string, chunk: SerovalNode) => {
6411
+ __deferred.getPromise(key);
6412
+ __deferred._resolvers[key].reject(fromCrossJSON(chunk, {}));
6413
+ };
6414
+ for (const key of Object.keys(__deferred._chunks)) {
6415
+ const entry = __deferred._chunks[key] as { a: 0 | 1; v: SerovalNode };
6416
+ const p = __deferred.getPromise(key) as Promise<unknown>;
6417
+ const resolver = __deferred._resolvers[key];
6418
+ const value = fromCrossJSON(entry.v, {});
6419
+ if (entry.a === 0) {
6420
+ resolver.resolve(value);
6421
+ } else {
6422
+ resolver.reject(value);
6423
+ }
6424
+ deferredData[key] = p;
6425
+ }
6426
+ for (const key of __deferred._deferredKeys ?? []) {
6427
+ if (!(key in deferredData)) {
6428
+ deferredData[key] = __deferred.getPromise(key) as Promise<unknown>;
6429
+ }
6430
+ }
6431
+ // Keys that have a resolver (getPromise was called by <Await>) but no
6432
+ // chunk yet (the late <script> hasn't arrived) still need a Promise entry
6433
+ // so the hydration data record is complete.
6434
+ for (const key of Object.keys(__deferred._resolvers ?? {})) {
6435
+ if (!(key in deferredData)) {
6436
+ deferredData[key] = __deferred.getPromise(key) as Promise<unknown>;
6437
+ }
6438
+ }
6439
+ }
4080
6440
  const rootEl = document.getElementById("root") as HTMLElement;
4081
6441
 
4082
6442
  // Eagerly load only the current page module for initial hydration.
@@ -4095,7 +6455,7 @@ const rootEl = document.getElementById("root") as HTMLElement;
4095
6455
  routes,
4096
6456
  root,
4097
6457
  initialMatch: match,
4098
- initialData: loaderData,
6458
+ initialData: { ...loaderData, ...deferredData },
4099
6459
  initialDigest: loaderData.__furinError?.digest,
4100
6460
  initialNotFound: isNotFound ? (loaderData.__furinNotFound ?? loaderData) : undefined,${routerProviderDefaults}
4101
6461
  } as any);
@@ -4195,6 +6555,8 @@ init_cache();
4195
6555
  init_render();
4196
6556
  init_template();
4197
6557
  init_router();
6558
+ init_await();
6559
+ init_client();
4198
6560
  init_not_found();
4199
6561
  init_cache();
4200
6562
  init_render();
@@ -4309,7 +6671,6 @@ async function furin({
4309
6671
  "/_client/**",
4310
6672
  "/public/**",
4311
6673
  "/favicon.ico",
4312
- "/_furin/!(ingest)",
4313
6674
  "/_bun_hmr_entry/**",
4314
6675
  ...userExclude ?? []
4315
6676
  ]
@@ -4362,7 +6723,7 @@ async function furin({
4362
6723
  if (pending.length > 0) {
4363
6724
  set.headers["x-furin-revalidate"] = pending.join(",");
4364
6725
  }
4365
- }).use(await staticPlugin({ assets: furinDir, prefix: "/_bun_hmr_entry", bunFullstack: true })).use(publicExists ? await staticPlugin({ assets: publicDir, prefix: "/public" }) : new Elysia4).get("/favicon.ico", publicExists ? file(join4(publicDir, "favicon.ico")) : () => new Response(null, { status: 404 })).use(createDevInspectorPlugin2()).use((app) => {
6726
+ }).use(await staticPlugin({ assets: furinDir, prefix: "/_bun_hmr_entry", bunFullstack: true })).use(publicExists ? await staticPlugin({ assets: publicDir, prefix: "/public" }) : new Elysia4).get("/favicon.ico", publicExists ? file(join4(publicDir, "favicon.ico")) : () => new Response(null, { status: 404 })).use(createDevInspectorPlugin2()).use(createDataEndpoint(routes2)).use((app) => {
4366
6727
  for (const route of routes2) {
4367
6728
  app.use(createRoutePlugin(route, root2));
4368
6729
  }
@@ -4427,7 +6788,7 @@ async function furin({
4427
6788
  }
4428
6789
  app.use(await staticPlugin({ assets: clientDir, prefix: "/_client" }));
4429
6790
  return app;
4430
- })()).use((app) => {
6791
+ })()).use(createDataEndpoint(routes)).use((app) => {
4431
6792
  for (const route of routes) {
4432
6793
  app.use(createRoutePlugin(route, root, prodBuildId));
4433
6794
  }
@@ -4436,10 +6797,15 @@ async function furin({
4436
6797
  return wrapWithRequestScope(prodApp);
4437
6798
  }
4438
6799
  export {
6800
+ useAsyncValue,
6801
+ useAsyncError,
4439
6802
  setCachePurger,
4440
6803
  revalidatePath,
4441
6804
  renderRootNotFound,
4442
6805
  notFound,
4443
6806
  isNotFoundError,
4444
- furin
6807
+ isDeferred,
6808
+ furin,
6809
+ defer,
6810
+ Await
4445
6811
  };