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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/dist/build/compile-entry.d.ts +2 -1
  2. package/dist/build/compile-entry.ts +17 -13
  3. package/dist/build/elysia-aot.d.ts +9 -0
  4. package/dist/build/entry-template.d.ts +5 -1
  5. package/dist/build/entry-template.ts +24 -5
  6. package/dist/build/index.js +753 -453
  7. package/dist/build/server-app-entry.d.ts +12 -0
  8. package/dist/cache.d.ts +1 -0
  9. package/dist/cache.js +185 -0
  10. package/dist/cli/index.js +766 -466
  11. package/dist/client/internal/runtime-types.d.ts +8 -1
  12. package/dist/client/link.js +221 -11
  13. package/dist/client/sync.d.ts +1 -0
  14. package/dist/config.d.ts +22 -21
  15. package/dist/config.js +1 -1
  16. package/dist/define-route.d.ts +273 -1009
  17. package/dist/furin.d.ts +20 -5
  18. package/dist/furin.js +6222 -5383
  19. package/dist/plugin/routes.d.ts +6 -0
  20. package/dist/server/assets/production.d.ts +3 -0
  21. package/dist/server/auto-invalidate/plugin.d.ts +8 -24
  22. package/dist/server/auto-invalidate/runtime.d.ts +2 -2
  23. package/dist/server/cache/invalidation.d.ts +1 -1
  24. package/dist/server/cache/page-cache-state.d.ts +5 -0
  25. package/dist/server/cache/page-cache.d.ts +53 -0
  26. package/dist/server/cache/redis/index.d.ts +39 -0
  27. package/dist/server/cache/redis/index.js +396 -0
  28. package/dist/server/cache/redis/scripts.d.ts +6 -0
  29. package/dist/server/context-logger.d.ts +2 -2
  30. package/dist/server/dev/runtime.production.d.ts +1 -0
  31. package/dist/server/dev-page-plugin.d.ts +7 -0
  32. package/dist/server/evlog.d.ts +14 -0
  33. package/dist/server/internal.d.ts +6 -0
  34. package/dist/server/internal.js +2537 -0
  35. package/dist/server/render/not-found.d.ts +1 -1
  36. package/dist/server/render/ssg.d.ts +5 -0
  37. package/dist/server/render/static-params.d.ts +4 -0
  38. package/dist/server/router/defined-route.d.ts +1 -1
  39. package/dist/server/router/schemas.d.ts +1 -0
  40. package/dist/server/sync/index.js +794 -116
  41. package/dist/server/sync/plugin.d.ts +31 -158
  42. package/dist/server/sync/stream.d.ts +34 -49
  43. package/dist/shared/elysia-contract.d.ts +8 -14
  44. package/package.json +13 -7
  45. package/src/adapter/README.md +9 -2
  46. package/src/adapter/bun.ts +73 -27
  47. package/src/adapter/package.ts +6 -2
  48. package/src/adapter/runtime-build.ts +11 -4
  49. package/src/adapter/static.ts +8 -6
  50. package/src/adapter/vercel.ts +49 -30
  51. package/src/build/client.ts +18 -1
  52. package/src/build/compile-entry.ts +17 -13
  53. package/src/build/elysia-aot.ts +102 -0
  54. package/src/build/entry-template.ts +24 -5
  55. package/src/build/index.ts +0 -5
  56. package/src/build/production-instrumentation.ts +2 -2
  57. package/src/build/server-app-entry.ts +60 -0
  58. package/src/build/shared.ts +3 -1
  59. package/src/build/ssg-cache.ts +5 -10
  60. package/src/build/virtual-entry.ts +5 -4
  61. package/src/cache.ts +12 -0
  62. package/src/cli/config.ts +3 -3
  63. package/src/cli/index.ts +5 -2
  64. package/src/client/internal/runtime-types.ts +10 -1
  65. package/src/client/sync.ts +1 -0
  66. package/src/config.ts +3 -2
  67. package/src/define-route.ts +266 -128
  68. package/src/furin.ts +138 -149
  69. package/src/plugin/route-config-autofix.ts +11 -2
  70. package/src/plugin/routes.ts +85 -29
  71. package/src/server/assets/production.ts +99 -0
  72. package/src/server/auto-invalidate/plugin.ts +4 -4
  73. package/src/server/auto-invalidate/runtime.ts +74 -42
  74. package/src/server/browser-events/plugin.ts +6 -1
  75. package/src/server/cache/invalidation.ts +61 -20
  76. package/src/server/cache/page-cache-state.ts +22 -0
  77. package/src/server/cache/page-cache.ts +300 -0
  78. package/src/server/cache/redis/index.ts +350 -0
  79. package/src/server/cache/redis/scripts.ts +160 -0
  80. package/src/server/context-logger.ts +5 -5
  81. package/src/server/dev/runtime.production.ts +4 -0
  82. package/src/server/dev-page-plugin.ts +54 -10
  83. package/src/server/evlog.ts +99 -0
  84. package/src/server/internal.ts +7 -0
  85. package/src/server/render/isr.ts +480 -132
  86. package/src/server/render/loaders.ts +18 -12
  87. package/src/server/render/not-found.ts +4 -4
  88. package/src/server/render/ppr-document.ts +2 -2
  89. package/src/server/render/ppr-route.ts +193 -7
  90. package/src/server/render/ssg.ts +148 -4
  91. package/src/server/render/ssr.ts +4 -6
  92. package/src/server/render/static-params.ts +174 -0
  93. package/src/server/router/defined-route.ts +2 -1
  94. package/src/server/router/hmr.ts +2 -0
  95. package/src/server/router/plugin.ts +44 -35
  96. package/src/server/router/schema-merge.ts +1 -1
  97. package/src/server/router/schemas.ts +174 -61
  98. package/src/server/sync/plugin.ts +14 -10
  99. package/src/server/sync/response.ts +3 -3
  100. package/src/shared/elysia-contract.ts +23 -25
@@ -333,7 +333,7 @@ var init_config = __esm(() => {
333
333
  requestSyncPath = new AsyncLocalStorage2;
334
334
  });
335
335
 
336
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/utils.mjs
336
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/utils.mjs
337
337
  function elapsedMs(startTime) {
338
338
  return Math.max(0, Date.now() - startTime);
339
339
  }
@@ -474,7 +474,7 @@ var init_utils = __esm(() => {
474
474
  _isoDate = /* @__PURE__ */ new Date;
475
475
  });
476
476
 
