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

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 (129) 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 +27 -6
  6. package/dist/build/index.js +969 -528
  7. package/dist/build/private-server-sourcemaps.d.ts +2 -0
  8. package/dist/build/server-app-entry.d.ts +12 -0
  9. package/dist/build/types.d.ts +2 -0
  10. package/dist/cache.d.ts +1 -0
  11. package/dist/cache.js +185 -0
  12. package/dist/cli/index.js +983 -541
  13. package/dist/client/document.d.ts +2 -0
  14. package/dist/client/internal/runtime-types.d.ts +8 -1
  15. package/dist/client/link.js +232 -11
  16. package/dist/client/sync.d.ts +1 -0
  17. package/dist/client.js +11 -0
  18. package/dist/config.d.ts +28 -22
  19. package/dist/config.js +25 -2
  20. package/dist/define-route.d.ts +273 -1009
  21. package/dist/furin.d.ts +20 -5
  22. package/dist/furin.js +6431 -5457
  23. package/dist/plugin/routes.d.ts +6 -0
  24. package/dist/rsc-client.js +9 -1
  25. package/dist/rsc.js +19 -7
  26. package/dist/server/assets/production.d.ts +3 -0
  27. package/dist/server/auto-invalidate/plugin.d.ts +8 -24
  28. package/dist/server/auto-invalidate/runtime.d.ts +2 -2
  29. package/dist/server/browser-events/shutdown.d.ts +3 -0
  30. package/dist/server/cache/invalidation.d.ts +1 -1
  31. package/dist/server/cache/page-cache-state.d.ts +5 -0
  32. package/dist/server/cache/page-cache.d.ts +53 -0
  33. package/dist/server/cache/redis/index.d.ts +41 -0
  34. package/dist/server/cache/redis/index.js +451 -0
  35. package/dist/server/cache/redis/scripts.d.ts +6 -0
  36. package/dist/server/context-logger.d.ts +2 -2
  37. package/dist/server/dev/plugin.d.ts +1 -0
  38. package/dist/server/dev/runtime.production.d.ts +1 -0
  39. package/dist/server/dev-page-plugin.d.ts +7 -0
  40. package/dist/server/evlog.d.ts +14 -0
  41. package/dist/server/internal.d.ts +6 -0
  42. package/dist/server/internal.js +2539 -0
  43. package/dist/server/production-server.d.ts +13 -0
  44. package/dist/server/production-server.js +2906 -0
  45. package/dist/server/render/not-found.d.ts +1 -1
  46. package/dist/server/render/ssg.d.ts +5 -0
  47. package/dist/server/render/static-params.d.ts +4 -0
  48. package/dist/server/router/defined-route.d.ts +1 -1
  49. package/dist/server/router/hmr.d.ts +6 -0
  50. package/dist/server/router/hmr.production.d.ts +5 -0
  51. package/dist/server/router/plugin.d.ts +5 -1
  52. package/dist/server/router/schemas.d.ts +1 -0
  53. package/dist/server/sync/index.js +798 -117
  54. package/dist/server/sync/plugin.d.ts +31 -158
  55. package/dist/server/sync/stream.d.ts +38 -49
  56. package/dist/shared/elysia-contract.d.ts +8 -14
  57. package/dist/shared/production-build.d.ts +2 -0
  58. package/package.json +19 -8
  59. package/src/adapter/README.md +9 -2
  60. package/src/adapter/bun.ts +146 -41
  61. package/src/adapter/package.ts +6 -2
  62. package/src/adapter/runtime-build.ts +11 -4
  63. package/src/adapter/static.ts +8 -6
  64. package/src/adapter/vercel.ts +64 -31
  65. package/src/build/client.ts +18 -1
  66. package/src/build/compile-entry.ts +17 -13
  67. package/src/build/elysia-aot.ts +102 -0
  68. package/src/build/entry-template.ts +27 -6
  69. package/src/build/hydrate.ts +5 -1
  70. package/src/build/index.ts +5 -5
  71. package/src/build/private-server-sourcemaps.ts +20 -0
  72. package/src/build/production-instrumentation.ts +2 -2
  73. package/src/build/server-app-entry.ts +61 -0
  74. package/src/build/shared.ts +3 -1
  75. package/src/build/ssg-cache.ts +5 -10
  76. package/src/build/types.ts +2 -0
  77. package/src/build/virtual-entry.ts +5 -4
  78. package/src/cache.ts +12 -0
  79. package/src/cli/config.ts +3 -3
  80. package/src/cli/index.ts +6 -2
  81. package/src/client/document.tsx +19 -0
  82. package/src/client/internal/runtime-types.ts +10 -1
  83. package/src/client/sync.ts +1 -0
  84. package/src/config.ts +33 -4
  85. package/src/define-route.ts +266 -128
  86. package/src/furin.ts +168 -154
  87. package/src/plugin/route-config-autofix.ts +11 -2
  88. package/src/plugin/routes.ts +85 -29
  89. package/src/rsc/codec.ts +11 -6
  90. package/src/rsc/render-error.ts +3 -1
  91. package/src/server/assets/production.ts +99 -0
  92. package/src/server/auto-invalidate/plugin.ts +4 -4
  93. package/src/server/auto-invalidate/runtime.ts +74 -42
  94. package/src/server/browser-events/plugin.ts +13 -1
  95. package/src/server/browser-events/shutdown.ts +32 -0
  96. package/src/server/cache/invalidation.ts +61 -20
  97. package/src/server/cache/page-cache-state.ts +22 -0
  98. package/src/server/cache/page-cache.ts +300 -0
  99. package/src/server/cache/redis/index.ts +367 -0
  100. package/src/server/cache/redis/scripts.ts +200 -0
  101. package/src/server/context-logger.ts +5 -5
  102. package/src/server/dev/plugin.ts +10 -1
  103. package/src/server/dev/runtime.production.ts +4 -0
  104. package/src/server/dev-page-plugin.ts +54 -10
  105. package/src/server/evlog.ts +106 -0
  106. package/src/server/internal.ts +7 -0
  107. package/src/server/production-server.ts +135 -0
  108. package/src/server/render/document.tsx +7 -1
  109. package/src/server/render/isr.ts +480 -132
  110. package/src/server/render/loaders.ts +18 -12
  111. package/src/server/render/not-found.ts +4 -4
  112. package/src/server/render/ppr-document.ts +2 -2
  113. package/src/server/render/ppr-route.ts +193 -7
  114. package/src/server/render/ssg.ts +148 -4
  115. package/src/server/render/ssr.ts +6 -7
  116. package/src/server/render/static-params.ts +174 -0
  117. package/src/server/render/template.ts +5 -1
  118. package/src/server/router/defined-route.ts +2 -1
  119. package/src/server/router/discovery.ts +3 -1
  120. package/src/server/router/hmr.production.ts +11 -0
  121. package/src/server/router/hmr.ts +85 -76
  122. package/src/server/router/plugin.ts +118 -50
  123. package/src/server/router/schema-merge.ts +10 -3
  124. package/src/server/router/schemas.ts +174 -61
  125. package/src/server/sync/plugin.ts +14 -10
  126. package/src/server/sync/response.ts +3 -3
  127. package/src/server/sync/stream.ts +43 -2
  128. package/src/shared/elysia-contract.ts +23 -25
  129. package/src/shared/production-build.ts +20 -0
@@ -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,69 @@ 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, runtimeWaitUntil;
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;
2856
+ runtimeWaitUntil = new Set;
2863
2857
  });
2864
2858
 
2865
2859
  // src/server/context-logger.ts
2866
2860
  import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
2867
- function useLogger3() {
2861
+ function getLogger() {
2868
2862
  try {
2869
- return useLogger2();
2863
+ return getRequestLogger();
2870
2864
  } catch {
2871
2865
  return syntheticRenderStorage.getStore() ?? noopLogger2;
2872
2866
  }
@@ -2886,7 +2880,7 @@ async function runInSyntheticRenderScope(fn, initialContext) {
2886
2880
  var noopLogger2, syntheticRenderStorage;
2887
2881
  var init_context_logger = __esm(() => {
2888
2882
  init_dist();
2889
- init_elysia();
2883
+ init_evlog();
2890
2884
  noopLogger2 = {
2891
2885
  emit: () => null,
2892
2886
  error: () => {},
@@ -2906,7 +2900,7 @@ var IS_DEV = true;
2906
2900
  // src/server/dev/graph.ts
2907
2901
  import { randomUUID } from "crypto";
2908
2902
  import { readFileSync as readFileSync4, statSync as statSync2 } from "fs";
2909
- import { dirname as dirname5, extname as extname3 } from "path";
2903
+ import { dirname as dirname7, extname as extname3 } from "path";
2910
2904
  function normalizeModulePath(path) {
2911
2905
  return path.replaceAll("\\", "/");
2912
2906
  }
@@ -2915,7 +2909,7 @@ function resolveDevSourceImports(source, path, loader) {
2915
2909
  const transpiler = new Bun.Transpiler({ loader });
2916
2910
  for (const imported of transpiler.scanImports(source)) {
2917
2911
  try {
2918
- const resolved = normalizeModulePath(Bun.resolveSync(imported.path, dirname5(path)));
2912
+ const resolved = normalizeModulePath(Bun.resolveSync(imported.path, dirname7(path)));
2919
2913
  if (!resolved.includes("/node_modules/")) {
2920
2914
  imports.push(resolved);
2921
2915
  }
@@ -3365,6 +3359,7 @@ function browserEventsClientSource() {
3365
3359
 
3366
3360
  // src/server/browser-events/plugin.ts
3367
3361
  import { Elysia as Elysia3 } from "elysia";
3362
+ import { websocket } from "elysia/websocket";
3368
3363
  function browserEventsClientScript(basePath) {
3369
3364
  return `<script data-furin-framework-module="" type="module" src="${basePath}${CLIENT_PATH2}"></script>`;
3370
3365
  }
@@ -3389,15 +3384,23 @@ function injectDevDiagnosticClient(html, basePath) {
3389
3384
  }
3390
3385
  return html.includes("</head>") ? html.replace("</head>", `${script}</head>`) : `${script}${html}`;
3391
3386
  }
3387
+ var extensionErrorFilterScript = `window.addEventListener("unhandledrejection", (event) => {
3388
+ const stack = event.reason?.stack;
3389
+ if (typeof stack !== "string") return;
3390
+ const firstFrame = stack.match(/^(?:\\s*at [^\\n]*|[^\\n]*@[^\\n]*)/m)?.[0];
3391
+ if (firstFrame && /\\b(?:chrome|moz)-extension:\\/\\//.test(firstFrame)) {
3392
+ event.stopImmediatePropagation();
3393
+ }
3394
+ }, true);`;
3392
3395
  var init_plugin2 = () => {};
3393
3396
 
3394
3397
  // 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";
3398
+ import { existsSync as existsSync15, writeFileSync as writeFileSync11 } from "fs";
3399
+ import { join as join17, relative as relative11, resolve as resolve9 } from "path";
3397
3400
 
3398
3401
  // src/adapter/bun.ts
3399
- import { existsSync as existsSync9, rmSync as rmSync2 } from "fs";
3400
- import { join as join10, resolve as resolve4 } from "path";
3402
+ import { existsSync as existsSync10, readFileSync as readFileSync6, rmSync as rmSync2, writeFileSync as writeFileSync7 } from "fs";
3403
+ import { join as join12, resolve as resolve6 } from "path";
3401
3404
 
3402
3405
  // src/build/bun-build.ts
3403
3406
  function runBunBuild(config) {
@@ -3464,6 +3467,7 @@ function buildAppContextBlock(app, varPrefix) {
3464
3467
  const routeEntries = app.routes.map((r) => ` { pattern: ${JSON.stringify(r.pattern)}, path: ${JSON.stringify(r.path.replace(/\\/g, "/"))}, mode: ${JSON.stringify(r.mode)} },`);
3465
3468
  const rootConventionsLine = app.rootConventions ? ` rootConventions: ${JSON.stringify(app.rootConventions)},` : "";
3466
3469
  const routeMetadataLine = app.routeMetadata ? ` routeMetadata: ${JSON.stringify(app.routeMetadata)},` : "";
3470
+ const deploymentTargetLine = app.deploymentTarget === undefined ? "" : ` deploymentTarget: ${JSON.stringify(app.deploymentTarget)},`;
3467
3471
  const serveAssetsLine = app.serveAssets === undefined ? "" : ` serveAssets: ${JSON.stringify(app.serveAssets)},`;
3468
3472
  const ssgCacheLine = app.ssgCache ? ` ssgCache: ${JSON.stringify(app.ssgCache)},` : "";
3469
3473
  const templateHtmlLine = app.templateHtml === undefined ? "" : ` templateHtml: ${JSON.stringify(app.templateHtml)},`;
@@ -3471,6 +3475,7 @@ function buildAppContextBlock(app, varPrefix) {
3471
3475
  "__setCompileContext({",
3472
3476
  ` buildId: ${JSON.stringify(app.buildId ?? "")},`,
3473
3477
  ` clientLogging: ${JSON.stringify(app.clientLogging ?? false)},`,
3478
+ deploymentTargetLine,
3474
3479
  ` prefix: ${JSON.stringify(app.prefix ?? "")},`,
3475
3480
  ` rootPath: ${JSON.stringify(app.rootPath.replace(/\\/g, "/"))},`,
3476
3481
  app.nativeRoutes ? ` nativeRoutes: ${nativeRoutesVar},` : "",
@@ -3494,6 +3499,7 @@ function buildEntrySource(options) {
3494
3499
  const { apps, headerComment, serverEntry } = options;
3495
3500
  const mode = options.mode ?? "boot";
3496
3501
  const internalSpecifier = mode === "register" ? "@teyik0/furin/internal" : INTERNAL_MODULE_PATH;
3502
+ const productionMode = mode !== "register";
3497
3503
  const importLines = [];
3498
3504
  const contextBlocks = [];
3499
3505
  for (let appIndex = 0;appIndex < apps.length; appIndex++) {
@@ -3506,17 +3512,17 @@ function buildEntrySource(options) {
3506
3512
  const lines = [
3507
3513
  headerComment,
3508
3514
  `import { __setCompileContext } from ${JSON.stringify(internalSpecifier)};`,
3509
- ...mode === "boot" ? [`import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`] : [],
3515
+ ...productionMode ? [`import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`] : [],
3510
3516
  ...importLines,
3511
- ...mode === "boot" ? [
3517
+ ...productionMode ? [
3512
3518
  "",
3513
3519
  "// Force production mode \u2014 Bun may inline process.env.NODE_ENV at bundle time.",
3514
3520
  "__setDevMode(false);",
3515
- 'process.env.NODE_ENV = "production";'
3521
+ ...mode === "boot" ? ['process.env.NODE_ENV = "production";'] : []
3516
3522
  ] : [],
3517
3523
  ...contextBlocks,
3518
3524
  "",
3519
- ...serverEntry ? [
3525
+ ...serverEntry && mode === "boot" ? [
3520
3526
  `const __serverModule = await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
3521
3527
  'if (typeof __serverModule.startServer === "function") {',
3522
3528
  " await __serverModule.startServer();",
@@ -3534,6 +3540,15 @@ function buildEntrySource(options) {
3534
3540
  " }",
3535
3541
  "}",
3536
3542
  ""
3543
+ ] : serverEntry && mode === "app" ? [
3544
+ `const __serverModule = await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
3545
+ "export const app = __serverModule.default;",
3546
+ "export const port = __serverModule.port;",
3547
+ "export const idleTimeout = __serverModule.idleTimeout;",
3548
+ "export const startServer = __serverModule.startServer;",
3549
+ "export const onShutdown = __serverModule.onShutdown;",
3550
+ "export default __serverModule.default;",
3551
+ ""
3537
3552
  ] : []
3538
3553
  ];
3539
3554
  return lines.join(`
@@ -3566,7 +3581,7 @@ function toBuildRouteManifestEntry(route, rootDir) {
3566
3581
  mode: route.mode,
3567
3582
  pagePath: toPosixPath(relative(rootDir, route.path)),
3568
3583
  hasLayout: route.routeChain.some((entry) => !!entry.layout),
3569
- hasStaticParams: !!route.page?.staticParams,
3584
+ hasStaticParams: route.page.staticParams !== undefined || route.routeChain.some((entry) => entry.staticParams !== undefined),
3570
3585
  revalidate: resolveRouteRevalidate(route.page) ?? null
3571
3586
  };
3572
3587
  }
@@ -3586,12 +3601,13 @@ function buildTargetManifest(rootDir, buildRoot, target, serverEntry) {
3586
3601
  // src/build/virtual-entry.ts
3587
3602
  var REGEX_SPECIAL_CHARACTERS_RE = /[.*+?^${}()|[\]\\]/g;
3588
3603
  function createVirtualBuildEntry(entrypoint, source, loader) {
3589
- const entrypointFilter = new RegExp(`^${entrypoint.replace(REGEX_SPECIAL_CHARACTERS_RE, "\\$&")}$`);
3604
+ const normalizedEntrypoint = entrypoint.replaceAll("\\", "/");
3605
+ const entrypointFilter = new RegExp(`^${normalizedEntrypoint.replace(REGEX_SPECIAL_CHARACTERS_RE, "\\$&")}$`);
3590
3606
  return {
3591
- entrypoint,
3592
- files: { [entrypoint]: source },
3607
+ entrypoint: normalizedEntrypoint,
3608
+ files: { [normalizedEntrypoint]: source },
3593
3609
  plugin: {
3594
- name: `furin-virtual-entry:${entrypoint}`,
3610
+ name: `furin-virtual-entry:${normalizedEntrypoint}`,
3595
3611
  setup(build) {
3596
3612
  build.onLoad({ filter: entrypointFilter }, () => ({ contents: source, loader }));
3597
3613
  }
@@ -3614,10 +3630,8 @@ function buildEmbeddedContext(clientDir, publicDir) {
3614
3630
  " },"
3615
3631
  ];
3616
3632
  }
3617
- function generateCompileEntry(options) {
3618
- const { apps, outDir, serverEntry, publicDir } = options;
3619
- ensureDir(outDir);
3620
- const preparedApps = apps.map((app) => {
3633
+ function prepareCompileEntryApps(options) {
3634
+ return options.apps.map((app) => {
3621
3635
  const { embed, ...context } = app;
3622
3636
  if (!embed) {
3623
3637
  return context;
@@ -3626,31 +3640,125 @@ function generateCompileEntry(options) {
3626
3640
  ...context,
3627
3641
  extraContext: [
3628
3642
  ...context.extraContext ?? [],
3629
- ...buildEmbeddedContext(embed.clientDir, publicDir)
3643
+ ...buildEmbeddedContext(embed.clientDir, options.publicDir)
3630
3644
  ]
3631
3645
  };
3632
3646
  });
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");
3647
+ }
3648
+
3649
+ // src/build/elysia-aot.ts
3650
+ import { dirname as dirname2, resolve } from "path";
3651
+ import { aotFactory } from "elysia/plugin/aot/unplugin";
3652
+ var AOT_NAMESPACE = "furin-elysia-aot";
3653
+ var ELYSIA_RESOLVE_DIR = dirname2(Bun.resolveSync("elysia", import.meta.dir));
3654
+ var SOURCE_FILTER = /\.[cm]?[jt]sx?$/;
3655
+ var WEBSOCKET_STUB_MARKER = "[elysia-aot] WebSocket route builder was stripped (strip mode) but a WS route was used.";
3656
+ function loaderFor(path) {
3657
+ const extension = path.slice(path.lastIndexOf("."));
3658
+ if (extension === ".jsx") {
3659
+ return "jsx";
3660
+ }
3661
+ if (extension === ".tsx") {
3662
+ return "tsx";
3663
+ }
3664
+ if (extension === ".ts" || extension === ".mts" || extension === ".cts") {
3665
+ return "ts";
3666
+ }
3667
+ return "js";
3668
+ }
3669
+ function patchElysiaWebSocketStub(source) {
3670
+ if (!source.includes(WEBSOCKET_STUB_MARKER) || source.includes("accumulateWSOptions")) {
3671
+ return source;
3672
+ }
3673
+ return `${source}
3674
+ export function accumulateWSOptions(){return e()}
3675
+ export function resolveWSOptions(){return e()}
3676
+ export function drainWaiters(){return e()}
3677
+ export function handleWSResponse(){return e()}
3678
+ `;
3679
+ }
3680
+ function elysiaAot(entry) {
3681
+ const entryPath = resolve(entry);
3682
+ const hooks = aotFactory({ entry, strip: false, target: "bun" });
3683
+ return {
3684
+ name: "elysia-aot",
3685
+ async setup(build) {
3686
+ try {
3687
+ await hooks.buildStart?.();
3688
+ } catch (error) {
3689
+ if (error instanceof Error && error.message.startsWith("[elysia-aot]") && error.message.includes("mounts a sub-app")) {
3690
+ console.warn("[furin] Elysia AOT skipped because the app uses .mount().");
3691
+ return;
3692
+ }
3693
+ throw error;
3694
+ }
3695
+ const entrySource = await Bun.file(entryPath).text();
3696
+ const transformedEntry = await hooks.transform?.(entrySource, entryPath);
3697
+ if (transformedEntry !== undefined) {
3698
+ await Bun.write(entryPath, transformedEntry);
3699
+ }
3700
+ build.onResolve({ filter: /^elysia(?:\/(?!compiled$|type$).*)?$/ }, ({ path }) => ({
3701
+ path: Bun.resolveSync(path, ELYSIA_RESOLVE_DIR)
3702
+ }));
3703
+ build.onResolve({ filter: /^elysia\/(?:compiled|type)$/ }, ({ path }) => {
3704
+ const resolved = hooks.resolveId?.(path);
3705
+ return resolved === undefined ? undefined : { namespace: AOT_NAMESPACE, path: resolved };
3706
+ });
3707
+ build.onLoad({ filter: /.*/, namespace: AOT_NAMESPACE }, ({ path }) => {
3708
+ const contents = hooks.load?.(path);
3709
+ return contents === undefined ? undefined : { contents, loader: "js", resolveDir: ELYSIA_RESOLVE_DIR };
3710
+ });
3711
+ build.onLoad({ filter: SOURCE_FILTER }, async ({ path }) => {
3712
+ if (resolve(path) === entryPath) {
3713
+ return;
3714
+ }
3715
+ if (hooks.transformInclude?.(path) === false) {
3716
+ return;
3717
+ }
3718
+ const original = await Bun.file(path).text();
3719
+ const transformed = await hooks.transform?.(original, path);
3720
+ if (transformed === undefined) {
3721
+ return;
3722
+ }
3723
+ return {
3724
+ contents: patchElysiaWebSocketStub(transformed),
3725
+ loader: loaderFor(path)
3726
+ };
3727
+ });
3728
+ build.onEnd(() => {
3729
+ hooks.buildEnd?.();
3730
+ });
3731
+ }
3732
+ };
3733
+ }
3734
+
3735
+ // src/build/private-server-sourcemaps.ts
3736
+ import { existsSync as existsSync4, renameSync } from "fs";
3737
+ import { dirname as dirname3, isAbsolute, join as join4, relative as relative2 } from "path";
3738
+ function movePrivateServerSourceMaps(outputDir, privateDir, filenames) {
3739
+ for (const filename of filenames) {
3740
+ const source = isAbsolute(filename) ? filename : join4(outputDir, filename);
3741
+ if (!existsSync4(source)) {
3742
+ continue;
3743
+ }
3744
+ const destination = join4(privateDir, relative2(outputDir, source));
3745
+ ensureDir(dirname3(destination));
3746
+ renameSync(source, destination);
3747
+ }
3640
3748
  }
3641
3749
 
3642
3750
  // src/build/production-instrumentation.ts
3643
- import { dirname as dirname2, relative as relative2, resolve } from "path";
3751
+ import { dirname as dirname4, relative as relative3, resolve as resolve2 } from "path";
3644
3752
  var INSTRUMENTATION_IMPORT = /(?:^|[/\\])devtools[/\\]instrumentation(?:\.ts|\.js)?$/;
3645
3753
  var DEV_PAGE_PLUGIN_IMPORT = /(?:^|[/\\])server[/\\]dev-page-plugin(?:\.ts|\.js)?$/;
3646
- var DEV_RUNTIME_IMPORT = /(?:^|[/\\])server[/\\]dev[/\\](?:browser-events|diagnostics|plugin)(?:\.ts|\.js)?$/;
3754
+ var DEV_RUNTIME_IMPORT = /(?:^|[/\\])server[/\\]dev[/\\](?:browser-events|diagnostics|graph|plugin)(?:\.ts|\.js)?$/;
3647
3755
  var DEV_BUILD_IMPORT = /(?:^|[/\\])(?:build[/\\]hydrate|plugin[/\\]route-config-autofix)(?:\.ts|\.js)?$/;
3648
3756
  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)?$/;
3757
+ var PRODUCTION_BOUNDARY_IMPORT = /(?:browser-events|instrumentation|dev-page-plugin|diagnostics|graph|plugin|hmr|hydrate|route-config-autofix)(?:\.ts|\.js)?$/;
3650
3758
  var PRODUCTION_STUB_NAMESPACE = "furin-production-runtime-stub";
3651
- var FURIN_RUNTIME_ROOT = resolve(import.meta.dir, "..");
3759
+ var FURIN_RUNTIME_ROOT = resolve2(import.meta.dir, "..");
3652
3760
  function isFurinRuntimePath(path) {
3653
- const fromRuntimeRoot = relative2(FURIN_RUNTIME_ROOT, path);
3761
+ const fromRuntimeRoot = relative3(FURIN_RUNTIME_ROOT, path);
3654
3762
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
3655
3763
  }
3656
3764
  function devBuildExport(path) {
@@ -3661,23 +3769,23 @@ function productionInstrumentationPlugin() {
3661
3769
  name: "furin-production-instrumentation",
3662
3770
  setup(build) {
3663
3771
  build.onResolve({ filter: PRODUCTION_BOUNDARY_IMPORT }, (args) => {
3664
- const importPath = resolve(dirname2(args.importer), args.path);
3772
+ const importPath = resolve2(dirname4(args.importer), args.path);
3665
3773
  if (!isFurinRuntimePath(importPath)) {
3666
3774
  return;
3667
3775
  }
3668
3776
  if (INSTRUMENTATION_IMPORT.test(importPath)) {
3669
3777
  return {
3670
- path: resolve(import.meta.dir, "../server/devtools/instrumentation.production.ts")
3778
+ path: resolve2(import.meta.dir, "../server/devtools/instrumentation.production.ts")
3671
3779
  };
3672
3780
  }
3673
3781
  if (DEV_PAGE_PLUGIN_IMPORT.test(importPath)) {
3674
- return { path: resolve(import.meta.dir, "../server/dev-page-plugin.production.ts") };
3782
+ return { path: resolve2(import.meta.dir, "../server/dev-page-plugin.production.ts") };
3675
3783
  }
3676
3784
  if (DEV_RUNTIME_IMPORT.test(importPath)) {
3677
- return { path: resolve(import.meta.dir, "../server/dev/runtime.production.ts") };
3785
+ return { path: resolve2(import.meta.dir, "../server/dev/runtime.production.ts") };
3678
3786
  }
3679
3787
  if (HMR_IMPORT.test(importPath)) {
3680
- return { path: resolve(import.meta.dir, "../server/router/hmr.production.ts") };
3788
+ return { path: resolve2(import.meta.dir, "../server/router/hmr.production.ts") };
3681
3789
  }
3682
3790
  if (DEV_BUILD_IMPORT.test(importPath)) {
3683
3791
  return { namespace: PRODUCTION_STUB_NAMESPACE, path: importPath };
@@ -3693,33 +3801,32 @@ function productionInstrumentationPlugin() {
3693
3801
  };
3694
3802
  }
3695
3803
 
3804
+ // src/build/server-app-entry.ts
3805
+ import { writeFileSync } from "fs";
3806
+ import { join as join6 } from "path";
3807
+
3696
3808
  // src/plugin/routes.ts
3697
3809
  import {
3698
- existsSync as existsSync4,
3810
+ existsSync as existsSync5,
3699
3811
  readdirSync as readdirSync2,
3700
3812
  readFileSync,
3701
3813
  realpathSync,
3702
3814
  statSync,
3703
3815
  watch
3704
3816
  } from "fs";
3705
- import { dirname as dirname3, extname, isAbsolute, join as join4, relative as relative3, resolve as resolve2, sep } from "path";
3817
+ import { dirname as dirname5, extname, isAbsolute as isAbsolute2, join as join5, relative as relative4, resolve as resolve3, sep } from "path";
3706
3818
  import { pathToFileURL } from "url";
3707
3819
  import { Elysia } from "elysia";
3708
3820
 
3709
3821
  // 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";
3822
+ import { Validator } from "elysia";
3716
3823
  var TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
3717
3824
  function isTypeBoxObjectSchema(schema) {
3718
3825
  if (schema === null || typeof schema !== "object") {
3719
3826
  return false;
3720
3827
  }
3721
3828
  const candidate = schema;
3722
- return candidate[TYPEBOX_KIND] === "Object" || candidate["~kind"] === "Object";
3829
+ return (candidate[TYPEBOX_KIND] === "Object" || candidate["~kind"] === "Object") && candidate.properties !== null && typeof candidate.properties === "object";
3723
3830
  }
3724
3831
 
3725
3832
  // src/shared/search-params.ts
@@ -3862,8 +3969,8 @@ function findSearchDefaultsForRouteTarget(to, routes) {
3862
3969
  init_patterns();
3863
3970
 
3864
3971
  // src/server/router/schema-merge.ts
3865
- import { t } from "elysia";
3866
3972
  var TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
3973
+ var TYPEBOX_OPTIONAL = Symbol.for("TypeBox.Optional");
3867
3974
  function mergeRouteSchemas(routeChain, key) {
3868
3975
  const schemas = routeChain.flatMap((route) => route[key] ? [route[key]] : []);
3869
3976
  if (schemas.length === 0) {
@@ -3873,11 +3980,17 @@ function mergeRouteSchemas(routeChain, key) {
3873
3980
  return schemas[0];
3874
3981
  }
3875
3982
  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.`);
3983
+ 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
3984
  }
3878
3985
  const properties = Object.assign({}, ...schemas.map((schema) => schema.properties));
3879
3986
  const options = Object.assign({}, ...schemas.map((schema) => Object.fromEntries(Object.entries(schema).filter(([name]) => !TOBJECT_STRUCTURAL_KEYS.has(name)))));
3880
- return t.Object(properties, options);
3987
+ const required = Object.keys(properties).filter((name) => {
3988
+ const property = properties[name];
3989
+ return !(property["~optional"] || property[TYPEBOX_OPTIONAL]);
3990
+ });
3991
+ return Object.defineProperty({ ...options, properties, required, type: "object" }, "~kind", {
3992
+ value: "Object"
3993
+ });
3881
3994
  }
3882
3995
 
3883
3996
  // src/server/router/schemas.ts
@@ -3937,10 +4050,11 @@ function unwrapTSExpression(node) {
3937
4050
  init_patterns();
3938
4051
  var ROUTES_NAMESPACE_PREFIX = "furin-routes";
3939
4052
  var ROUTES_REGISTRY_SPECIFIER = "furin/routes?registry";
3940
- var ROUTES_REGISTRY_FILTER = /^furin\/routes\?registry$/;
4053
+ var COMPOSABLE_ROUTES_REGISTRY_SPECIFIER = "furin/routes?registry=composable";
4054
+ var ROUTES_REGISTRY_FILTER = /^furin\/routes\?registry(?:=composable)?$/;
3941
4055
  var ROUTE_FILE_FILTER = /^furin-route-file:.+$/;
3942
4056
  var ROUTE_FILES_NAMESPACE = "furin-route-files";
3943
- var ROUTES_REGISTRY_FILE_FILTER = /[\\/]\.furin-routes-registry\.ts\?furin-virtual$/;
4057
+ var ROUTES_REGISTRY_FILE_FILTER = /[\\/]\.furin-routes-registry(?:-composable)?\.ts\?furin-virtual$/;
3944
4058
  var CLIENT_ROUTES_NAMESPACE = "furin-routes-client";
3945
4059
  var CLIENT_ROUTES_FILTER = /^(?:@teyik0\/furin|furin)\/routes$/;
3946
4060
  var SERVER_ROUTES_FILTER = /^(?:@teyik0\/furin|furin)\/routes\?instance=.+$/;
@@ -3951,11 +4065,14 @@ var DEV_ROUTES_APPS_SYMBOL = Symbol.for("@teyik0/furin/dev-routes-apps");
3951
4065
  var DEV_ROUTE_WATCHERS_SYMBOL = Symbol.for("@teyik0/furin/dev-route-watchers");
3952
4066
  var devInstancesBySpecifier = new Map;
3953
4067
  function instanceKey(instance) {
3954
- return `${resolve2(instance.pagesDir)}\x00${instance.prefix}`;
4068
+ return `${resolve3(instance.pagesDir)}\x00${instance.prefix}`;
3955
4069
  }
3956
4070
  function routeModuleSpecifier(instance) {
3957
4071
  return `@teyik0/furin/routes?instance=${Bun.hash(instanceKey(instance)).toString(16)}`;
3958
4072
  }
4073
+ function composableRouteModuleSpecifier(instance) {
4074
+ return `${routeModuleSpecifier(instance)}&composable`;
4075
+ }
3959
4076
  function instanceNamespace(instance) {
3960
4077
  return `${ROUTES_NAMESPACE_PREFIX}-${Bun.hash(instanceKey(instance)).toString(16)}`;
3961
4078
  }
@@ -3965,7 +4082,7 @@ function scanRouteFiles(directory, directorySegments, files) {
3965
4082
  if (entry.name.startsWith("_")) {
3966
4083
  continue;
3967
4084
  }
3968
- scanRouteFiles(join4(directory, entry.name), [...directorySegments, entry.name], files);
4085
+ scanRouteFiles(join5(directory, entry.name), [...directorySegments, entry.name], files);
3969
4086
  continue;
3970
4087
  }
3971
4088
  const extension = extname(entry.name);
@@ -3973,7 +4090,7 @@ function scanRouteFiles(directory, directorySegments, files) {
3973
4090
  continue;
3974
4091
  }
3975
4092
  const base = entry.name.slice(0, -extension.length);
3976
- const sourcePath = join4(directory, entry.name);
4093
+ const sourcePath = join5(directory, entry.name);
3977
4094
  for (const segment of [...directorySegments, base]) {
3978
4095
  parseDynamicRouteSegment(segment, sourcePath);
3979
4096
  }
@@ -4062,9 +4179,9 @@ function collectRouteFiles(root) {
4062
4179
  }
4063
4180
  function routeSourcePaths(instance) {
4064
4181
  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));
4182
+ return collectRouteFiles(buildRouteTree(instance.pagesDir, instanceId)).map(({ sourcePath }) => resolve3(sourcePath)).toSorted((left, right) => left.localeCompare(right));
4066
4183
  }
4067
- function emitRouteNode(node, indentation) {
4184
+ function emitRouteNode(node, indentation, includeRootCatchAll) {
4068
4185
  const childIndentation = `${indentation} `;
4069
4186
  const prefix = node.name ? `/${segmentPath(node.name)}` : "";
4070
4187
  const head = `new Elysia({ prefix: ${JSON.stringify(prefix)} })`;
@@ -4072,13 +4189,13 @@ function emitRouteNode(node, indentation) {
4072
4189
  if (node.indexRoute) {
4073
4190
  content.push(`${childIndentation}.use(new Elysia({ prefix: "" }).use(${node.indexRoute.id}.elysia))`);
4074
4191
  }
4075
- for (const route of node.fileRoutes) {
4192
+ for (const route of node.fileRoutes.filter((file) => includeRootCatchAll || file.path !== "/*")) {
4076
4193
  const segment = route.path.slice(route.path.lastIndexOf("/") + 1);
4077
4194
  content.push(`${childIndentation}.use(new Elysia({ prefix: ${JSON.stringify(`/${segment}`)} }).use(${route.id}.elysia))`);
4078
4195
  }
4079
4196
  for (const child of node.children) {
4080
4197
  content.push(`${childIndentation}.use(`);
4081
- content.push(emitRouteNode(child, `${childIndentation} `));
4198
+ content.push(emitRouteNode(child, `${childIndentation} `, includeRootCatchAll));
4082
4199
  content.push(`${childIndentation})`);
4083
4200
  }
4084
4201
  if (node.layout) {
@@ -4111,28 +4228,28 @@ async function retainComposableRoutes(node) {
4111
4228
  node.fileRoutes = composableRoutes;
4112
4229
  await Promise.all(node.children.map((child) => retainComposableRoutes(child)));
4113
4230
  }
4114
- async function generateServerInstance(instance, routeFilesBySpecifier) {
4231
+ async function generateServerInstance(instance, routeFilesBySpecifier, materialized, includeRootCatchAll) {
4115
4232
  const instanceId = Bun.hash(instanceKey(instance)).toString(16);
4116
4233
  const tree = buildRouteTree(instance.pagesDir, instanceId);
4117
4234
  await retainComposableRoutes(tree);
4118
4235
  const imports = collectRouteFiles(tree).sort((left, right) => left.sourcePath.localeCompare(right.sourcePath)).map((route) => {
4119
- const specifier = routeFileSpecifier(route);
4236
+ const specifier = materialized ? resolve3(route.sourcePath).replaceAll("\\", "/") : routeFileSpecifier(route);
4120
4237
  routeFilesBySpecifier.set(specifier, {
4121
4238
  routePath: route.path,
4122
- sourcePath: resolve2(route.sourcePath)
4239
+ sourcePath: resolve3(route.sourcePath)
4123
4240
  });
4124
4241
  return `import { route as ${route.id} } from ${JSON.stringify(specifier)};`;
4125
4242
  }).join(`
4126
4243
  `);
4127
4244
  return {
4128
- appExpression: emitRouteNode(tree, ""),
4245
+ appExpression: emitRouteNode(tree, "", includeRootCatchAll),
4129
4246
  exportName: `furinApp_${instanceId}`,
4130
4247
  imports
4131
4248
  };
4132
4249
  }
4133
- async function serverRegistrySource(instances, routeFilesBySpecifier) {
4250
+ async function serverRegistrySource(instances, routeFilesBySpecifier, materialized, includeRootCatchAll) {
4134
4251
  routeFilesBySpecifier.clear();
4135
- const generated = await Promise.all(instances.map((instance) => generateServerInstance(instance, routeFilesBySpecifier)));
4252
+ const generated = await Promise.all(instances.map((instance) => generateServerInstance(instance, routeFilesBySpecifier, materialized, includeRootCatchAll)));
4136
4253
  return `import { Elysia } from "elysia";
4137
4254
  ${generated.map(({ imports }) => imports).join(`
4138
4255
  `)}
@@ -4141,6 +4258,15 @@ ${generated.map(({ appExpression, exportName }) => `export const ${exportName} =
4141
4258
  `)}
4142
4259
  `;
4143
4260
  }
4261
+ async function materializedRouteModuleSource(instance) {
4262
+ const routeFilesBySpecifier = new Map;
4263
+ const source = await serverRegistrySource([instance], routeFilesBySpecifier, true, false);
4264
+ await validateRouteModules(routeFilesBySpecifier.values());
4265
+ const exportName = `furinApp_${Bun.hash(instanceKey(instance)).toString(16)}`;
4266
+ return `${source}
4267
+ export { ${exportName} as furinApp };
4268
+ `;
4269
+ }
4144
4270
  function validateRouteParams(path, schemas) {
4145
4271
  const pathParams = path.split("/").filter((segment) => segment === "*" || segment.startsWith(":")).map((segment) => segment === "*" ? segment : segment.slice(1));
4146
4272
  if (pathParams.length === 0) {
@@ -4163,19 +4289,19 @@ function routeModuleCache() {
4163
4289
  return cache;
4164
4290
  }
4165
4291
  function findPackageRoot(sourcePath) {
4166
- const fallback = dirname3(sourcePath);
4292
+ const fallback = dirname5(sourcePath);
4167
4293
  let directory = fallback;
4168
- while (dirname3(directory) !== directory) {
4169
- if (existsSync4(join4(directory, "package.json"))) {
4294
+ while (dirname5(directory) !== directory) {
4295
+ if (existsSync5(join5(directory, "package.json"))) {
4170
4296
  return directory;
4171
4297
  }
4172
- directory = dirname3(directory);
4298
+ directory = dirname5(directory);
4173
4299
  }
4174
- return existsSync4(join4(directory, "package.json")) ? directory : fallback;
4300
+ return existsSync5(join5(directory, "package.json")) ? directory : fallback;
4175
4301
  }
4176
4302
  function isWithinDirectory(path, directory) {
4177
- const relativePath = relative3(directory, path);
4178
- return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute(relativePath));
4303
+ const relativePath = relative4(directory, path);
4304
+ return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute2(relativePath));
4179
4305
  }
4180
4306
  function isFurinPackageImport(specifier) {
4181
4307
  return specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/");
@@ -4192,8 +4318,8 @@ function resolveRouteModuleImports(dependencyPath, packageRoot) {
4192
4318
  continue;
4193
4319
  }
4194
4320
  try {
4195
- const resolvedImport = realpathSync(Bun.resolveSync(imported.path, dirname3(dependencyPath)));
4196
- if (isAbsolute(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot)) {
4321
+ const resolvedImport = realpathSync(Bun.resolveSync(imported.path, dirname5(dependencyPath)));
4322
+ if (isAbsolute2(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot)) {
4197
4323
  resolvedImports.push(resolvedImport);
4198
4324
  }
4199
4325
  } catch {}
@@ -4282,18 +4408,30 @@ function primaryInstance(instances) {
4282
4408
  }
4283
4409
  return instance;
4284
4410
  }
4285
- function serverProxySource(instance) {
4411
+ function serverProxySource(instance, includeRootCatchAll) {
4286
4412
  const exportName = `furinApp_${Bun.hash(instanceKey(instance)).toString(16)}`;
4287
- return `export { ${exportName} as furinApp } from ${JSON.stringify(ROUTES_REGISTRY_SPECIFIER)};
4413
+ const registry = includeRootCatchAll ? ROUTES_REGISTRY_SPECIFIER : COMPOSABLE_ROUTES_REGISTRY_SPECIFIER;
4414
+ return `export { ${exportName} as furinApp } from ${JSON.stringify(registry)};
4288
4415
  `;
4289
4416
  }
4290
4417
  function createRoutesPlugin(options) {
4291
4418
  const routeFilesBySpecifier = new Map;
4292
4419
  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) }
4420
+ const registryVirtualPath = join5(resolve3(primaryInstance(options.instances).pagesDir), ".furin-routes-registry.ts?furin-virtual");
4421
+ const composableRegistryVirtualPath = join5(resolve3(primaryInstance(options.instances).pagesDir), ".furin-routes-registry-composable.ts?furin-virtual");
4422
+ const instancesBySpecifier = new Map(options.instances.flatMap((instance) => [
4423
+ [
4424
+ routeModuleSpecifier(instance),
4425
+ { includeRootCatchAll: true, instance, namespace: instanceNamespace(instance) }
4426
+ ],
4427
+ [
4428
+ composableRouteModuleSpecifier(instance),
4429
+ {
4430
+ includeRootCatchAll: false,
4431
+ instance,
4432
+ namespace: `${instanceNamespace(instance)}-composable`
4433
+ }
4434
+ ]
4297
4435
  ]));
4298
4436
  return {
4299
4437
  name: `furin-routes-${options.target}`,
@@ -4314,12 +4452,12 @@ function createRoutesPlugin(options) {
4314
4452
  }
4315
4453
  return { namespace: registered.namespace, path };
4316
4454
  });
4317
- build.onResolve({ filter: ROUTES_REGISTRY_FILTER }, () => ({
4455
+ build.onResolve({ filter: ROUTES_REGISTRY_FILTER }, ({ path }) => ({
4318
4456
  namespace: "file",
4319
- path: registryVirtualPath
4457
+ path: path === ROUTES_REGISTRY_SPECIFIER ? registryVirtualPath : composableRegistryVirtualPath
4320
4458
  }));
4321
- build.onLoad({ filter: ROUTES_REGISTRY_FILE_FILTER, namespace: "file" }, async () => {
4322
- const contents = await serverRegistrySource(options.instances, routeFilesBySpecifier);
4459
+ build.onLoad({ filter: ROUTES_REGISTRY_FILE_FILTER, namespace: "file" }, async ({ path }) => {
4460
+ const contents = await serverRegistrySource(options.instances, routeFilesBySpecifier, false, path === registryVirtualPath);
4323
4461
  await validateRouteModules(routeFilesBySpecifier.values());
4324
4462
  return { contents, loader: "ts" };
4325
4463
  });
@@ -4340,12 +4478,12 @@ function createRoutesPlugin(options) {
4340
4478
  return {
4341
4479
  contents: await Bun.file(routeFile.sourcePath).text(),
4342
4480
  loader: detectLoaderFromPath(routeFile.sourcePath),
4343
- resolveDir: dirname3(routeFile.sourcePath)
4481
+ resolveDir: dirname5(routeFile.sourcePath)
4344
4482
  };
4345
4483
  });
4346
- for (const { instance, namespace } of instancesBySpecifier.values()) {
4484
+ for (const { instance, namespace, includeRootCatchAll } of instancesBySpecifier.values()) {
4347
4485
  build.onLoad({ filter: VIRTUAL_ROUTES_FILTER, namespace }, () => ({
4348
- contents: serverProxySource(instance),
4486
+ contents: serverProxySource(instance, includeRootCatchAll),
4349
4487
  loader: "ts"
4350
4488
  }));
4351
4489
  }
@@ -4353,6 +4491,44 @@ function createRoutesPlugin(options) {
4353
4491
  };
4354
4492
  }
4355
4493
 
4494
+ // src/build/server-app-entry.ts
4495
+ async function materializeServerAppEntry(options) {
4496
+ ensureDir(options.outDir);
4497
+ const apps = await Promise.all(options.apps.map(async (app, index) => {
4498
+ const instance = options.instances[index];
4499
+ if (!instance) {
4500
+ throw new Error(`[furin] Missing route instance for server app ${index}.`);
4501
+ }
4502
+ const routePath = join6(options.outDir, `_furin-routes-${index}.ts`);
4503
+ writeFileSync(routePath, await materializedRouteModuleSource(instance));
4504
+ return { ...app, nativeRoutes: toPosixPath(routePath) };
4505
+ }));
4506
+ const entryPath = join6(options.outDir, "_furin-app.ts");
4507
+ writeFileSync(entryPath, buildEntrySource({
4508
+ apps,
4509
+ headerComment: options.headerComment,
4510
+ mode: "app",
4511
+ serverEntry: options.serverEntry
4512
+ }));
4513
+ return entryPath;
4514
+ }
4515
+ function serverBootSource(appEntry) {
4516
+ return `// Auto-generated by furin build - do not edit
4517
+ import { startProductionServer } from "@teyik0/furin/production-server";
4518
+ import app, { idleTimeout, onShutdown, port, startServer } from ${JSON.stringify(toPosixPath(appEntry))};
4519
+
4520
+ if (typeof startServer === "function") {
4521
+ await startServer();
4522
+ } else if (app && typeof app.listen === "function" && !app.server) {
4523
+ const serverPort = process.env.PORT === undefined
4524
+ ? typeof port === "number" ? port : 3000
4525
+ : Number(process.env.PORT);
4526
+ startProductionServer({ app, idleTimeout, onShutdown, port: serverPort });
4527
+ console.log(\`[furin] Server running at http://localhost:\${app.server?.port}\`);
4528
+ }
4529
+ `;
4530
+ }
4531
+
4356
4532
  // ../../node_modules/.bun/magic-string@1.2.3/node_modules/magic-string/dist/index.mjs
4357
4533
  init_sourcemap_codec();
4358
4534
  var BitSet = class BitSet {
@@ -6808,13 +6984,13 @@ function assertNoPrefixSlugCollisions(prefixes) {
6808
6984
  }
6809
6985
 
6810
6986
  // 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";
6987
+ import { existsSync as existsSync9, writeFileSync as writeFileSync6 } from "fs";
6988
+ import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute3, join as join11, relative as relative7, resolve as resolve5 } from "path";
6813
6989
  import { fileURLToPath as fileURLToPath5 } from "url";
6814
6990
 
6815
6991
  // 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";
6992
+ import { existsSync as existsSync8, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "fs";
6993
+ import { basename as basename2, dirname as dirname6, join as join9, resolve as resolve4 } from "path";
6818
6994
 
6819
6995
  // src/plugin/transform-client.ts
6820
6996
  var FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
@@ -7451,8 +7627,8 @@ if (import.meta.hot && route?.component) {
7451
7627
  }
7452
7628
 
7453
7629
  // 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";
7630
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
7631
+ import { join as join8 } from "path";
7456
7632
 
7457
7633
  // src/server/render/shell.ts
7458
7634
  function escapeHtml(str) {
@@ -7506,8 +7682,8 @@ ${buildIdMeta}${modeMeta}${faviconLink}${cssLinks ? `${cssLinks}
7506
7682
  init_patterns();
7507
7683
 
7508
7684
  // 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";
7685
+ import { existsSync as existsSync6, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "fs";
7686
+ import { extname as extname2, join as join7, relative as relative5 } from "path";
7511
7687
 
7512
7688
  // src/shared/route-map.ts
7513
7689
  function routeTypeProperty(pattern) {
@@ -7554,7 +7730,7 @@ function writeRouteTypes(routes, projectRoot) {
7554
7730
  const entries = routes.map((route) => {
7555
7731
  const extension = extname2(route.path);
7556
7732
  const sourcePath = extension ? route.path.slice(0, -extension.length) : route.path;
7557
- const relativePath = relative4(projectRoot, sourcePath).replaceAll("\\", "/");
7733
+ const relativePath = relative5(projectRoot, sourcePath).replaceAll("\\", "/");
7558
7734
  const specifier = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
7559
7735
  return { importSpecifier: specifier, pattern: route.pattern };
7560
7736
  });
@@ -7573,14 +7749,14 @@ import "@teyik0/furin/routes";
7573
7749
 
7574
7750
  ${routeMapDeclaration(entries)}${tagBlock}
7575
7751
  `;
7576
- const typesPath = join5(projectRoot, "furin-env.d.ts");
7577
- const existing = existsSync5(typesPath) ? readFileSync2(typesPath, "utf8") : "";
7752
+ const typesPath = join7(projectRoot, "furin-env.d.ts");
7753
+ const existing = existsSync6(typesPath) ? readFileSync2(typesPath, "utf8") : "";
7578
7754
  if (content === existing) {
7579
7755
  return false;
7580
7756
  }
7581
7757
  const temporaryPath = `${typesPath}.${process.pid}.${Bun.nanoseconds()}.tmp`;
7582
- writeFileSync(temporaryPath, content);
7583
- renameSync(temporaryPath, typesPath);
7758
+ writeFileSync2(temporaryPath, content);
7759
+ renameSync2(temporaryPath, typesPath);
7584
7760
  return true;
7585
7761
  }
7586
7762
 
@@ -7720,6 +7896,7 @@ const _match = routes.find((r) => r.regex.test(pathname));
7720
7896
  // a matched loader threw notFound(). The latter still has a _match; the
7721
7897
  // former does not \u2014 so the two cases fork on _match below.
7722
7898
  const dataEl = document.getElementById("__FURIN_DATA__");
7899
+ const frameTemplate = document.getElementById("__FURIN_ROUTE_FRAMES__") as HTMLTemplateElement | null;
7723
7900
  let loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
7724
7901
  const syncEl = document.getElementById("__FURIN_SYNC__");
7725
7902
  const syncConfig = syncEl ? JSON.parse(syncEl.textContent || "{}") : {};
@@ -7736,6 +7913,7 @@ const documentState: DocumentState = {
7736
7913
  assets: {
7737
7914
  buildId,
7738
7915
  entryModule: entryEl?.getAttribute("src") ?? undefined,
7916
+ extensionErrorFilterScript: document.querySelector("[data-furin-extension-error-filter]")?.textContent ?? undefined,
7739
7917
  faviconHref,
7740
7918
  frameworkModules,
7741
7919
  staticMode: document.querySelector('meta[name="furin-mode"][content="static"]') !== null,
@@ -7745,6 +7923,9 @@ const documentState: DocumentState = {
7745
7923
  },
7746
7924
  dataJson: dataEl?.textContent ?? undefined,
7747
7925
  head,
7926
+ routeFrames: frameTemplate?.hasAttribute("data-furin-document-state")
7927
+ ? (frameTemplate.content.textContent ?? "")
7928
+ : undefined,
7748
7929
  syncJson: syncEl?.textContent ?? undefined,
7749
7930
  };
7750
7931
 
@@ -7819,7 +8000,6 @@ if (__deferred && __deferred._chunks) {
7819
8000
  // Wrapped in an async IIFE to avoid top-level await, which causes Bun's HTML
7820
8001
  // bundler to misidentify which chunk to reference as the entry in index.html.
7821
8002
  (async () => {
7822
- const frameTemplate = document.getElementById("__FURIN_ROUTE_FRAMES__") as HTMLTemplateElement | null;
7823
8003
  if (frameTemplate) {
7824
8004
  const payload = frameTemplate.content.textContent || "";
7825
8005
  const routeFrameStream = (window as unknown as { __FURIN_ROUTE_FRAME_STREAM__?: FurinRouteFrameStream })
@@ -7947,22 +8127,22 @@ if (__deferred && __deferred._chunks) {
7947
8127
  `;
7948
8128
  }
7949
8129
  function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging, skipRouteTypes }, projectRoot) {
7950
- if (!existsSync6(outDir)) {
8130
+ if (!existsSync7(outDir)) {
7951
8131
  mkdirSync2(outDir, { recursive: true });
7952
8132
  }
7953
8133
  const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
7954
- const hydratePath = join6(outDir, "_hydrate.tsx");
7955
- const existingHydrate = existsSync6(hydratePath) ? readFileSync3(hydratePath, "utf8") : "";
8134
+ const hydratePath = join8(outDir, "_hydrate.tsx");
8135
+ const existingHydrate = existsSync7(hydratePath) ? readFileSync3(hydratePath, "utf8") : "";
7956
8136
  let changed = false;
7957
8137
  if (hydrateCode !== existingHydrate) {
7958
- writeFileSync2(hydratePath, hydrateCode);
8138
+ writeFileSync3(hydratePath, hydrateCode);
7959
8139
  changed = true;
7960
8140
  }
7961
8141
  const indexHtml = generateIndexHtml();
7962
- const indexPath = join6(outDir, "index.html");
7963
- const existingIndex = existsSync6(indexPath) ? readFileSync3(indexPath, "utf8") : "";
8142
+ const indexPath = join8(outDir, "index.html");
8143
+ const existingIndex = existsSync7(indexPath) ? readFileSync3(indexPath, "utf8") : "";
7964
8144
  if (indexHtml !== existingIndex) {
7965
- writeFileSync2(indexPath, indexHtml);
8145
+ writeFileSync3(indexPath, indexHtml);
7966
8146
  changed = true;
7967
8147
  }
7968
8148
  if (!skipRouteTypes) {
@@ -7975,6 +8155,7 @@ function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging, sk
7975
8155
 
7976
8156
  // src/build/client.ts
7977
8157
  var SCRIPT_FILE_FILTER2 = /\.(tsx?|jsx?)$/;
8158
+ var ROUTER_PROVIDER_PATH = resolve4(import.meta.dir, "../client/router/provider.tsx");
7978
8159
  function resolveClientModuleSpecifiers(code) {
7979
8160
  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
8161
  }
@@ -7992,15 +8173,15 @@ async function buildClient(routes, {
7992
8173
  pagesDir
7993
8174
  }) {
7994
8175
  const dirName = clientDirName ?? "client";
7995
- const clientDir = join7(outDir, dirName);
7996
- if (!existsSync7(outDir)) {
8176
+ const clientDir = join9(outDir, dirName);
8177
+ if (!existsSync8(outDir)) {
7997
8178
  mkdirSync3(outDir, { recursive: true });
7998
8179
  }
7999
- if (!existsSync7(clientDir)) {
8180
+ if (!existsSync8(clientDir)) {
8000
8181
  mkdirSync3(clientDir, { recursive: true });
8001
8182
  }
8002
8183
  const hydrateCode = resolveClientModuleSpecifiers(generateHydrateEntry(routes, rootLayout, basePath, clientLogging));
8003
- const hydratePath = join7(outDir, dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`);
8184
+ const hydratePath = join9(outDir, dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`);
8004
8185
  const hydrateEntry = createVirtualBuildEntry(hydratePath, hydrateCode, "tsx");
8005
8186
  console.log("[furin] Building production client bundle\u2026");
8006
8187
  const transformPlugin = {
@@ -8021,6 +8202,20 @@ async function buildClient(routes, {
8021
8202
  });
8022
8203
  }
8023
8204
  };
8205
+ const routerLoggerPlugin = {
8206
+ name: "furin-client-router-logger",
8207
+ setup(build) {
8208
+ build.onResolve({ filter: /^evlog$/ }, ({ importer }) => {
8209
+ if (importer === ROUTER_PROVIDER_PATH) {
8210
+ return { namespace: "furin-client-router-logger", path: "router-logger" };
8211
+ }
8212
+ });
8213
+ build.onLoad({ filter: /.*/, namespace: "furin-client-router-logger" }, () => ({
8214
+ contents: "export const log = { warn: console.warn, error: console.error };",
8215
+ loader: "js"
8216
+ }));
8217
+ }
8218
+ };
8024
8219
  const clientBuildConfig = {
8025
8220
  entrypoints: [hydrateEntry.entrypoint],
8026
8221
  files: hydrateEntry.files,
@@ -8042,6 +8237,7 @@ async function buildClient(routes, {
8042
8237
  plugins: [
8043
8238
  hydrateEntry.plugin,
8044
8239
  ...plugins ?? [],
8240
+ ...!clientLogging ? [routerLoggerPlugin] : [],
8045
8241
  ...pagesDir ? [createRoutesPlugin({ instances: [{ pagesDir, prefix: basePath }], target: "client" })] : [],
8046
8242
  environmentGuardPlugin("client"),
8047
8243
  transformPlugin
@@ -8060,8 +8256,8 @@ async function buildClient(routes, {
8060
8256
  if (result.metafile === undefined) {
8061
8257
  throw new Error("[furin] client build did not produce the requested metafile");
8062
8258
  }
8063
- mkdirSync3(dirname4(metafilePath), { recursive: true });
8064
- writeFileSync3(metafilePath, `${JSON.stringify(result.metafile, null, 2)}
8259
+ mkdirSync3(dirname6(metafilePath), { recursive: true });
8260
+ writeFileSync4(metafilePath, `${JSON.stringify(result.metafile, null, 2)}
8065
8261
  `);
8066
8262
  console.log(`[furin] Client metafile: ${metafilePath}`);
8067
8263
  }
@@ -9909,6 +10105,10 @@ function HeadContent() {
9909
10105
  }
9910
10106
  return /* @__PURE__ */ jsxDEV(Fragment, {
9911
10107
  children: [
10108
+ state.assets.extensionErrorFilterScript === undefined ? null : /* @__PURE__ */ jsxDEV("script", {
10109
+ dangerouslySetInnerHTML: { __html: state.assets.extensionErrorFilterScript },
10110
+ "data-furin-extension-error-filter": ""
10111
+ }, undefined, false, undefined, this),
9912
10112
  /* @__PURE__ */ jsxDEV("meta", {
9913
10113
  charSet: "utf-8",
9914
10114
  "data-furin-head": ""
@@ -9966,6 +10166,13 @@ function Scripts() {
9966
10166
  id: "__FURIN_DATA__",
9967
10167
  type: "application/json"
9968
10168
  }, undefined, false, undefined, this),
10169
+ state.routeFrames === undefined ? null : /* @__PURE__ */ jsxDEV("template", {
10170
+ dangerouslySetInnerHTML: {
10171
+ __html: state.routeFrames.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
10172
+ },
10173
+ "data-furin-document-state": "",
10174
+ id: "__FURIN_ROUTE_FRAMES__"
10175
+ }, undefined, false, undefined, this),
9969
10176
  /* @__PURE__ */ jsxDEV("script", {
9970
10177
  dangerouslySetInnerHTML: { __html: serializeJson(state.head ?? {}) },
9971
10178
  "data-furin-scripts": "",
@@ -10246,6 +10453,21 @@ function cyrb53(input) {
10246
10453
  return 4294967296 * (2097151 & h2) + (4294967295 & h1);
10247
10454
  }
10248
10455
 
10456
+ // src/shared/production-build.ts
10457
+ var productionBuildScope;
10458
+ var productionBuildScopePromise;
10459
+ async function withProductionBuild(build) {
10460
+ productionBuildScopePromise ??= import("async_hooks").then(({ AsyncLocalStorage }) => {
10461
+ productionBuildScope = new AsyncLocalStorage;
10462
+ return productionBuildScope;
10463
+ });
10464
+ const scope = await productionBuildScopePromise;
10465
+ return scope.run(true, build);
10466
+ }
10467
+ function isProductionBuild() {
10468
+ return productionBuildScope?.getStore() === true || typeof process !== "undefined" && false;
10469
+ }
10470
+
10249
10471
  // src/rsc/shared.tsx
10250
10472
  import {
10251
10473
  Children,
@@ -10271,7 +10493,7 @@ var FRAME_VERSION = 3;
10271
10493
  var MAX_FRAME_BYTES = 1024 * 1024;
10272
10494
  var MAX_ROUTE_FRAME_STREAM_BYTES = 8 * 1024 * 1024;
10273
10495
  var RSC_DESCRIPTOR = "__furinRsc";
10274
- function isPlainObject3(value) {
10496
+ function isPlainObject4(value) {
10275
10497
  const prototype = Object.getPrototypeOf(value);
10276
10498
  return prototype === Object.prototype || prototype === null;
10277
10499
  }
@@ -10300,7 +10522,7 @@ function extractRscSources(value, sources, seen, idPrefix) {
10300
10522
  }
10301
10523
  return result;
10302
10524
  }
10303
- if (!isPlainObject3(value)) {
10525
+ if (!isPlainObject4(value)) {
10304
10526
  return value;
10305
10527
  }
10306
10528
  const result = {};
@@ -10380,7 +10602,7 @@ function containsRscSourceInner(value, seen) {
10380
10602
  if (Array.isArray(value)) {
10381
10603
  return value.some((entry) => containsRscSourceInner(entry, seen));
10382
10604
  }
10383
- return isPlainObject3(value) && Object.values(value).some((entry) => containsRscSourceInner(entry, seen));
10605
+ return isPlainObject4(value) && Object.values(value).some((entry) => containsRscSourceInner(entry, seen));
10384
10606
  }
10385
10607
  function serializeRouteFrames(data, deferredKeys) {
10386
10608
  const sources = [];
@@ -10421,10 +10643,12 @@ function withDocumentState(element, assets, head, data) {
10421
10643
  ...assets,
10422
10644
  frameworkModules: [browserEventsClientPath, ...assets.frameworkModules]
10423
10645
  };
10646
+ const routeFrames = data !== undefined && containsRscSource(data) ? serializeRouteFrames(data, undefined) : undefined;
10424
10647
  const state = {
10425
10648
  assets: resolvedAssets,
10426
- dataJson: data === undefined ? undefined : safeJson(data),
10649
+ dataJson: data === undefined || routeFrames !== undefined ? undefined : safeJson(data),
10427
10650
  head,
10651
+ routeFrames,
10428
10652
  syncJson: syncPath === undefined ? undefined : safeJson({ path: syncPath })
10429
10653
  };
10430
10654
  return createElement3(DocumentProvider, { value: state }, element);
@@ -11180,7 +11404,9 @@ function errorStack(error) {
11180
11404
  return error instanceof Error ? error.stack : undefined;
11181
11405
  }
11182
11406
  function renderErrorMessage(options) {
11183
- if (typeof process !== "undefined" && false) {}
11407
+ if (isProductionBuild()) {
11408
+ return `[furin/rsc] Server Component rendering failed inside ${options.operation}().`;
11409
+ }
11184
11410
  if (options.hook !== undefined && options.component !== undefined) {
11185
11411
  const diagnostic = `[furin/rsc] A component rendered inside ${options.operation}()
11186
11412
  used a client-only React hook.
@@ -11284,13 +11510,17 @@ function injectInstrumentationClient(html, prefix) {
11284
11510
  var REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
11285
11511
  var FURIN_RESERVED_KEY_PREFIX = "__furin";
11286
11512
  var ROUTE_CTX_RESERVED_KEYS = new Set([
11513
+ "catch",
11287
11514
  "children",
11515
+ "finally",
11288
11516
  "key",
11289
11517
  "params",
11290
11518
  "path",
11291
11519
  "query",
11292
11520
  "ref",
11293
- "requestData"
11521
+ "requestData",
11522
+ "then",
11523
+ "toJSON"
11294
11524
  ]);
11295
11525
  function assertPublicLoaderKey(key) {
11296
11526
  if (key.startsWith(FURIN_RESERVED_KEY_PREFIX)) {
@@ -11324,7 +11554,7 @@ function createLoaderCtx(ctx, accumulatedParentPromise) {
11324
11554
  if (prop === "then" || prop === "catch" || prop === "finally" || prop === "toJSON") {
11325
11555
  return Reflect.get(target, prop);
11326
11556
  }
11327
- if (Object.hasOwn(target, prop)) {
11557
+ if (Object.hasOwn(target, prop) || prop in target && !Object.hasOwn(Object.prototype, prop)) {
11328
11558
  return target[prop];
11329
11559
  }
11330
11560
  let entry = cache.get(prop);
@@ -11366,7 +11596,7 @@ function createRequestLoaderContext(ctx) {
11366
11596
  get: (name) => headers.get(name),
11367
11597
  has: (name) => headers.has(name)
11368
11598
  }),
11369
- log: useLogger3(),
11599
+ log: getLogger(),
11370
11600
  params: ctx.params,
11371
11601
  path: ctx.path,
11372
11602
  query: ctx.query,
@@ -11491,7 +11721,7 @@ async function normalizeLoaderError(err, headers) {
11491
11721
  return { error: err, headers, message, status, type: "error" };
11492
11722
  }
11493
11723
  if (isFurinRscRenderError(err)) {
11494
- useLogger3().error(err);
11724
+ getLogger().error(err);
11495
11725
  return {
11496
11726
  error: err,
11497
11727
  headers,
@@ -11511,7 +11741,7 @@ async function normalizeLoaderError(err, headers) {
11511
11741
  async function runLoadersInternal(route, ctx, includeRequestData) {
11512
11742
  try {
11513
11743
  const requestData = includeRequestData ? runRequestLoaderData(route, ctx) : undefined;
11514
- const ctxRecord = includeRequestData ? { ...ctx, log: useLogger3() } : createPublicLoaderContext(ctx);
11744
+ const ctxRecord = includeRequestData ? Object.assign(Object.create(Object.getPrototypeOf(ctx)), ctx, { log: getLogger() }) : createPublicLoaderContext(ctx);
11515
11745
  const loaderMap = new Map;
11516
11746
  let accumulatedParentPromise = Promise.resolve({});
11517
11747
  let loaderIndex = 0;
@@ -11526,7 +11756,7 @@ async function runLoadersInternal(route, ctx, includeRequestData) {
11526
11756
  if (IS_DEV) {
11527
11757
  for (const key of Object.keys(own)) {
11528
11758
  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).`);
11759
+ 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
11760
  }
11531
11761
  }
11532
11762
  }
@@ -11570,7 +11800,7 @@ function createPublicLoaderContext(ctx) {
11570
11800
  Object.defineProperties(publicContext, {
11571
11801
  cookie: { enumerable: true, get: fail },
11572
11802
  headers: { enumerable: true, get: fail },
11573
- log: { enumerable: true, value: useLogger3() },
11803
+ log: { enumerable: true, value: getLogger() },
11574
11804
  params: { enumerable: true, value: ctx.params },
11575
11805
  path: { enumerable: true, value: ctx.path },
11576
11806
  query: { enumerable: true, value: ctx.query },
@@ -11706,7 +11936,11 @@ async function getDevDocumentAssets(origin) {
11706
11936
  if (state.devAssets && Date.now() - state.devAssets.ts < DEV_TEMPLATE_TTL_MS) {
11707
11937
  return state.devAssets.assets;
11708
11938
  }
11709
- const assets = documentAssetsFromTemplate(await getDevTemplate(origin));
11939
+ await Promise.resolve().then(() => init_plugin2());
11940
+ const assets = {
11941
+ ...documentAssetsFromTemplate(await getDevTemplate(origin)),
11942
+ extensionErrorFilterScript
11943
+ };
11710
11944
  state.devAssets = { assets, ts: Date.now() };
11711
11945
  return assets;
11712
11946
  }
@@ -11988,7 +12222,7 @@ function renderForPath(route, params, root, origin, mode, basePath, searchRoutes
11988
12222
  if (prepared instanceof Response) {
11989
12223
  return prepared;
11990
12224
  }
11991
- useLogger3().set({
12225
+ getLogger().set({
11992
12226
  furin: {
11993
12227
  cache: mode === "isr" ? "revalidated" : "miss",
11994
12228
  loader_ms: prepared.loader_ms,
@@ -12022,6 +12256,118 @@ async function serializeLoaderDataNdjson(syncData, deferredPromises) {
12022
12256
  `;
12023
12257
  }
12024
12258
 
12259
+ // src/server/render/static-params.ts
12260
+ import { dirname as dirname8, relative as relative6 } from "path";
12261
+ init_patterns();
12262
+ var STATIC_PARAMS_CONCURRENCY = 4;
12263
+ function collectStaticParamsStages(route) {
12264
+ const stages = [];
12265
+ for (const [index, entry] of route.routeChain.entries()) {
12266
+ if (entry.staticParams) {
12267
+ stages.push({ ancestors: route.routeChain.slice(0, index), run: entry.staticParams });
12268
+ }
12269
+ }
12270
+ if (route.page.staticParams) {
12271
+ stages.push({ ancestors: route.routeChain, run: route.page.staticParams });
12272
+ }
12273
+ return stages;
12274
+ }
12275
+ function ancestorPattern(route, ancestors) {
12276
+ const rootSourcePath = route.routeChain[0]?.sourcePath;
12277
+ const ancestorSourcePath = ancestors.at(-1)?.sourcePath;
12278
+ if (rootSourcePath === undefined || ancestorSourcePath === undefined) {
12279
+ return route.pattern;
12280
+ }
12281
+ const pagesDir = dirname8(rootSourcePath);
12282
+ const ancestorDir = dirname8(ancestorSourcePath);
12283
+ if (ancestorDir === pagesDir) {
12284
+ return "/";
12285
+ }
12286
+ return filePathToPattern(`${relative6(pagesDir, ancestorDir)}/index.tsx`);
12287
+ }
12288
+ function createBuildContext(pattern, params, origin) {
12289
+ const path = resolvePath(pattern, params);
12290
+ return {
12291
+ cookie: {},
12292
+ headers: {},
12293
+ params,
12294
+ path,
12295
+ query: {},
12296
+ redirect: (url, status) => new Response(null, { headers: { Location: url }, status: status ?? 302 }),
12297
+ request: new Request(new URL(path, origin)),
12298
+ set: { headers: {} }
12299
+ };
12300
+ }
12301
+ async function runAncestorLoaders(route, ancestors, params, origin) {
12302
+ const pattern = ancestorPattern(route, ancestors);
12303
+ const result = await runPublicLoaders({
12304
+ ...route,
12305
+ page: { ...route.page, loader: undefined },
12306
+ pattern,
12307
+ routeChain: ancestors
12308
+ }, createBuildContext(pattern, params, origin));
12309
+ if (result.type === "redirect") {
12310
+ throw result.response;
12311
+ }
12312
+ if (result.type === "not-found") {
12313
+ throw result.error;
12314
+ }
12315
+ if (result.type === "error") {
12316
+ throw result.error;
12317
+ }
12318
+ const data = {};
12319
+ for (const [key, value] of Object.entries(result.syncData)) {
12320
+ if (key !== "params" && key !== "path" && key !== "query") {
12321
+ data[key] = value;
12322
+ }
12323
+ }
12324
+ Object.assign(data, result.deferredPromises);
12325
+ return data;
12326
+ }
12327
+ function createStaticParamsContext(route, ancestors, params, origin) {
12328
+ const target = { params };
12329
+ const fields = new Map;
12330
+ let parentData;
12331
+ return new Proxy(target, {
12332
+ get(context, property) {
12333
+ if (typeof property !== "string" || Object.hasOwn(context, property)) {
12334
+ return Reflect.get(context, property);
12335
+ }
12336
+ if (property === "then" || property === "catch" || property === "finally" || property === "toJSON") {
12337
+ return;
12338
+ }
12339
+ let field = fields.get(property);
12340
+ if (!field) {
12341
+ parentData ??= runAncestorLoaders(route, ancestors, params, origin);
12342
+ field = parentData.then((data) => data[property]);
12343
+ fields.set(property, field);
12344
+ }
12345
+ return field;
12346
+ }
12347
+ });
12348
+ }
12349
+ function hasStaticParams(route) {
12350
+ return route.page.staticParams !== undefined || route.routeChain.some((entry) => entry.staticParams !== undefined);
12351
+ }
12352
+ async function resolveStaticParams(route, origin) {
12353
+ const stages = collectStaticParamsStages(route);
12354
+ if (stages.length === 0) {
12355
+ return;
12356
+ }
12357
+ let branches = [{}];
12358
+ for (const stage of stages) {
12359
+ const branchValues = await mapWithConcurrency(branches, STATIC_PARAMS_CONCURRENCY, async (params) => {
12360
+ const values = await stage.run(createStaticParamsContext(route, stage.ancestors, params, origin));
12361
+ if (!Array.isArray(values)) {
12362
+ throw new TypeError(`[furin] staticParams() for "${route.pattern}" must return an array.`);
12363
+ }
12364
+ return values.map((value) => ({ ...params, ...value }));
12365
+ });
12366
+ branches = branchValues.flat();
12367
+ }
12368
+ return branches;
12369
+ }
12370
+
12025
12371
  // src/server/render/ssg.ts
12026
12372
  async function prerenderRoute(route, params, root, origin, mode, basePath, searchRoutes, requestContext) {
12027
12373
  const renderResult = await renderForPath(route, params, root, origin, mode, basePath, searchRoutes, undefined, requestContext);
@@ -12074,12 +12420,8 @@ async function buildRoutePrerenders(routes, root, origin, basePath) {
12074
12420
  let paramSets;
12075
12421
  if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
12076
12422
  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;
12423
+ } else if (hasStaticParams(route)) {
12424
+ paramSets = await resolveStaticParams(route, origin) ?? [];
12083
12425
  } else {
12084
12426
  continue;
12085
12427
  }
@@ -12102,10 +12444,10 @@ async function buildSSGCacheSnapshot(routes, root, origin, basePath) {
12102
12444
  const snapshot = {};
12103
12445
  const searchRoutes = createSearchRouteMetadata(routes);
12104
12446
  for (const route of routes) {
12105
- if (route.mode !== "ssg" || !route.page.staticParams || hasRequestLoader(route)) {
12447
+ if (route.mode !== "ssg" || !hasStaticParams(route) || hasRequestLoader(route)) {
12106
12448
  continue;
12107
12449
  }
12108
- const paramSets = await route.page.staticParams();
12450
+ const paramSets = await resolveStaticParams(route, origin) ?? [];
12109
12451
  for (const params of paramSets) {
12110
12452
  const result = await prerenderSSG(route, params, root, origin, basePath, searchRoutes);
12111
12453
  if (!(result instanceof Response)) {
@@ -12117,8 +12459,8 @@ async function buildSSGCacheSnapshot(routes, root, origin, basePath) {
12117
12459
  }
12118
12460
 
12119
12461
  // 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";
12462
+ import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync5 } from "fs";
12463
+ import { basename as basename3, join as join10 } from "path";
12122
12464
  import { fileURLToPath as fileURLToPath4 } from "url";
12123
12465
 
12124
12466
  // src/rsc/version.ts
@@ -12166,7 +12508,7 @@ function assertInstalledRscVersions() {
12166
12508
  // src/rsc/build/index.ts
12167
12509
  async function buildRscGraph(apps, outDir, buildId, userPlugins) {
12168
12510
  await assertInstalledRscVersions();
12169
- const graphDir = join8(outDir, "rsc");
12511
+ const graphDir = join10(outDir, "rsc");
12170
12512
  mkdirSync4(graphDir, { recursive: true });
12171
12513
  const rscEntry = fileURLToPath4(import.meta.resolve("../../rsc-server.tsx"));
12172
12514
  const entrypoints = [
@@ -12228,13 +12570,13 @@ ${codecResult.logs.map((log) => log.message).join(`
12228
12570
  }
12229
12571
  const css = result.outputs.filter((output) => output.path.endsWith(".css")).map((output) => ({ href: `/_rsc/${basename3(output.path)}` }));
12230
12572
  const manifest = { buildId, clientReferences: [], css };
12231
- writeFileSync4(join8(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
12573
+ writeFileSync5(join10(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
12232
12574
  return manifest;
12233
12575
  }
12234
12576
 
12235
12577
  // 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");
12578
+ var _pkgRoot2 = dirname9(dirname9(fileURLToPath5(import.meta.resolve("@teyik0/furin"))));
12579
+ var _pkgSrcDir2 = existsSync9(join11(_pkgRoot2, "src", "furin.ts")) ? join11(_pkgRoot2, "src") : join11(_pkgRoot2, "dist");
12238
12580
  var _ext2 = ".ts";
12239
12581
  var PPR_ROUTE_IMPORT_RE = /ppr-route(?:\.ts)?$/;
12240
12582
  var ANY_MODULE_RE = /.*/;
@@ -12294,13 +12636,13 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
12294
12636
  }
12295
12637
  }
12296
12638
  for (const path of BUILD_ID_INPUT_PATHS) {
12297
- if (!existsSync8(path)) {
12639
+ if (!existsSync9(path)) {
12298
12640
  console.warn(`[furin] Warning: build fingerprint input "${toPosixPath(path)}" is missing \u2014 ` + "the generated build ID may not reflect all framework changes.");
12299
12641
  }
12300
12642
  fingerprintPaths.add(path);
12301
12643
  }
12302
12644
  const fileParts = await Promise.all([...fingerprintPaths].toSorted().map(async (path) => {
12303
- const content = existsSync8(path) ? await Bun.file(path).text() : "";
12645
+ const content = existsSync9(path) ? await Bun.file(path).text() : "";
12304
12646
  return `${stableFingerprintPath(path, projectRoot)}:${content}`;
12305
12647
  }));
12306
12648
  const routeParts = routes.map((route) => JSON.stringify({
@@ -12312,12 +12654,12 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
12312
12654
  `);
12313
12655
  }
12314
12656
  function stableFingerprintPath(path, projectRoot) {
12315
- const projectPath = relative5(projectRoot, path);
12316
- if (projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
12657
+ const projectPath = relative7(projectRoot, path);
12658
+ if (!isAbsolute3(projectPath) && projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
12317
12659
  return `app/${toPosixPath(projectPath)}`;
12318
12660
  }
12319
- const frameworkPath = relative5(_pkgRoot2, path);
12320
- if (frameworkPath !== ".." && !frameworkPath.startsWith("../") && !frameworkPath.startsWith("..\\")) {
12661
+ const frameworkPath = relative7(_pkgRoot2, path);
12662
+ if (!isAbsolute3(frameworkPath) && frameworkPath !== ".." && !frameworkPath.startsWith("../") && !frameworkPath.startsWith("..\\")) {
12321
12663
  return `furin/${toPosixPath(frameworkPath)}`;
12322
12664
  }
12323
12665
  return `external/${basename4(path)}`;
@@ -12342,7 +12684,7 @@ function buildCompileMetadata(root, routes) {
12342
12684
  }
12343
12685
  function pprRuntimePlugin(apps) {
12344
12686
  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");
12687
+ const pprPath = resolve5(_pkgSrcDir2, "server/render/ppr-route.ts");
12346
12688
  const reactServerPath = fileURLToPath5(import.meta.resolve(enabled ? "react-dom/server.edge" : "react-dom/server"));
12347
12689
  const reactStaticPath = fileURLToPath5(import.meta.resolve("react-dom/static.edge"));
12348
12690
  return {
@@ -12354,7 +12696,7 @@ function pprRuntimePlugin(apps) {
12354
12696
  return;
12355
12697
  }
12356
12698
  build.onResolve({ filter: PPR_ROUTE_IMPORT_RE }, ({ path, importer }) => {
12357
- const absolute = resolve3(dirname6(importer.split("?")[0]), path);
12699
+ const absolute = resolve5(dirname9(importer.split("?")[0]), path);
12358
12700
  if (absolute !== pprPath && `${absolute}.ts` !== pprPath) {
12359
12701
  return;
12360
12702
  }
@@ -12374,7 +12716,7 @@ function isFrameworkRuntimeImporter(importer) {
12374
12716
  if (importer === "") {
12375
12717
  return false;
12376
12718
  }
12377
- const fromRuntimeRoot = relative5(_pkgSrcDir2, importer.split("?")[0]);
12719
+ const fromRuntimeRoot = relative7(_pkgSrcDir2, importer.split("?")[0]);
12378
12720
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
12379
12721
  }
12380
12722
  async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options, targetName) {
@@ -12386,7 +12728,7 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
12386
12728
  basePath: prefix,
12387
12729
  clientDirName,
12388
12730
  clientLogging: options.clientLogging ?? false,
12389
- metafilePath: options.analyze ? join9(dirname6(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
12731
+ metafilePath: options.analyze ? join11(dirname9(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
12390
12732
  optimizeImports: options.optimizeImports,
12391
12733
  outDir: targetDir,
12392
12734
  pagesDir: app.pagesDir,
@@ -12398,9 +12740,9 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
12398
12740
  const buildFingerprint = await createBuildFingerprint(`${prefix}
12399
12741
  ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
12400
12742
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
12401
- const clientDir = join9(targetDir, clientDirName);
12743
+ const clientDir = join11(targetDir, clientDirName);
12402
12744
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
12403
- writeFileSync5(join9(clientDir, "index.html"), indexHtml);
12745
+ writeFileSync6(join11(clientDir, "index.html"), indexHtml);
12404
12746
  setProductionTemplateContent(indexHtml);
12405
12747
  ssgRouteCache().clear();
12406
12748
  let ssgCache;
@@ -12420,9 +12762,10 @@ ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
12420
12762
  entryApp: {
12421
12763
  buildId,
12422
12764
  clientLogging: options.clientLogging ?? false,
12765
+ deploymentTarget: targetName === "vercel" ? "vercel" : undefined,
12423
12766
  embed: options.compile === "embed" ? { clientDir } : undefined,
12424
12767
  modulePaths,
12425
- nativeRoutes: routeModuleSpecifier(app),
12768
+ nativeRoutes: composableRouteModuleSpecifier(app),
12426
12769
  prefix,
12427
12770
  rootConventions,
12428
12771
  rootPath: root.path,
@@ -12457,15 +12800,10 @@ async function buildRuntimeAppsSequentially(apps, projectRoot, targetDir, server
12457
12800
  }
12458
12801
 
12459
12802
  // 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");
12803
+ function generateBootEntry(appEntry, outDir, filename) {
12804
+ ensureDir(outDir);
12805
+ const entryPath = join12(outDir, filename);
12806
+ return createVirtualBuildEntry(entryPath, serverBootSource(appEntry), "ts");
12469
12807
  }
12470
12808
  function collectEmbeddedAssets(entryApps, publicDir, compile) {
12471
12809
  if (compile !== "embed") {
@@ -12477,6 +12815,70 @@ function collectEmbeddedAssets(entryApps, publicDir, compile) {
12477
12815
  }
12478
12816
  return assets;
12479
12817
  }
12818
+ function compiledServerFilename(platform) {
12819
+ return platform === "win32" ? "server.exe" : "server";
12820
+ }
12821
+ function serverSourcemapMode(enabled) {
12822
+ return enabled ? "external" : "none";
12823
+ }
12824
+ function relocateServerMaps(build, enabled, targetDir, buildRoot) {
12825
+ if (!enabled) {
12826
+ return;
12827
+ }
12828
+ movePrivateServerSourceMaps(targetDir, join12(buildRoot, "private", "server-sourcemaps", "bun"), build.outputs.filter((output) => output.kind === "sourcemap").map((output) => output.path));
12829
+ }
12830
+ function writeServerMetafile(build, analyze, buildRoot) {
12831
+ if (!analyze) {
12832
+ return;
12833
+ }
12834
+ if (build.metafile === undefined) {
12835
+ throw new Error("[furin] Bun server build did not produce the requested metafile.");
12836
+ }
12837
+ const analysisDir = join12(buildRoot, "analysis");
12838
+ ensureDir(analysisDir);
12839
+ const metafilePath = join12(analysisDir, "bun-server.json");
12840
+ writeFileSync7(metafilePath, `${JSON.stringify(build.metafile, null, 2)}
12841
+ `);
12842
+ console.log(`[furin] Server metafile: ${toPosixPath(metafilePath)}`);
12843
+ }
12844
+ function finalizeEmbeddedAssets(compile, apps, targetDir, manifest) {
12845
+ if (compile !== "embed") {
12846
+ return;
12847
+ }
12848
+ for (const app of apps) {
12849
+ rmSync2(join12(targetDir, clientDirNameForPrefix(app.prefix)), {
12850
+ force: true,
12851
+ recursive: true
12852
+ });
12853
+ }
12854
+ manifest.clientDir = null;
12855
+ manifest.templatePath = null;
12856
+ }
12857
+ async function createBunAppEntry(apps, entryApps, options, publicDir, serverEntry, targetDir) {
12858
+ if (!serverEntry) {
12859
+ return;
12860
+ }
12861
+ const contexts = options.compile ? prepareCompileEntryApps({
12862
+ apps: entryApps,
12863
+ outDir: targetDir,
12864
+ publicDir,
12865
+ serverEntry
12866
+ }) : entryApps.map(({ embed: _embed, ...context }) => ({
12867
+ ...context,
12868
+ extraContext: [
12869
+ ...context.extraContext ?? [],
12870
+ ` clientDir: import.meta.dir + ${JSON.stringify(`/${clientDirNameForPrefix(context.prefix ?? "")}`)},`
12871
+ ],
12872
+ templateHtml: readFileSync6(join12(targetDir, clientDirNameForPrefix(context.prefix ?? ""), "index.html"), "utf8")
12873
+ }));
12874
+ return await materializeServerAppEntry({
12875
+ apps: contexts,
12876
+ headerComment: "// Auto-generated by furin build - do not edit",
12877
+ instances: apps,
12878
+ outDir: targetDir,
12879
+ serverEntry
12880
+ });
12881
+ }
12480
12882
  async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12481
12883
  if (options.compile && !serverEntry) {
12482
12884
  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,35 +12888,37 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12486
12888
  }
12487
12889
  const target = "bun";
12488
12890
  const targetManifest = buildTargetManifest(rootDir, buildRoot, target, serverEntry);
12489
- const targetDir = resolve4(rootDir, targetManifest.targetDir);
12891
+ const targetDir = resolve6(rootDir, targetManifest.targetDir);
12490
12892
  rmSync2(targetDir, { force: true, recursive: true });
12893
+ rmSync2(join12(buildRoot, "private", "server-sourcemaps", "bun"), {
12894
+ force: true,
12895
+ recursive: true
12896
+ });
12491
12897
  ensureDir(targetDir);
12492
- const publicDir = existsSync9(join10(rootDir, "public")) ? join10(rootDir, "public") : undefined;
12898
+ const publicDir = existsSync10(join12(rootDir, "public")) ? join12(rootDir, "public") : undefined;
12493
12899
  const { entryApps, headlineBuildId } = await buildRuntimeAppsSequentially(apps, rootDir, targetDir, serverEntry, options, "bun");
12494
12900
  targetManifest.buildId = headlineBuildId;
12495
12901
  if (serverEntry) {
12496
- targetManifest.rscManifestPath = toPosixPath(join10(targetManifest.targetDir, "rsc", "manifest.json"));
12902
+ targetManifest.rscManifestPath = toPosixPath(join12(targetManifest.targetDir, "rsc", "manifest.json"));
12497
12903
  }
12498
- const targetPublicDir = publicDir ? join10(targetDir, "public") : undefined;
12904
+ const targetPublicDir = publicDir ? join12(targetDir, "public") : undefined;
12499
12905
  if (publicDir && targetPublicDir && options.compile !== "embed") {
12500
12906
  copyDirRecursive(publicDir, targetPublicDir);
12501
12907
  }
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
- });
12908
+ const appEntry = await createBunAppEntry(apps, entryApps, options, publicDir, serverEntry, targetDir);
12909
+ if (options.compile && serverEntry && appEntry) {
12910
+ const serverFilename = compiledServerFilename(process.platform);
12911
+ const outfile = join12(targetDir, serverFilename);
12912
+ const entry = generateBootEntry(appEntry, targetDir, "_compile-entry.ts");
12510
12913
  const embeddedAssets = collectEmbeddedAssets(entryApps, publicDir, options.compile);
12511
- await runBunBuild({
12914
+ const serverBuild = await runBunBuild({
12512
12915
  bytecode: true,
12513
12916
  compile: { assets: embeddedAssets, outfile },
12514
12917
  define: { "process.env.NODE_ENV": JSON.stringify("production") },
12515
12918
  entrypoints: [entry.entrypoint],
12516
12919
  files: entry.files,
12517
12920
  format: "esm",
12921
+ metafile: options.analyze,
12518
12922
  minify: true,
12519
12923
  plugins: [
12520
12924
  entry.plugin,
@@ -12523,33 +12927,24 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12523
12927
  ...options.plugins ?? [],
12524
12928
  createRoutesPlugin({ instances: apps, target: "server" }),
12525
12929
  isomorphicTransformPlugin("server"),
12526
- environmentGuardPlugin("ssr")
12930
+ environmentGuardPlugin("ssr"),
12931
+ elysiaAot(appEntry)
12527
12932
  ],
12528
- sourcemap: "none",
12933
+ sourcemap: serverSourcemapMode(options.serverSourceMaps),
12529
12934
  splitting: true,
12530
12935
  target: "bun"
12531
12936
  });
12937
+ relocateServerMaps(serverBuild, options.serverSourceMaps, targetDir, buildRoot);
12938
+ writeServerMetafile(serverBuild, options.analyze, buildRoot);
12532
12939
  console.log(`[furin] Server binary: ${outfile}`);
12533
- targetManifest.serverPath = toPosixPath(join10(targetManifest.targetDir, "server"));
12534
- if (options.compile === "embed") {
12535
- for (const app of apps) {
12536
- rmSync2(join10(targetDir, clientDirNameForPrefix(app.prefix)), {
12537
- force: true,
12538
- recursive: true
12539
- });
12540
- }
12541
- targetManifest.clientDir = null;
12542
- targetManifest.templatePath = null;
12543
- }
12544
- } else if (serverEntry) {
12545
- const entry = generateDiskEntry({
12546
- apps: entryApps,
12547
- outDir: targetDir,
12548
- serverEntry
12549
- });
12550
- await runBunBuild({
12940
+ targetManifest.serverPath = toPosixPath(join12(targetManifest.targetDir, serverFilename));
12941
+ finalizeEmbeddedAssets(options.compile, apps, targetDir, targetManifest);
12942
+ } else if (serverEntry && appEntry) {
12943
+ const entry = generateBootEntry(appEntry, targetDir, "server.ts");
12944
+ const serverBuild = await runBunBuild({
12551
12945
  entrypoints: [entry.entrypoint],
12552
12946
  files: entry.files,
12947
+ metafile: options.analyze,
12553
12948
  minify: true,
12554
12949
  naming: { chunk: "[name]-[hash].[ext]", entry: "[name].[ext]" },
12555
12950
  outdir: targetDir,
@@ -12560,30 +12955,33 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12560
12955
  ...options.plugins ?? [],
12561
12956
  createRoutesPlugin({ instances: apps, target: "server" }),
12562
12957
  isomorphicTransformPlugin("server"),
12563
- environmentGuardPlugin("ssr")
12958
+ environmentGuardPlugin("ssr"),
12959
+ elysiaAot(appEntry)
12564
12960
  ],
12565
- sourcemap: "none",
12961
+ sourcemap: serverSourcemapMode(options.serverSourceMaps),
12566
12962
  target: "bun"
12567
12963
  });
12568
- console.log(`[furin] Server bundle: ${toPosixPath(join10(targetManifest.targetDir, "server.js"))}`);
12569
- targetManifest.serverPath = toPosixPath(join10(targetManifest.targetDir, "server.js"));
12964
+ relocateServerMaps(serverBuild, options.serverSourceMaps, targetDir, buildRoot);
12965
+ writeServerMetafile(serverBuild, options.analyze, buildRoot);
12966
+ console.log(`[furin] Server bundle: ${toPosixPath(join12(targetManifest.targetDir, "server.js"))}`);
12967
+ targetManifest.serverPath = toPosixPath(join12(targetManifest.targetDir, "server.js"));
12570
12968
  }
12571
12969
  return targetManifest;
12572
12970
  }
12573
12971
 
12574
12972
  // 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";
12973
+ import { existsSync as existsSync11, rmSync as rmSync3, writeFileSync as writeFileSync8 } from "fs";
12974
+ import { join as join13, relative as relative8, resolve as resolve7 } from "path";
12577
12975
  async function buildPackageTarget(app, rootDir, buildRoot, options) {
12578
12976
  const { prefix, root, routes, pagesDir } = app;
12579
12977
  const modulePaths = routeSourcePaths(app);
12580
- const targetDir = join11(buildRoot, "package");
12978
+ const targetDir = join13(buildRoot, "package");
12581
12979
  rmSync3(targetDir, { force: true, recursive: true });
12582
12980
  ensureDir(targetDir);
12583
12981
  const { entryChunk, cssChunks } = await buildClient(routes, {
12584
12982
  basePath: prefix,
12585
12983
  clientLogging: options.clientLogging ?? false,
12586
- metafilePath: options.analyze ? join11(buildRoot, "analysis", "package-client.json") : undefined,
12984
+ metafilePath: options.analyze ? join13(buildRoot, "analysis", "package-client.json") : undefined,
12587
12985
  optimizeImports: options.optimizeImports,
12588
12986
  outDir: targetDir,
12589
12987
  pagesDir,
@@ -12595,13 +12993,13 @@ async function buildPackageTarget(app, rootDir, buildRoot, options) {
12595
12993
  const buildFingerprint = await createBuildFingerprint(`${prefix}
12596
12994
  ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12597
12995
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
12598
- const clientDir = join11(targetDir, "client");
12599
- const publicDir = join11(rootDir, "public");
12600
- if (existsSync10(publicDir)) {
12601
- copyDirRecursive(publicDir, join11(targetDir, "public"));
12996
+ const clientDir = join13(targetDir, "client");
12997
+ const publicDir = join13(rootDir, "public");
12998
+ if (existsSync11(publicDir)) {
12999
+ copyDirRecursive(publicDir, join13(targetDir, "public"));
12602
13000
  }
12603
13001
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
12604
- writeFileSync6(join11(clientDir, "index.html"), indexHtml);
13002
+ writeFileSync8(join13(clientDir, "index.html"), indexHtml);
12605
13003
  setProductionTemplateContent(indexHtml);
12606
13004
  ssgRouteCache().clear();
12607
13005
  const ssgCache = await buildSSGCacheSnapshot(routes, root, "http://localhost", prefix);
@@ -12626,7 +13024,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12626
13024
  buildId,
12627
13025
  clientLogging: options.clientLogging ?? false,
12628
13026
  modulePaths,
12629
- nativeRoutes: routeModuleSpecifier(app),
13027
+ nativeRoutes: composableRouteModuleSpecifier(app),
12630
13028
  prefix,
12631
13029
  rootConventions,
12632
13030
  rootPath: root.path,
@@ -12638,7 +13036,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12638
13036
  headerComment: "// Auto-generated by `furin build --target package` \u2014 do not edit",
12639
13037
  mode: "register"
12640
13038
  });
12641
- const registerEntry = join11(targetDir, "register.ts");
13039
+ const registerEntry = join13(targetDir, "register.ts");
12642
13040
  const register = createVirtualBuildEntry(registerEntry, registerSource, "ts");
12643
13041
  const result = await runBunBuild({
12644
13042
  entrypoints: [register.entrypoint],
@@ -12658,7 +13056,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12658
13056
  if (!result.success) {
12659
13057
  throw new AggregateError(result.logs, "[furin] package register build failed");
12660
13058
  }
12661
- const relativePagesDir = toPosixPath(relative6(targetDir, resolve5(rootDir, pagesDir)));
13059
+ const relativePagesDir = toPosixPath(relative8(targetDir, resolve7(rootDir, pagesDir)));
12662
13060
  const factorySource = `// Auto-generated by \`furin build --target package\` \u2014 do not edit
12663
13061
  import { fileURLToPath } from "node:url";
12664
13062
  import { furin } from "@teyik0/furin";
@@ -12685,7 +13083,7 @@ export function createFurinApp(options = {}) {
12685
13083
 
12686
13084
  export const prefix = ${JSON.stringify(prefix)};
12687
13085
  `;
12688
- writeFileSync6(join11(targetDir, "index.js"), factorySource);
13086
+ writeFileSync8(join13(targetDir, "index.js"), factorySource);
12689
13087
  const dtsSource = `import type { FurinOptions, furin } from "@teyik0/furin";
12690
13088
 
12691
13089
  /** Extra furin() options \u2014 pagesDir/prefix/clientDir are baked into the package and cannot be overridden. */
@@ -12693,29 +13091,29 @@ export type CreateFurinAppOptions = Omit<FurinOptions, "pagesDir" | "prefix" | "
12693
13091
  export declare function createFurinApp(options?: CreateFurinAppOptions): ReturnType<typeof furin>;
12694
13092
  export declare const prefix: string;
12695
13093
  `;
12696
- writeFileSync6(join11(targetDir, "index.d.ts"), dtsSource);
12697
- console.log(`[furin] Package artifact: ${toPosixPath(relative6(rootDir, targetDir))}`);
13094
+ writeFileSync8(join13(targetDir, "index.d.ts"), dtsSource);
13095
+ console.log(`[furin] Package artifact: ${toPosixPath(relative8(rootDir, targetDir))}`);
12698
13096
  return {
12699
13097
  buildId,
12700
13098
  generatedAt: new Date().toISOString(),
12701
13099
  prefix,
12702
- targetDir: toPosixPath(relative6(rootDir, targetDir))
13100
+ targetDir: toPosixPath(relative8(rootDir, targetDir))
12703
13101
  };
12704
13102
  }
12705
13103
 
12706
13104
  // 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";
13105
+ import { cpSync as cpSync2, existsSync as existsSync12, rmSync as rmSync4, writeFileSync as writeFileSync9 } from "fs";
13106
+ import { dirname as dirname10, isAbsolute as isAbsolute4, join as join14, parse as parse3, relative as relative9, resolve as resolve8, sep as sep2, win32 } from "path";
12709
13107
  var STATIC_CONCURRENCY = 4;
12710
13108
  var DYNAMIC_SEGMENT_RE2 = /\/:[^/]+|\/\*/;
12711
13109
  var TRAILING_SLASHES_RE = /\/+$/;
12712
13110
  var STATIC_RENDER_ORIGIN = "http://localhost";
12713
13111
  function pathToOutputFile(urlPath, outDir, fileName) {
12714
- const normalizedOutDir = resolve6(outDir);
13112
+ const normalizedOutDir = resolve8(outDir);
12715
13113
  if (urlPath === "/" || urlPath === "") {
12716
- return join12(normalizedOutDir, fileName);
13114
+ return join14(normalizedOutDir, fileName);
12717
13115
  }
12718
- const resolved = resolve6(normalizedOutDir, urlPath.slice(1), fileName);
13116
+ const resolved = resolve8(normalizedOutDir, urlPath.slice(1), fileName);
12719
13117
  if (!resolved.startsWith(`${normalizedOutDir}${sep2}`)) {
12720
13118
  throw new Error(`[furin] static: unsafe output path detected for URL "${urlPath}" \u2014 path traversal via ".." is not allowed.`);
12721
13119
  }
@@ -12788,22 +13186,22 @@ async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, sk
12788
13186
  throw new Error(`[furin] static: route "${route.pattern}" returned a response that cannot be exported.`);
12789
13187
  }
12790
13188
  const staticLocation = resolveStaticRedirectLocation(location, basePath, urlPath);
12791
- ensureDir(dirname7(htmlOutputFile));
12792
- writeFileSync7(htmlOutputFile, createStaticRedirectHtml(staticLocation.html));
13189
+ ensureDir(dirname10(htmlOutputFile));
13190
+ writeFileSync9(htmlOutputFile, createStaticRedirectHtml(staticLocation.html));
12793
13191
  if (staticLocation.spa !== null) {
12794
13192
  const serializedRedirect = await toCrossJSONAsync({
12795
13193
  __furinRedirect: staticLocation.spa
12796
13194
  });
12797
- writeFileSync7(dataOutputFile, `${JSON.stringify(serializedRedirect)}
13195
+ writeFileSync9(dataOutputFile, `${JSON.stringify(serializedRedirect)}
12798
13196
  `);
12799
13197
  }
12800
13198
  renderedRoutes.push(urlPath);
12801
13199
  console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)} (redirects to ${staticLocation.html})`);
12802
13200
  return;
12803
13201
  }
12804
- ensureDir(dirname7(htmlOutputFile));
12805
- writeFileSync7(htmlOutputFile, entry.html);
12806
- writeFileSync7(dataOutputFile, entry.ndjson);
13202
+ ensureDir(dirname10(htmlOutputFile));
13203
+ writeFileSync9(htmlOutputFile, entry.html);
13204
+ writeFileSync9(dataOutputFile, entry.ndjson);
12807
13205
  renderedRoutes.push(urlPath);
12808
13206
  console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)}`);
12809
13207
  } catch (err) {
@@ -12836,13 +13234,13 @@ async function buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRo
12836
13234
  if (!DYNAMIC_SEGMENT_RE2.test(route.pattern)) {
12837
13235
  return { paramSets: [{}], route };
12838
13236
  }
12839
- if (!route.page.staticParams) {
13237
+ if (!hasStaticParams(route)) {
12840
13238
  console.warn(`[furin] static: skipping dynamic route "${route.pattern}" \u2014 no staticParams() defined.`);
12841
13239
  skippedRoutes.push(route.pattern);
12842
13240
  return { paramSets: null, route };
12843
13241
  }
12844
13242
  try {
12845
- const paramSets = await route.page.staticParams() ?? [];
13243
+ const paramSets = await resolveStaticParams(route, STATIC_RENDER_ORIGIN) ?? [];
12846
13244
  return { paramSets, route };
12847
13245
  } catch (err) {
12848
13246
  return { error: err, paramSets: null, route };
@@ -12909,15 +13307,16 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
12909
13307
  if (basePath && !basePath.startsWith("/")) {
12910
13308
  throw new Error(`[furin] static: basePath must start with "/" (received "${rawBasePath}"). ` + `Use "" for root deployments or "/sub-path" for sub-path deployments.`);
12911
13309
  }
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 === ".") {
13310
+ const rawOutDir = staticConfig.outDir ?? "dist";
13311
+ const outDir = resolve8(rootDir, rawOutDir);
13312
+ const normalizedRoot = resolve8(rootDir);
13313
+ const normalizedBuildRoot = resolve8(buildRoot);
13314
+ if (outDir === normalizedRoot || outDir === normalizedBuildRoot || outDir === parse3(outDir).root || rawOutDir === win32.parse(rawOutDir).root) {
12916
13315
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
12917
13316
  }
12918
13317
  function isOutsideOutDir(target) {
12919
- const rel = relative7(outDir, target);
12920
- return rel.startsWith("..") || isAbsolute2(rel);
13318
+ const rel = relative9(outDir, target);
13319
+ return rel.startsWith("..") || isAbsolute4(rel);
12921
13320
  }
12922
13321
  if (!(isOutsideOutDir(normalizedRoot) && isOutsideOutDir(normalizedBuildRoot))) {
12923
13322
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
@@ -12933,36 +13332,36 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
12933
13332
  const afterQueueCount = skippedRoutes.length;
12934
13333
  rmSync4(outDir, { force: true, recursive: true });
12935
13334
  ensureDir(outDir);
12936
- const targetDir = join12(buildRoot, "static");
13335
+ const targetDir = join14(buildRoot, "static");
12937
13336
  rmSync4(targetDir, { force: true, recursive: true });
12938
13337
  ensureDir(targetDir);
12939
13338
  const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
12940
13339
  basePath,
12941
13340
  clientLogging: Boolean(options.clientLogging),
12942
- metafilePath: options.analyze ? join12(buildRoot, "analysis", "static-client.json") : undefined,
13341
+ metafilePath: options.analyze ? join14(buildRoot, "analysis", "static-client.json") : undefined,
12943
13342
  optimizeImports: options.optimizeImports,
12944
13343
  outDir: targetDir,
12945
- pagesDir: dirname7(root.path),
13344
+ pagesDir: dirname10(root.path),
12946
13345
  plugins: options.plugins,
12947
13346
  publicPath,
12948
13347
  reactCompiler: options.reactCompiler,
12949
13348
  rootLayout: root.path
12950
13349
  });
12951
- const publicFavicon = join12(rootDir, "public", "favicon.ico");
12952
- const faviconHref = existsSync11(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
13350
+ const publicFavicon = join14(rootDir, "public", "favicon.ico");
13351
+ const faviconHref = existsSync12(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
12953
13352
  const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref, true);
12954
13353
  setProductionTemplateContent(shellHtml);
12955
- const publicSrcDir = join12(rootDir, "public");
12956
- if (existsSync11(publicSrcDir)) {
13354
+ const publicSrcDir = join14(rootDir, "public");
13355
+ if (existsSync12(publicSrcDir)) {
12957
13356
  cpSync2(publicSrcDir, outDir, { recursive: true });
12958
13357
  }
12959
- const clientSrcDir = join12(targetDir, "client");
12960
- if (existsSync11(clientSrcDir)) {
12961
- cpSync2(clientSrcDir, join12(outDir, "_client"), { recursive: true });
13358
+ const clientSrcDir = join14(targetDir, "client");
13359
+ if (existsSync12(clientSrcDir)) {
13360
+ cpSync2(clientSrcDir, join14(outDir, "_client"), { recursive: true });
12962
13361
  }
12963
13362
  await runWithConcurrency(tasks, STATIC_CONCURRENCY);
12964
13363
  assertNoPrerenderSkips(onSSR, skippedRoutes, afterQueueCount);
12965
- writeFileSync7(join12(outDir, "404.html"), shellHtml);
13364
+ writeFileSync9(join14(outDir, "404.html"), shellHtml);
12966
13365
  console.log("[furin] static: wrote 404.html (SPA shell fallback)");
12967
13366
  rmSync4(targetDir, { force: true, recursive: true });
12968
13367
  console.log(`[furin] static: export complete \u2192 ${toPosixPath(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
@@ -12976,32 +13375,24 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
12976
13375
  }
12977
13376
 
12978
13377
  // 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";
13378
+ import { cpSync as cpSync3, existsSync as existsSync13, readFileSync as readFileSync7, rmSync as rmSync5, symlinkSync, writeFileSync as writeFileSync10 } from "fs";
13379
+ import { basename as basename5, dirname as dirname11, extname as extname4, join as join15, relative as relative10 } from "path";
12989
13380
  import { fileURLToPath as fileURLToPath6, pathToFileURL as pathToFileURL2 } from "url";
12990
13381
  init_patterns();
12991
13382
  var ISR_PATH_PARAM = "__furin_path";
12992
13383
  var DYNAMIC_SEGMENT_RE3 = /\/:[^/]+|\/\*/;
12993
- var ELYSIA_STATIC_IMPORT_RE = /^@elysiajs\/static$/;
13384
+ var ELYSIA_STATIC_IMPORT_RE = /^@elysia\/static$/;
12994
13385
  var MATCH_ALL_RE = /.*/;
12995
13386
  var REGEX_META_RE = /[.*+?^${}()|[\]\\]/;
12996
13387
  var UNSAFE_FUNCTION_PATH_RE = /[^a-zA-Z0-9_.[\]/-]/g;
12997
13388
  var VERCEL_FUNCTIONS_PATH = fileURLToPath6(import.meta.resolve("@vercel/functions"));
12998
13389
  var VERCEL_RUNTIME_STUB_NAMESPACE = "furin-vercel-runtime-stub";
12999
- var FURIN_RUNTIME_ROOT2 = dirname8(import.meta.dir);
13390
+ var FURIN_RUNTIME_ROOT2 = dirname11(import.meta.dir);
13000
13391
  function isFurinRuntimeImporter(importer) {
13001
13392
  if (importer === "") {
13002
13393
  return false;
13003
13394
  }
13004
- const fromRuntimeRoot = relative8(FURIN_RUNTIME_ROOT2, importer.split("?")[0]);
13395
+ const fromRuntimeRoot = relative10(FURIN_RUNTIME_ROOT2, importer.split("?")[0]);
13005
13396
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
13006
13397
  }
13007
13398
  function vercelRuntimePlugin() {
@@ -13010,11 +13401,11 @@ function vercelRuntimePlugin() {
13010
13401
  setup(build) {
13011
13402
  build.onResolve({ filter: ELYSIA_STATIC_IMPORT_RE }, ({ importer }) => {
13012
13403
  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.");
13404
+ throw new Error("[furin] Application @elysia/static mounts are not supported by the Vercel target. Put CDN assets under public/ instead.");
13014
13405
  }
13015
13406
  return {
13016
13407
  namespace: VERCEL_RUNTIME_STUB_NAMESPACE,
13017
- path: "@elysiajs/static"
13408
+ path: "@elysia/static"
13018
13409
  };
13019
13410
  });
13020
13411
  build.onLoad({ filter: MATCH_ALL_RE, namespace: VERCEL_RUNTIME_STUB_NAMESPACE }, () => ({
@@ -13027,8 +13418,8 @@ function vercelRuntimePlugin() {
13027
13418
  };
13028
13419
  }
13029
13420
  function frameworkVersion() {
13030
- const packageRoot = dirname8(dirname8(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
13031
- const packageJson = JSON.parse(readFileSync6(join13(packageRoot, "package.json"), "utf8"));
13421
+ const packageRoot = dirname11(dirname11(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
13422
+ const packageJson = JSON.parse(readFileSync7(join15(packageRoot, "package.json"), "utf8"));
13032
13423
  return packageJson.version;
13033
13424
  }
13034
13425
  function serverEntryLoader(serverEntry) {
@@ -13046,10 +13437,15 @@ function serverEntryLoader(serverEntry) {
13046
13437
  }
13047
13438
  function assertDefaultServerExport(serverEntry) {
13048
13439
  const transpiler = new Bun.Transpiler({ loader: serverEntryLoader(serverEntry) });
13049
- const { exports } = transpiler.scan(readFileSync6(serverEntry, "utf8"));
13440
+ const { exports, imports } = transpiler.scan(readFileSync7(serverEntry, "utf8"));
13050
13441
  if (!exports.includes("default")) {
13051
13442
  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
13443
  }
13444
+ if (imports.some(({ path }) => ELYSIA_STATIC_IMPORT_RE.test(path))) {
13445
+ throw new AggregateError([
13446
+ new Error("[furin] Application @elysia/static mounts are not supported by the Vercel target. Put CDN assets under public/ instead.")
13447
+ ], "[furin] Vercel build rejected application static mounts.");
13448
+ }
13053
13449
  }
13054
13450
  function escapeRegex(value) {
13055
13451
  let escaped = "";
@@ -13139,9 +13535,9 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
13139
13535
  body = result.html;
13140
13536
  ({ status } = result);
13141
13537
  }
13142
- const fallbackPath = join13(dirname8(join13(functionsDir, spec.functionName)), fallback);
13143
- ensureDir(dirname8(fallbackPath));
13144
- writeFileSync8(fallbackPath, body);
13538
+ const fallbackPath = join15(dirname11(join15(functionsDir, spec.functionName)), fallback);
13539
+ ensureDir(dirname11(fallbackPath));
13540
+ writeFileSync10(fallbackPath, body);
13145
13541
  spec.config.fallback = fallback;
13146
13542
  spec.config.initialHeaders = {
13147
13543
  "content-type": contentType,
@@ -13152,9 +13548,9 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
13152
13548
  spec.config.initialStatus = status;
13153
13549
  }
13154
13550
  function createFunctionAlias(functionsDir, serverFunctionDir, functionName) {
13155
- const aliasPath = join13(functionsDir, `${functionName}.func`);
13156
- ensureDir(dirname8(aliasPath));
13157
- const target = relative8(dirname8(aliasPath), serverFunctionDir);
13551
+ const aliasPath = join15(functionsDir, `${functionName}.func`);
13552
+ ensureDir(dirname11(aliasPath));
13553
+ const target = relative10(dirname11(aliasPath), serverFunctionDir);
13158
13554
  symlinkSync(target, aliasPath, process.platform === "win32" ? "junction" : "dir");
13159
13555
  }
13160
13556
  function createExactPrerenderSpec(prerender, routePath) {
@@ -13224,7 +13620,7 @@ async function createPrerenderSpecs(apps, builds, functionsDir, pprResumeKey) {
13224
13620
  return compareRouteSpecificity(right.pattern, left.pattern);
13225
13621
  });
13226
13622
  }
13227
- function vercelEntrySource(apps, builds, prerenderSpecs, serverEntry, pprResumeKey) {
13623
+ function vercelEntrySource(apps, builds, prerenderSpecs, appEntry, pprResumeKey) {
13228
13624
  const routeCount = builds.reduce((count, build) => count + build.entryApp.routes.length, 0);
13229
13625
  const prerenderAliases = prerenderSpecs.map((spec) => [
13230
13626
  `/${spec.functionName}`,
@@ -13241,15 +13637,6 @@ function vercelEntrySource(apps, builds, prerenderSpecs, serverEntry, pprResumeK
13241
13637
  source: `^(?:${routePatternSource(app.prefix, route.pattern)})$`,
13242
13638
  tags: route.tags ?? []
13243
13639
  }))).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
13640
  return `import {
13254
13641
  addCacheTag,
13255
13642
  getCache as getVercelCache,
@@ -13262,12 +13649,11 @@ import {
13262
13649
  markExternalPrerenderRequest,
13263
13650
  restorePprResumeRequest,
13264
13651
  setCacheTagPurger,
13652
+ setRuntimeEvlogWaitUntil,
13265
13653
  setRuntimeCacheProvider,
13266
13654
  waitForPendingISRRevalidations,
13267
13655
  } from "@teyik0/furin/internal";
13268
13656
 
13269
- ${contextSource}
13270
-
13271
13657
  const prerenderAliases = new Map(
13272
13658
  ${JSON.stringify(prerenderAliases)}.map(([alias, source]) => [alias, new RegExp(source)])
13273
13659
  );
@@ -13287,6 +13673,7 @@ function encodeCacheTag(value) {
13287
13673
  setRuntimeCacheProvider({
13288
13674
  getCache: (options) => getVercelCache(options),
13289
13675
  });
13676
+ setRuntimeEvlogWaitUntil(waitUntil);
13290
13677
 
13291
13678
  async function purgeCacheTags(paths) {
13292
13679
  const purge = Promise.all([
@@ -13300,7 +13687,7 @@ setCachePurger(purgeCacheTags);
13300
13687
  setCacheTagPurger(purgeCacheTags);
13301
13688
 
13302
13689
  const serverInitStartedAt = performance.now();
13303
- const serverModule = await import(${JSON.stringify(toPosixPath(serverEntry))});
13690
+ const serverModule = await import(${JSON.stringify(toPosixPath(appEntry))});
13304
13691
  const app = serverModule.default;
13305
13692
  if (!app || typeof app.handle !== "function") {
13306
13693
  throw new TypeError("[furin] Vercel server entry must export the Elysia app as default.");
@@ -13385,10 +13772,10 @@ async function buildPprFallbacks(apps, builds, specs, functionsDir, rootDir, tar
13385
13772
  if (jobs.length === 0) {
13386
13773
  return;
13387
13774
  }
13388
- const resultPath = join13(targetDir, "ppr-results.json");
13775
+ const resultPath = join15(targetDir, "ppr-results.json");
13389
13776
  const requests = jobs.map(({ path, spec }) => `http://localhost/${spec.functionName}?${ISR_PATH_PARAM}=${encodeURIComponent(path)}`);
13390
13777
  const script = `
13391
- const handler = (await import(${JSON.stringify(pathToFileURL2(join13(functionsDir, "__server.func/index.js")).href)})).default;
13778
+ const handler = (await import(${JSON.stringify(pathToFileURL2(join15(functionsDir, "__server.func/index.js")).href)})).default;
13392
13779
  const results = [];
13393
13780
  for (const url of ${JSON.stringify(requests)}) {
13394
13781
  const response = await handler.fetch(new Request(url));
@@ -13415,7 +13802,7 @@ process.exit(0);
13415
13802
  ${stderr}
13416
13803
  ${stdout}`);
13417
13804
  }
13418
- const results = JSON.parse(readFileSync6(resultPath, "utf8"));
13805
+ const results = JSON.parse(readFileSync7(resultPath, "utf8"));
13419
13806
  for (const [index, job] of jobs.entries()) {
13420
13807
  const result = results[index];
13421
13808
  await addPrerenderFallback(job.spec, job.path, {
@@ -13487,6 +13874,7 @@ async function handle(request) {
13487
13874
  \`furin_server_init;dur=\${initialization.server_init_ms}\`,
13488
13875
  \`furin_handler_wait;dur=\${requestWaitMs}\`,
13489
13876
  \`furin_handler;dur=\${handlerMs}\`,
13877
+ ...(isFirstRequest ? ["furin_instance_first_request"] : []),
13490
13878
  ].join(", ");
13491
13879
  return appendServerTiming(response, serverTiming);
13492
13880
  }
@@ -13496,32 +13884,57 @@ export default { fetch: handle };
13496
13884
  }
13497
13885
  async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options) {
13498
13886
  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");
13887
+ const targetDir = join15(buildRoot, "vercel");
13888
+ const outputDir = join15(rootDir, ".vercel", "output");
13889
+ const staticDir = join15(outputDir, "static");
13890
+ const functionsDir = join15(outputDir, "functions");
13891
+ const serverFunctionDir = join15(functionsDir, "__server.func");
13504
13892
  rmSync5(targetDir, { force: true, recursive: true });
13893
+ rmSync5(join15(buildRoot, "private", "server-sourcemaps", "vercel"), {
13894
+ force: true,
13895
+ recursive: true
13896
+ });
13505
13897
  rmSync5(outputDir, { force: true, recursive: true });
13506
13898
  ensureDir(targetDir);
13507
13899
  ensureDir(staticDir);
13508
13900
  ensureDir(serverFunctionDir);
13509
13901
  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");
13512
- if (existsSync12(publicDir)) {
13902
+ cpSync3(join15(targetDir, "server-codec.js"), join15(serverFunctionDir, "server-codec.js"));
13903
+ const publicDir = join15(rootDir, "public");
13904
+ if (existsSync13(publicDir)) {
13513
13905
  cpSync3(publicDir, staticDir, { recursive: true });
13906
+ for (const app of apps) {
13907
+ const appStaticDir = join15(staticDir, app.prefix.slice(1));
13908
+ const appPublicDir = join15(appStaticDir, "public");
13909
+ cpSync3(publicDir, appPublicDir, { recursive: true });
13910
+ const favicon = join15(publicDir, "favicon.ico");
13911
+ if (app.prefix !== "" && existsSync13(favicon)) {
13912
+ cpSync3(favicon, join15(appStaticDir, "favicon.ico"));
13913
+ }
13914
+ }
13514
13915
  }
13515
13916
  for (let appIndex = 0;appIndex < apps.length; appIndex += 1) {
13516
13917
  const app = apps[appIndex];
13517
13918
  const build = builds[appIndex];
13518
- const clientOutputDir = join13(staticDir, app.prefix.slice(1), "_client");
13919
+ const clientOutputDir = join15(staticDir, app.prefix.slice(1), "_client");
13519
13920
  cpSync3(build.clientDir, clientOutputDir, { recursive: true });
13520
13921
  }
13521
13922
  const pprResumeKey = crypto.randomUUID();
13522
13923
  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");
13924
+ const appEntry = await materializeServerAppEntry({
13925
+ apps: builds.map(({ entryApp, indexHtml }) => ({
13926
+ ...entryApp,
13927
+ embed: undefined,
13928
+ serveAssets: false,
13929
+ templateHtml: indexHtml
13930
+ })),
13931
+ headerComment: "// Auto-generated by `furin build --target vercel` \u2014 do not edit",
13932
+ instances: apps,
13933
+ outDir: serverFunctionDir,
13934
+ serverEntry
13935
+ });
13936
+ const entryPath = join15(serverFunctionDir, "_vercel-handler.ts");
13937
+ const entry = createVirtualBuildEntry(entryPath, vercelEntrySource(apps, builds, prerenderSpecs, appEntry, pprResumeKey), "ts");
13525
13938
  const serverBuild = await runBunBuild({
13526
13939
  define: { "process.env.NODE_ENV": JSON.stringify("production") },
13527
13940
  entrypoints: [entry.entrypoint],
@@ -13539,26 +13952,30 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13539
13952
  ...options.plugins ?? [],
13540
13953
  createRoutesPlugin({ instances: apps, target: "server" }),
13541
13954
  isomorphicTransformPlugin("server"),
13542
- environmentGuardPlugin("ssr")
13955
+ environmentGuardPlugin("ssr"),
13956
+ elysiaAot(appEntry)
13543
13957
  ],
13544
- sourcemap: "none",
13958
+ sourcemap: options.serverSourceMaps ? "external" : "none",
13959
+ splitting: true,
13545
13960
  target: "bun"
13546
13961
  });
13962
+ if (options.serverSourceMaps) {
13963
+ movePrivateServerSourceMaps(serverFunctionDir, join15(buildRoot, "private", "server-sourcemaps", "vercel"), serverBuild.outputs.filter((output) => output.kind === "sourcemap").map((output) => output.path));
13964
+ }
13547
13965
  if (options.analyze) {
13548
13966
  if (serverBuild.metafile === undefined) {
13549
13967
  throw new Error("[furin] Vercel server build did not produce the requested metafile.");
13550
13968
  }
13551
- const metafilePath = join13(buildRoot, "analysis", "vercel-server.json");
13552
- ensureDir(dirname8(metafilePath));
13553
- writeFileSync8(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}
13969
+ const metafilePath = join15(buildRoot, "analysis", "vercel-server.json");
13970
+ ensureDir(dirname11(metafilePath));
13971
+ writeFileSync10(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}
13554
13972
  `);
13555
13973
  console.log(`[furin] Server metafile: ${toPosixPath(metafilePath)}`);
13556
13974
  }
13557
- const handlerPath = join13(serverFunctionDir, "handler.js");
13558
- const serverBundleBytes = existsSync12(handlerPath) ? statSync3(handlerPath).size : 0;
13559
- writeFileSync8(join13(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
13975
+ const serverBundleBytes = serverBuild.outputs.filter((output) => output.path.endsWith(".js")).reduce((total, output) => total + output.size, 0);
13976
+ writeFileSync10(join15(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
13560
13977
  await buildPprFallbacks(apps, builds, prerenderSpecs, functionsDir, rootDir, targetDir);
13561
- writeFileSync8(join13(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
13978
+ writeFileSync10(join15(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
13562
13979
  handler: "index.js",
13563
13980
  launcherType: "Nodejs",
13564
13981
  ...options.vercelConfig?.regions === undefined ? {} : { regions: options.vercelConfig.regions },
@@ -13569,7 +13986,7 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13569
13986
  `);
13570
13987
  for (const spec of prerenderSpecs) {
13571
13988
  createFunctionAlias(functionsDir, serverFunctionDir, spec.functionName);
13572
- writeFileSync8(join13(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
13989
+ writeFileSync10(join15(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
13573
13990
  `);
13574
13991
  }
13575
13992
  const assetRoutes = apps.map((app) => ({
@@ -13599,48 +14016,71 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13599
14016
  ],
13600
14017
  version: 3
13601
14018
  };
13602
- writeFileSync8(join13(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
14019
+ writeFileSync10(join15(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
13603
14020
  `);
13604
14021
  const ssgRoutes = builds.flatMap((build, index) => build.prerenders.filter((prerender) => prerender.route.mode === "ssg").map((prerender) => physicalPath(apps[index].prefix, prerender.path))).toSorted();
13605
14022
  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))}`);
14023
+ console.log(`[furin] Vercel output: ${toPosixPath(relative10(rootDir, outputDir))}`);
13607
14024
  return {
13608
14025
  buildId: headlineBuildId,
13609
14026
  generatedAt: new Date().toISOString(),
13610
14027
  isrRoutes,
13611
- outputDir: toPosixPath(relative8(rootDir, outputDir)),
13612
- serverPath: toPosixPath(relative8(rootDir, serverFunctionDir)),
14028
+ outputDir: toPosixPath(relative10(rootDir, outputDir)),
14029
+ serverPath: toPosixPath(relative10(rootDir, serverFunctionDir)),
13613
14030
  ssgRoutes
13614
14031
  };
13615
14032
  }
13616
14033
 
13617
14034
  // src/config.ts
13618
- import { t as t2 } from "elysia";
13619
- var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare", "static", "package"];
13620
- var buildTargetSchema = t2.Union(BUILD_TARGETS.map((v) => t2.Literal(v)));
13621
- var compileTargetSchema = t2.Union([t2.Literal("server"), t2.Literal("embed")]);
13622
- var configSchema = t2.Object({
13623
- apps: t2.Optional(t2.Array(t2.Object({
13624
- pagesDir: t2.String(),
13625
- prefix: t2.Optional(t2.String())
14035
+ import { t } from "elysia";
14036
+ var BUILD_TARGETS = ["bun", "vercel", "static", "package"];
14037
+ var VERCEL_REGIONS = [
14038
+ "arn1",
14039
+ "bom1",
14040
+ "cdg1",
14041
+ "cle1",
14042
+ "cpt1",
14043
+ "dub1",
14044
+ "dxb1",
14045
+ "fra1",
14046
+ "gru1",
14047
+ "hkg1",
14048
+ "hnd1",
14049
+ "iad1",
14050
+ "icn1",
14051
+ "kix1",
14052
+ "lhr1",
14053
+ "pdx1",
14054
+ "sfo1",
14055
+ "sin1",
14056
+ "syd1",
14057
+ "yul1"
14058
+ ];
14059
+ var buildTargetSchema = t.Union(BUILD_TARGETS.map((v) => t.Literal(v)));
14060
+ var compileTargetSchema = t.Union([t.Literal("server"), t.Literal("embed")]);
14061
+ var configSchema = t.Object({
14062
+ apps: t.Optional(t.Array(t.Object({
14063
+ pagesDir: t.String(),
14064
+ prefix: t.Optional(t.String())
13626
14065
  }))),
13627
- bun: t2.Optional(t2.Object({
13628
- compile: t2.Optional(compileTargetSchema)
14066
+ bun: t.Optional(t.Object({
14067
+ compile: t.Optional(compileTargetSchema)
13629
14068
  })),
13630
- clientLogging: t2.Optional(t2.Boolean()),
13631
- optimizeImports: t2.Optional(t2.Array(t2.String())),
13632
- pagesDir: t2.Optional(t2.String()),
13633
- reactCompiler: t2.Optional(t2.Boolean()),
13634
- rootDir: t2.Optional(t2.String()),
13635
- serverEntry: t2.Optional(t2.String()),
13636
- static: t2.Optional(t2.Object({
13637
- basePath: t2.Optional(t2.String()),
13638
- onSSR: t2.Optional(t2.Union([t2.Literal("error"), t2.Literal("skip")])),
13639
- outDir: t2.Optional(t2.String())
14069
+ clientLogging: t.Optional(t.Boolean()),
14070
+ optimizeImports: t.Optional(t.Array(t.String())),
14071
+ pagesDir: t.Optional(t.String()),
14072
+ reactCompiler: t.Optional(t.Boolean()),
14073
+ rootDir: t.Optional(t.String()),
14074
+ serverEntry: t.Optional(t.String()),
14075
+ serverSourceMaps: t.Optional(t.Boolean()),
14076
+ static: t.Optional(t.Object({
14077
+ basePath: t.Optional(t.String()),
14078
+ onSSR: t.Optional(t.Union([t.Literal("error"), t.Literal("skip")])),
14079
+ outDir: t.Optional(t.String())
13640
14080
  })),
13641
- targets: t2.Optional(t2.Array(buildTargetSchema)),
13642
- vercel: t2.Optional(t2.Object({
13643
- regions: t2.Optional(t2.Array(t2.String({ pattern: "^[a-z]{3}[1-9][0-9]*$" }), {
14081
+ targets: t.Optional(t.Array(buildTargetSchema)),
14082
+ vercel: t.Optional(t.Object({
14083
+ regions: t.Optional(t.Array(t.Enum(VERCEL_REGIONS), {
13644
14084
  minItems: 1,
13645
14085
  uniqueItems: true
13646
14086
  }))
@@ -13651,9 +14091,9 @@ var configSchema = t2.Object({
13651
14091
  init_instance();
13652
14092
 
13653
14093
  // src/server/router/discovery.ts
13654
- import { existsSync as existsSync13 } from "fs";
14094
+ import { existsSync as existsSync14 } from "fs";
13655
14095
  import { readdir } from "fs/promises";
13656
- import { join as join14, parse as parse3 } from "path";
14096
+ import { join as join16, parse as parse4 } from "path";
13657
14097
 
13658
14098
  // src/server/internal.ts
13659
14099
  var _compileContexts = new Map;
@@ -13738,6 +14178,7 @@ function adaptDefinedLayout(route, parent, sourcePath) {
13738
14178
  requestLoader: route.requestLoader,
13739
14179
  revalidate: route.revalidate,
13740
14180
  sourcePath,
14181
+ staticParams: route.staticParams,
13741
14182
  tags: copyTags(route.tags)
13742
14183
  };
13743
14184
  }
@@ -13802,7 +14243,7 @@ async function scanPages(pagesDir) {
13802
14243
  async function scanRootLayout(pagesDir) {
13803
14244
  const rootPath = `${pagesDir}/root.tsx`;
13804
14245
  const ctx = getCompileContext();
13805
- if (!(existsSync13(rootPath) || ctx?.modules[rootPath])) {
14246
+ if (!(existsSync14(rootPath) || ctx?.modules[rootPath])) {
13806
14247
  throw new Error("[furin] root.tsx: not found.");
13807
14248
  }
13808
14249
  const mod = ctx?.modules[rootPath] ?? await import(rootPath);
@@ -13842,8 +14283,8 @@ function getSourceModuleCandidates(dir, name) {
13842
14283
  async function loadConventionComponent(dir, name) {
13843
14284
  const ctx = getCompileContext();
13844
14285
  for (const filePath of getSourceModuleCandidates(dir, name)) {
13845
- if (existsSync13(filePath) || ctx?.modules[filePath]) {
13846
- const moduleSpecifier = IS_DEV && existsSync13(filePath) ? `${filePath}?furin-server&t=${routeModuleSourceVersion(filePath)}` : filePath;
14286
+ if (existsSync14(filePath) || ctx?.modules[filePath]) {
14287
+ const moduleSpecifier = IS_DEV && existsSync14(filePath) ? `${filePath}?furin-server&t=${routeModuleSourceVersion(filePath)}` : filePath;
13847
14288
  const mod = ctx?.modules[filePath] ?? await import(moduleSpecifier);
13848
14289
  if (mod.default) {
13849
14290
  return { component: mod.default, path: filePath };
@@ -13861,7 +14302,7 @@ async function scanPageFiles(pagesDir, root) {
13861
14302
  continue;
13862
14303
  }
13863
14304
  const relativePath = routeRelativePath(pagesDir, absolutePath);
13864
- const fileName = parse3(relativePath).name;
14305
+ const fileName = parse4(relativePath).name;
13865
14306
  if (fileName.startsWith("_") || fileName === "root" || isConventionFileName(fileName)) {
13866
14307
  continue;
13867
14308
  }
@@ -13926,10 +14367,10 @@ async function resolveDefinedLayoutParent(pagePath, pagesDir, rootRoute) {
13926
14367
  for (const segment of segments) {
13927
14368
  directory = `${directory}/${segment}`;
13928
14369
  for (const candidate of getSourceModuleCandidates(directory, "_route")) {
13929
- if (!existsSync13(candidate)) {
14370
+ if (!existsSync14(candidate)) {
13930
14371
  continue;
13931
14372
  }
13932
- const layoutModule = await import(candidate);
14373
+ const layoutModule = await (IS_DEV ? import(`${candidate}?furin-server&t=${routeModuleSourceVersion(candidate)}`) : import(candidate));
13933
14374
  const layout = layoutModule.route;
13934
14375
  if (isDefinedRouteTerminal(layout) && typeof layout.layout === "function") {
13935
14376
  parent = adaptDefinedLayout(layout, parent, candidate);
@@ -14026,7 +14467,7 @@ async function collectPageFilePaths(dir) {
14026
14467
  const files = [];
14027
14468
  const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
14028
14469
  const resolved = await mapWithConcurrency(entries, DIR_SCAN_CONCURRENCY, async (entry) => {
14029
- const absolutePath = toPosixPath2(join14(dir, entry.name));
14470
+ const absolutePath = toPosixPath2(join16(dir, entry.name));
14030
14471
  if (entry.isDirectory()) {
14031
14472
  return await collectPageFilePaths(absolutePath);
14032
14473
  }
@@ -14043,9 +14484,9 @@ async function collectPageFilePaths(dir) {
14043
14484
 
14044
14485
  // src/build/scan-server.ts
14045
14486
  init_instance();
14046
- import { readFileSync as readFileSync7 } from "fs";
14487
+ import { readFileSync as readFileSync8 } from "fs";
14047
14488
  function scanFurinInstances(serverEntryPath) {
14048
- const code = readFileSync7(serverEntryPath, "utf8");
14489
+ const code = readFileSync8(serverEntryPath, "utf8");
14049
14490
  const lang = detectLangFromPath(serverEntryPath);
14050
14491
  if (lang === "dts") {
14051
14492
  return [];
@@ -14126,39 +14567,42 @@ function registerIsomorphicRuntimePlugin() {
14126
14567
  function resolveAppSpecs(options, serverEntry, rootDir) {
14127
14568
  if (options.apps && options.apps.length > 0) {
14128
14569
  return options.apps.map((app) => ({
14129
- pagesDir: resolve7(rootDir, app.pagesDir),
14570
+ pagesDir: resolve9(rootDir, app.pagesDir),
14130
14571
  prefix: normalizePrefix(app.prefix)
14131
14572
  }));
14132
14573
  }
14133
14574
  if (options.pagesDir) {
14134
- return [{ pagesDir: resolve7(rootDir, options.pagesDir), prefix: "" }];
14575
+ return [{ pagesDir: resolve9(rootDir, options.pagesDir), prefix: "" }];
14135
14576
  }
14136
14577
  if (serverEntry) {
14137
14578
  const detected = scanFurinInstances(serverEntry);
14138
14579
  if (detected.length > 0) {
14139
14580
  return detected.map((app) => ({
14140
- pagesDir: resolve7(rootDir, app.pagesDir),
14581
+ pagesDir: resolve9(rootDir, app.pagesDir),
14141
14582
  prefix: app.prefix
14142
14583
  }));
14143
14584
  }
14144
14585
  }
14145
- return [{ pagesDir: resolve7(rootDir, "src/pages"), prefix: "" }];
14586
+ return [{ pagesDir: resolve9(rootDir, "src/pages"), prefix: "" }];
14146
14587
  }
14147
14588
  async function buildApp(options) {
14148
- const rootDir = resolve7(options.rootDir ?? process.cwd());
14149
- const buildRoot = join15(rootDir, BUILD_OUTPUT_DIR);
14589
+ return withProductionBuild(() => buildAppInternal(options));
14590
+ }
14591
+ async function buildAppInternal(options) {
14592
+ const rootDir = resolve9(options.rootDir ?? process.cwd());
14593
+ const buildRoot = join17(rootDir, BUILD_OUTPUT_DIR);
14150
14594
  const serverEntry = (() => {
14151
14595
  if (options.target === "static" || options.target === "package") {
14152
14596
  return null;
14153
14597
  }
14154
14598
  if (options.serverEntry) {
14155
- const resolved = resolve7(rootDir, options.serverEntry);
14156
- if (existsSync14(resolved)) {
14599
+ const resolved = resolve9(rootDir, options.serverEntry);
14600
+ if (existsSync15(resolved)) {
14157
14601
  return resolved;
14158
14602
  }
14159
14603
  }
14160
- const entry = resolve7(rootDir, "src/server.ts");
14161
- if (!existsSync14(entry)) {
14604
+ const entry = resolve9(rootDir, "src/server.ts");
14605
+ if (!existsSync15(entry)) {
14162
14606
  throw new Error("[furin] Entrypoint server.ts not found");
14163
14607
  }
14164
14608
  return entry;
@@ -14198,12 +14642,12 @@ async function buildApp(options) {
14198
14642
  version: 1,
14199
14643
  generatedAt: new Date().toISOString(),
14200
14644
  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,
14645
+ pagesDir: toPosixPath(relative11(rootDir, primaryApp.pagesDir)),
14646
+ rootPath: toPosixPath(relative11(rootDir, primaryApp.root.path)),
14647
+ serverEntry: serverEntry ? toPosixPath(relative11(rootDir, serverEntry)) : null,
14204
14648
  routes: primaryApp.routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
14205
14649
  apps: apps.map((app) => ({
14206
- pagesDir: toPosixPath(relative9(rootDir, app.pagesDir)),
14650
+ pagesDir: toPosixPath(relative11(rootDir, app.pagesDir)),
14207
14651
  prefix: app.prefix,
14208
14652
  routes: app.routes.map((route) => toBuildRouteManifestEntry(route, rootDir))
14209
14653
  })),
@@ -14235,14 +14679,11 @@ async function buildApp(options) {
14235
14679
  }
14236
14680
  manifest.targets.vercel = await buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options);
14237
14681
  break;
14238
- case "node":
14239
- case "cloudflare":
14240
- throw new Error(`[furin] \`--target ${target}\` is planned but not implemented yet in this branch.`);
14241
14682
  default:
14242
14683
  throw new Error(`[furin] Unsupported build target "${target}"`);
14243
14684
  }
14244
14685
  }
14245
- writeFileSync9(join15(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
14686
+ writeFileSync11(join17(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
14246
14687
  `);
14247
14688
  return {
14248
14689
  manifest,