477
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/redact-C7FmdhwI.mjs
477
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/redact-C7FmdhwI.mjs
478
478
  function normalizeRedactPathPattern(pattern) {
479
479
  if (!pattern.includes("*") && !pattern.includes("."))
480
480
  return `**.${pattern}`;
@@ -783,7 +783,7 @@ var init_redact_C7FmdhwI = __esm(() => {
783
783
  globallyRedacted = Symbol.for("evlog.globallyRedacted");
784
784
  });
785
785
 
786
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
786
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
787
787
  function logPluginError(name, hook, err) {
788
788
  console.error(`[evlog/${name}] ${hook} failed:`, err);
789
789
  }
@@ -953,7 +953,7 @@ var init_globalRegistry_Bh3bIGwA = __esm(() => {
953
953
  globalConfig = getRegistry().config;
954
954
  });
955
955
 
956
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/pretty-error-DTIHxnBN.mjs
956
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
957
957
  function pushTreeSpacer(children) {
958
958
  children.push(PRETTY_ERROR_TREE_SPACER);
959
959
  }
@@ -1179,7 +1179,7 @@ function formatGuidanceLine(label, text, labelColor) {
1179
1179
  let remaining = text.trim();
1180
1180
  let first = true;
1181
1181
  while (remaining.length > 0) {
1182
- const budget = first ? Math.max(24, GUIDANCE_WRAP_WIDTH - prefix.length) : Math.max(24, GUIDANCE_WRAP_WIDTH - 5);
1182
+ const budget = first ? Math.max(24, GUIDANCE_WRAP_WIDTH - prefix.length) : Math.max(24, 71);
1183
1183
  if (remaining.length <= budget) {
1184
1184
  lines.push(first ? `${prefix}${remaining}` : `${GUIDANCE_CONTINUATION}${remaining}`);
1185
1185
  break;
@@ -1247,14 +1247,14 @@ function buildErrorEntries(error, options = {}) {
1247
1247
  }];
1248
1248
  }
1249
1249
  var snippetReader = null, PRETTY_ERROR_TREE_SPACER = "__EVLOG_TREE_SPACER__", SKIP_PATH_RE, SKIP_FRAME_PATH_RE, SKIP_FRAME_FN_RE, GUIDANCE_WRAP_WIDTH = 76, GUIDANCE_CONTINUATION = " ";
1250
- var init_pretty_error_DTIHxnBN = __esm(() => {
1250
+ var init_pretty_error_D8rlWNL1 = __esm(() => {
1251
1251
  init_utils();
1252
1252
  SKIP_PATH_RE = /(?:^|[/\\])(?:node_modules|\.nuxt|\.next|\.output)(?:[/\\]|$)/;
1253
1253
  SKIP_FRAME_PATH_RE = /(?:^|[/\\])(?:packages[/\\]evlog|evlog[/\\](?:dist|src))(?:[/\\]|$)/;
1254
1254
  SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
1255
1255
  });
1256
1256
 
1257
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
1257
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
1258
1258
  function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
1259
1259
  const compact = partial.compact ?? (inDev && pretty);
1260
1260
  const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
@@ -1307,7 +1307,7 @@ var init_dev_terminal_Brarc6vc = __esm(() => {
1307
1307
  };
1308
1308
  });
1309
1309
 
1310
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
1310
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
1311
1311
  function hasWideEventPublisher() {
1312
1312
  return publisher !== null;
1313
1313
  }
@@ -1323,7 +1323,7 @@ function publishWideEvent(event) {
1323
1323
  var publisher = null;
1324
1324
  var init_wideEventChannel_BUDW48oP = () => {};
1325
1325
 
1326
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
1326
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
1327
1327
  function isEvlogError(error) {
1328
1328
  return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
1329
1329
  }
@@ -1332,7 +1332,7 @@ var init_error_brand_D0_DCPvr = __esm(() => {
1332
1332
  evlogErrorBrand = Symbol.for("evlog.error.brand");
1333
1333
  });
1334
1334
 
1335
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/error.mjs
1335
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/error.mjs
1336
1336
  var evlogErrorInternalKey, evlogErrorDataKey, EvlogError;
1337
1337
  var init_error = __esm(() => {
1338
1338
  init_utils();
@@ -1441,7 +1441,7 @@ var init_error = __esm(() => {
1441
1441
  });
1442
1442
  });
1443
1443
 
1444
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
1444
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
1445
1445
  function extractSafeHeaders(headers) {
1446
1446
  const raw = {};
1447
1447
  headers.forEach((value, key) => {
@@ -1462,7 +1462,7 @@ var init_headers_Bx1ieR_m = __esm(() => {
1462
1462
  init_utils();
1463
1463
  });
1464
1464
 
1465
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/audit-CW8wdQDm.mjs
1465
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/audit-C8euLMvu.mjs
1466
1466
  function writePrettyStdout(text) {
1467
1467
  (globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
1468
1468
  }
@@ -1596,13 +1596,14 @@ function emitWideEvent(level, event, options = {}) {
1596
1596
  formatted = redactEvent(formatted, state.redact);
1597
1597
  markGloballyRedacted(formatted);
1598
1598
  }
1599
- if (!state.silent)
1599
+ if (!state.silent) {
1600
1600
  if (state.pretty)
1601
1601
  prettyPrintWideEvent(formatted);
1602
1602
  else if (state.stringify)
1603
1603
  console[getConsoleMethod(level)](JSON.stringify(formatted));
1604
1604
  else
1605
1605
  console[getConsoleMethod(level)](formatted);
1606
+ }
1606
1607
  if (!deferDrain) {
1607
1608
  publishWideEvent(formatted);
1608
1609
  const drainPromises = [];
@@ -1653,11 +1654,12 @@ function formatValue(value) {
1653
1654
  if (isPlainObject$1(value)) {
1654
1655
  const pairs = [];
1655
1656
  for (const [k, v] of Object.entries(value))
1656
- if (v !== undefined && v !== null)
1657
+ if (v !== undefined && v !== null) {
1657
1658
  if (typeof v === "object")
1658
1659
  pairs.push(`${k}=${JSON.stringify(v)}`);
1659
1660
  else
1660
1661
  pairs.push(`${k}=${v}`);
1662
+ }
1661
1663
  return pairs.join(" ");
1662
1664
  }
1663
1665
  return String(value);
@@ -1712,6 +1714,20 @@ function asToolCallArray(value) {
1712
1714
  return;
1713
1715
  return value.every(isToolCallEntry) ? value : undefined;
1714
1716
  }
1717
+ function asCapturedLines(value) {
1718
+ if (typeof value !== "string" || value.length === 0)
1719
+ return;
1720
+ const lines = value.split(`
1721
+ `).map((line) => {
1722
+ return line.length > CAPTURED_LINE_MAX_LENGTH ? `${line.slice(0, CAPTURED_LINE_MAX_LENGTH)}\u2026` : line;
1723
+ });
1724
+ if (lines.length > CAPTURED_MAX_LINES) {
1725
+ lines.length = CAPTURED_MAX_LINES;
1726
+ lines.push(`+${value.split(`
1727
+ `).length - CAPTURED_MAX_LINES} more lines (full text in the event)`);
1728
+ }
1729
+ return lines;
1730
+ }
1715
1731
  function buildAIEntries(ai) {
1716
1732
  const entries = [];
1717
1733
  const headerParts = [];
@@ -1806,7 +1822,7 @@ function buildAIEntries(ai) {
1806
1822
  value: "",
1807
1823
  children
1808
1824
  });
1809
- } else if (toolCalls?.length)
1825
+ } else if (toolCalls?.length) {
1810
1826
  if (toolCallEntries?.length) {
1811
1827
  const children = toolCallEntries.map((tc) => {
1812
1828
  const inputStr = serializeToolInput(tc.input);
@@ -1826,6 +1842,7 @@ function buildAIEntries(ai) {
1826
1842
  value: names.join(", ")
1827
1843
  });
1828
1844
  }
1845
+ }
1829
1846
  const stepsUsage = Array.isArray(ai.stepsUsage) ? ai.stepsUsage.filter(isPlainObject$1) : undefined;
1830
1847
  if (stepsUsage?.length) {
1831
1848
  const firstModel = stepsUsage[0]?.model;
@@ -1847,6 +1864,20 @@ function buildAIEntries(ai) {
1847
1864
  key: "ai.steps",
1848
1865
  value: String(steps)
1849
1866
  });
1867
+ const promptLines = asCapturedLines(ai.prompt);
1868
+ if (promptLines)
1869
+ entries.push({
1870
+ key: "ai.prompt",
1871
+ value: "",
1872
+ children: promptLines
1873
+ });
1874
+ const outputLines = asCapturedLines(ai.output);
1875
+ if (outputLines)
1876
+ entries.push({
1877
+ key: "ai.output",
1878
+ value: "",
1879
+ children: outputLines
1880
+ });
1850
1881
  const embedding = isPlainObject$1(ai.embedding) ? ai.embedding : undefined;
1851
1882
  if (embedding) {
1852
1883
  const parts = [];
@@ -1997,10 +2028,63 @@ function prettyPrintWideEvent(event) {
1997
2028
  if (!browser && lines.length > 0)
1998
2029
  flushPrettyLines(lines);
1999
2030
  }
2031
+ function removeErrorCycles(value, ancestors) {
2032
+ if (value === null || typeof value !== "object")
2033
+ return value;
2034
+ if (ancestors.has(value))
2035
+ return "[Circular]";
2036
+ ancestors.add(value);
2037
+ let changed = false;
2038
+ const visit = (item) => {
2039
+ const result = removeErrorCycles(item, ancestors);
2040
+ if (!Object.is(result, item))
2041
+ changed = true;
2042
+ return result;
2043
+ };
2044
+ const copy = Array.isArray(value) ? value.map(visit) : Object.fromEntries(Object.entries(value).map(([key, item]) => [key, visit(item)]));
2045
+ ancestors.delete(value);
2046
+ return changed ? copy : value;
2047
+ }
2048
+ function serializeError(err) {
2049
+ const errorObj = {
2050
+ name: err.name,
2051
+ message: err.message,
2052
+ stack: isDev() ? compactStackForStorage(err.stack) : err.stack
2053
+ };
2054
+ const errRecord = err;
2055
+ const ancestors = new WeakSet([err]);
2056
+ for (const k of [
2057
+ "code",
2058
+ "status",
2059
+ "statusText",
2060
+ "statusCode",
2061
+ "statusMessage",
2062
+ "data",
2063
+ "cause",
2064
+ "internal"
2065
+ ])
2066
+ if (k in err)
2067
+ errorObj[k] = removeErrorCycles(errRecord[k], ancestors);
2068
+ if (EvlogError.isEvlogError(err)) {
2069
+ if (err.code)
2070
+ errorObj.code = err.code;
2071
+ if (err.why)
2072
+ errorObj.why = err.why;
2073
+ if (err.fix)
2074
+ errorObj.fix = err.fix;
2075
+ if (err.link)
2076
+ errorObj.link = err.link;
2077
+ if (err.status)
2078
+ errorObj.status = err.status;
2079
+ }
2080
+ return errorObj;
2081
+ }
2000
2082
  function createLogMethod(level) {
2001
2083
  return function logMethod(tagOrEvent, message) {
2002
2084
  if (typeof tagOrEvent === "string" && message !== undefined)
2003
2085
  emitTaggedLog(level, tagOrEvent, message);
2086
+ else if (tagOrEvent instanceof Error)
2087
+ emitWideEvent(level, { error: serializeError(tagOrEvent) });
2004
2088
  else if (typeof tagOrEvent === "object")
2005
2089
  emitWideEvent(level, tagOrEvent);
2006
2090
  else
@@ -2079,36 +2163,7 @@ function createLogger(initialContext = {}, internalOptions) {
2079
2163
  const err = typeof error === "string" ? new Error(error) : error;
2080
2164
  if (errorContext)
2081
2165
  mergeInto(context, errorContext);
2082
- const errorObj = {
2083
- name: err.name,
2084
- message: err.message,
2085
- stack: isDev() ? compactStackForStorage(err.stack) : err.stack
2086
- };
2087
- const errRecord = err;
2088
- for (const k of [
2089
- "code",
2090
- "status",
2091
- "statusText",
2092
- "statusCode",
2093
- "statusMessage",
2094
- "data",
2095
- "cause",
2096
- "internal"
2097
- ])
2098
- if (k in err)
2099
- errorObj[k] = errRecord[k];
2100
- if (EvlogError.isEvlogError(err)) {
2101
- if (err.code)
2102
- errorObj.code = err.code;
2103
- if (err.why)
2104
- errorObj.why = err.why;
2105
- if (err.fix)
2106
- errorObj.fix = err.fix;
2107
- if (err.link)
2108
- errorObj.link = err.link;
2109
- if (err.status)
2110
- errorObj.status = err.status;
2111
- }
2166
+ const errorObj = serializeError(err);
2112
2167
  if (isPlainObject$1(context.error))
2113
2168
  mergeInto(context.error, errorObj);
2114
2169
  else
@@ -2293,12 +2348,12 @@ function finalizeAudit(event) {
2293
2348
  event.audit = decorated;
2294
2349
  _testCollector?.(decorated, event);
2295
2350
  }
2296
- var nativeStdoutWrite, 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).", pendingDrainState, state, _log, noopLogger, _testCollector = null;
2297
- var init_audit_CW8wdQDm = __esm(() => {
2351
+ var nativeStdoutWrite, 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).", pendingDrainState, state, CAPTURED_LINE_MAX_LENGTH = 160, CAPTURED_MAX_LINES = 8, _log, noopLogger, _testCollector = null;
2352
+ var init_audit_C8euLMvu = __esm(() => {
2298
2353
  init_utils();
2299
2354
  init_redact_C7FmdhwI();
2300
2355
  init_globalRegistry_Bh3bIGwA();
2301
- init_pretty_error_DTIHxnBN();
2356
+ init_pretty_error_D8rlWNL1();
2302
2357
  init_dev_terminal_Brarc6vc();
2303
2358
  init_wideEventChannel_BUDW48oP();
2304
2359
  init_error();
@@ -2329,12 +2384,12 @@ var init_audit_CW8wdQDm = __esm(() => {
2329
2384
  initLogger(__EVLOG_CONFIG__);
2330
2385
  });
2331
2386
 
2332
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/index.mjs
2387
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/index.mjs
2333
2388
  var init_dist = __esm(() => {
2334
- init_audit_CW8wdQDm();
2389
+ init_audit_C8euLMvu();
2335
2390
  });
2336
2391
 
2337
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
2392
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
2338
2393
  function shouldDeferEmitForResponse(response) {
2339
2394
  if (!response.body)
2340
2395
  return false;
@@ -2414,7 +2469,7 @@ function bindStreamingResponseLifecycle(response, onComplete) {
2414
2469
  }
2415
2470
  var init_streamResponse_OlirMA5P = () => {};
2416
2471
 
2417
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/errors-CL8dDgIi.mjs
2472
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/errors-CL8dDgIi.mjs
2418
2473
  function extractErrorStatus(error) {
2419
2474
  if (error === null || typeof error !== "object")
2420
2475
  return 500;
@@ -2424,7 +2479,7 @@ function extractErrorStatus(error) {
2424
2479
  }
2425
2480
  var init_errors_CL8dDgIi = () => {};
2426
2481
 
2427
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
2482
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
2428
2483
  function shouldLog(path, include, exclude) {
2429
2484
  if (exclude && exclude.length > 0) {
2430
2485
  if (exclude.some((pattern) => matchesPattern(path, pattern)))
@@ -2452,7 +2507,7 @@ var init_deferred_drain_CfRYimo5 = __esm(() => {
2452
2507
  init_utils();
2453
2508
  });
2454
2509
 
2455
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/middleware-DHm89-gB.mjs
2510
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/middleware-fam3VyaL.mjs
2456
2511
  function resolveMiddlewarePluginRunner(options) {
2457
2512
  const global2 = getGlobalPluginRunner();
2458
2513
  const local = options.plugins;
@@ -2629,29 +2684,17 @@ function createMiddlewareLogger(options) {
2629
2684
  };
2630
2685
  }
2631
2686
  var noopResult, runnerCache;
2632
- var init_middleware_DHm89_gB = __esm(() => {
2687
+ var init_middleware_fam3VyaL = __esm(() => {
2633
2688
  init_utils();
2634
2689
  init_redact_C7FmdhwI();
2635
2690
  init_globalRegistry_Bh3bIGwA();
2636
2691
  init_wideEventChannel_BUDW48oP();
2637
- init_audit_CW8wdQDm();
2692
+ init_audit_C8euLMvu();
2638
2693
  init_errors_CL8dDgIi();
2639
2694
  init_deferred_drain_CfRYimo5();
2640
2695
  init_streamResponse_OlirMA5P();
2641
2696
  noopResult = {
2642
- logger: {
2643
- set() {},
2644
- error() {},
2645
- info() {},
2646
- warn() {},
2647
- setLevel() {},
2648
- emit() {
2649
- return null;
2650
- },
2651
- getContext() {
2652
- return {};
2653
- }
2654
- },
2697
+ logger: noopLogger,
2655
2698
  finish: () => Promise.resolve(null),
2656
2699
  finishResponse: (response) => Promise.resolve(response),
2657
2700
  skipped: true
@@ -2659,7 +2702,7 @@ var init_middleware_DHm89_gB = __esm(() => {
2659
2702
  runnerCache = /* @__PURE__ */ new WeakMap;
2660
2703
  });
2661
2704
 
2662
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/integration-Dprr4POU.mjs
2705
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/integration-CGD18W8r.mjs
2663
2706
  function attachForkToLogger(storage, parent, middlewareOptions, lifecycle) {
2664
2707
  const log = parent;
2665
2708
  log.fork = (label, fn) => {
@@ -2755,118 +2798,68 @@ function defineFrameworkIntegration(spec) {
2755
2798
  };
2756
2799
  } };
2757
2800
  }
2758
- var init_integration_Dprr4POU = __esm(() => {
2759
- init_audit_CW8wdQDm();
2801
+ var init_integration_CGD18W8r = __esm(() => {
2802
+ init_audit_C8euLMvu();
2760
2803
  init_headers_Bx1ieR_m();
2761
2804
  init_errors_CL8dDgIi();
2762
- init_middleware_DHm89_gB();
2805
+ init_middleware_fam3VyaL();
2763
2806
  });
2764
2807
 
2765
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/asyncStorageScope-CnJiW7V3.mjs
2766
- function supportsAsyncLocalStorageEnterWith(storage) {
2767
- if (typeof storage.enterWith !== "function")
2768
- return false;
2769
- try {
2770
- storage.enterWith(undefined);
2771
- return true;
2772
- } catch {
2773
- return false;
2808
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/toolkit/storage.mjs
2809
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
2810
+ function createLoggerStorage(contextHint, id = contextHint) {
2811
+ const storage = getSharedStorage(id, () => new AsyncLocalStorage3);
2812
+ function useLogger() {
2813
+ const logger = storage.getStore();
2814
+ if (!logger)
2815
+ throw new Error(`[evlog] useLogger() was called outside of an evlog ${contextHint}`);
2816
+ return logger;
2774
2817
  }
2818
+ return {
2819
+ storage,
2820
+ useLogger
2821
+ };
2775
2822
  }
2776
- function createSharedEnterWithStorage(id, create) {
2777
- return getSharedStorage(id, () => {
2778
- const storage = create();
2779
- patchAsyncLocalStorageEnterWith(storage);
2780
- return storage;
2781
- });
2782
- }
2783
- function patchAsyncLocalStorageEnterWith(storage) {
2784
- if (supportsAsyncLocalStorageEnterWith(storage))
2785
- return;
2786
- let fallbackStore;
2787
- let runDepth = 0;
2788
- const originalGetStore = storage.getStore.bind(storage);
2789
- const originalRun = storage.run.bind(storage);
2790
- Object.defineProperty(storage, "enterWith", {
2791
- configurable: true,
2792
- writable: true,
2793
- value(store) {
2794
- fallbackStore = store;
2795
- }
2796
- });
2797
- Object.defineProperty(storage, "run", {
2798
- configurable: true,
2799
- writable: true,
2800
- value(store, callback, ...args) {
2801
- runDepth++;
2802
- try {
2803
- return originalRun(store, callback, ...args);
2804
- } finally {
2805
- runDepth--;
2806
- }
2807
- }
2808
- });
2809
- Object.defineProperty(storage, "getStore", {
2810
- configurable: true,
2811
- writable: true,
2812
- value() {
2813
- if (runDepth > 0)
2814
- return originalGetStore();
2815
- const active = originalGetStore();
2816
- return active !== undefined ? active : fallbackStore;
2817
- }
2818
- });
2819
- }
2820
- var init_asyncStorageScope_CnJiW7V3 = __esm(() => {
2823
+ var init_storage = __esm(() => {
2821
2824
  init_globalRegistry_Bh3bIGwA();
2822
2825
  });
2823
2826
 
2824
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/elysia/index.mjs
2825
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
2827
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/toolkit.mjs
2828
+ var init_toolkit = __esm(() => {
2829
+ init_integration_CGD18W8r();
2830
+ init_storage();
2831
+ });
2832
+
2833
+ // src/server/evlog.ts
2826
2834
  import { Elysia as Elysia2 } from "elysia";
2827
- function useLogger2() {
2828
- const logger = storage.getStore();
2829
- if (!logger || !activeLoggers.has(logger))
2830
- throw new Error("[evlog] useLogger() was called outside of an evlog plugin context. Make sure app.use(evlog()) is registered before your routes.");
2831
- return logger;
2832
- }
2833
- var storage, activeLoggers, integration;
2834
- var init_elysia = __esm(() => {
2835
- init_integration_Dprr4POU();
2836
- init_asyncStorageScope_CnJiW7V3();
2837
- storage = createSharedEnterWithStorage("evlog:elysia", () => new AsyncLocalStorage3);
2838
- activeLoggers = /* @__PURE__ */ new WeakSet;
2835
+ var loggerStorage, integration, getRequestLogger;
2836
+ var init_evlog = __esm(() => {
2837
+ init_toolkit();
2838
+ loggerStorage = createLoggerStorage("Furin request context. Make sure the Furin plugin is registered before your routes.", "@teyik0/furin:evlog");
2839
2839
  integration = defineFrameworkIntegration({
2840
- name: "elysia",
2841
- extractRequest: ({ request, path, headers }) => ({
2842
- method: request.method,
2843
- path,
2844
- headers,
2845
- requestId: headers["x-request-id"]
2846
- }),
2847
- attachLogger: ({ request, path, headers }, logger) => {
2848
- attachForkToLogger(storage, logger, {
2840
+ attachLogger: () => {
2841
+ return;
2842
+ },
2843
+ extractRequest: ({ request }) => {
2844
+ const url = new URL(request.url);
2845
+ return {
2846
+ headers: request.headers,
2849
2847
  method: request.method,
2850
- path,
2851
- requestId: headers["x-request-id"]
2852
- }, {
2853
- onChildEnter: (child) => {
2854
- activeLoggers.add(child);
2855
- },
2856
- onChildExit: (child) => {
2857
- activeLoggers.delete(child);
2858
- }
2859
- });
2860
- activeLoggers.add(logger);
2861
- }
2848
+ path: url.pathname,
2849
+ requestId: request.headers.get("x-request-id") ?? undefined
2850
+ };
2851
+ },
2852
+ name: "furin",
2853
+ storage: loggerStorage.storage
2862
2854
  });
2855
+ getRequestLogger = loggerStorage.useLogger;
2863
2856
  });
2864
2857
 
2865
2858
  // src/server/context-logger.ts
2866
2859
  import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
2867
- function useLogger3() {
2860
+ function getLogger() {
2868
2861
  try {
2869
- return useLogger2();
2862
+ return getRequestLogger();
2870
2863
  } catch {
2871
2864
  return syntheticRenderStorage.getStore() ?? noopLogger2;
2872
2865
  }
@@ -2886,7 +2879,7 @@ async function runInSyntheticRenderScope(fn, initialContext) {
2886
2879
  var noopLogger2, syntheticRenderStorage;
2887
2880
  var init_context_logger = __esm(() => {
2888
2881
  init_dist();
2889
- init_elysia();
2882
+ init_evlog();
2890
2883
  noopLogger2 = {
2891
2884
  emit: () => null,
2892
2885
  error: () => {},
@@ -2906,7 +2899,7 @@ var IS_DEV = true;
2906
2899
  // src/server/dev/graph.ts
2907
2900
  import { randomUUID } from "crypto";
2908
2901
  import { readFileSync as readFileSync4, statSync as statSync2 } from "fs";
2909
- import { dirname as dirname5, extname as extname3 } from "path";
2902
+ import { dirname as dirname6, extname as extname3 } from "path";
2910
2903
  function normalizeModulePath(path) {
2911
2904
  return path.replaceAll("\\", "/");
2912
2905
  }
@@ -2915,7 +2908,7 @@ function resolveDevSourceImports(source, path, loader) {
2915
2908
  const transpiler = new Bun.Transpiler({ loader });
2916
2909
  for (const imported of transpiler.scanImports(source)) {
2917
2910
  try {
2918
- const resolved = normalizeModulePath(Bun.resolveSync(imported.path, dirname5(path)));
2911
+ const resolved = normalizeModulePath(Bun.resolveSync(imported.path, dirname6(path)));
2919
2912
  if (!resolved.includes("/node_modules/")) {
2920
2913
  imports.push(resolved);
2921
2914
  }
@@ -3365,6 +3358,7 @@ function browserEventsClientSource() {
3365
3358
 
3366
3359
  // src/server/browser-events/plugin.ts
3367
3360
  import { Elysia as Elysia3 } from "elysia";
3361
+ import { websocket } from "elysia/websocket";
3368
3362
  function browserEventsClientScript(basePath) {
3369
3363
  return `<script data-furin-framework-module="" type="module" src="${basePath}${CLIENT_PATH2}"></script>`;
3370
3364
  }
@@ -3392,12 +3386,12 @@ function injectDevDiagnosticClient(html, basePath) {
3392
3386
  var init_plugin2 = () => {};
3393
3387
 
3394
3388
  // src/build/index.ts
3395
- import { existsSync as existsSync14, writeFileSync as writeFileSync9 } from "fs";
3396
- import { join as join15, relative as relative9, resolve as resolve7 } from "path";
3389
+ import { existsSync as existsSync14, writeFileSync as writeFileSync10 } from "fs";
3390
+ import { join as join16, relative as relative10, resolve as resolve9 } from "path";
3397
3391
 
3398
3392
  // src/adapter/bun.ts
3399
- import { existsSync as existsSync9, rmSync as rmSync2 } from "fs";
3400
- import { join as join10, resolve as resolve4 } from "path";
3393
+ import { existsSync as existsSync9, readFileSync as readFileSync6, rmSync as rmSync2 } from "fs";
3394
+ import { join as join11, resolve as resolve6 } from "path";
3401
3395
 
3402
3396
  // src/build/bun-build.ts
3403
3397
  function runBunBuild(config) {
@@ -3464,6 +3458,7 @@ function buildAppContextBlock(app, varPrefix) {
3464
3458
  const routeEntries = app.routes.map((r) => ` { pattern: ${JSON.stringify(r.pattern)}, path: ${JSON.stringify(r.path.replace(/\\/g, "/"))}, mode: ${JSON.stringify(r.mode)} },`);
3465
3459
  const rootConventionsLine = app.rootConventions ? ` rootConventions: ${JSON.stringify(app.rootConventions)},` : "";
3466
3460
  const routeMetadataLine = app.routeMetadata ? ` routeMetadata: ${JSON.stringify(app.routeMetadata)},` : "";
3461
+ const deploymentTargetLine = app.deploymentTarget === undefined ? "" : ` deploymentTarget: ${JSON.stringify(app.deploymentTarget)},`;
3467
3462
  const serveAssetsLine = app.serveAssets === undefined ? "" : ` serveAssets: ${JSON.stringify(app.serveAssets)},`;
3468
3463
  const ssgCacheLine = app.ssgCache ? ` ssgCache: ${JSON.stringify(app.ssgCache)},` : "";
3469
3464
  const templateHtmlLine = app.templateHtml === undefined ? "" : ` templateHtml: ${JSON.stringify(app.templateHtml)},`;
@@ -3471,6 +3466,7 @@ function buildAppContextBlock(app, varPrefix) {
3471
3466
  "__setCompileContext({",
3472
3467
  ` buildId: ${JSON.stringify(app.buildId ?? "")},`,
3473
3468
  ` clientLogging: ${JSON.stringify(app.clientLogging ?? false)},`,
3469
+ deploymentTargetLine,
3474
3470
  ` prefix: ${JSON.stringify(app.prefix ?? "")},`,
3475
3471
  ` rootPath: ${JSON.stringify(app.rootPath.replace(/\\/g, "/"))},`,
3476
3472
  app.nativeRoutes ? ` nativeRoutes: ${nativeRoutesVar},` : "",
@@ -3494,6 +3490,7 @@ function buildEntrySource(options) {
3494
3490
  const { apps, headerComment, serverEntry } = options;
3495
3491
  const mode = options.mode ?? "boot";
3496
3492
  const internalSpecifier = mode === "register" ? "@teyik0/furin/internal" : INTERNAL_MODULE_PATH;
3493
+ const productionMode = mode !== "register";
3497
3494
  const importLines = [];
3498
3495
  const contextBlocks = [];
3499
3496
  for (let appIndex = 0;appIndex < apps.length; appIndex++) {
@@ -3506,9 +3503,9 @@ function buildEntrySource(options) {
3506
3503
  const lines = [
3507
3504
  headerComment,
3508
3505
  `import { __setCompileContext } from ${JSON.stringify(internalSpecifier)};`,
3509
- ...mode === "boot" ? [`import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`] : [],
3506
+ ...productionMode ? [`import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`] : [],
3510
3507
  ...importLines,
3511
- ...mode === "boot" ? [
3508
+ ...productionMode ? [
3512
3509
  "",
3513
3510
  "// Force production mode \u2014 Bun may inline process.env.NODE_ENV at bundle time.",
3514
3511
  "__setDevMode(false);",
@@ -3516,7 +3513,7 @@ function buildEntrySource(options) {
3516
3513
  ] : [],
3517
3514
  ...contextBlocks,
3518
3515
  "",
3519
- ...serverEntry ? [
3516
+ ...serverEntry && mode === "boot" ? [
3520
3517
  `const __serverModule = await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
3521
3518
  'if (typeof __serverModule.startServer === "function") {',
3522
3519
  " await __serverModule.startServer();",
@@ -3534,6 +3531,13 @@ function buildEntrySource(options) {
3534
3531
  " }",
3535
3532
  "}",
3536
3533
  ""
3534
+ ] : serverEntry && mode === "app" ? [
3535
+ `const __serverModule = await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
3536
+ "export const app = __serverModule.default;",
3537
+ "export const port = __serverModule.port;",
3538
+ "export const startServer = __serverModule.startServer;",
3539
+ "export default __serverModule.default;",
3540
+ ""
3537
3541
  ] : []
3538
3542
  ];
3539
3543
  return lines.join(`
@@ -3566,7 +3570,7 @@ function toBuildRouteManifestEntry(route, rootDir) {
3566
3570
  mode: route.mode,
3567
3571
  pagePath: toPosixPath(relative(rootDir, route.path)),
3568
3572
  hasLayout: route.routeChain.some((entry) => !!entry.layout),
3569
- hasStaticParams: !!route.page?.staticParams,
3573
+ hasStaticParams: route.page.staticParams !== undefined || route.routeChain.some((entry) => entry.staticParams !== undefined),
3570
3574
  revalidate: resolveRouteRevalidate(route.page) ?? null
3571
3575
  };
3572
3576
  }
@@ -3586,12 +3590,13 @@ function buildTargetManifest(rootDir, buildRoot, target, serverEntry) {
3586
3590
  // src/build/virtual-entry.ts
3587
3591
  var REGEX_SPECIAL_CHARACTERS_RE = /[.*+?^${}()|[\]\\]/g;
3588
3592
  function createVirtualBuildEntry(entrypoint, source, loader) {
3589
- const entrypointFilter = new RegExp(`^${entrypoint.replace(REGEX_SPECIAL_CHARACTERS_RE, "\\$&")}$`);
3593
+ const normalizedEntrypoint = entrypoint.replaceAll("\\", "/");
3594
+ const entrypointFilter = new RegExp(`^${normalizedEntrypoint.replace(REGEX_SPECIAL_CHARACTERS_RE, "\\$&")}$`);
3590
3595
  return {
3591
- entrypoint,
3592
- files: { [entrypoint]: source },
3596
+ entrypoint: normalizedEntrypoint,
3597
+ files: { [normalizedEntrypoint]: source },
3593
3598
  plugin: {
3594
- name: `furin-virtual-entry:${entrypoint}`,
3599
+ name: `furin-virtual-entry:${normalizedEntrypoint}`,
3595
3600
  setup(build) {
3596
3601
  build.onLoad({ filter: entrypointFilter }, () => ({ contents: source, loader }));
3597
3602
  }
@@ -3614,10 +3619,8 @@ function buildEmbeddedContext(clientDir, publicDir) {
3614
3619
  " },"
3615
3620
  ];
3616
3621
  }
3617
- function generateCompileEntry(options) {
3618
- const { apps, outDir, serverEntry, publicDir } = options;
3619
- ensureDir(outDir);
3620
- const preparedApps = apps.map((app) => {
3622
+ function prepareCompileEntryApps(options) {
3623
+ return options.apps.map((app) => {
3621
3624
  const { embed, ...context } = app;
3622
3625
  if (!embed) {
3623
3626
  return context;
@@ -3626,29 +3629,108 @@ function generateCompileEntry(options) {
3626
3629
  ...context,
3627
3630
  extraContext: [
3628
3631
  ...context.extraContext ?? [],
3629
- ...buildEmbeddedContext(embed.clientDir, publicDir)
3632
+ ...buildEmbeddedContext(embed.clientDir, options.publicDir)
3630
3633
  ]
3631
3634
  };
3632
3635
  });
3633
- const source = buildEntrySource({
3634
- apps: preparedApps,
3635
- headerComment: options.headerComment ?? "// Auto-generated by furin compile \u2014 do not edit",
3636
- serverEntry
3637
- });
3638
- const entryPath = join3(outDir, "_compile-entry.ts");
3639
- return createVirtualBuildEntry(entryPath, source, "ts");
3636
+ }
3637
+
3638
+ // src/build/elysia-aot.ts
3639
+ import { dirname as dirname2, resolve } from "path";
3640
+ import { aotFactory } from "elysia/plugin/aot/unplugin";
3641
+ var AOT_NAMESPACE = "furin-elysia-aot";
3642
+ var ELYSIA_RESOLVE_DIR = dirname2(Bun.resolveSync("elysia", import.meta.dir));
3643
+ var SOURCE_FILTER = /\.[cm]?[jt]sx?$/;
3644
+ var WEBSOCKET_STUB_MARKER = "[elysia-aot] WebSocket route builder was stripped (strip mode) but a WS route was used.";
3645
+ function loaderFor(path) {
3646
+ const extension = path.slice(path.lastIndexOf("."));
3647
+ if (extension === ".jsx") {
3648
+ return "jsx";
3649
+ }
3650
+ if (extension === ".tsx") {
3651
+ return "tsx";
3652
+ }
3653
+ if (extension === ".ts" || extension === ".mts" || extension === ".cts") {
3654
+ return "ts";
3655
+ }
3656
+ return "js";
3657
+ }
3658
+ function patchElysiaWebSocketStub(source) {
3659
+ if (!source.includes(WEBSOCKET_STUB_MARKER) || source.includes("accumulateWSOptions")) {
3660
+ return source;
3661
+ }
3662
+ return `${source}
3663
+ export function accumulateWSOptions(){return e()}
3664
+ export function resolveWSOptions(){return e()}
3665
+ export function drainWaiters(){return e()}
3666
+ export function handleWSResponse(){return e()}
3667
+ `;
3668
+ }
3669
+ function elysiaAot(entry) {
3670
+ const entryPath = resolve(entry);
3671
+ const hooks = aotFactory({ entry, strip: "auto", target: "bun" });
3672
+ return {
3673
+ name: "elysia-aot",
3674
+ async setup(build) {
3675
+ try {
3676
+ await hooks.buildStart?.();
3677
+ } catch (error) {
3678
+ if (error instanceof Error && error.message.startsWith("[elysia-aot]") && error.message.includes("mounts a sub-app")) {
3679
+ console.warn("[furin] Elysia AOT skipped because the app uses .mount().");
3680
+ return;
3681
+ }
3682
+ throw error;
3683
+ }
3684
+ const entrySource = await Bun.file(entryPath).text();
3685
+ const transformedEntry = await hooks.transform?.(entrySource, entryPath);
3686
+ if (transformedEntry !== undefined) {
3687
+ await Bun.write(entryPath, transformedEntry);
3688
+ }
3689
+ build.onResolve({ filter: /^elysia(?:\/(?!compiled$|type$).*)?$/ }, ({ path }) => ({
3690
+ path: Bun.resolveSync(path, ELYSIA_RESOLVE_DIR)
3691
+ }));
3692
+ build.onResolve({ filter: /^elysia\/(?:compiled|type)$/ }, ({ path }) => {
3693
+ const resolved = hooks.resolveId?.(path);
3694
+ return resolved === undefined ? undefined : { namespace: AOT_NAMESPACE, path: resolved };
3695
+ });
3696
+ build.onLoad({ filter: /.*/, namespace: AOT_NAMESPACE }, ({ path }) => {
3697
+ const contents = hooks.load?.(path);
3698
+ return contents === undefined ? undefined : { contents, loader: "js", resolveDir: ELYSIA_RESOLVE_DIR };
3699
+ });
3700
+ build.onLoad({ filter: SOURCE_FILTER }, async ({ path }) => {
3701
+ if (resolve(path) === entryPath) {
3702
+ return;
3703
+ }
3704
+ if (hooks.transformInclude?.(path) === false) {
3705
+ return;
3706
+ }
3707
+ const original = await Bun.file(path).text();
3708
+ const transformed = await hooks.transform?.(original, path);
3709
+ if (transformed === undefined) {
3710
+ return;
3711
+ }
3712
+ return {
3713
+ contents: patchElysiaWebSocketStub(transformed),
3714
+ loader: loaderFor(path)
3715
+ };
3716
+ });
3717
+ build.onEnd(() => {
3718
+ hooks.buildEnd?.();
3719
+ });
3720
+ }
3721
+ };
3640
3722
  }
3641
3723
 
3642
3724
  // src/build/production-instrumentation.ts
3643
- import { dirname as dirname2, relative as relative2, resolve } from "path";
3725
+ import { dirname as dirname3, relative as relative2, resolve as resolve2 } from "path";
3644
3726
  var INSTRUMENTATION_IMPORT = /(?:^|[/\\])devtools[/\\]instrumentation(?:\.ts|\.js)?$/;
3645
3727
  var DEV_PAGE_PLUGIN_IMPORT = /(?:^|[/\\])server[/\\]dev-page-plugin(?:\.ts|\.js)?$/;
3646
- var DEV_RUNTIME_IMPORT = /(?:^|[/\\])server[/\\]dev[/\\](?:browser-events|diagnostics|plugin)(?:\.ts|\.js)?$/;
3728
+ var DEV_RUNTIME_IMPORT = /(?:^|[/\\])server[/\\]dev[/\\](?:browser-events|diagnostics|graph|plugin)(?:\.ts|\.js)?$/;
3647
3729
  var DEV_BUILD_IMPORT = /(?:^|[/\\])(?:build[/\\]hydrate|plugin[/\\]route-config-autofix)(?:\.ts|\.js)?$/;
3648
3730
  var HMR_IMPORT = /(?:^|[/\\])server[/\\]router[/\\]hmr(?:\.ts|\.js)?$/;
3649
- var PRODUCTION_BOUNDARY_IMPORT = /(?:browser-events|instrumentation|dev-page-plugin|diagnostics|plugin|hmr|hydrate|route-config-autofix)(?:\.ts|\.js)?$/;
3731
+ var PRODUCTION_BOUNDARY_IMPORT = /(?:browser-events|instrumentation|dev-page-plugin|diagnostics|graph|plugin|hmr|hydrate|route-config-autofix)(?:\.ts|\.js)?$/;
3650
3732
  var PRODUCTION_STUB_NAMESPACE = "furin-production-runtime-stub";
3651
- var FURIN_RUNTIME_ROOT = resolve(import.meta.dir, "..");
3733
+ var FURIN_RUNTIME_ROOT = resolve2(import.meta.dir, "..");
3652
3734
  function isFurinRuntimePath(path) {
3653
3735
  const fromRuntimeRoot = relative2(FURIN_RUNTIME_ROOT, path);
3654
3736
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
@@ -3661,23 +3743,23 @@ function productionInstrumentationPlugin() {
3661
3743
  name: "furin-production-instrumentation",
3662
3744
  setup(build) {
3663
3745
  build.onResolve({ filter: PRODUCTION_BOUNDARY_IMPORT }, (args) => {
3664
- const importPath = resolve(dirname2(args.importer), args.path);
3746
+ const importPath = resolve2(dirname3(args.importer), args.path);
3665
3747
  if (!isFurinRuntimePath(importPath)) {
3666
3748
  return;
3667
3749
  }
3668
3750
  if (INSTRUMENTATION_IMPORT.test(importPath)) {
3669
3751
  return {
3670
- path: resolve(import.meta.dir, "../server/devtools/instrumentation.production.ts")
3752
+ path: resolve2(import.meta.dir, "../server/devtools/instrumentation.production.ts")
3671
3753
  };
3672
3754
  }
3673
3755
  if (DEV_PAGE_PLUGIN_IMPORT.test(importPath)) {
3674
- return { path: resolve(import.meta.dir, "../server/dev-page-plugin.production.ts") };
3756
+ return { path: resolve2(import.meta.dir, "../server/dev-page-plugin.production.ts") };
3675
3757
  }
3676
3758
  if (DEV_RUNTIME_IMPORT.test(importPath)) {
3677
- return { path: resolve(import.meta.dir, "../server/dev/runtime.production.ts") };
3759
+ return { path: resolve2(import.meta.dir, "../server/dev/runtime.production.ts") };
3678
3760
  }
3679
3761
  if (HMR_IMPORT.test(importPath)) {
3680
- return { path: resolve(import.meta.dir, "../server/router/hmr.production.ts") };
3762
+ return { path: resolve2(import.meta.dir, "../server/router/hmr.production.ts") };
3681
3763
  }
3682
3764
  if (DEV_BUILD_IMPORT.test(importPath)) {
3683
3765
  return { namespace: PRODUCTION_STUB_NAMESPACE, path: importPath };
@@ -3693,6 +3775,10 @@ function productionInstrumentationPlugin() {
3693
3775
  };
3694
3776
  }
3695
3777
 
3778
+ // src/build/server-app-entry.ts
3779
+ import { writeFileSync } from "fs";
3780
+ import { join as join5 } from "path";
3781
+
3696
3782
  // src/plugin/routes.ts
3697
3783
  import {
3698
3784
  existsSync as existsSync4,
@@ -3702,24 +3788,19 @@ import {
3702
3788
  statSync,
3703
3789
  watch
3704
3790
  } from "fs";
3705
- import { dirname as dirname3, extname, isAbsolute, join as join4, relative as relative3, resolve as resolve2, sep } from "path";
3791
+ import { dirname as dirname4, extname, isAbsolute, join as join4, relative as relative3, resolve as resolve3, sep } from "path";
3706
3792
  import { pathToFileURL } from "url";
3707
3793
  import { Elysia } from "elysia";
3708
3794
 
3709
3795
  // src/shared/elysia-contract.ts
3710
- import { getSchemaValidator as elysiaGetSchemaValidator } from "elysia";
3711
- import {
3712
- parseQueryFromURL as elysiaParseQueryFromURL,
3713
- parseQueryStandardSchema as elysiaParseQueryStandardSchema
3714
- } from "elysia/parse-query";
3715
- import { TypeCompiler as ElysiaTypeCompiler } from "elysia/type-system";
3796
+ import { Validator } from "elysia";
3716
3797
  var TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
3717
3798
  function isTypeBoxObjectSchema(schema) {
3718
3799
  if (schema === null || typeof schema !== "object") {
3719
3800
  return false;
3720
3801
  }
3721
3802
  const candidate = schema;
3722
- return candidate[TYPEBOX_KIND] === "Object" || candidate["~kind"] === "Object";
3803
+ return (candidate[TYPEBOX_KIND] === "Object" || candidate["~kind"] === "Object") && candidate.properties !== null && typeof candidate.properties === "object";
3723
3804
  }
3724
3805
 
3725
3806
  // src/shared/search-params.ts
@@ -3873,7 +3954,7 @@ function mergeRouteSchemas(routeChain, key) {
3873
3954
  return schemas[0];
3874
3955
  }
3875
3956
  if (schemas.some((schema) => !isTypeBoxObjectSchema(schema))) {
3876
- throw new Error(`[furin] Merging ${key} schemas across the route chain requires TypeBox in V1. Use TypeBox for parent/child ${key}, or define ${key} only on leaf routes.`);
3957
+ throw new Error(`[furin] Merging ${key} schemas across the route chain requires TypeBox object schemas. Use TypeBox for parent/child ${key}, or define ${key} only on leaf routes.`);
3877
3958
  }
3878
3959
  const properties = Object.assign({}, ...schemas.map((schema) => schema.properties));
3879
3960
  const options = Object.assign({}, ...schemas.map((schema) => Object.fromEntries(Object.entries(schema).filter(([name]) => !TOBJECT_STRUCTURAL_KEYS.has(name)))));
@@ -3937,10 +4018,11 @@ function unwrapTSExpression(node) {
3937
4018
  init_patterns();
3938
4019
  var ROUTES_NAMESPACE_PREFIX = "furin-routes";
3939
4020
  var ROUTES_REGISTRY_SPECIFIER = "furin/routes?registry";
3940
- var ROUTES_REGISTRY_FILTER = /^furin\/routes\?registry$/;
4021
+ var COMPOSABLE_ROUTES_REGISTRY_SPECIFIER = "furin/routes?registry=composable";
4022
+ var ROUTES_REGISTRY_FILTER = /^furin\/routes\?registry(?:=composable)?$/;
3941
4023
  var ROUTE_FILE_FILTER = /^furin-route-file:.+$/;
3942
4024
  var ROUTE_FILES_NAMESPACE = "furin-route-files";
3943
- var ROUTES_REGISTRY_FILE_FILTER = /[\\/]\.furin-routes-registry\.ts\?furin-virtual$/;
4025
+ var ROUTES_REGISTRY_FILE_FILTER = /[\\/]\.furin-routes-registry(?:-composable)?\.ts\?furin-virtual$/;
3944
4026
  var CLIENT_ROUTES_NAMESPACE = "furin-routes-client";
3945
4027
  var CLIENT_ROUTES_FILTER = /^(?:@teyik0\/furin|furin)\/routes$/;
3946
4028
  var SERVER_ROUTES_FILTER = /^(?:@teyik0\/furin|furin)\/routes\?instance=.+$/;
@@ -3951,11 +4033,14 @@ var DEV_ROUTES_APPS_SYMBOL = Symbol.for("@teyik0/furin/dev-routes-apps");
3951
4033
  var DEV_ROUTE_WATCHERS_SYMBOL = Symbol.for("@teyik0/furin/dev-route-watchers");
3952
4034
  var devInstancesBySpecifier = new Map;
3953
4035
  function instanceKey(instance) {
3954
- return `${resolve2(instance.pagesDir)}\x00${instance.prefix}`;
4036
+ return `${resolve3(instance.pagesDir)}\x00${instance.prefix}`;
3955
4037
  }
3956
4038
  function routeModuleSpecifier(instance) {
3957
4039
  return `@teyik0/furin/routes?instance=${Bun.hash(instanceKey(instance)).toString(16)}`;
3958
4040
  }
4041
+ function composableRouteModuleSpecifier(instance) {
4042
+ return `${routeModuleSpecifier(instance)}&composable`;
4043
+ }
3959
4044
  function instanceNamespace(instance) {
3960
4045
  return `${ROUTES_NAMESPACE_PREFIX}-${Bun.hash(instanceKey(instance)).toString(16)}`;
3961
4046
  }
@@ -4062,9 +4147,9 @@ function collectRouteFiles(root) {
4062
4147
  }
4063
4148
  function routeSourcePaths(instance) {
4064
4149
  const instanceId = Bun.hash(instanceKey(instance)).toString(16);
4065
- return collectRouteFiles(buildRouteTree(instance.pagesDir, instanceId)).map(({ sourcePath }) => resolve2(sourcePath)).toSorted((left, right) => left.localeCompare(right));
4150
+ return collectRouteFiles(buildRouteTree(instance.pagesDir, instanceId)).map(({ sourcePath }) => resolve3(sourcePath)).toSorted((left, right) => left.localeCompare(right));
4066
4151
  }
4067
- function emitRouteNode(node, indentation) {
4152
+ function emitRouteNode(node, indentation, includeRootCatchAll) {
4068
4153
  const childIndentation = `${indentation} `;
4069
4154
  const prefix = node.name ? `/${segmentPath(node.name)}` : "";
4070
4155
  const head = `new Elysia({ prefix: ${JSON.stringify(prefix)} })`;
@@ -4072,13 +4157,13 @@ function emitRouteNode(node, indentation) {
4072
4157
  if (node.indexRoute) {
4073
4158
  content.push(`${childIndentation}.use(new Elysia({ prefix: "" }).use(${node.indexRoute.id}.elysia))`);
4074
4159
  }
4075
- for (const route of node.fileRoutes) {
4160
+ for (const route of node.fileRoutes.filter((file) => includeRootCatchAll || file.path !== "/*")) {
4076
4161
  const segment = route.path.slice(route.path.lastIndexOf("/") + 1);
4077
4162
  content.push(`${childIndentation}.use(new Elysia({ prefix: ${JSON.stringify(`/${segment}`)} }).use(${route.id}.elysia))`);
4078
4163
  }
4079
4164
  for (const child of node.children) {
4080
4165
  content.push(`${childIndentation}.use(`);
4081
- content.push(emitRouteNode(child, `${childIndentation} `));
4166
+ content.push(emitRouteNode(child, `${childIndentation} `, includeRootCatchAll));
4082
4167
  content.push(`${childIndentation})`);
4083
4168
  }
4084
4169
  if (node.layout) {
@@ -4111,28 +4196,28 @@ async function retainComposableRoutes(node) {
4111
4196
  node.fileRoutes = composableRoutes;
4112
4197
  await Promise.all(node.children.map((child) => retainComposableRoutes(child)));
4113
4198
  }
4114
- async function generateServerInstance(instance, routeFilesBySpecifier) {
4199
+ async function generateServerInstance(instance, routeFilesBySpecifier, materialized, includeRootCatchAll) {
4115
4200
  const instanceId = Bun.hash(instanceKey(instance)).toString(16);
4116
4201
  const tree = buildRouteTree(instance.pagesDir, instanceId);
4117
4202
  await retainComposableRoutes(tree);
4118
4203
  const imports = collectRouteFiles(tree).sort((left, right) => left.sourcePath.localeCompare(right.sourcePath)).map((route) => {
4119
- const specifier = routeFileSpecifier(route);
4204
+ const specifier = materialized ? resolve3(route.sourcePath).replaceAll("\\", "/") : routeFileSpecifier(route);
4120
4205
  routeFilesBySpecifier.set(specifier, {
4121
4206
  routePath: route.path,
4122
- sourcePath: resolve2(route.sourcePath)
4207
+ sourcePath: resolve3(route.sourcePath)
4123
4208
  });
4124
4209
  return `import { route as ${route.id} } from ${JSON.stringify(specifier)};`;
4125
4210
  }).join(`
4126
4211
  `);
4127
4212
  return {
4128
- appExpression: emitRouteNode(tree, ""),
4213
+ appExpression: emitRouteNode(tree, "", includeRootCatchAll),
4129
4214
  exportName: `furinApp_${instanceId}`,
4130
4215
  imports
4131
4216
  };
4132
4217
  }
4133
- async function serverRegistrySource(instances, routeFilesBySpecifier) {
4218
+ async function serverRegistrySource(instances, routeFilesBySpecifier, materialized, includeRootCatchAll) {
4134
4219
  routeFilesBySpecifier.clear();
4135
- const generated = await Promise.all(instances.map((instance) => generateServerInstance(instance, routeFilesBySpecifier)));
4220
+ const generated = await Promise.all(instances.map((instance) => generateServerInstance(instance, routeFilesBySpecifier, materialized, includeRootCatchAll)));
4136
4221
  return `import { Elysia } from "elysia";
4137
4222
  ${generated.map(({ imports }) => imports).join(`
4138
4223
  `)}
@@ -4141,6 +4226,15 @@ ${generated.map(({ appExpression, exportName }) => `export const ${exportName} =
4141
4226
  `)}
4142
4227
  `;
4143
4228
  }
4229
+ async function materializedRouteModuleSource(instance) {
4230
+ const routeFilesBySpecifier = new Map;
4231
+ const source = await serverRegistrySource([instance], routeFilesBySpecifier, true, false);
4232
+ await validateRouteModules(routeFilesBySpecifier.values());
4233
+ const exportName = `furinApp_${Bun.hash(instanceKey(instance)).toString(16)}`;
4234
+ return `${source}
4235
+ export { ${exportName} as furinApp };
4236
+ `;
4237
+ }
4144
4238
  function validateRouteParams(path, schemas) {
4145
4239
  const pathParams = path.split("/").filter((segment) => segment === "*" || segment.startsWith(":")).map((segment) => segment === "*" ? segment : segment.slice(1));
4146
4240
  if (pathParams.length === 0) {
@@ -4163,13 +4257,13 @@ function routeModuleCache() {
4163
4257
  return cache;
4164
4258
  }
4165
4259
  function findPackageRoot(sourcePath) {
4166
- const fallback = dirname3(sourcePath);
4260
+ const fallback = dirname4(sourcePath);
4167
4261
  let directory = fallback;
4168
- while (dirname3(directory) !== directory) {
4262
+ while (dirname4(directory) !== directory) {
4169
4263
  if (existsSync4(join4(directory, "package.json"))) {
4170
4264
  return directory;
4171
4265
  }
4172
- directory = dirname3(directory);
4266
+ directory = dirname4(directory);
4173
4267
  }
4174
4268
  return existsSync4(join4(directory, "package.json")) ? directory : fallback;
4175
4269
  }
@@ -4192,7 +4286,7 @@ function resolveRouteModuleImports(dependencyPath, packageRoot) {
4192
4286
  continue;
4193
4287
  }
4194
4288
  try {
4195
- const resolvedImport = realpathSync(Bun.resolveSync(imported.path, dirname3(dependencyPath)));
4289
+ const resolvedImport = realpathSync(Bun.resolveSync(imported.path, dirname4(dependencyPath)));
4196
4290
  if (isAbsolute(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot)) {
4197
4291
  resolvedImports.push(resolvedImport);
4198
4292
  }
@@ -4282,18 +4376,30 @@ function primaryInstance(instances) {
4282
4376
  }
4283
4377
  return instance;
4284
4378
  }
4285
- function serverProxySource(instance) {
4379
+ function serverProxySource(instance, includeRootCatchAll) {
4286
4380
  const exportName = `furinApp_${Bun.hash(instanceKey(instance)).toString(16)}`;
4287
- return `export { ${exportName} as furinApp } from ${JSON.stringify(ROUTES_REGISTRY_SPECIFIER)};
4381
+ const registry = includeRootCatchAll ? ROUTES_REGISTRY_SPECIFIER : COMPOSABLE_ROUTES_REGISTRY_SPECIFIER;
4382
+ return `export { ${exportName} as furinApp } from ${JSON.stringify(registry)};
4288
4383
  `;
4289
4384
  }
4290
4385
  function createRoutesPlugin(options) {
4291
4386
  const routeFilesBySpecifier = new Map;
4292
4387
  const routeFilesByResolvedPath = new Map;
4293
- const registryVirtualPath = join4(resolve2(primaryInstance(options.instances).pagesDir), ".furin-routes-registry.ts?furin-virtual");
4294
- const instancesBySpecifier = new Map(options.instances.map((instance) => [
4295
- routeModuleSpecifier(instance),
4296
- { instance, namespace: instanceNamespace(instance) }
4388
+ const registryVirtualPath = join4(resolve3(primaryInstance(options.instances).pagesDir), ".furin-routes-registry.ts?furin-virtual");
4389
+ const composableRegistryVirtualPath = join4(resolve3(primaryInstance(options.instances).pagesDir), ".furin-routes-registry-composable.ts?furin-virtual");
4390
+ const instancesBySpecifier = new Map(options.instances.flatMap((instance) => [
4391
+ [
4392
+ routeModuleSpecifier(instance),
4393
+ { includeRootCatchAll: true, instance, namespace: instanceNamespace(instance) }
4394
+ ],
4395
+ [
4396
+ composableRouteModuleSpecifier(instance),
4397
+ {
4398
+ includeRootCatchAll: false,
4399
+ instance,
4400
+ namespace: `${instanceNamespace(instance)}-composable`
4401
+ }
4402
+ ]
4297
4403
  ]));
4298
4404
  return {
4299
4405
  name: `furin-routes-${options.target}`,
@@ -4314,12 +4420,12 @@ function createRoutesPlugin(options) {
4314
4420
  }
4315
4421
  return { namespace: registered.namespace, path };
4316
4422
  });
4317
- build.onResolve({ filter: ROUTES_REGISTRY_FILTER }, () => ({
4423
+ build.onResolve({ filter: ROUTES_REGISTRY_FILTER }, ({ path }) => ({
4318
4424
  namespace: "file",
4319
- path: registryVirtualPath
4425
+ path: path === ROUTES_REGISTRY_SPECIFIER ? registryVirtualPath : composableRegistryVirtualPath
4320
4426
  }));
4321
- build.onLoad({ filter: ROUTES_REGISTRY_FILE_FILTER, namespace: "file" }, async () => {
4322
- const contents = await serverRegistrySource(options.instances, routeFilesBySpecifier);
4427
+ build.onLoad({ filter: ROUTES_REGISTRY_FILE_FILTER, namespace: "file" }, async ({ path }) => {
4428
+ const contents = await serverRegistrySource(options.instances, routeFilesBySpecifier, false, path === registryVirtualPath);
4323
4429
  await validateRouteModules(routeFilesBySpecifier.values());
4324
4430
  return { contents, loader: "ts" };
4325
4431
  });
@@ -4340,12 +4446,12 @@ function createRoutesPlugin(options) {
4340
4446
  return {
4341
4447
  contents: await Bun.file(routeFile.sourcePath).text(),
4342
4448
  loader: detectLoaderFromPath(routeFile.sourcePath),
4343
- resolveDir: dirname3(routeFile.sourcePath)
4449
+ resolveDir: dirname4(routeFile.sourcePath)
4344
4450
  };
4345
4451
  });
4346
- for (const { instance, namespace } of instancesBySpecifier.values()) {
4452
+ for (const { instance, namespace, includeRootCatchAll } of instancesBySpecifier.values()) {
4347
4453
  build.onLoad({ filter: VIRTUAL_ROUTES_FILTER, namespace }, () => ({
4348
- contents: serverProxySource(instance),
4454
+ contents: serverProxySource(instance, includeRootCatchAll),
4349
4455
  loader: "ts"
4350
4456
  }));
4351
4457
  }
@@ -4353,6 +4459,43 @@ function createRoutesPlugin(options) {
4353
4459
  };
4354
4460
  }
4355
4461
 
4462
+ // src/build/server-app-entry.ts
4463
+ async function materializeServerAppEntry(options) {
4464
+ ensureDir(options.outDir);
4465
+ const apps = await Promise.all(options.apps.map(async (app, index) => {
4466
+ const instance = options.instances[index];
4467
+ if (!instance) {
4468
+ throw new Error(`[furin] Missing route instance for server app ${index}.`);
4469
+ }
4470
+ const routePath = join5(options.outDir, `_furin-routes-${index}.ts`);
4471
+ writeFileSync(routePath, await materializedRouteModuleSource(instance));
4472
+ return { ...app, nativeRoutes: toPosixPath(routePath) };
4473
+ }));
4474
+ const entryPath = join5(options.outDir, "_furin-app.ts");
4475
+ writeFileSync(entryPath, buildEntrySource({
4476
+ apps,
4477
+ headerComment: options.headerComment,
4478
+ mode: "app",
4479
+ serverEntry: options.serverEntry
4480
+ }));
4481
+ return entryPath;
4482
+ }
4483
+ function serverBootSource(appEntry) {
4484
+ return `// Auto-generated by furin build - do not edit
4485
+ import app, { port, startServer } from ${JSON.stringify(toPosixPath(appEntry))};
4486
+
4487
+ if (typeof startServer === "function") {
4488
+ await startServer();
4489
+ } else if (app && typeof app.listen === "function" && !app.server) {
4490
+ const serverPort = process.env.PORT === undefined
4491
+ ? typeof port === "number" ? port : 3000
4492
+ : Number(process.env.PORT);
4493
+ app.listen(serverPort);
4494
+ console.log(\`[furin] Server running at http://localhost:\${app.server?.port}\`);
4495
+ }
4496
+ `;
4497
+ }
4498
+
4356
4499
  // ../../node_modules/.bun/magic-string@1.2.3/node_modules/magic-string/dist/index.mjs
4357
4500
  init_sourcemap_codec();
4358
4501
  var BitSet = class BitSet {
@@ -6808,13 +6951,13 @@ function assertNoPrefixSlugCollisions(prefixes) {
6808
6951
  }
6809
6952
 
6810
6953
  // src/adapter/runtime-build.ts
6811
- import { existsSync as existsSync8, writeFileSync as writeFileSync5 } from "fs";
6812
- import { basename as basename4, dirname as dirname6, join as join9, relative as relative5, resolve as resolve3 } from "path";
6954
+ import { existsSync as existsSync8, writeFileSync as writeFileSync6 } from "fs";
6955
+ import { basename as basename4, dirname as dirname8, isAbsolute as isAbsolute2, join as join10, relative as relative6, resolve as resolve5 } from "path";
6813
6956
  import { fileURLToPath as fileURLToPath5 } from "url";
6814
6957
 
6815
6958
  // src/build/client.ts
6816
- import { existsSync as existsSync7, mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "fs";
6817
- import { basename as basename2, dirname as dirname4, join as join7 } from "path";
6959
+ import { existsSync as existsSync7, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "fs";
6960
+ import { basename as basename2, dirname as dirname5, join as join8, resolve as resolve4 } from "path";
6818
6961
 
6819
6962
  // src/plugin/transform-client.ts
6820
6963
  var FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
@@ -7451,8 +7594,8 @@ if (import.meta.hot && route?.component) {
7451
7594
  }
7452
7595
 
7453
7596
  // src/build/hydrate.ts
7454
- import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
7455
- import { join as join6 } from "path";
7597
+ import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
7598
+ import { join as join7 } from "path";
7456
7599
 
7457
7600
  // src/server/render/shell.ts
7458
7601
  function escapeHtml(str) {
@@ -7506,8 +7649,8 @@ ${buildIdMeta}${modeMeta}${faviconLink}${cssLinks ? `${cssLinks}
7506
7649
  init_patterns();
7507
7650
 
7508
7651
  // src/build/route-types.ts
7509
- import { existsSync as existsSync5, readFileSync as readFileSync2, renameSync, writeFileSync } from "fs";
7510
- import { extname as extname2, join as join5, relative as relative4 } from "path";
7652
+ import { existsSync as existsSync5, readFileSync as readFileSync2, renameSync, writeFileSync as writeFileSync2 } from "fs";
7653
+ import { extname as extname2, join as join6, relative as relative4 } from "path";
7511
7654
 
7512
7655
  // src/shared/route-map.ts
7513
7656
  function routeTypeProperty(pattern) {
@@ -7573,13 +7716,13 @@ import "@teyik0/furin/routes";
7573
7716
 
7574
7717
  ${routeMapDeclaration(entries)}${tagBlock}
7575
7718
  `;
7576
- const typesPath = join5(projectRoot, "furin-env.d.ts");
7719
+ const typesPath = join6(projectRoot, "furin-env.d.ts");
7577
7720
  const existing = existsSync5(typesPath) ? readFileSync2(typesPath, "utf8") : "";
7578
7721
  if (content === existing) {
7579
7722
  return false;
7580
7723
  }
7581
7724
  const temporaryPath = `${typesPath}.${process.pid}.${Bun.nanoseconds()}.tmp`;
7582
- writeFileSync(temporaryPath, content);
7725
+ writeFileSync2(temporaryPath, content);
7583
7726
  renameSync(temporaryPath, typesPath);
7584
7727
  return true;
7585
7728
  }
@@ -7951,18 +8094,18 @@ function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging, sk
7951
8094
  mkdirSync2(outDir, { recursive: true });
7952
8095
  }
7953
8096
  const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
7954
- const hydratePath = join6(outDir, "_hydrate.tsx");
8097
+ const hydratePath = join7(outDir, "_hydrate.tsx");
7955
8098
  const existingHydrate = existsSync6(hydratePath) ? readFileSync3(hydratePath, "utf8") : "";
7956
8099
  let changed = false;
7957
8100
  if (hydrateCode !== existingHydrate) {
7958
- writeFileSync2(hydratePath, hydrateCode);
8101
+ writeFileSync3(hydratePath, hydrateCode);
7959
8102
  changed = true;
7960
8103
  }
7961
8104
  const indexHtml = generateIndexHtml();
7962
- const indexPath = join6(outDir, "index.html");
8105
+ const indexPath = join7(outDir, "index.html");
7963
8106
  const existingIndex = existsSync6(indexPath) ? readFileSync3(indexPath, "utf8") : "";
7964
8107
  if (indexHtml !== existingIndex) {
7965
- writeFileSync2(indexPath, indexHtml);
8108
+ writeFileSync3(indexPath, indexHtml);
7966
8109
  changed = true;
7967
8110
  }
7968
8111
  if (!skipRouteTypes) {
@@ -7975,6 +8118,7 @@ function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging, sk
7975
8118
 
7976
8119
  // src/build/client.ts
7977
8120
  var SCRIPT_FILE_FILTER2 = /\.(tsx?|jsx?)$/;
8121
+ var ROUTER_PROVIDER_PATH = resolve4(import.meta.dir, "../client/router/provider.tsx");
7978
8122
  function resolveClientModuleSpecifiers(code) {
7979
8123
  return code.replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH)).replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH)).replaceAll(`"@teyik0/furin/search"`, JSON.stringify(SEARCH_MODULE_PATH)).replaceAll(`'furin/search'`, JSON.stringify(SEARCH_MODULE_PATH));
7980
8124
  }
@@ -7992,7 +8136,7 @@ async function buildClient(routes, {
7992
8136
  pagesDir
7993
8137
  }) {
7994
8138
  const dirName = clientDirName ?? "client";
7995
- const clientDir = join7(outDir, dirName);
8139
+ const clientDir = join8(outDir, dirName);
7996
8140
  if (!existsSync7(outDir)) {
7997
8141
  mkdirSync3(outDir, { recursive: true });
7998
8142
  }
@@ -8000,7 +8144,7 @@ async function buildClient(routes, {
8000
8144
  mkdirSync3(clientDir, { recursive: true });
8001
8145
  }
8002
8146
  const hydrateCode = resolveClientModuleSpecifiers(generateHydrateEntry(routes, rootLayout, basePath, clientLogging));
8003
- const hydratePath = join7(outDir, dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`);
8147
+ const hydratePath = join8(outDir, dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`);
8004
8148
  const hydrateEntry = createVirtualBuildEntry(hydratePath, hydrateCode, "tsx");
8005
8149
  console.log("[furin] Building production client bundle\u2026");
8006
8150
  const transformPlugin = {
@@ -8021,6 +8165,20 @@ async function buildClient(routes, {
8021
8165
  });
8022
8166
  }
8023
8167
  };
8168
+ const routerLoggerPlugin = {
8169
+ name: "furin-client-router-logger",
8170
+ setup(build) {
8171
+ build.onResolve({ filter: /^evlog$/ }, ({ importer }) => {
8172
+ if (importer === ROUTER_PROVIDER_PATH) {
8173
+ return { namespace: "furin-client-router-logger", path: "router-logger" };
8174
+ }
8175
+ });
8176
+ build.onLoad({ filter: /.*/, namespace: "furin-client-router-logger" }, () => ({
8177
+ contents: "export const log = { warn: console.warn, error: console.error };",
8178
+ loader: "js"
8179
+ }));
8180
+ }
8181
+ };
8024
8182
  const clientBuildConfig = {
8025
8183
  entrypoints: [hydrateEntry.entrypoint],
8026
8184
  files: hydrateEntry.files,
@@ -8042,6 +8200,7 @@ async function buildClient(routes, {
8042
8200
  plugins: [
8043
8201
  hydrateEntry.plugin,
8044
8202
  ...plugins ?? [],
8203
+ ...!clientLogging ? [routerLoggerPlugin] : [],
8045
8204
  ...pagesDir ? [createRoutesPlugin({ instances: [{ pagesDir, prefix: basePath }], target: "client" })] : [],
8046
8205
  environmentGuardPlugin("client"),
8047
8206
  transformPlugin
@@ -8060,8 +8219,8 @@ async function buildClient(routes, {
8060
8219
  if (result.metafile === undefined) {
8061
8220
  throw new Error("[furin] client build did not produce the requested metafile");
8062
8221
  }
8063
- mkdirSync3(dirname4(metafilePath), { recursive: true });
8064
- writeFileSync3(metafilePath, `${JSON.stringify(result.metafile, null, 2)}
8222
+ mkdirSync3(dirname5(metafilePath), { recursive: true });
8223
+ writeFileSync4(metafilePath, `${JSON.stringify(result.metafile, null, 2)}
8065
8224
  `);
8066
8225
  console.log(`[furin] Client metafile: ${metafilePath}`);
8067
8226
  }
@@ -10271,7 +10430,7 @@ var FRAME_VERSION = 3;
10271
10430
  var MAX_FRAME_BYTES = 1024 * 1024;
10272
10431
  var MAX_ROUTE_FRAME_STREAM_BYTES = 8 * 1024 * 1024;
10273
10432
  var RSC_DESCRIPTOR = "__furinRsc";
10274
- function isPlainObject3(value) {
10433
+ function isPlainObject4(value) {
10275
10434
  const prototype = Object.getPrototypeOf(value);
10276
10435
  return prototype === Object.prototype || prototype === null;
10277
10436
  }
@@ -10300,7 +10459,7 @@ function extractRscSources(value, sources, seen, idPrefix) {
10300
10459
  }
10301
10460
  return result;
10302
10461
  }
10303
- if (!isPlainObject3(value)) {
10462
+ if (!isPlainObject4(value)) {
10304
10463
  return value;
10305
10464
  }
10306
10465
  const result = {};
@@ -10380,7 +10539,7 @@ function containsRscSourceInner(value, seen) {
10380
10539
  if (Array.isArray(value)) {
10381
10540
  return value.some((entry) => containsRscSourceInner(entry, seen));
10382
10541
  }
10383
- return isPlainObject3(value) && Object.values(value).some((entry) => containsRscSourceInner(entry, seen));
10542
+ return isPlainObject4(value) && Object.values(value).some((entry) => containsRscSourceInner(entry, seen));
10384
10543
  }
10385
10544
  function serializeRouteFrames(data, deferredKeys) {
10386
10545
  const sources = [];
@@ -11284,13 +11443,17 @@ function injectInstrumentationClient(html, prefix) {
11284
11443
  var REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
11285
11444
  var FURIN_RESERVED_KEY_PREFIX = "__furin";
11286
11445
  var ROUTE_CTX_RESERVED_KEYS = new Set([
11446
+ "catch",
11287
11447
  "children",
11448
+ "finally",
11288
11449
  "key",
11289
11450
  "params",
11290
11451
  "path",
11291
11452
  "query",
11292
11453
  "ref",
11293
- "requestData"
11454
+ "requestData",
11455
+ "then",
11456
+ "toJSON"
11294
11457
  ]);
11295
11458
  function assertPublicLoaderKey(key) {
11296
11459
  if (key.startsWith(FURIN_RESERVED_KEY_PREFIX)) {
@@ -11324,7 +11487,7 @@ function createLoaderCtx(ctx, accumulatedParentPromise) {
11324
11487
  if (prop === "then" || prop === "catch" || prop === "finally" || prop === "toJSON") {
11325
11488
  return Reflect.get(target, prop);
11326
11489
  }
11327
- if (Object.hasOwn(target, prop)) {
11490
+ if (Object.hasOwn(target, prop) || prop in target && !Object.hasOwn(Object.prototype, prop)) {
11328
11491
  return target[prop];
11329
11492
  }
11330
11493
  let entry = cache.get(prop);
@@ -11366,7 +11529,7 @@ function createRequestLoaderContext(ctx) {
11366
11529
  get: (name) => headers.get(name),
11367
11530
  has: (name) => headers.has(name)
11368
11531
  }),
11369
- log: useLogger3(),
11532
+ log: getLogger(),
11370
11533
  params: ctx.params,
11371
11534
  path: ctx.path,
11372
11535
  query: ctx.query,
@@ -11491,7 +11654,7 @@ async function normalizeLoaderError(err, headers) {
11491
11654
  return { error: err, headers, message, status, type: "error" };
11492
11655
  }
11493
11656
  if (isFurinRscRenderError(err)) {
11494
- useLogger3().error(err);
11657
+ getLogger().error(err);
11495
11658
  return {
11496
11659
  error: err,
11497
11660
  headers,
@@ -11511,7 +11674,7 @@ async function normalizeLoaderError(err, headers) {
11511
11674
  async function runLoadersInternal(route, ctx, includeRequestData) {
11512
11675
  try {
11513
11676
  const requestData = includeRequestData ? runRequestLoaderData(route, ctx) : undefined;
11514
- const ctxRecord = includeRequestData ? { ...ctx, log: useLogger3() } : createPublicLoaderContext(ctx);
11677
+ const ctxRecord = includeRequestData ? Object.assign(Object.create(Object.getPrototypeOf(ctx)), ctx, { log: getLogger() }) : createPublicLoaderContext(ctx);
11515
11678
  const loaderMap = new Map;
11516
11679
  let accumulatedParentPromise = Promise.resolve({});
11517
11680
  let loaderIndex = 0;
@@ -11526,7 +11689,7 @@ async function runLoadersInternal(route, ctx, includeRequestData) {
11526
11689
  if (IS_DEV) {
11527
11690
  for (const key of Object.keys(own)) {
11528
11691
  if (Object.hasOwn(acc, key)) {
11529
- useLogger3().warn(`[furin] Loader data collision on "${key}" for ${ctx.path}: a deeper loader overwrites the value inherited from its layout chain (deepest wins).`);
11692
+ getLogger().warn(`[furin] Loader data collision on "${key}" for ${ctx.path}: a deeper loader overwrites the value inherited from its layout chain (deepest wins).`);
11530
11693
  }
11531
11694
  }
11532
11695
  }
@@ -11570,7 +11733,7 @@ function createPublicLoaderContext(ctx) {
11570
11733
  Object.defineProperties(publicContext, {
11571
11734
  cookie: { enumerable: true, get: fail },
11572
11735
  headers: { enumerable: true, get: fail },
11573
- log: { enumerable: true, value: useLogger3() },
11736
+ log: { enumerable: true, value: getLogger() },
11574
11737
  params: { enumerable: true, value: ctx.params },
11575
11738
  path: { enumerable: true, value: ctx.path },
11576
11739
  query: { enumerable: true, value: ctx.query },
@@ -11988,7 +12151,7 @@ function renderForPath(route, params, root, origin, mode, basePath, searchRoutes
11988
12151
  if (prepared instanceof Response) {
11989
12152
  return prepared;
11990
12153
  }
11991
- useLogger3().set({
12154
+ getLogger().set({
11992
12155
  furin: {
11993
12156
  cache: mode === "isr" ? "revalidated" : "miss",
11994
12157
  loader_ms: prepared.loader_ms,
@@ -12022,6 +12185,118 @@ async function serializeLoaderDataNdjson(syncData, deferredPromises) {
12022
12185
  `;
12023
12186
  }
12024
12187
 
12188
+ // src/server/render/static-params.ts
12189
+ import { dirname as dirname7, relative as relative5 } from "path";
12190
+ init_patterns();
12191
+ var STATIC_PARAMS_CONCURRENCY = 4;
12192
+ function collectStaticParamsStages(route) {
12193
+ const stages = [];
12194
+ for (const [index, entry] of route.routeChain.entries()) {
12195
+ if (entry.staticParams) {
12196
+ stages.push({ ancestors: route.routeChain.slice(0, index), run: entry.staticParams });
12197
+ }
12198
+ }
12199
+ if (route.page.staticParams) {
12200
+ stages.push({ ancestors: route.routeChain, run: route.page.staticParams });
12201
+ }
12202
+ return stages;
12203
+ }
12204
+ function ancestorPattern(route, ancestors) {
12205
+ const rootSourcePath = route.routeChain[0]?.sourcePath;
12206
+ const ancestorSourcePath = ancestors.at(-1)?.sourcePath;
12207
+ if (rootSourcePath === undefined || ancestorSourcePath === undefined) {
12208
+ return route.pattern;
12209
+ }
12210
+ const pagesDir = dirname7(rootSourcePath);
12211
+ const ancestorDir = dirname7(ancestorSourcePath);
12212
+ if (ancestorDir === pagesDir) {
12213
+ return "/";
12214
+ }
12215
+ return filePathToPattern(`${relative5(pagesDir, ancestorDir)}/index.tsx`);
12216
+ }
12217
+ function createBuildContext(pattern, params, origin) {
12218
+ const path = resolvePath(pattern, params);
12219
+ return {
12220
+ cookie: {},
12221
+ headers: {},
12222
+ params,
12223
+ path,
12224
+ query: {},
12225
+ redirect: (url, status) => new Response(null, { headers: { Location: url }, status: status ?? 302 }),
12226
+ request: new Request(new URL(path, origin)),
12227
+ set: { headers: {} }
12228
+ };
12229
+ }
12230
+ async function runAncestorLoaders(route, ancestors, params, origin) {
12231
+ const pattern = ancestorPattern(route, ancestors);
12232
+ const result = await runPublicLoaders({
12233
+ ...route,
12234
+ page: { ...route.page, loader: undefined },
12235
+ pattern,
12236
+ routeChain: ancestors
12237
+ }, createBuildContext(pattern, params, origin));
12238
+ if (result.type === "redirect") {
12239
+ throw result.response;
12240
+ }
12241
+ if (result.type === "not-found") {
12242
+ throw result.error;
12243
+ }
12244
+ if (result.type === "error") {
12245
+ throw result.error;
12246
+ }
12247
+ const data = {};
12248
+ for (const [key, value] of Object.entries(result.syncData)) {
12249
+ if (key !== "params" && key !== "path" && key !== "query") {
12250
+ data[key] = value;
12251
+ }
12252
+ }
12253
+ Object.assign(data, result.deferredPromises);
12254
+ return data;
12255
+ }
12256
+ function createStaticParamsContext(route, ancestors, params, origin) {
12257
+ const target = { params };
12258
+ const fields = new Map;
12259
+ let parentData;
12260
+ return new Proxy(target, {
12261
+ get(context, property) {
12262
+ if (typeof property !== "string" || Object.hasOwn(context, property)) {
12263
+ return Reflect.get(context, property);
12264
+ }
12265
+ if (property === "then" || property === "catch" || property === "finally" || property === "toJSON") {
12266
+ return;
12267
+ }
12268
+ let field = fields.get(property);
12269
+ if (!field) {
12270
+ parentData ??= runAncestorLoaders(route, ancestors, params, origin);
12271
+ field = parentData.then((data) => data[property]);
12272
+ fields.set(property, field);
12273
+ }
12274
+ return field;
12275
+ }
12276
+ });
12277
+ }
12278
+ function hasStaticParams(route) {
12279
+ return route.page.staticParams !== undefined || route.routeChain.some((entry) => entry.staticParams !== undefined);
12280
+ }
12281
+ async function resolveStaticParams(route, origin) {
12282
+ const stages = collectStaticParamsStages(route);
12283
+ if (stages.length === 0) {
12284
+ return;
12285
+ }
12286
+ let branches = [{}];
12287
+ for (const stage of stages) {
12288
+ const branchValues = await mapWithConcurrency(branches, STATIC_PARAMS_CONCURRENCY, async (params) => {
12289
+ const values = await stage.run(createStaticParamsContext(route, stage.ancestors, params, origin));
12290
+ if (!Array.isArray(values)) {
12291
+ throw new TypeError(`[furin] staticParams() for "${route.pattern}" must return an array.`);
12292
+ }
12293
+ return values.map((value) => ({ ...params, ...value }));
12294
+ });
12295
+ branches = branchValues.flat();
12296
+ }
12297
+ return branches;
12298
+ }
12299
+
12025
12300
  // src/server/render/ssg.ts
12026
12301
  async function prerenderRoute(route, params, root, origin, mode, basePath, searchRoutes, requestContext) {
12027
12302
  const renderResult = await renderForPath(route, params, root, origin, mode, basePath, searchRoutes, undefined, requestContext);
@@ -12074,12 +12349,8 @@ async function buildRoutePrerenders(routes, root, origin, basePath) {
12074
12349
  let paramSets;
12075
12350
  if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
12076
12351
  paramSets = [{}];
12077
- } else if (route.page.staticParams) {
12078
- const resolvedParams = await route.page.staticParams();
12079
- if (!Array.isArray(resolvedParams)) {
12080
- throw new TypeError(`[furin] staticParams() for "${route.pattern}" must return an array.`);
12081
- }
12082
- paramSets = resolvedParams;
12352
+ } else if (hasStaticParams(route)) {
12353
+ paramSets = await resolveStaticParams(route, origin) ?? [];
12083
12354
  } else {
12084
12355
  continue;
12085
12356
  }
@@ -12102,10 +12373,10 @@ async function buildSSGCacheSnapshot(routes, root, origin, basePath) {
12102
12373
  const snapshot = {};
12103
12374
  const searchRoutes = createSearchRouteMetadata(routes);
12104
12375
  for (const route of routes) {
12105
- if (route.mode !== "ssg" || !route.page.staticParams || hasRequestLoader(route)) {
12376
+ if (route.mode !== "ssg" || !hasStaticParams(route) || hasRequestLoader(route)) {
12106
12377
  continue;
12107
12378
  }
12108
- const paramSets = await route.page.staticParams();
12379
+ const paramSets = await resolveStaticParams(route, origin) ?? [];
12109
12380
  for (const params of paramSets) {
12110
12381
  const result = await prerenderSSG(route, params, root, origin, basePath, searchRoutes);
12111
12382
  if (!(result instanceof Response)) {
@@ -12117,8 +12388,8 @@ async function buildSSGCacheSnapshot(routes, root, origin, basePath) {
12117
12388
  }
12118
12389
 
12119
12390
  // src/rsc/build/index.ts
12120
- import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync4 } from "fs";
12121
- import { basename as basename3, join as join8 } from "path";
12391
+ import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync5 } from "fs";
12392
+ import { basename as basename3, join as join9 } from "path";
12122
12393
  import { fileURLToPath as fileURLToPath4 } from "url";
12123
12394
 
12124
12395
  // src/rsc/version.ts
@@ -12166,7 +12437,7 @@ function assertInstalledRscVersions() {
12166
12437
  // src/rsc/build/index.ts
12167
12438
  async function buildRscGraph(apps, outDir, buildId, userPlugins) {
12168
12439
  await assertInstalledRscVersions();
12169
- const graphDir = join8(outDir, "rsc");
12440
+ const graphDir = join9(outDir, "rsc");
12170
12441
  mkdirSync4(graphDir, { recursive: true });
12171
12442
  const rscEntry = fileURLToPath4(import.meta.resolve("../../rsc-server.tsx"));
12172
12443
  const entrypoints = [
@@ -12228,13 +12499,13 @@ ${codecResult.logs.map((log) => log.message).join(`
12228
12499
  }
12229
12500
  const css = result.outputs.filter((output) => output.path.endsWith(".css")).map((output) => ({ href: `/_rsc/${basename3(output.path)}` }));
12230
12501
  const manifest = { buildId, clientReferences: [], css };
12231
- writeFileSync4(join8(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
12502
+ writeFileSync5(join9(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
12232
12503
  return manifest;
12233
12504
  }
12234
12505
 
12235
12506
  // src/adapter/runtime-build.ts
12236
- var _pkgRoot2 = dirname6(dirname6(fileURLToPath5(import.meta.resolve("@teyik0/furin"))));
12237
- var _pkgSrcDir2 = existsSync8(join9(_pkgRoot2, "src", "furin.ts")) ? join9(_pkgRoot2, "src") : join9(_pkgRoot2, "dist");
12507
+ var _pkgRoot2 = dirname8(dirname8(fileURLToPath5(import.meta.resolve("@teyik0/furin"))));
12508
+ var _pkgSrcDir2 = existsSync8(join10(_pkgRoot2, "src", "furin.ts")) ? join10(_pkgRoot2, "src") : join10(_pkgRoot2, "dist");
12238
12509
  var _ext2 = ".ts";
12239
12510
  var PPR_ROUTE_IMPORT_RE = /ppr-route(?:\.ts)?$/;
12240
12511
  var ANY_MODULE_RE = /.*/;
@@ -12312,12 +12583,12 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
12312
12583
  `);
12313
12584
  }
12314
12585
  function stableFingerprintPath(path, projectRoot) {
12315
- const projectPath = relative5(projectRoot, path);
12316
- if (projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
12586
+ const projectPath = relative6(projectRoot, path);
12587
+ if (!isAbsolute2(projectPath) && projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
12317
12588
  return `app/${toPosixPath(projectPath)}`;
12318
12589
  }
12319
- const frameworkPath = relative5(_pkgRoot2, path);
12320
- if (frameworkPath !== ".." && !frameworkPath.startsWith("../") && !frameworkPath.startsWith("..\\")) {
12590
+ const frameworkPath = relative6(_pkgRoot2, path);
12591
+ if (!isAbsolute2(frameworkPath) && frameworkPath !== ".." && !frameworkPath.startsWith("../") && !frameworkPath.startsWith("..\\")) {
12321
12592
  return `furin/${toPosixPath(frameworkPath)}`;
12322
12593
  }
12323
12594
  return `external/${basename4(path)}`;
@@ -12342,7 +12613,7 @@ function buildCompileMetadata(root, routes) {
12342
12613
  }
12343
12614
  function pprRuntimePlugin(apps) {
12344
12615
  const enabled = apps.some((app) => app.routes.some((route) => route.mode !== "ssr" && (app.root.route.requestLoader !== undefined || hasRequestLoader(route))));
12345
- const pprPath = resolve3(_pkgSrcDir2, "server/render/ppr-route.ts");
12616
+ const pprPath = resolve5(_pkgSrcDir2, "server/render/ppr-route.ts");
12346
12617
  const reactServerPath = fileURLToPath5(import.meta.resolve(enabled ? "react-dom/server.edge" : "react-dom/server"));
12347
12618
  const reactStaticPath = fileURLToPath5(import.meta.resolve("react-dom/static.edge"));
12348
12619
  return {
@@ -12354,7 +12625,7 @@ function pprRuntimePlugin(apps) {
12354
12625
  return;
12355
12626
  }
12356
12627
  build.onResolve({ filter: PPR_ROUTE_IMPORT_RE }, ({ path, importer }) => {
12357
- const absolute = resolve3(dirname6(importer.split("?")[0]), path);
12628
+ const absolute = resolve5(dirname8(importer.split("?")[0]), path);
12358
12629
  if (absolute !== pprPath && `${absolute}.ts` !== pprPath) {
12359
12630
  return;
12360
12631
  }
@@ -12374,7 +12645,7 @@ function isFrameworkRuntimeImporter(importer) {
12374
12645
  if (importer === "") {
12375
12646
  return false;
12376
12647
  }
12377
- const fromRuntimeRoot = relative5(_pkgSrcDir2, importer.split("?")[0]);
12648
+ const fromRuntimeRoot = relative6(_pkgSrcDir2, importer.split("?")[0]);
12378
12649
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
12379
12650
  }
12380
12651
  async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options, targetName) {
@@ -12386,7 +12657,7 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
12386
12657
  basePath: prefix,
12387
12658
  clientDirName,
12388
12659
  clientLogging: options.clientLogging ?? false,
12389
- metafilePath: options.analyze ? join9(dirname6(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
12660
+ metafilePath: options.analyze ? join10(dirname8(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
12390
12661
  optimizeImports: options.optimizeImports,
12391
12662
  outDir: targetDir,
12392
12663
  pagesDir: app.pagesDir,
@@ -12398,9 +12669,9 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
12398
12669
  const buildFingerprint = await createBuildFingerprint(`${prefix}
12399
12670
  ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
12400
12671
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
12401
- const clientDir = join9(targetDir, clientDirName);
12672
+ const clientDir = join10(targetDir, clientDirName);
12402
12673
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
12403
- writeFileSync5(join9(clientDir, "index.html"), indexHtml);
12674
+ writeFileSync6(join10(clientDir, "index.html"), indexHtml);
12404
12675
  setProductionTemplateContent(indexHtml);
12405
12676
  ssgRouteCache().clear();
12406
12677
  let ssgCache;
@@ -12420,9 +12691,10 @@ ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
12420
12691
  entryApp: {
12421
12692
  buildId,
12422
12693
  clientLogging: options.clientLogging ?? false,
12694
+ deploymentTarget: targetName === "vercel" ? "vercel" : undefined,
12423
12695
  embed: options.compile === "embed" ? { clientDir } : undefined,
12424
12696
  modulePaths,
12425
- nativeRoutes: routeModuleSpecifier(app),
12697
+ nativeRoutes: composableRouteModuleSpecifier(app),
12426
12698
  prefix,
12427
12699
  rootConventions,
12428
12700
  rootPath: root.path,
@@ -12457,15 +12729,10 @@ async function buildRuntimeAppsSequentially(apps, projectRoot, targetDir, server
12457
12729
  }
12458
12730
 
12459
12731
  // src/adapter/bun.ts
12460
- function generateDiskEntry(options) {
12461
- ensureDir(options.outDir);
12462
- const source = buildEntrySource({
12463
- apps: options.apps.map(({ embed: _embed, ...context }) => context),
12464
- headerComment: "// Auto-generated by furin build - do not edit",
12465
- serverEntry: options.serverEntry
12466
- });
12467
- const entryPath = join10(options.outDir, "server.ts");
12468
- return createVirtualBuildEntry(entryPath, source, "ts");
12732
+ function generateBootEntry(appEntry, outDir, filename) {
12733
+ ensureDir(outDir);
12734
+ const entryPath = join11(outDir, filename);
12735
+ return createVirtualBuildEntry(entryPath, serverBootSource(appEntry), "ts");
12469
12736
  }
12470
12737
  function collectEmbeddedAssets(entryApps, publicDir, compile) {
12471
12738
  if (compile !== "embed") {
@@ -12477,6 +12744,34 @@ function collectEmbeddedAssets(entryApps, publicDir, compile) {
12477
12744
  }
12478
12745
  return assets;
12479
12746
  }
12747
+ function compiledServerFilename(platform) {
12748
+ return platform === "win32" ? "server.exe" : "server";
12749
+ }
12750
+ async function createBunAppEntry(apps, entryApps, options, publicDir, serverEntry, targetDir) {
12751
+ if (!serverEntry) {
12752
+ return;
12753
+ }
12754
+ const contexts = options.compile ? prepareCompileEntryApps({
12755
+ apps: entryApps,
12756
+ outDir: targetDir,
12757
+ publicDir,
12758
+ serverEntry
12759
+ }) : entryApps.map(({ embed: _embed, ...context }) => ({
12760
+ ...context,
12761
+ extraContext: [
12762
+ ...context.extraContext ?? [],
12763
+ ` clientDir: import.meta.dir + ${JSON.stringify(`/${clientDirNameForPrefix(context.prefix ?? "")}`)},`
12764
+ ],
12765
+ templateHtml: readFileSync6(join11(targetDir, clientDirNameForPrefix(context.prefix ?? ""), "index.html"), "utf8")
12766
+ }));
12767
+ return await materializeServerAppEntry({
12768
+ apps: contexts,
12769
+ headerComment: "// Auto-generated by furin build - do not edit",
12770
+ instances: apps,
12771
+ outDir: targetDir,
12772
+ serverEntry
12773
+ });
12774
+ }
12480
12775
  async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12481
12776
  if (options.compile && !serverEntry) {
12482
12777
  throw new Error(`[furin] \`compile: "${options.compile}"\` requires a server entry point. ` + "Create src/server.ts or set `serverEntry` in your furin.config.ts.");
@@ -12486,27 +12781,24 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12486
12781
  }
12487
12782
  const target = "bun";
12488
12783
  const targetManifest = buildTargetManifest(rootDir, buildRoot, target, serverEntry);
12489
- const targetDir = resolve4(rootDir, targetManifest.targetDir);
12784
+ const targetDir = resolve6(rootDir, targetManifest.targetDir);
12490
12785
  rmSync2(targetDir, { force: true, recursive: true });
12491
12786
  ensureDir(targetDir);
12492
- const publicDir = existsSync9(join10(rootDir, "public")) ? join10(rootDir, "public") : undefined;
12787
+ const publicDir = existsSync9(join11(rootDir, "public")) ? join11(rootDir, "public") : undefined;
12493
12788
  const { entryApps, headlineBuildId } = await buildRuntimeAppsSequentially(apps, rootDir, targetDir, serverEntry, options, "bun");
12494
12789
  targetManifest.buildId = headlineBuildId;
12495
12790
  if (serverEntry) {
12496
- targetManifest.rscManifestPath = toPosixPath(join10(targetManifest.targetDir, "rsc", "manifest.json"));
12791
+ targetManifest.rscManifestPath = toPosixPath(join11(targetManifest.targetDir, "rsc", "manifest.json"));
12497
12792
  }
12498
- const targetPublicDir = publicDir ? join10(targetDir, "public") : undefined;
12793
+ const targetPublicDir = publicDir ? join11(targetDir, "public") : undefined;
12499
12794
  if (publicDir && targetPublicDir && options.compile !== "embed") {
12500
12795
  copyDirRecursive(publicDir, targetPublicDir);
12501
12796
  }
12502
- if (options.compile && serverEntry) {
12503
- const outfile = join10(targetDir, "server");
12504
- const entry = generateCompileEntry({
12505
- apps: entryApps,
12506
- outDir: targetDir,
12507
- publicDir,
12508
- serverEntry
12509
- });
12797
+ const appEntry = await createBunAppEntry(apps, entryApps, options, publicDir, serverEntry, targetDir);
12798
+ if (options.compile && serverEntry && appEntry) {
12799
+ const serverFilename = compiledServerFilename(process.platform);
12800
+ const outfile = join11(targetDir, serverFilename);
12801
+ const entry = generateBootEntry(appEntry, targetDir, "_compile-entry.ts");
12510
12802
  const embeddedAssets = collectEmbeddedAssets(entryApps, publicDir, options.compile);
12511
12803
  await runBunBuild({
12512
12804
  bytecode: true,
@@ -12523,17 +12815,18 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12523
12815
  ...options.plugins ?? [],
12524
12816
  createRoutesPlugin({ instances: apps, target: "server" }),
12525
12817
  isomorphicTransformPlugin("server"),
12526
- environmentGuardPlugin("ssr")
12818
+ environmentGuardPlugin("ssr"),
12819
+ elysiaAot(appEntry)
12527
12820
  ],
12528
12821
  sourcemap: "none",
12529
12822
  splitting: true,
12530
12823
  target: "bun"
12531
12824
  });
12532
12825
  console.log(`[furin] Server binary: ${outfile}`);
12533
- targetManifest.serverPath = toPosixPath(join10(targetManifest.targetDir, "server"));
12826
+ targetManifest.serverPath = toPosixPath(join11(targetManifest.targetDir, serverFilename));
12534
12827
  if (options.compile === "embed") {
12535
12828
  for (const app of apps) {
12536
- rmSync2(join10(targetDir, clientDirNameForPrefix(app.prefix)), {
12829
+ rmSync2(join11(targetDir, clientDirNameForPrefix(app.prefix)), {
12537
12830
  force: true,
12538
12831
  recursive: true
12539
12832
  });
@@ -12541,12 +12834,8 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12541
12834
  targetManifest.clientDir = null;
12542
12835
  targetManifest.templatePath = null;
12543
12836
  }
12544
- } else if (serverEntry) {
12545
- const entry = generateDiskEntry({
12546
- apps: entryApps,
12547
- outDir: targetDir,
12548
- serverEntry
12549
- });
12837
+ } else if (serverEntry && appEntry) {
12838
+ const entry = generateBootEntry(appEntry, targetDir, "server.ts");
12550
12839
  await runBunBuild({
12551
12840
  entrypoints: [entry.entrypoint],
12552
12841
  files: entry.files,
@@ -12560,30 +12849,31 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12560
12849
  ...options.plugins ?? [],
12561
12850
  createRoutesPlugin({ instances: apps, target: "server" }),
12562
12851
  isomorphicTransformPlugin("server"),
12563
- environmentGuardPlugin("ssr")
12852
+ environmentGuardPlugin("ssr"),
12853
+ elysiaAot(appEntry)
12564
12854
  ],
12565
12855
  sourcemap: "none",
12566
12856
  target: "bun"
12567
12857
  });
12568
- console.log(`[furin] Server bundle: ${toPosixPath(join10(targetManifest.targetDir, "server.js"))}`);
12569
- targetManifest.serverPath = toPosixPath(join10(targetManifest.targetDir, "server.js"));
12858
+ console.log(`[furin] Server bundle: ${toPosixPath(join11(targetManifest.targetDir, "server.js"))}`);
12859
+ targetManifest.serverPath = toPosixPath(join11(targetManifest.targetDir, "server.js"));
12570
12860
  }
12571
12861
  return targetManifest;
12572
12862
  }
12573
12863
 
12574
12864
  // src/adapter/package.ts
12575
- import { existsSync as existsSync10, rmSync as rmSync3, writeFileSync as writeFileSync6 } from "fs";
12576
- import { join as join11, relative as relative6, resolve as resolve5 } from "path";
12865
+ import { existsSync as existsSync10, rmSync as rmSync3, writeFileSync as writeFileSync7 } from "fs";
12866
+ import { join as join12, relative as relative7, resolve as resolve7 } from "path";
12577
12867
  async function buildPackageTarget(app, rootDir, buildRoot, options) {
12578
12868
  const { prefix, root, routes, pagesDir } = app;
12579
12869
  const modulePaths = routeSourcePaths(app);
12580
- const targetDir = join11(buildRoot, "package");
12870
+ const targetDir = join12(buildRoot, "package");
12581
12871
  rmSync3(targetDir, { force: true, recursive: true });
12582
12872
  ensureDir(targetDir);
12583
12873
  const { entryChunk, cssChunks } = await buildClient(routes, {
12584
12874
  basePath: prefix,
12585
12875
  clientLogging: options.clientLogging ?? false,
12586
- metafilePath: options.analyze ? join11(buildRoot, "analysis", "package-client.json") : undefined,
12876
+ metafilePath: options.analyze ? join12(buildRoot, "analysis", "package-client.json") : undefined,
12587
12877
  optimizeImports: options.optimizeImports,
12588
12878
  outDir: targetDir,
12589
12879
  pagesDir,
@@ -12595,13 +12885,13 @@ async function buildPackageTarget(app, rootDir, buildRoot, options) {
12595
12885
  const buildFingerprint = await createBuildFingerprint(`${prefix}
12596
12886
  ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12597
12887
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
12598
- const clientDir = join11(targetDir, "client");
12599
- const publicDir = join11(rootDir, "public");
12888
+ const clientDir = join12(targetDir, "client");
12889
+ const publicDir = join12(rootDir, "public");
12600
12890
  if (existsSync10(publicDir)) {
12601
- copyDirRecursive(publicDir, join11(targetDir, "public"));
12891
+ copyDirRecursive(publicDir, join12(targetDir, "public"));
12602
12892
  }
12603
12893
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
12604
- writeFileSync6(join11(clientDir, "index.html"), indexHtml);
12894
+ writeFileSync7(join12(clientDir, "index.html"), indexHtml);
12605
12895
  setProductionTemplateContent(indexHtml);
12606
12896
  ssgRouteCache().clear();
12607
12897
  const ssgCache = await buildSSGCacheSnapshot(routes, root, "http://localhost", prefix);
@@ -12626,7 +12916,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12626
12916
  buildId,
12627
12917
  clientLogging: options.clientLogging ?? false,
12628
12918
  modulePaths,
12629
- nativeRoutes: routeModuleSpecifier(app),
12919
+ nativeRoutes: composableRouteModuleSpecifier(app),
12630
12920
  prefix,
12631
12921
  rootConventions,
12632
12922
  rootPath: root.path,
@@ -12638,7 +12928,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12638
12928
  headerComment: "// Auto-generated by `furin build --target package` \u2014 do not edit",
12639
12929
  mode: "register"
12640
12930
  });
12641
- const registerEntry = join11(targetDir, "register.ts");
12931
+ const registerEntry = join12(targetDir, "register.ts");
12642
12932
  const register = createVirtualBuildEntry(registerEntry, registerSource, "ts");
12643
12933
  const result = await runBunBuild({
12644
12934
  entrypoints: [register.entrypoint],
@@ -12658,7 +12948,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12658
12948
  if (!result.success) {
12659
12949
  throw new AggregateError(result.logs, "[furin] package register build failed");
12660
12950
  }
12661
- const relativePagesDir = toPosixPath(relative6(targetDir, resolve5(rootDir, pagesDir)));
12951
+ const relativePagesDir = toPosixPath(relative7(targetDir, resolve7(rootDir, pagesDir)));
12662
12952
  const factorySource = `// Auto-generated by \`furin build --target package\` \u2014 do not edit
12663
12953
  import { fileURLToPath } from "node:url";
12664
12954
  import { furin } from "@teyik0/furin";
@@ -12685,7 +12975,7 @@ export function createFurinApp(options = {}) {
12685
12975
 
12686
12976
  export const prefix = ${JSON.stringify(prefix)};
12687
12977
  `;
12688
- writeFileSync6(join11(targetDir, "index.js"), factorySource);
12978
+ writeFileSync7(join12(targetDir, "index.js"), factorySource);
12689
12979
  const dtsSource = `import type { FurinOptions, furin } from "@teyik0/furin";
12690
12980
 
12691
12981
  /** Extra furin() options \u2014 pagesDir/prefix/clientDir are baked into the package and cannot be overridden. */
@@ -12693,29 +12983,29 @@ export type CreateFurinAppOptions = Omit<FurinOptions, "pagesDir" | "prefix" | "
12693
12983
  export declare function createFurinApp(options?: CreateFurinAppOptions): ReturnType<typeof furin>;
12694
12984
  export declare const prefix: string;
12695
12985
  `;
12696
- writeFileSync6(join11(targetDir, "index.d.ts"), dtsSource);
12697
- console.log(`[furin] Package artifact: ${toPosixPath(relative6(rootDir, targetDir))}`);
12986
+ writeFileSync7(join12(targetDir, "index.d.ts"), dtsSource);
12987
+ console.log(`[furin] Package artifact: ${toPosixPath(relative7(rootDir, targetDir))}`);
12698
12988
  return {
12699
12989
  buildId,
12700
12990
  generatedAt: new Date().toISOString(),
12701
12991
  prefix,
12702
- targetDir: toPosixPath(relative6(rootDir, targetDir))
12992
+ targetDir: toPosixPath(relative7(rootDir, targetDir))
12703
12993
  };
12704
12994
  }
12705
12995
 
12706
12996
  // src/adapter/static.ts
12707
- import { cpSync as cpSync2, existsSync as existsSync11, rmSync as rmSync4, writeFileSync as writeFileSync7 } from "fs";
12708
- import { dirname as dirname7, isAbsolute as isAbsolute2, join as join12, relative as relative7, resolve as resolve6, sep as sep2 } from "path";
12997
+ import { cpSync as cpSync2, existsSync as existsSync11, rmSync as rmSync4, writeFileSync as writeFileSync8 } from "fs";
12998
+ import { dirname as dirname9, isAbsolute as isAbsolute3, join as join13, parse as parse3, relative as relative8, resolve as resolve8, sep as sep2, win32 } from "path";
12709
12999
  var STATIC_CONCURRENCY = 4;
12710
13000
  var DYNAMIC_SEGMENT_RE2 = /\/:[^/]+|\/\*/;
12711
13001
  var TRAILING_SLASHES_RE = /\/+$/;
12712
13002
  var STATIC_RENDER_ORIGIN = "http://localhost";
12713
13003
  function pathToOutputFile(urlPath, outDir, fileName) {
12714
- const normalizedOutDir = resolve6(outDir);
13004
+ const normalizedOutDir = resolve8(outDir);
12715
13005
  if (urlPath === "/" || urlPath === "") {
12716
- return join12(normalizedOutDir, fileName);
13006
+ return join13(normalizedOutDir, fileName);
12717
13007
  }
12718
- const resolved = resolve6(normalizedOutDir, urlPath.slice(1), fileName);
13008
+ const resolved = resolve8(normalizedOutDir, urlPath.slice(1), fileName);
12719
13009
  if (!resolved.startsWith(`${normalizedOutDir}${sep2}`)) {
12720
13010
  throw new Error(`[furin] static: unsafe output path detected for URL "${urlPath}" \u2014 path traversal via ".." is not allowed.`);
12721
13011
  }
@@ -12788,22 +13078,22 @@ async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, sk
12788
13078
  throw new Error(`[furin] static: route "${route.pattern}" returned a response that cannot be exported.`);
12789
13079
  }
12790
13080
  const staticLocation = resolveStaticRedirectLocation(location, basePath, urlPath);
12791
- ensureDir(dirname7(htmlOutputFile));
12792
- writeFileSync7(htmlOutputFile, createStaticRedirectHtml(staticLocation.html));
13081
+ ensureDir(dirname9(htmlOutputFile));
13082
+ writeFileSync8(htmlOutputFile, createStaticRedirectHtml(staticLocation.html));
12793
13083
  if (staticLocation.spa !== null) {
12794
13084
  const serializedRedirect = await toCrossJSONAsync({
12795
13085
  __furinRedirect: staticLocation.spa
12796
13086
  });
12797
- writeFileSync7(dataOutputFile, `${JSON.stringify(serializedRedirect)}
13087
+ writeFileSync8(dataOutputFile, `${JSON.stringify(serializedRedirect)}
12798
13088
  `);
12799
13089
  }
12800
13090
  renderedRoutes.push(urlPath);
12801
13091
  console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)} (redirects to ${staticLocation.html})`);
12802
13092
  return;
12803
13093
  }
12804
- ensureDir(dirname7(htmlOutputFile));
12805
- writeFileSync7(htmlOutputFile, entry.html);
12806
- writeFileSync7(dataOutputFile, entry.ndjson);
13094
+ ensureDir(dirname9(htmlOutputFile));
13095
+ writeFileSync8(htmlOutputFile, entry.html);
13096
+ writeFileSync8(dataOutputFile, entry.ndjson);
12807
13097
  renderedRoutes.push(urlPath);
12808
13098
  console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)}`);
12809
13099
  } catch (err) {
@@ -12836,13 +13126,13 @@ async function buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRo
12836
13126
  if (!DYNAMIC_SEGMENT_RE2.test(route.pattern)) {
12837
13127
  return { paramSets: [{}], route };
12838
13128
  }
12839
- if (!route.page.staticParams) {
13129
+ if (!hasStaticParams(route)) {
12840
13130
  console.warn(`[furin] static: skipping dynamic route "${route.pattern}" \u2014 no staticParams() defined.`);
12841
13131
  skippedRoutes.push(route.pattern);
12842
13132
  return { paramSets: null, route };
12843
13133
  }
12844
13134
  try {
12845
- const paramSets = await route.page.staticParams() ?? [];
13135
+ const paramSets = await resolveStaticParams(route, STATIC_RENDER_ORIGIN) ?? [];
12846
13136
  return { paramSets, route };
12847
13137
  } catch (err) {
12848
13138
  return { error: err, paramSets: null, route };
@@ -12909,15 +13199,16 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
12909
13199
  if (basePath && !basePath.startsWith("/")) {
12910
13200
  throw new Error(`[furin] static: basePath must start with "/" (received "${rawBasePath}"). ` + `Use "" for root deployments or "/sub-path" for sub-path deployments.`);
12911
13201
  }
12912
- const outDir = resolve6(rootDir, staticConfig.outDir ?? "dist");
12913
- const normalizedRoot = resolve6(rootDir);
12914
- const normalizedBuildRoot = resolve6(buildRoot);
12915
- if (outDir === normalizedRoot || outDir === normalizedBuildRoot || outDir === "/" || outDir === ".") {
13202
+ const rawOutDir = staticConfig.outDir ?? "dist";
13203
+ const outDir = resolve8(rootDir, rawOutDir);
13204
+ const normalizedRoot = resolve8(rootDir);
13205
+ const normalizedBuildRoot = resolve8(buildRoot);
13206
+ if (outDir === normalizedRoot || outDir === normalizedBuildRoot || outDir === parse3(outDir).root || rawOutDir === win32.parse(rawOutDir).root) {
12916
13207
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
12917
13208
  }
12918
13209
  function isOutsideOutDir(target) {
12919
- const rel = relative7(outDir, target);
12920
- return rel.startsWith("..") || isAbsolute2(rel);
13210
+ const rel = relative8(outDir, target);
13211
+ return rel.startsWith("..") || isAbsolute3(rel);
12921
13212
  }
12922
13213
  if (!(isOutsideOutDir(normalizedRoot) && isOutsideOutDir(normalizedBuildRoot))) {
12923
13214
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
@@ -12933,36 +13224,36 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
12933
13224
  const afterQueueCount = skippedRoutes.length;
12934
13225
  rmSync4(outDir, { force: true, recursive: true });
12935
13226
  ensureDir(outDir);
12936
- const targetDir = join12(buildRoot, "static");
13227
+ const targetDir = join13(buildRoot, "static");
12937
13228
  rmSync4(targetDir, { force: true, recursive: true });
12938
13229
  ensureDir(targetDir);
12939
13230
  const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
12940
13231
  basePath,
12941
13232
  clientLogging: Boolean(options.clientLogging),
12942
- metafilePath: options.analyze ? join12(buildRoot, "analysis", "static-client.json") : undefined,
13233
+ metafilePath: options.analyze ? join13(buildRoot, "analysis", "static-client.json") : undefined,
12943
13234
  optimizeImports: options.optimizeImports,
12944
13235
  outDir: targetDir,
12945
- pagesDir: dirname7(root.path),
13236
+ pagesDir: dirname9(root.path),
12946
13237
  plugins: options.plugins,
12947
13238
  publicPath,
12948
13239
  reactCompiler: options.reactCompiler,
12949
13240
  rootLayout: root.path
12950
13241
  });
12951
- const publicFavicon = join12(rootDir, "public", "favicon.ico");
13242
+ const publicFavicon = join13(rootDir, "public", "favicon.ico");
12952
13243
  const faviconHref = existsSync11(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
12953
13244
  const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref, true);
12954
13245
  setProductionTemplateContent(shellHtml);
12955
- const publicSrcDir = join12(rootDir, "public");
13246
+ const publicSrcDir = join13(rootDir, "public");
12956
13247
  if (existsSync11(publicSrcDir)) {
12957
13248
  cpSync2(publicSrcDir, outDir, { recursive: true });
12958
13249
  }
12959
- const clientSrcDir = join12(targetDir, "client");
13250
+ const clientSrcDir = join13(targetDir, "client");
12960
13251
  if (existsSync11(clientSrcDir)) {
12961
- cpSync2(clientSrcDir, join12(outDir, "_client"), { recursive: true });
13252
+ cpSync2(clientSrcDir, join13(outDir, "_client"), { recursive: true });
12962
13253
  }
12963
13254
  await runWithConcurrency(tasks, STATIC_CONCURRENCY);
12964
13255
  assertNoPrerenderSkips(onSSR, skippedRoutes, afterQueueCount);
12965
- writeFileSync7(join12(outDir, "404.html"), shellHtml);
13256
+ writeFileSync8(join13(outDir, "404.html"), shellHtml);
12966
13257
  console.log("[furin] static: wrote 404.html (SPA shell fallback)");
12967
13258
  rmSync4(targetDir, { force: true, recursive: true });
12968
13259
  console.log(`[furin] static: export complete \u2192 ${toPosixPath(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
@@ -12976,32 +13267,24 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
12976
13267
  }
12977
13268
 
12978
13269
  // src/adapter/vercel.ts
12979
- import {
12980
- cpSync as cpSync3,
12981
- existsSync as existsSync12,
12982
- readFileSync as readFileSync6,
12983
- rmSync as rmSync5,
12984
- statSync as statSync3,
12985
- symlinkSync,
12986
- writeFileSync as writeFileSync8
12987
- } from "fs";
12988
- import { basename as basename5, dirname as dirname8, extname as extname4, join as join13, relative as relative8 } from "path";
13270
+ import { cpSync as cpSync3, existsSync as existsSync12, readFileSync as readFileSync7, rmSync as rmSync5, symlinkSync, writeFileSync as writeFileSync9 } from "fs";
13271
+ import { basename as basename5, dirname as dirname10, extname as extname4, join as join14, relative as relative9 } from "path";
12989
13272
  import { fileURLToPath as fileURLToPath6, pathToFileURL as pathToFileURL2 } from "url";
12990
13273
  init_patterns();
12991
13274
  var ISR_PATH_PARAM = "__furin_path";
12992
13275
  var DYNAMIC_SEGMENT_RE3 = /\/:[^/]+|\/\*/;
12993
- var ELYSIA_STATIC_IMPORT_RE = /^@elysiajs\/static$/;
13276
+ var ELYSIA_STATIC_IMPORT_RE = /^@elysia\/static$/;
12994
13277
  var MATCH_ALL_RE = /.*/;
12995
13278
  var REGEX_META_RE = /[.*+?^${}()|[\]\\]/;
12996
13279
  var UNSAFE_FUNCTION_PATH_RE = /[^a-zA-Z0-9_.[\]/-]/g;
12997
13280
  var VERCEL_FUNCTIONS_PATH = fileURLToPath6(import.meta.resolve("@vercel/functions"));
12998
13281
  var VERCEL_RUNTIME_STUB_NAMESPACE = "furin-vercel-runtime-stub";
12999
- var FURIN_RUNTIME_ROOT2 = dirname8(import.meta.dir);
13282
+ var FURIN_RUNTIME_ROOT2 = dirname10(import.meta.dir);
13000
13283
  function isFurinRuntimeImporter(importer) {
13001
13284
  if (importer === "") {
13002
13285
  return false;
13003
13286
  }
13004
- const fromRuntimeRoot = relative8(FURIN_RUNTIME_ROOT2, importer.split("?")[0]);
13287
+ const fromRuntimeRoot = relative9(FURIN_RUNTIME_ROOT2, importer.split("?")[0]);
13005
13288
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
13006
13289
  }
13007
13290
  function vercelRuntimePlugin() {
@@ -13010,11 +13293,11 @@ function vercelRuntimePlugin() {
13010
13293
  setup(build) {
13011
13294
  build.onResolve({ filter: ELYSIA_STATIC_IMPORT_RE }, ({ importer }) => {
13012
13295
  if (!isFurinRuntimeImporter(importer)) {
13013
- throw new Error("[furin] Application @elysiajs/static mounts are not supported by the Vercel target. Put CDN assets under public/ instead.");
13296
+ throw new Error("[furin] Application @elysia/static mounts are not supported by the Vercel target. Put CDN assets under public/ instead.");
13014
13297
  }
13015
13298
  return {
13016
13299
  namespace: VERCEL_RUNTIME_STUB_NAMESPACE,
13017
- path: "@elysiajs/static"
13300
+ path: "@elysia/static"
13018
13301
  };
13019
13302
  });
13020
13303
  build.onLoad({ filter: MATCH_ALL_RE, namespace: VERCEL_RUNTIME_STUB_NAMESPACE }, () => ({
@@ -13027,8 +13310,8 @@ function vercelRuntimePlugin() {
13027
13310
  };
13028
13311
  }
13029
13312
  function frameworkVersion() {
13030
- const packageRoot = dirname8(dirname8(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
13031
- const packageJson = JSON.parse(readFileSync6(join13(packageRoot, "package.json"), "utf8"));
13313
+ const packageRoot = dirname10(dirname10(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
13314
+ const packageJson = JSON.parse(readFileSync7(join14(packageRoot, "package.json"), "utf8"));
13032
13315
  return packageJson.version;
13033
13316
  }
13034
13317
  function serverEntryLoader(serverEntry) {
@@ -13046,10 +13329,15 @@ function serverEntryLoader(serverEntry) {
13046
13329
  }
13047
13330
  function assertDefaultServerExport(serverEntry) {
13048
13331
  const transpiler = new Bun.Transpiler({ loader: serverEntryLoader(serverEntry) });
13049
- const { exports } = transpiler.scan(readFileSync6(serverEntry, "utf8"));
13332
+ const { exports, imports } = transpiler.scan(readFileSync7(serverEntry, "utf8"));
13050
13333
  if (!exports.includes("default")) {
13051
13334
  throw new Error(`[furin] Vercel server entry "${toPosixPath(serverEntry)}" must export the Elysia app as default. ` + "Guard app.listen() with `if (import.meta.main)` so the same entry also runs locally.");
13052
13335
  }
13336
+ if (imports.some(({ path }) => ELYSIA_STATIC_IMPORT_RE.test(path))) {
13337
+ throw new AggregateError([
13338
+ new Error("[furin] Application @elysia/static mounts are not supported by the Vercel target. Put CDN assets under public/ instead.")
13339
+ ], "[furin] Vercel build rejected application static mounts.");
13340
+ }
13053
13341
  }
13054
13342
  function escapeRegex(value) {
13055
13343
  let escaped = "";
@@ -13139,9 +13427,9 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
13139
13427
  body = result.html;
13140
13428
  ({ status } = result);
13141
13429
  }
13142
- const fallbackPath = join13(dirname8(join13(functionsDir, spec.functionName)), fallback);
13143
- ensureDir(dirname8(fallbackPath));
13144
- writeFileSync8(fallbackPath, body);
13430
+ const fallbackPath = join14(dirname10(join14(functionsDir, spec.functionName)), fallback);
13431
+ ensureDir(dirname10(fallbackPath));
13432
+ writeFileSync9(fallbackPath, body);
13145
13433
  spec.config.fallback = fallback;
13146
13434
  spec.config.initialHeaders = {
13147
13435
  "content-type": contentType,
@@ -13152,9 +13440,9 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
13152
13440
  spec.config.initialStatus = status;
13153
13441
  }
13154
13442
  function createFunctionAlias(functionsDir, serverFunctionDir, functionName) {
13155
- const aliasPath = join13(functionsDir, `${functionName}.func`);
13156
- ensureDir(dirname8(aliasPath));
13157
- const target = relative8(dirname8(aliasPath), serverFunctionDir);
13443
+ const aliasPath = join14(functionsDir, `${functionName}.func`);
13444
+ ensureDir(dirname10(aliasPath));
13445
+ const target = relative9(dirname10(aliasPath), serverFunctionDir);
13158
13446
  symlinkSync(target, aliasPath, process.platform === "win32" ? "junction" : "dir");
13159
13447
  }
13160
13448
  function createExactPrerenderSpec(prerender, routePath) {
@@ -13224,7 +13512,7 @@ async function createPrerenderSpecs(apps, builds, functionsDir, pprResumeKey) {
13224
13512
  return compareRouteSpecificity(right.pattern, left.pattern);
13225
13513
  });
13226
13514
  }
13227
- function vercelEntrySource(apps, builds, prerenderSpecs, serverEntry, pprResumeKey) {
13515
+ function vercelEntrySource(apps, builds, prerenderSpecs, appEntry, pprResumeKey) {
13228
13516
  const routeCount = builds.reduce((count, build) => count + build.entryApp.routes.length, 0);
13229
13517
  const prerenderAliases = prerenderSpecs.map((spec) => [
13230
13518
  `/${spec.functionName}`,
@@ -13241,15 +13529,6 @@ function vercelEntrySource(apps, builds, prerenderSpecs, serverEntry, pprResumeK
13241
13529
  source: `^(?:${routePatternSource(app.prefix, route.pattern)})$`,
13242
13530
  tags: route.tags ?? []
13243
13531
  }))).sort((left, right) => compareRouteSpecificity(right.pattern, left.pattern)).map(({ source, tags }) => [source, tags]);
13244
- const contextSource = buildEntrySource({
13245
- apps: builds.map(({ entryApp, indexHtml }) => ({
13246
- ...entryApp,
13247
- embed: undefined,
13248
- serveAssets: false,
13249
- templateHtml: indexHtml
13250
- })),
13251
- headerComment: "// Auto-generated by `furin build --target vercel` \u2014 do not edit"
13252
- });
13253
13532
  return `import {
13254
13533
  addCacheTag,
13255
13534
  getCache as getVercelCache,
@@ -13262,12 +13541,11 @@ import {
13262
13541
  markExternalPrerenderRequest,
13263
13542
  restorePprResumeRequest,
13264
13543
  setCacheTagPurger,
13544
+ setRuntimeEvlogWaitUntil,
13265
13545
  setRuntimeCacheProvider,
13266
13546
  waitForPendingISRRevalidations,
13267
13547
  } from "@teyik0/furin/internal";
13268
13548
 
13269
- ${contextSource}
13270
-
13271
13549
  const prerenderAliases = new Map(
13272
13550
  ${JSON.stringify(prerenderAliases)}.map(([alias, source]) => [alias, new RegExp(source)])
13273
13551
  );
@@ -13287,6 +13565,7 @@ function encodeCacheTag(value) {
13287
13565
  setRuntimeCacheProvider({
13288
13566
  getCache: (options) => getVercelCache(options),
13289
13567
  });
13568
+ setRuntimeEvlogWaitUntil(waitUntil);
13290
13569
 
13291
13570
  async function purgeCacheTags(paths) {
13292
13571
  const purge = Promise.all([
@@ -13300,7 +13579,7 @@ setCachePurger(purgeCacheTags);
13300
13579
  setCacheTagPurger(purgeCacheTags);
13301
13580
 
13302
13581
  const serverInitStartedAt = performance.now();
13303
- const serverModule = await import(${JSON.stringify(toPosixPath(serverEntry))});
13582
+ const serverModule = await import(${JSON.stringify(toPosixPath(appEntry))});
13304
13583
  const app = serverModule.default;
13305
13584
  if (!app || typeof app.handle !== "function") {
13306
13585
  throw new TypeError("[furin] Vercel server entry must export the Elysia app as default.");
@@ -13385,10 +13664,10 @@ async function buildPprFallbacks(apps, builds, specs, functionsDir, rootDir, tar
13385
13664
  if (jobs.length === 0) {
13386
13665
  return;
13387
13666
  }
13388
- const resultPath = join13(targetDir, "ppr-results.json");
13667
+ const resultPath = join14(targetDir, "ppr-results.json");
13389
13668
  const requests = jobs.map(({ path, spec }) => `http://localhost/${spec.functionName}?${ISR_PATH_PARAM}=${encodeURIComponent(path)}`);
13390
13669
  const script = `
13391
- const handler = (await import(${JSON.stringify(pathToFileURL2(join13(functionsDir, "__server.func/index.js")).href)})).default;
13670
+ const handler = (await import(${JSON.stringify(pathToFileURL2(join14(functionsDir, "__server.func/index.js")).href)})).default;
13392
13671
  const results = [];
13393
13672
  for (const url of ${JSON.stringify(requests)}) {
13394
13673
  const response = await handler.fetch(new Request(url));
@@ -13415,7 +13694,7 @@ process.exit(0);
13415
13694
  ${stderr}
13416
13695
  ${stdout}`);
13417
13696
  }
13418
- const results = JSON.parse(readFileSync6(resultPath, "utf8"));
13697
+ const results = JSON.parse(readFileSync7(resultPath, "utf8"));
13419
13698
  for (const [index, job] of jobs.entries()) {
13420
13699
  const result = results[index];
13421
13700
  await addPrerenderFallback(job.spec, job.path, {
@@ -13487,6 +13766,7 @@ async function handle(request) {
13487
13766
  \`furin_server_init;dur=\${initialization.server_init_ms}\`,
13488
13767
  \`furin_handler_wait;dur=\${requestWaitMs}\`,
13489
13768
  \`furin_handler;dur=\${handlerMs}\`,
13769
+ ...(isFirstRequest ? ["furin_instance_first_request"] : []),
13490
13770
  ].join(", ");
13491
13771
  return appendServerTiming(response, serverTiming);
13492
13772
  }
@@ -13496,32 +13776,53 @@ export default { fetch: handle };
13496
13776
  }
13497
13777
  async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options) {
13498
13778
  assertDefaultServerExport(serverEntry);
13499
- const targetDir = join13(buildRoot, "vercel");
13500
- const outputDir = join13(rootDir, ".vercel", "output");
13501
- const staticDir = join13(outputDir, "static");
13502
- const functionsDir = join13(outputDir, "functions");
13503
- const serverFunctionDir = join13(functionsDir, "__server.func");
13779
+ const targetDir = join14(buildRoot, "vercel");
13780
+ const outputDir = join14(rootDir, ".vercel", "output");
13781
+ const staticDir = join14(outputDir, "static");
13782
+ const functionsDir = join14(outputDir, "functions");
13783
+ const serverFunctionDir = join14(functionsDir, "__server.func");
13504
13784
  rmSync5(targetDir, { force: true, recursive: true });
13505
13785
  rmSync5(outputDir, { force: true, recursive: true });
13506
13786
  ensureDir(targetDir);
13507
13787
  ensureDir(staticDir);
13508
13788
  ensureDir(serverFunctionDir);
13509
13789
  const { builds, headlineBuildId } = await buildRuntimeAppsSequentially(apps, rootDir, targetDir, serverEntry, options, "vercel");
13510
- cpSync3(join13(targetDir, "server-codec.js"), join13(serverFunctionDir, "server-codec.js"));
13511
- const publicDir = join13(rootDir, "public");
13790
+ cpSync3(join14(targetDir, "server-codec.js"), join14(serverFunctionDir, "server-codec.js"));
13791
+ const publicDir = join14(rootDir, "public");
13512
13792
  if (existsSync12(publicDir)) {
13513
13793
  cpSync3(publicDir, staticDir, { recursive: true });
13794
+ for (const app of apps) {
13795
+ const appStaticDir = join14(staticDir, app.prefix.slice(1));
13796
+ const appPublicDir = join14(appStaticDir, "public");
13797
+ cpSync3(publicDir, appPublicDir, { recursive: true });
13798
+ const favicon = join14(publicDir, "favicon.ico");
13799
+ if (app.prefix !== "" && existsSync12(favicon)) {
13800
+ cpSync3(favicon, join14(appStaticDir, "favicon.ico"));
13801
+ }
13802
+ }
13514
13803
  }
13515
13804
  for (let appIndex = 0;appIndex < apps.length; appIndex += 1) {
13516
13805
  const app = apps[appIndex];
13517
13806
  const build = builds[appIndex];
13518
- const clientOutputDir = join13(staticDir, app.prefix.slice(1), "_client");
13807
+ const clientOutputDir = join14(staticDir, app.prefix.slice(1), "_client");
13519
13808
  cpSync3(build.clientDir, clientOutputDir, { recursive: true });
13520
13809
  }
13521
13810
  const pprResumeKey = crypto.randomUUID();
13522
13811
  const prerenderSpecs = await createPrerenderSpecs(apps, builds, functionsDir, pprResumeKey);
13523
- const entryPath = join13(serverFunctionDir, "_vercel-handler.ts");
13524
- const entry = createVirtualBuildEntry(entryPath, vercelEntrySource(apps, builds, prerenderSpecs, serverEntry, pprResumeKey), "ts");
13812
+ const appEntry = await materializeServerAppEntry({
13813
+ apps: builds.map(({ entryApp, indexHtml }) => ({
13814
+ ...entryApp,
13815
+ embed: undefined,
13816
+ serveAssets: false,
13817
+ templateHtml: indexHtml
13818
+ })),
13819
+ headerComment: "// Auto-generated by `furin build --target vercel` \u2014 do not edit",
13820
+ instances: apps,
13821
+ outDir: serverFunctionDir,
13822
+ serverEntry
13823
+ });
13824
+ const entryPath = join14(serverFunctionDir, "_vercel-handler.ts");
13825
+ const entry = createVirtualBuildEntry(entryPath, vercelEntrySource(apps, builds, prerenderSpecs, appEntry, pprResumeKey), "ts");
13525
13826
  const serverBuild = await runBunBuild({
13526
13827
  define: { "process.env.NODE_ENV": JSON.stringify("production") },
13527
13828
  entrypoints: [entry.entrypoint],
@@ -13539,26 +13840,27 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13539
13840
  ...options.plugins ?? [],
13540
13841
  createRoutesPlugin({ instances: apps, target: "server" }),
13541
13842
  isomorphicTransformPlugin("server"),
13542
- environmentGuardPlugin("ssr")
13843
+ environmentGuardPlugin("ssr"),
13844
+ elysiaAot(appEntry)
13543
13845
  ],
13544
13846
  sourcemap: "none",
13847
+ splitting: true,
13545
13848
  target: "bun"
13546
13849
  });
13547
13850
  if (options.analyze) {
13548
13851
  if (serverBuild.metafile === undefined) {
13549
13852
  throw new Error("[furin] Vercel server build did not produce the requested metafile.");
13550
13853
  }
13551
- const metafilePath = join13(buildRoot, "analysis", "vercel-server.json");
13552
- ensureDir(dirname8(metafilePath));
13553
- writeFileSync8(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}
13854
+ const metafilePath = join14(buildRoot, "analysis", "vercel-server.json");
13855
+ ensureDir(dirname10(metafilePath));
13856
+ writeFileSync9(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}
13554
13857
  `);
13555
13858
  console.log(`[furin] Server metafile: ${toPosixPath(metafilePath)}`);
13556
13859
  }
13557
- const handlerPath = join13(serverFunctionDir, "handler.js");
13558
- const serverBundleBytes = existsSync12(handlerPath) ? statSync3(handlerPath).size : 0;
13559
- writeFileSync8(join13(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
13860
+ const serverBundleBytes = serverBuild.outputs.filter((output) => output.path.endsWith(".js")).reduce((total, output) => total + output.size, 0);
13861
+ writeFileSync9(join14(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
13560
13862
  await buildPprFallbacks(apps, builds, prerenderSpecs, functionsDir, rootDir, targetDir);
13561
- writeFileSync8(join13(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
13863
+ writeFileSync9(join14(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
13562
13864
  handler: "index.js",
13563
13865
  launcherType: "Nodejs",
13564
13866
  ...options.vercelConfig?.regions === undefined ? {} : { regions: options.vercelConfig.regions },
@@ -13569,7 +13871,7 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13569
13871
  `);
13570
13872
  for (const spec of prerenderSpecs) {
13571
13873
  createFunctionAlias(functionsDir, serverFunctionDir, spec.functionName);
13572
- writeFileSync8(join13(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
13874
+ writeFileSync9(join14(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
13573
13875
  `);
13574
13876
  }
13575
13877
  const assetRoutes = apps.map((app) => ({
@@ -13599,24 +13901,24 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13599
13901
  ],
13600
13902
  version: 3
13601
13903
  };
13602
- writeFileSync8(join13(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
13904
+ writeFileSync9(join14(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
13603
13905
  `);
13604
13906
  const ssgRoutes = builds.flatMap((build, index) => build.prerenders.filter((prerender) => prerender.route.mode === "ssg").map((prerender) => physicalPath(apps[index].prefix, prerender.path))).toSorted();
13605
13907
  const isrRoutes = apps.flatMap((app) => app.routes.filter((route) => route.mode === "isr").map((route) => physicalPath(app.prefix, route.pattern))).toSorted();
13606
- console.log(`[furin] Vercel output: ${toPosixPath(relative8(rootDir, outputDir))}`);
13908
+ console.log(`[furin] Vercel output: ${toPosixPath(relative9(rootDir, outputDir))}`);
13607
13909
  return {
13608
13910
  buildId: headlineBuildId,
13609
13911
  generatedAt: new Date().toISOString(),
13610
13912
  isrRoutes,
13611
- outputDir: toPosixPath(relative8(rootDir, outputDir)),
13612
- serverPath: toPosixPath(relative8(rootDir, serverFunctionDir)),
13913
+ outputDir: toPosixPath(relative9(rootDir, outputDir)),
13914
+ serverPath: toPosixPath(relative9(rootDir, serverFunctionDir)),
13613
13915
  ssgRoutes
13614
13916
  };
13615
13917
  }
13616
13918
 
13617
13919
  // src/config.ts
13618
13920
  import { t as t2 } from "elysia";
13619
- var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare", "static", "package"];
13921
+ var BUILD_TARGETS = ["bun", "vercel", "static", "package"];
13620
13922
  var buildTargetSchema = t2.Union(BUILD_TARGETS.map((v) => t2.Literal(v)));
13621
13923
  var compileTargetSchema = t2.Union([t2.Literal("server"), t2.Literal("embed")]);
13622
13924
  var configSchema = t2.Object({
@@ -13653,7 +13955,7 @@ init_instance();
13653
13955
  // src/server/router/discovery.ts
13654
13956
  import { existsSync as existsSync13 } from "fs";
13655
13957
  import { readdir } from "fs/promises";
13656
- import { join as join14, parse as parse3 } from "path";
13958
+ import { join as join15, parse as parse4 } from "path";
13657
13959
 
13658
13960
  // src/server/internal.ts
13659
13961
  var _compileContexts = new Map;
@@ -13738,6 +14040,7 @@ function adaptDefinedLayout(route, parent, sourcePath) {
13738
14040
  requestLoader: route.requestLoader,
13739
14041
  revalidate: route.revalidate,
13740
14042
  sourcePath,
14043
+ staticParams: route.staticParams,
13741
14044
  tags: copyTags(route.tags)
13742
14045
  };
13743
14046
  }
@@ -13861,7 +14164,7 @@ async function scanPageFiles(pagesDir, root) {
13861
14164
  continue;
13862
14165
  }
13863
14166
  const relativePath = routeRelativePath(pagesDir, absolutePath);
13864
- const fileName = parse3(relativePath).name;
14167
+ const fileName = parse4(relativePath).name;
13865
14168
  if (fileName.startsWith("_") || fileName === "root" || isConventionFileName(fileName)) {
13866
14169
  continue;
13867
14170
  }
@@ -14026,7 +14329,7 @@ async function collectPageFilePaths(dir) {
14026
14329
  const files = [];
14027
14330
  const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
14028
14331
  const resolved = await mapWithConcurrency(entries, DIR_SCAN_CONCURRENCY, async (entry) => {
14029
- const absolutePath = toPosixPath2(join14(dir, entry.name));
14332
+ const absolutePath = toPosixPath2(join15(dir, entry.name));
14030
14333
  if (entry.isDirectory()) {
14031
14334
  return await collectPageFilePaths(absolutePath);
14032
14335
  }
@@ -14043,9 +14346,9 @@ async function collectPageFilePaths(dir) {
14043
14346
 
14044
14347
  // src/build/scan-server.ts
14045
14348
  init_instance();
14046
- import { readFileSync as readFileSync7 } from "fs";
14349
+ import { readFileSync as readFileSync8 } from "fs";
14047
14350
  function scanFurinInstances(serverEntryPath) {
14048
- const code = readFileSync7(serverEntryPath, "utf8");
14351
+ const code = readFileSync8(serverEntryPath, "utf8");
14049
14352
  const lang = detectLangFromPath(serverEntryPath);
14050
14353
  if (lang === "dts") {
14051
14354
  return [];
@@ -14126,38 +14429,38 @@ function registerIsomorphicRuntimePlugin() {
14126
14429
  function resolveAppSpecs(options, serverEntry, rootDir) {
14127
14430
  if (options.apps && options.apps.length > 0) {
14128
14431
  return options.apps.map((app) => ({
14129
- pagesDir: resolve7(rootDir, app.pagesDir),
14432
+ pagesDir: resolve9(rootDir, app.pagesDir),
14130
14433
  prefix: normalizePrefix(app.prefix)
14131
14434
  }));
14132
14435
  }
14133
14436
  if (options.pagesDir) {
14134
- return [{ pagesDir: resolve7(rootDir, options.pagesDir), prefix: "" }];
14437
+ return [{ pagesDir: resolve9(rootDir, options.pagesDir), prefix: "" }];
14135
14438
  }
14136
14439
  if (serverEntry) {
14137
14440
  const detected = scanFurinInstances(serverEntry);
14138
14441
  if (detected.length > 0) {
14139
14442
  return detected.map((app) => ({
14140
- pagesDir: resolve7(rootDir, app.pagesDir),
14443
+ pagesDir: resolve9(rootDir, app.pagesDir),
14141
14444
  prefix: app.prefix
14142
14445
  }));
14143
14446
  }
14144
14447
  }
14145
- return [{ pagesDir: resolve7(rootDir, "src/pages"), prefix: "" }];
14448
+ return [{ pagesDir: resolve9(rootDir, "src/pages"), prefix: "" }];
14146
14449
  }
14147
14450
  async function buildApp(options) {
14148
- const rootDir = resolve7(options.rootDir ?? process.cwd());
14149
- const buildRoot = join15(rootDir, BUILD_OUTPUT_DIR);
14451
+ const rootDir = resolve9(options.rootDir ?? process.cwd());
14452
+ const buildRoot = join16(rootDir, BUILD_OUTPUT_DIR);
14150
14453
  const serverEntry = (() => {
14151
14454
  if (options.target === "static" || options.target === "package") {
14152
14455
  return null;
14153
14456
  }
14154
14457
  if (options.serverEntry) {
14155
- const resolved = resolve7(rootDir, options.serverEntry);
14458
+ const resolved = resolve9(rootDir, options.serverEntry);
14156
14459
  if (existsSync14(resolved)) {
14157
14460
  return resolved;
14158
14461
  }
14159
14462
  }
14160
- const entry = resolve7(rootDir, "src/server.ts");
14463
+ const entry = resolve9(rootDir, "src/server.ts");
14161
14464
  if (!existsSync14(entry)) {
14162
14465
  throw new Error("[furin] Entrypoint server.ts not found");
14163
14466
  }
@@ -14198,12 +14501,12 @@ async function buildApp(options) {
14198
14501
  version: 1,
14199
14502
  generatedAt: new Date().toISOString(),
14200
14503
  rootDir: toPosixPath(rootDir),
14201
- pagesDir: toPosixPath(relative9(rootDir, primaryApp.pagesDir)),
14202
- rootPath: toPosixPath(relative9(rootDir, primaryApp.root.path)),
14203
- serverEntry: serverEntry ? toPosixPath(relative9(rootDir, serverEntry)) : null,
14504
+ pagesDir: toPosixPath(relative10(rootDir, primaryApp.pagesDir)),
14505
+ rootPath: toPosixPath(relative10(rootDir, primaryApp.root.path)),
14506
+ serverEntry: serverEntry ? toPosixPath(relative10(rootDir, serverEntry)) : null,
14204
14507
  routes: primaryApp.routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
14205
14508
  apps: apps.map((app) => ({
14206
- pagesDir: toPosixPath(relative9(rootDir, app.pagesDir)),
14509
+ pagesDir: toPosixPath(relative10(rootDir, app.pagesDir)),
14207
14510
  prefix: app.prefix,
14208
14511
  routes: app.routes.map((route) => toBuildRouteManifestEntry(route, rootDir))
14209
14512
  })),
@@ -14235,14 +14538,11 @@ async function buildApp(options) {
14235
14538
  }
14236
14539
  manifest.targets.vercel = await buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options);
14237
14540
  break;
14238
- case "node":
14239
- case "cloudflare":
14240
- throw new Error(`[furin] \`--target ${target}\` is planned but not implemented yet in this branch.`);
14241
14541
  default:
14242
14542
  throw new Error(`[furin] Unsupported build target "${target}"`);
14243
14543
  }
14244
14544
  }
14245
- writeFileSync9(join15(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
14545
+ writeFileSync10(join16(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
14246
14546
  `);
14247
14547
  return {
14248
14548
  manifest,