@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
package/dist/cli/index.js CHANGED
@@ -334,7 +334,7 @@ var init_config = __esm(() => {
334
334
  requestSyncPath = new AsyncLocalStorage2;
335
335
  });
336
336
 
337
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/utils.mjs
337
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/utils.mjs
338
338
  function elapsedMs(startTime) {
339
339
  return Math.max(0, Date.now() - startTime);
340
340
  }
@@ -475,7 +475,7 @@ var init_utils = __esm(() => {
475
475
  _isoDate = /* @__PURE__ */ new Date;
476
476
  });
477
477
 
478
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/redact-C7FmdhwI.mjs
478
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/redact-C7FmdhwI.mjs
479
479
  function normalizeRedactPathPattern(pattern) {
480
480
  if (!pattern.includes("*") && !pattern.includes("."))
481
481
  return `**.${pattern}`;
@@ -784,7 +784,7 @@ var init_redact_C7FmdhwI = __esm(() => {
784
784
  globallyRedacted = Symbol.for("evlog.globallyRedacted");
785
785
  });
786
786
 
787
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
787
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
788
788
  function logPluginError(name, hook, err) {
789
789
  console.error(`[evlog/${name}] ${hook} failed:`, err);
790
790
  }
@@ -954,7 +954,7 @@ var init_globalRegistry_Bh3bIGwA = __esm(() => {
954
954
  globalConfig = getRegistry().config;
955
955
  });
956
956
 
957
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/pretty-error-DTIHxnBN.mjs
957
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
958
958
  function pushTreeSpacer(children) {
959
959
  children.push(PRETTY_ERROR_TREE_SPACER);
960
960
  }
@@ -1180,7 +1180,7 @@ function formatGuidanceLine(label, text, labelColor) {
1180
1180
  let remaining = text.trim();
1181
1181
  let first = true;
1182
1182
  while (remaining.length > 0) {
1183
- const budget = first ? Math.max(24, GUIDANCE_WRAP_WIDTH - prefix.length) : Math.max(24, GUIDANCE_WRAP_WIDTH - 5);
1183
+ const budget = first ? Math.max(24, GUIDANCE_WRAP_WIDTH - prefix.length) : Math.max(24, 71);
1184
1184
  if (remaining.length <= budget) {
1185
1185
  lines.push(first ? `${prefix}${remaining}` : `${GUIDANCE_CONTINUATION}${remaining}`);
1186
1186
  break;
@@ -1248,14 +1248,14 @@ function buildErrorEntries(error, options = {}) {
1248
1248
  }];
1249
1249
  }
1250
1250
  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 = " ";
1251
- var init_pretty_error_DTIHxnBN = __esm(() => {
1251
+ var init_pretty_error_D8rlWNL1 = __esm(() => {
1252
1252
  init_utils();
1253
1253
  SKIP_PATH_RE = /(?:^|[/\\])(?:node_modules|\.nuxt|\.next|\.output)(?:[/\\]|$)/;
1254
1254
  SKIP_FRAME_PATH_RE = /(?:^|[/\\])(?:packages[/\\]evlog|evlog[/\\](?:dist|src))(?:[/\\]|$)/;
1255
1255
  SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
1256
1256
  });
1257
1257
 
1258
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
1258
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
1259
1259
  function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
1260
1260
  const compact = partial.compact ?? (inDev && pretty);
1261
1261
  const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
@@ -1308,7 +1308,7 @@ var init_dev_terminal_Brarc6vc = __esm(() => {
1308
1308
  };
1309
1309
  });
1310
1310
 
1311
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
1311
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
1312
1312
  function hasWideEventPublisher() {
1313
1313
  return publisher !== null;
1314
1314
  }
@@ -1324,7 +1324,7 @@ function publishWideEvent(event) {
1324
1324
  var publisher = null;
1325
1325
  var init_wideEventChannel_BUDW48oP = () => {};
1326
1326
 
1327
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
1327
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
1328
1328
  function isEvlogError(error) {
1329
1329
  return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
1330
1330
  }
@@ -1333,7 +1333,7 @@ var init_error_brand_D0_DCPvr = __esm(() => {
1333
1333
  evlogErrorBrand = Symbol.for("evlog.error.brand");
1334
1334
  });
1335
1335
 
1336
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/error.mjs
1336
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/error.mjs
1337
1337
  var evlogErrorInternalKey, evlogErrorDataKey, EvlogError;
1338
1338
  var init_error = __esm(() => {
1339
1339
  init_utils();
@@ -1442,7 +1442,7 @@ var init_error = __esm(() => {
1442
1442
  });
1443
1443
  });
1444
1444
 
1445
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
1445
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
1446
1446
  function extractSafeHeaders(headers) {
1447
1447
  const raw = {};
1448
1448
  headers.forEach((value, key) => {
@@ -1463,7 +1463,7 @@ var init_headers_Bx1ieR_m = __esm(() => {
1463
1463
  init_utils();
1464
1464
  });
1465
1465
 
1466
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/audit-CW8wdQDm.mjs
1466
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/audit-C8euLMvu.mjs
1467
1467
  function writePrettyStdout(text) {
1468
1468
  (globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
1469
1469
  }
@@ -1597,13 +1597,14 @@ function emitWideEvent(level, event, options = {}) {
1597
1597
  formatted = redactEvent(formatted, state.redact);
1598
1598
  markGloballyRedacted(formatted);
1599
1599
  }
1600
- if (!state.silent)
1600
+ if (!state.silent) {
1601
1601
  if (state.pretty)
1602
1602
  prettyPrintWideEvent(formatted);
1603
1603
  else if (state.stringify)
1604
1604
  console[getConsoleMethod(level)](JSON.stringify(formatted));
1605
1605
  else
1606
1606
  console[getConsoleMethod(level)](formatted);
1607
+ }
1607
1608
  if (!deferDrain) {
1608
1609
  publishWideEvent(formatted);
1609
1610
  const drainPromises = [];
@@ -1654,11 +1655,12 @@ function formatValue(value) {
1654
1655
  if (isPlainObject$1(value)) {
1655
1656
  const pairs = [];
1656
1657
  for (const [k, v] of Object.entries(value))
1657
- if (v !== undefined && v !== null)
1658
+ if (v !== undefined && v !== null) {
1658
1659
  if (typeof v === "object")
1659
1660
  pairs.push(`${k}=${JSON.stringify(v)}`);
1660
1661
  else
1661
1662
  pairs.push(`${k}=${v}`);
1663
+ }
1662
1664
  return pairs.join(" ");
1663
1665
  }
1664
1666
  return String(value);
@@ -1713,6 +1715,20 @@ function asToolCallArray(value) {
1713
1715
  return;
1714
1716
  return value.every(isToolCallEntry) ? value : undefined;
1715
1717
  }
1718
+ function asCapturedLines(value) {
1719
+ if (typeof value !== "string" || value.length === 0)
1720
+ return;
1721
+ const lines = value.split(`
1722
+ `).map((line) => {
1723
+ return line.length > CAPTURED_LINE_MAX_LENGTH ? `${line.slice(0, CAPTURED_LINE_MAX_LENGTH)}\u2026` : line;
1724
+ });
1725
+ if (lines.length > CAPTURED_MAX_LINES) {
1726
+ lines.length = CAPTURED_MAX_LINES;
1727
+ lines.push(`+${value.split(`
1728
+ `).length - CAPTURED_MAX_LINES} more lines (full text in the event)`);
1729
+ }
1730
+ return lines;
1731
+ }
1716
1732
  function buildAIEntries(ai) {
1717
1733
  const entries = [];
1718
1734
  const headerParts = [];
@@ -1807,7 +1823,7 @@ function buildAIEntries(ai) {
1807
1823
  value: "",
1808
1824
  children
1809
1825
  });
1810
- } else if (toolCalls?.length)
1826
+ } else if (toolCalls?.length) {
1811
1827
  if (toolCallEntries?.length) {
1812
1828
  const children = toolCallEntries.map((tc) => {
1813
1829
  const inputStr = serializeToolInput(tc.input);
@@ -1827,6 +1843,7 @@ function buildAIEntries(ai) {
1827
1843
  value: names.join(", ")
1828
1844
  });
1829
1845
  }
1846
+ }
1830
1847
  const stepsUsage = Array.isArray(ai.stepsUsage) ? ai.stepsUsage.filter(isPlainObject$1) : undefined;
1831
1848
  if (stepsUsage?.length) {
1832
1849
  const firstModel = stepsUsage[0]?.model;
@@ -1848,6 +1865,20 @@ function buildAIEntries(ai) {
1848
1865
  key: "ai.steps",
1849
1866
  value: String(steps)
1850
1867
  });
1868
+ const promptLines = asCapturedLines(ai.prompt);
1869
+ if (promptLines)
1870
+ entries.push({
1871
+ key: "ai.prompt",
1872
+ value: "",
1873
+ children: promptLines
1874
+ });
1875
+ const outputLines = asCapturedLines(ai.output);
1876
+ if (outputLines)
1877
+ entries.push({
1878
+ key: "ai.output",
1879
+ value: "",
1880
+ children: outputLines
1881
+ });
1851
1882
  const embedding = isPlainObject$1(ai.embedding) ? ai.embedding : undefined;
1852
1883
  if (embedding) {
1853
1884
  const parts = [];
@@ -1998,10 +2029,63 @@ function prettyPrintWideEvent(event) {
1998
2029
  if (!browser && lines.length > 0)
1999
2030
  flushPrettyLines(lines);
2000
2031
  }
2032
+ function removeErrorCycles(value, ancestors) {
2033
+ if (value === null || typeof value !== "object")
2034
+ return value;
2035
+ if (ancestors.has(value))
2036
+ return "[Circular]";
2037
+ ancestors.add(value);
2038
+ let changed = false;
2039
+ const visit = (item) => {
2040
+ const result = removeErrorCycles(item, ancestors);
2041
+ if (!Object.is(result, item))
2042
+ changed = true;
2043
+ return result;
2044
+ };
2045
+ const copy = Array.isArray(value) ? value.map(visit) : Object.fromEntries(Object.entries(value).map(([key, item]) => [key, visit(item)]));
2046
+ ancestors.delete(value);
2047
+ return changed ? copy : value;
2048
+ }
2049
+ function serializeError(err) {
2050
+ const errorObj = {
2051
+ name: err.name,
2052
+ message: err.message,
2053
+ stack: isDev() ? compactStackForStorage(err.stack) : err.stack
2054
+ };
2055
+ const errRecord = err;
2056
+ const ancestors = new WeakSet([err]);
2057
+ for (const k of [
2058
+ "code",
2059
+ "status",
2060
+ "statusText",
2061
+ "statusCode",
2062
+ "statusMessage",
2063
+ "data",
2064
+ "cause",
2065
+ "internal"
2066
+ ])
2067
+ if (k in err)
2068
+ errorObj[k] = removeErrorCycles(errRecord[k], ancestors);
2069
+ if (EvlogError.isEvlogError(err)) {
2070
+ if (err.code)
2071
+ errorObj.code = err.code;
2072
+ if (err.why)
2073
+ errorObj.why = err.why;
2074
+ if (err.fix)
2075
+ errorObj.fix = err.fix;
2076
+ if (err.link)
2077
+ errorObj.link = err.link;
2078
+ if (err.status)
2079
+ errorObj.status = err.status;
2080
+ }
2081
+ return errorObj;
2082
+ }
2001
2083
  function createLogMethod(level) {
2002
2084
  return function logMethod(tagOrEvent, message) {
2003
2085
  if (typeof tagOrEvent === "string" && message !== undefined)
2004
2086
  emitTaggedLog(level, tagOrEvent, message);
2087
+ else if (tagOrEvent instanceof Error)
2088
+ emitWideEvent(level, { error: serializeError(tagOrEvent) });
2005
2089
  else if (typeof tagOrEvent === "object")
2006
2090
  emitWideEvent(level, tagOrEvent);
2007
2091
  else
@@ -2080,36 +2164,7 @@ function createLogger(initialContext = {}, internalOptions) {
2080
2164
  const err = typeof error === "string" ? new Error(error) : error;
2081
2165
  if (errorContext)
2082
2166
  mergeInto(context, errorContext);
2083
- const errorObj = {
2084
- name: err.name,
2085
- message: err.message,
2086
- stack: isDev() ? compactStackForStorage(err.stack) : err.stack
2087
- };
2088
- const errRecord = err;
2089
- for (const k of [
2090
- "code",
2091
- "status",
2092
- "statusText",
2093
- "statusCode",
2094
- "statusMessage",
2095
- "data",
2096
- "cause",
2097
- "internal"
2098
- ])
2099
- if (k in err)
2100
- errorObj[k] = errRecord[k];
2101
- if (EvlogError.isEvlogError(err)) {
2102
- if (err.code)
2103
- errorObj.code = err.code;
2104
- if (err.why)
2105
- errorObj.why = err.why;
2106
- if (err.fix)
2107
- errorObj.fix = err.fix;
2108
- if (err.link)
2109
- errorObj.link = err.link;
2110
- if (err.status)
2111
- errorObj.status = err.status;
2112
- }
2167
+ const errorObj = serializeError(err);
2113
2168
  if (isPlainObject$1(context.error))
2114
2169
  mergeInto(context.error, errorObj);
2115
2170
  else
@@ -2294,12 +2349,12 @@ function finalizeAudit(event) {
2294
2349
  event.audit = decorated;
2295
2350
  _testCollector?.(decorated, event);
2296
2351
  }
2297
- 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;
2298
- var init_audit_CW8wdQDm = __esm(() => {
2352
+ 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;
2353
+ var init_audit_C8euLMvu = __esm(() => {
2299
2354
  init_utils();
2300
2355
  init_redact_C7FmdhwI();
2301
2356
  init_globalRegistry_Bh3bIGwA();
2302
- init_pretty_error_DTIHxnBN();
2357
+ init_pretty_error_D8rlWNL1();
2303
2358
  init_dev_terminal_Brarc6vc();
2304
2359
  init_wideEventChannel_BUDW48oP();
2305
2360
  init_error();
@@ -2330,12 +2385,12 @@ var init_audit_CW8wdQDm = __esm(() => {
2330
2385
  initLogger(__EVLOG_CONFIG__);
2331
2386
  });
2332
2387
 
2333
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/index.mjs
2388
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/index.mjs
2334
2389
  var init_dist = __esm(() => {
2335
- init_audit_CW8wdQDm();
2390
+ init_audit_C8euLMvu();
2336
2391
  });
2337
2392
 
2338
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
2393
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
2339
2394
  function shouldDeferEmitForResponse(response) {
2340
2395
  if (!response.body)
2341
2396
  return false;
@@ -2415,7 +2470,7 @@ function bindStreamingResponseLifecycle(response, onComplete) {
2415
2470
  }
2416
2471
  var init_streamResponse_OlirMA5P = () => {};
2417
2472
 
2418
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/errors-CL8dDgIi.mjs
2473
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/errors-CL8dDgIi.mjs
2419
2474
  function extractErrorStatus(error) {
2420
2475
  if (error === null || typeof error !== "object")
2421
2476
  return 500;
@@ -2425,7 +2480,7 @@ function extractErrorStatus(error) {
2425
2480
  }
2426
2481
  var init_errors_CL8dDgIi = () => {};
2427
2482
 
2428
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
2483
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
2429
2484
  function shouldLog(path, include, exclude) {
2430
2485
  if (exclude && exclude.length > 0) {
2431
2486
  if (exclude.some((pattern) => matchesPattern(path, pattern)))
@@ -2453,7 +2508,7 @@ var init_deferred_drain_CfRYimo5 = __esm(() => {
2453
2508
  init_utils();
2454
2509
  });
2455
2510
 
2456
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/middleware-DHm89-gB.mjs
2511
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/middleware-fam3VyaL.mjs
2457
2512
  function resolveMiddlewarePluginRunner(options) {
2458
2513
  const global2 = getGlobalPluginRunner();
2459
2514
  const local = options.plugins;
@@ -2630,29 +2685,17 @@ function createMiddlewareLogger(options) {
2630
2685
  };
2631
2686
  }
2632
2687
  var noopResult, runnerCache;
2633
- var init_middleware_DHm89_gB = __esm(() => {
2688
+ var init_middleware_fam3VyaL = __esm(() => {
2634
2689
  init_utils();
2635
2690
  init_redact_C7FmdhwI();
2636
2691
  init_globalRegistry_Bh3bIGwA();
2637
2692
  init_wideEventChannel_BUDW48oP();
2638
- init_audit_CW8wdQDm();
2693
+ init_audit_C8euLMvu();
2639
2694
  init_errors_CL8dDgIi();
2640
2695
  init_deferred_drain_CfRYimo5();
2641
2696
  init_streamResponse_OlirMA5P();
2642
2697
  noopResult = {
2643
- logger: {
2644
- set() {},
2645
- error() {},
2646
- info() {},
2647
- warn() {},
2648
- setLevel() {},
2649
- emit() {
2650
- return null;
2651
- },
2652
- getContext() {
2653
- return {};
2654
- }
2655
- },
2698
+ logger: noopLogger,
2656
2699
  finish: () => Promise.resolve(null),
2657
2700
  finishResponse: (response) => Promise.resolve(response),
2658
2701
  skipped: true
@@ -2660,7 +2703,7 @@ var init_middleware_DHm89_gB = __esm(() => {
2660
2703
  runnerCache = /* @__PURE__ */ new WeakMap;
2661
2704
  });
2662
2705
 
2663
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/integration-Dprr4POU.mjs
2706
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/integration-CGD18W8r.mjs
2664
2707
  function attachForkToLogger(storage, parent, middlewareOptions, lifecycle) {
2665
2708
  const log = parent;
2666
2709
  log.fork = (label, fn) => {
@@ -2756,118 +2799,69 @@ function defineFrameworkIntegration(spec) {
2756
2799
  };
2757
2800
  } };
2758
2801
  }
2759
- var init_integration_Dprr4POU = __esm(() => {
2760
- init_audit_CW8wdQDm();
2802
+ var init_integration_CGD18W8r = __esm(() => {
2803
+ init_audit_C8euLMvu();
2761
2804
  init_headers_Bx1ieR_m();
2762
2805
  init_errors_CL8dDgIi();
2763
- init_middleware_DHm89_gB();
2806
+ init_middleware_fam3VyaL();
2764
2807
  });
2765
2808
 
2766
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/asyncStorageScope-CnJiW7V3.mjs
2767
- function supportsAsyncLocalStorageEnterWith(storage) {
2768
- if (typeof storage.enterWith !== "function")
2769
- return false;
2770
- try {
2771
- storage.enterWith(undefined);
2772
- return true;
2773
- } catch {
2774
- return false;
2809
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/toolkit/storage.mjs
2810
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
2811
+ function createLoggerStorage(contextHint, id = contextHint) {
2812
+ const storage = getSharedStorage(id, () => new AsyncLocalStorage3);
2813
+ function useLogger() {
2814
+ const logger = storage.getStore();
2815
+ if (!logger)
2816
+ throw new Error(`[evlog] useLogger() was called outside of an evlog ${contextHint}`);
2817
+ return logger;
2775
2818
  }
2819
+ return {
2820
+ storage,
2821
+ useLogger
2822
+ };
2776
2823
  }
2777
- function createSharedEnterWithStorage(id, create) {
2778
- return getSharedStorage(id, () => {
2779
- const storage = create();
2780
- patchAsyncLocalStorageEnterWith(storage);
2781
- return storage;
2782
- });
2783
- }
2784
- function patchAsyncLocalStorageEnterWith(storage) {
2785
- if (supportsAsyncLocalStorageEnterWith(storage))
2786
- return;
2787
- let fallbackStore;
2788
- let runDepth = 0;
2789
- const originalGetStore = storage.getStore.bind(storage);
2790
- const originalRun = storage.run.bind(storage);
2791
- Object.defineProperty(storage, "enterWith", {
2792
- configurable: true,
2793
- writable: true,
2794
- value(store) {
2795
- fallbackStore = store;
2796
- }
2797
- });
2798
- Object.defineProperty(storage, "run", {
2799
- configurable: true,
2800
- writable: true,
2801
- value(store, callback, ...args) {
2802
- runDepth++;
2803
- try {
2804
- return originalRun(store, callback, ...args);
2805
- } finally {
2806
- runDepth--;
2807
- }
2808
- }
2809
- });
2810
- Object.defineProperty(storage, "getStore", {
2811
- configurable: true,
2812
- writable: true,
2813
- value() {
2814
- if (runDepth > 0)
2815
- return originalGetStore();
2816
- const active = originalGetStore();
2817
- return active !== undefined ? active : fallbackStore;
2818
- }
2819
- });
2820
- }
2821
- var init_asyncStorageScope_CnJiW7V3 = __esm(() => {
2824
+ var init_storage = __esm(() => {
2822
2825
  init_globalRegistry_Bh3bIGwA();
2823
2826
  });
2824
2827
 
2825
- // ../../node_modules/.bun/evlog@2.28.1+70108eec0745116d/node_modules/evlog/dist/elysia/index.mjs
2826
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
2828
+ // ../../node_modules/.bun/evlog@2.29.0+6594568e47c8e14b/node_modules/evlog/dist/toolkit.mjs
2829
+ var init_toolkit = __esm(() => {
2830
+ init_integration_CGD18W8r();
2831
+ init_storage();
2832
+ });
2833
+
2834
+ // src/server/evlog.ts
2827
2835
  import { Elysia as Elysia2 } from "elysia";
2828
- function useLogger2() {
2829
- const logger = storage.getStore();
2830
- if (!logger || !activeLoggers.has(logger))
2831
- throw new Error("[evlog] useLogger() was called outside of an evlog plugin context. Make sure app.use(evlog()) is registered before your routes.");
2832
- return logger;
2833
- }
2834
- var storage, activeLoggers, integration;
2835
- var init_elysia = __esm(() => {
2836
- init_integration_Dprr4POU();
2837
- init_asyncStorageScope_CnJiW7V3();
2838
- storage = createSharedEnterWithStorage("evlog:elysia", () => new AsyncLocalStorage3);
2839
- activeLoggers = /* @__PURE__ */ new WeakSet;
2836
+ var loggerStorage, integration, getRequestLogger, runtimeWaitUntil;
2837
+ var init_evlog = __esm(() => {
2838
+ init_toolkit();
2839
+ loggerStorage = createLoggerStorage("Furin request context. Make sure the Furin plugin is registered before your routes.", "@teyik0/furin:evlog");
2840
2840
  integration = defineFrameworkIntegration({
2841
- name: "elysia",
2842
- extractRequest: ({ request, path, headers }) => ({
2843
- method: request.method,
2844
- path,
2845
- headers,
2846
- requestId: headers["x-request-id"]
2847
- }),
2848
- attachLogger: ({ request, path, headers }, logger) => {
2849
- attachForkToLogger(storage, logger, {
2841
+ attachLogger: () => {
2842
+ return;
2843
+ },
2844
+ extractRequest: ({ request }) => {
2845
+ const url = new URL(request.url);
2846
+ return {
2847
+ headers: request.headers,
2850
2848
  method: request.method,
2851
- path,
2852
- requestId: headers["x-request-id"]
2853
- }, {
2854
- onChildEnter: (child) => {
2855
- activeLoggers.add(child);
2856
- },
2857
- onChildExit: (child) => {
2858
- activeLoggers.delete(child);
2859
- }
2860
- });
2861
- activeLoggers.add(logger);
2862
- }
2849
+ path: url.pathname,
2850
+ requestId: request.headers.get("x-request-id") ?? undefined
2851
+ };
2852
+ },
2853
+ name: "furin",
2854
+ storage: loggerStorage.storage
2863
2855
  });
2856
+ getRequestLogger = loggerStorage.useLogger;
2857
+ runtimeWaitUntil = new Set;
2864
2858
  });
2865
2859
 
2866
2860
  // src/server/context-logger.ts
2867
2861
  import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
2868
- function useLogger3() {
2862
+ function getLogger() {
2869
2863
  try {
2870
- return useLogger2();
2864
+ return getRequestLogger();
2871
2865
  } catch {
2872
2866
  return syntheticRenderStorage.getStore() ?? noopLogger2;
2873
2867
  }
@@ -2887,7 +2881,7 @@ async function runInSyntheticRenderScope(fn, initialContext) {
2887
2881
  var noopLogger2, syntheticRenderStorage;
2888
2882
  var init_context_logger = __esm(() => {
2889
2883
  init_dist();
2890
- init_elysia();
2884
+ init_evlog();
2891
2885
  noopLogger2 = {
2892
2886
  emit: () => null,
2893
2887
  error: () => {},
@@ -2907,7 +2901,7 @@ var IS_DEV = true;
2907
2901
  // src/server/dev/graph.ts
2908
2902
  import { randomUUID } from "crypto";
2909
2903
  import { readFileSync as readFileSync2, statSync as statSync2 } from "fs";
2910
- import { dirname as dirname5, extname as extname2 } from "path";
2904
+ import { dirname as dirname7, extname as extname2 } from "path";
2911
2905
  function normalizeModulePath(path) {
2912
2906
  return path.replaceAll("\\", "/");
2913
2907
  }
@@ -2916,7 +2910,7 @@ function resolveDevSourceImports(source, path, loader) {
2916
2910
  const transpiler = new Bun.Transpiler({ loader });
2917
2911
  for (const imported of transpiler.scanImports(source)) {
2918
2912
  try {
2919
- const resolved = normalizeModulePath(Bun.resolveSync(imported.path, dirname5(path)));
2913
+ const resolved = normalizeModulePath(Bun.resolveSync(imported.path, dirname7(path)));
2920
2914
  if (!resolved.includes("/node_modules/")) {
2921
2915
  imports.push(resolved);
2922
2916
  }
@@ -3366,6 +3360,7 @@ function browserEventsClientSource() {
3366
3360
 
3367
3361
  // src/server/browser-events/plugin.ts
3368
3362
  import { Elysia as Elysia3 } from "elysia";
3363
+ import { websocket } from "elysia/websocket";
3369
3364
  function browserEventsClientScript(basePath) {
3370
3365
  return `<script data-furin-framework-module="" type="module" src="${basePath}${CLIENT_PATH2}"></script>`;
3371
3366
  }
@@ -3390,20 +3385,28 @@ function injectDevDiagnosticClient(html, basePath) {
3390
3385
  }
3391
3386
  return html.includes("</head>") ? html.replace("</head>", `${script}</head>`) : `${script}${html}`;
3392
3387
  }
3388
+ var extensionErrorFilterScript = `window.addEventListener("unhandledrejection", (event) => {
3389
+ const stack = event.reason?.stack;
3390
+ if (typeof stack !== "string") return;
3391
+ const firstFrame = stack.match(/^(?:\\s*at [^\\n]*|[^\\n]*@[^\\n]*)/m)?.[0];
3392
+ if (firstFrame && /\\b(?:chrome|moz)-extension:\\/\\//.test(firstFrame)) {
3393
+ event.stopImmediatePropagation();
3394
+ }
3395
+ }, true);`;
3393
3396
  var init_plugin2 = () => {};
3394
3397
 
3395
3398
  // src/cli/index.ts
3396
- import { existsSync as existsSync15 } from "fs";
3397
- import { resolve as resolve10 } from "path";
3399
+ import { existsSync as existsSync16 } from "fs";
3400
+ import { resolve as resolve12 } from "path";
3398
3401
  import { parseArgs } from "util";
3399
3402
 
3400
3403
  // src/build/index.ts
3401
- import { existsSync as existsSync12, writeFileSync as writeFileSync7 } from "fs";
3402
- import { join as join13, relative as relative8, resolve as resolve7 } from "path";
3404
+ import { existsSync as existsSync13, writeFileSync as writeFileSync9 } from "fs";
3405
+ import { join as join15, relative as relative10, resolve as resolve9 } from "path";
3403
3406
 
3404
3407
  // src/adapter/bun.ts
3405
- import { existsSync as existsSync7, rmSync as rmSync2 } from "fs";
3406
- import { join as join8, resolve as resolve4 } from "path";
3408
+ import { existsSync as existsSync8, readFileSync as readFileSync4, rmSync as rmSync2, writeFileSync as writeFileSync5 } from "fs";
3409
+ import { join as join10, resolve as resolve6 } from "path";
3407
3410
 
3408
3411
  // src/build/bun-build.ts
3409
3412
  function runBunBuild(config) {
@@ -3470,6 +3473,7 @@ function buildAppContextBlock(app, varPrefix) {
3470
3473
  const routeEntries = app.routes.map((r) => ` { pattern: ${JSON.stringify(r.pattern)}, path: ${JSON.stringify(r.path.replace(/\\/g, "/"))}, mode: ${JSON.stringify(r.mode)} },`);
3471
3474
  const rootConventionsLine = app.rootConventions ? ` rootConventions: ${JSON.stringify(app.rootConventions)},` : "";
3472
3475
  const routeMetadataLine = app.routeMetadata ? ` routeMetadata: ${JSON.stringify(app.routeMetadata)},` : "";
3476
+ const deploymentTargetLine = app.deploymentTarget === undefined ? "" : ` deploymentTarget: ${JSON.stringify(app.deploymentTarget)},`;
3473
3477
  const serveAssetsLine = app.serveAssets === undefined ? "" : ` serveAssets: ${JSON.stringify(app.serveAssets)},`;
3474
3478
  const ssgCacheLine = app.ssgCache ? ` ssgCache: ${JSON.stringify(app.ssgCache)},` : "";
3475
3479
  const templateHtmlLine = app.templateHtml === undefined ? "" : ` templateHtml: ${JSON.stringify(app.templateHtml)},`;
@@ -3477,6 +3481,7 @@ function buildAppContextBlock(app, varPrefix) {
3477
3481
  "__setCompileContext({",
3478
3482
  ` buildId: ${JSON.stringify(app.buildId ?? "")},`,
3479
3483
  ` clientLogging: ${JSON.stringify(app.clientLogging ?? false)},`,
3484
+ deploymentTargetLine,
3480
3485
  ` prefix: ${JSON.stringify(app.prefix ?? "")},`,
3481
3486
  ` rootPath: ${JSON.stringify(app.rootPath.replace(/\\/g, "/"))},`,
3482
3487
  app.nativeRoutes ? ` nativeRoutes: ${nativeRoutesVar},` : "",
@@ -3500,6 +3505,7 @@ function buildEntrySource(options) {
3500
3505
  const { apps, headerComment, serverEntry } = options;
3501
3506
  const mode = options.mode ?? "boot";
3502
3507
  const internalSpecifier = mode === "register" ? "@teyik0/furin/internal" : INTERNAL_MODULE_PATH;
3508
+ const productionMode = mode !== "register";
3503
3509
  const importLines = [];
3504
3510
  const contextBlocks = [];
3505
3511
  for (let appIndex = 0;appIndex < apps.length; appIndex++) {
@@ -3512,17 +3518,17 @@ function buildEntrySource(options) {
3512
3518
  const lines = [
3513
3519
  headerComment,
3514
3520
  `import { __setCompileContext } from ${JSON.stringify(internalSpecifier)};`,
3515
- ...mode === "boot" ? [`import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`] : [],
3521
+ ...productionMode ? [`import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`] : [],
3516
3522
  ...importLines,
3517
- ...mode === "boot" ? [
3523
+ ...productionMode ? [
3518
3524
  "",
3519
3525
  "// Force production mode \u2014 Bun may inline process.env.NODE_ENV at bundle time.",
3520
3526
  "__setDevMode(false);",
3521
- 'process.env.NODE_ENV = "production";'
3527
+ ...mode === "boot" ? ['process.env.NODE_ENV = "production";'] : []
3522
3528
  ] : [],
3523
3529
  ...contextBlocks,
3524
3530
  "",
3525
- ...serverEntry ? [
3531
+ ...serverEntry && mode === "boot" ? [
3526
3532
  `const __serverModule = await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
3527
3533
  'if (typeof __serverModule.startServer === "function") {',
3528
3534
  " await __serverModule.startServer();",
@@ -3540,6 +3546,15 @@ function buildEntrySource(options) {
3540
3546
  " }",
3541
3547
  "}",
3542
3548
  ""
3549
+ ] : serverEntry && mode === "app" ? [
3550
+ `const __serverModule = await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
3551
+ "export const app = __serverModule.default;",
3552
+ "export const port = __serverModule.port;",
3553
+ "export const idleTimeout = __serverModule.idleTimeout;",
3554
+ "export const startServer = __serverModule.startServer;",
3555
+ "export const onShutdown = __serverModule.onShutdown;",
3556
+ "export default __serverModule.default;",
3557
+ ""
3543
3558
  ] : []
3544
3559
  ];
3545
3560
  return lines.join(`
@@ -3572,7 +3587,7 @@ function toBuildRouteManifestEntry(route, rootDir) {
3572
3587
  mode: route.mode,
3573
3588
  pagePath: toPosixPath(relative(rootDir, route.path)),
3574
3589
  hasLayout: route.routeChain.some((entry) => !!entry.layout),
3575
- hasStaticParams: !!route.page?.staticParams,
3590
+ hasStaticParams: route.page.staticParams !== undefined || route.routeChain.some((entry) => entry.staticParams !== undefined),
3576
3591
  revalidate: resolveRouteRevalidate(route.page) ?? null
3577
3592
  };
3578
3593
  }
@@ -3592,12 +3607,13 @@ function buildTargetManifest(rootDir, buildRoot, target, serverEntry) {
3592
3607
  // src/build/virtual-entry.ts
3593
3608
  var REGEX_SPECIAL_CHARACTERS_RE = /[.*+?^${}()|[\]\\]/g;
3594
3609
  function createVirtualBuildEntry(entrypoint, source, loader) {
3595
- const entrypointFilter = new RegExp(`^${entrypoint.replace(REGEX_SPECIAL_CHARACTERS_RE, "\\$&")}$`);
3610
+ const normalizedEntrypoint = entrypoint.replaceAll("\\", "/");
3611
+ const entrypointFilter = new RegExp(`^${normalizedEntrypoint.replace(REGEX_SPECIAL_CHARACTERS_RE, "\\$&")}$`);
3596
3612
  return {
3597
- entrypoint,
3598
- files: { [entrypoint]: source },
3613
+ entrypoint: normalizedEntrypoint,
3614
+ files: { [normalizedEntrypoint]: source },
3599
3615
  plugin: {
3600
- name: `furin-virtual-entry:${entrypoint}`,
3616
+ name: `furin-virtual-entry:${normalizedEntrypoint}`,
3601
3617
  setup(build) {
3602
3618
  build.onLoad({ filter: entrypointFilter }, () => ({ contents: source, loader }));
3603
3619
  }
@@ -3620,10 +3636,8 @@ function buildEmbeddedContext(clientDir, publicDir) {
3620
3636
  " },"
3621
3637
  ];
3622
3638
  }
3623
- function generateCompileEntry(options) {
3624
- const { apps, outDir, serverEntry, publicDir } = options;
3625
- ensureDir(outDir);
3626
- const preparedApps = apps.map((app) => {
3639
+ function prepareCompileEntryApps(options) {
3640
+ return options.apps.map((app) => {
3627
3641
  const { embed, ...context } = app;
3628
3642
  if (!embed) {
3629
3643
  return context;
@@ -3632,31 +3646,125 @@ function generateCompileEntry(options) {
3632
3646
  ...context,
3633
3647
  extraContext: [
3634
3648
  ...context.extraContext ?? [],
3635
- ...buildEmbeddedContext(embed.clientDir, publicDir)
3649
+ ...buildEmbeddedContext(embed.clientDir, options.publicDir)
3636
3650
  ]
3637
3651
  };
3638
3652
  });
3639
- const source = buildEntrySource({
3640
- apps: preparedApps,
3641
- headerComment: options.headerComment ?? "// Auto-generated by furin compile \u2014 do not edit",
3642
- serverEntry
3643
- });
3644
- const entryPath = join3(outDir, "_compile-entry.ts");
3645
- return createVirtualBuildEntry(entryPath, source, "ts");
3653
+ }
3654
+
3655
+ // src/build/elysia-aot.ts
3656
+ import { dirname as dirname2, resolve } from "path";
3657
+ import { aotFactory } from "elysia/plugin/aot/unplugin";
3658
+ var AOT_NAMESPACE = "furin-elysia-aot";
3659
+ var ELYSIA_RESOLVE_DIR = dirname2(Bun.resolveSync("elysia", import.meta.dir));
3660
+ var SOURCE_FILTER = /\.[cm]?[jt]sx?$/;
3661
+ var WEBSOCKET_STUB_MARKER = "[elysia-aot] WebSocket route builder was stripped (strip mode) but a WS route was used.";
3662
+ function loaderFor(path) {
3663
+ const extension = path.slice(path.lastIndexOf("."));
3664
+ if (extension === ".jsx") {
3665
+ return "jsx";
3666
+ }
3667
+ if (extension === ".tsx") {
3668
+ return "tsx";
3669
+ }
3670
+ if (extension === ".ts" || extension === ".mts" || extension === ".cts") {
3671
+ return "ts";
3672
+ }
3673
+ return "js";
3674
+ }
3675
+ function patchElysiaWebSocketStub(source) {
3676
+ if (!source.includes(WEBSOCKET_STUB_MARKER) || source.includes("accumulateWSOptions")) {
3677
+ return source;
3678
+ }
3679
+ return `${source}
3680
+ export function accumulateWSOptions(){return e()}
3681
+ export function resolveWSOptions(){return e()}
3682
+ export function drainWaiters(){return e()}
3683
+ export function handleWSResponse(){return e()}
3684
+ `;
3685
+ }
3686
+ function elysiaAot(entry) {
3687
+ const entryPath = resolve(entry);
3688
+ const hooks = aotFactory({ entry, strip: false, target: "bun" });
3689
+ return {
3690
+ name: "elysia-aot",
3691
+ async setup(build) {
3692
+ try {
3693
+ await hooks.buildStart?.();
3694
+ } catch (error) {
3695
+ if (error instanceof Error && error.message.startsWith("[elysia-aot]") && error.message.includes("mounts a sub-app")) {
3696
+ console.warn("[furin] Elysia AOT skipped because the app uses .mount().");
3697
+ return;
3698
+ }
3699
+ throw error;
3700
+ }
3701
+ const entrySource = await Bun.file(entryPath).text();
3702
+ const transformedEntry = await hooks.transform?.(entrySource, entryPath);
3703
+ if (transformedEntry !== undefined) {
3704
+ await Bun.write(entryPath, transformedEntry);
3705
+ }
3706
+ build.onResolve({ filter: /^elysia(?:\/(?!compiled$|type$).*)?$/ }, ({ path }) => ({
3707
+ path: Bun.resolveSync(path, ELYSIA_RESOLVE_DIR)
3708
+ }));
3709
+ build.onResolve({ filter: /^elysia\/(?:compiled|type)$/ }, ({ path }) => {
3710
+ const resolved = hooks.resolveId?.(path);
3711
+ return resolved === undefined ? undefined : { namespace: AOT_NAMESPACE, path: resolved };
3712
+ });
3713
+ build.onLoad({ filter: /.*/, namespace: AOT_NAMESPACE }, ({ path }) => {
3714
+ const contents = hooks.load?.(path);
3715
+ return contents === undefined ? undefined : { contents, loader: "js", resolveDir: ELYSIA_RESOLVE_DIR };
3716
+ });
3717
+ build.onLoad({ filter: SOURCE_FILTER }, async ({ path }) => {
3718
+ if (resolve(path) === entryPath) {
3719
+ return;
3720
+ }
3721
+ if (hooks.transformInclude?.(path) === false) {
3722
+ return;
3723
+ }
3724
+ const original = await Bun.file(path).text();
3725
+ const transformed = await hooks.transform?.(original, path);
3726
+ if (transformed === undefined) {
3727
+ return;
3728
+ }
3729
+ return {
3730
+ contents: patchElysiaWebSocketStub(transformed),
3731
+ loader: loaderFor(path)
3732
+ };
3733
+ });
3734
+ build.onEnd(() => {
3735
+ hooks.buildEnd?.();
3736
+ });
3737
+ }
3738
+ };
3739
+ }
3740
+
3741
+ // src/build/private-server-sourcemaps.ts
3742
+ import { existsSync as existsSync4, renameSync } from "fs";
3743
+ import { dirname as dirname3, isAbsolute, join as join4, relative as relative2 } from "path";
3744
+ function movePrivateServerSourceMaps(outputDir, privateDir, filenames) {
3745
+ for (const filename of filenames) {
3746
+ const source = isAbsolute(filename) ? filename : join4(outputDir, filename);
3747
+ if (!existsSync4(source)) {
3748
+ continue;
3749
+ }
3750
+ const destination = join4(privateDir, relative2(outputDir, source));
3751
+ ensureDir(dirname3(destination));
3752
+ renameSync(source, destination);
3753
+ }
3646
3754
  }
3647
3755
 
3648
3756
  // src/build/production-instrumentation.ts
3649
- import { dirname as dirname2, relative as relative2, resolve } from "path";
3757
+ import { dirname as dirname4, relative as relative3, resolve as resolve2 } from "path";
3650
3758
  var INSTRUMENTATION_IMPORT = /(?:^|[/\\])devtools[/\\]instrumentation(?:\.ts|\.js)?$/;
3651
3759
  var DEV_PAGE_PLUGIN_IMPORT = /(?:^|[/\\])server[/\\]dev-page-plugin(?:\.ts|\.js)?$/;
3652
- var DEV_RUNTIME_IMPORT = /(?:^|[/\\])server[/\\]dev[/\\](?:browser-events|diagnostics|plugin)(?:\.ts|\.js)?$/;
3760
+ var DEV_RUNTIME_IMPORT = /(?:^|[/\\])server[/\\]dev[/\\](?:browser-events|diagnostics|graph|plugin)(?:\.ts|\.js)?$/;
3653
3761
  var DEV_BUILD_IMPORT = /(?:^|[/\\])(?:build[/\\]hydrate|plugin[/\\]route-config-autofix)(?:\.ts|\.js)?$/;
3654
3762
  var HMR_IMPORT = /(?:^|[/\\])server[/\\]router[/\\]hmr(?:\.ts|\.js)?$/;
3655
- var PRODUCTION_BOUNDARY_IMPORT = /(?:browser-events|instrumentation|dev-page-plugin|diagnostics|plugin|hmr|hydrate|route-config-autofix)(?:\.ts|\.js)?$/;
3763
+ var PRODUCTION_BOUNDARY_IMPORT = /(?:browser-events|instrumentation|dev-page-plugin|diagnostics|graph|plugin|hmr|hydrate|route-config-autofix)(?:\.ts|\.js)?$/;
3656
3764
  var PRODUCTION_STUB_NAMESPACE = "furin-production-runtime-stub";
3657
- var FURIN_RUNTIME_ROOT = resolve(import.meta.dir, "..");
3765
+ var FURIN_RUNTIME_ROOT = resolve2(import.meta.dir, "..");
3658
3766
  function isFurinRuntimePath(path) {
3659
- const fromRuntimeRoot = relative2(FURIN_RUNTIME_ROOT, path);
3767
+ const fromRuntimeRoot = relative3(FURIN_RUNTIME_ROOT, path);
3660
3768
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
3661
3769
  }
3662
3770
  function devBuildExport(path) {
@@ -3667,23 +3775,23 @@ function productionInstrumentationPlugin() {
3667
3775
  name: "furin-production-instrumentation",
3668
3776
  setup(build) {
3669
3777
  build.onResolve({ filter: PRODUCTION_BOUNDARY_IMPORT }, (args) => {
3670
- const importPath = resolve(dirname2(args.importer), args.path);
3778
+ const importPath = resolve2(dirname4(args.importer), args.path);
3671
3779
  if (!isFurinRuntimePath(importPath)) {
3672
3780
  return;
3673
3781
  }
3674
3782
  if (INSTRUMENTATION_IMPORT.test(importPath)) {
3675
3783
  return {
3676
- path: resolve(import.meta.dir, "../server/devtools/instrumentation.production.ts")
3784
+ path: resolve2(import.meta.dir, "../server/devtools/instrumentation.production.ts")
3677
3785
  };
3678
3786
  }
3679
3787
  if (DEV_PAGE_PLUGIN_IMPORT.test(importPath)) {
3680
- return { path: resolve(import.meta.dir, "../server/dev-page-plugin.production.ts") };
3788
+ return { path: resolve2(import.meta.dir, "../server/dev-page-plugin.production.ts") };
3681
3789
  }
3682
3790
  if (DEV_RUNTIME_IMPORT.test(importPath)) {
3683
- return { path: resolve(import.meta.dir, "../server/dev/runtime.production.ts") };
3791
+ return { path: resolve2(import.meta.dir, "../server/dev/runtime.production.ts") };
3684
3792
  }
3685
3793
  if (HMR_IMPORT.test(importPath)) {
3686
- return { path: resolve(import.meta.dir, "../server/router/hmr.production.ts") };
3794
+ return { path: resolve2(import.meta.dir, "../server/router/hmr.production.ts") };
3687
3795
  }
3688
3796
  if (DEV_BUILD_IMPORT.test(importPath)) {
3689
3797
  return { namespace: PRODUCTION_STUB_NAMESPACE, path: importPath };
@@ -3699,34 +3807,32 @@ function productionInstrumentationPlugin() {
3699
3807
  };
3700
3808
  }
3701
3809
 
3810
+ // src/build/server-app-entry.ts
3811
+ import { writeFileSync } from "fs";
3812
+ import { join as join6 } from "path";
3813
+
3702
3814
  // src/plugin/routes.ts
3703
3815
  import {
3704
- existsSync as existsSync4,
3816
+ existsSync as existsSync5,
3705
3817
  readdirSync as readdirSync2,
3706
3818
  readFileSync,
3707
3819
  realpathSync,
3708
3820
  statSync,
3709
3821
  watch
3710
3822
  } from "fs";
3711
- import { dirname as dirname3, extname, isAbsolute, join as join4, relative as relative3, resolve as resolve2, sep } from "path";
3823
+ import { dirname as dirname5, extname, isAbsolute as isAbsolute2, join as join5, relative as relative4, resolve as resolve3, sep } from "path";
3712
3824
  import { pathToFileURL } from "url";
3713
3825
  import { Elysia } from "elysia";
3714
3826
 
3715
3827
  // src/shared/elysia-contract.ts
3716
- import { getSchemaValidator as elysiaGetSchemaValidator } from "elysia";
3717
- import {
3718
- parseQueryFromURL as elysiaParseQueryFromURL,
3719
- parseQueryStandardSchema as elysiaParseQueryStandardSchema
3720
- } from "elysia/parse-query";
3721
- import { TypeCompiler as ElysiaTypeCompiler } from "elysia/type-system";
3722
- var TypeCompiler = ElysiaTypeCompiler;
3828
+ import { Validator } from "elysia";
3723
3829
  var TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
3724
3830
  function isTypeBoxObjectSchema(schema) {
3725
3831
  if (schema === null || typeof schema !== "object") {
3726
3832
  return false;
3727
3833
  }
3728
3834
  const candidate = schema;
3729
- return candidate[TYPEBOX_KIND] === "Object" || candidate["~kind"] === "Object";
3835
+ return (candidate[TYPEBOX_KIND] === "Object" || candidate["~kind"] === "Object") && candidate.properties !== null && typeof candidate.properties === "object";
3730
3836
  }
3731
3837
 
3732
3838
  // src/shared/search-params.ts
@@ -3869,8 +3975,8 @@ function findSearchDefaultsForRouteTarget(to, routes) {
3869
3975
  init_patterns();
3870
3976
 
3871
3977
  // src/server/router/schema-merge.ts
3872
- import { t } from "elysia";
3873
3978
  var TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
3979
+ var TYPEBOX_OPTIONAL = Symbol.for("TypeBox.Optional");
3874
3980
  function mergeRouteSchemas(routeChain, key) {
3875
3981
  const schemas = routeChain.flatMap((route) => route[key] ? [route[key]] : []);
3876
3982
  if (schemas.length === 0) {
@@ -3880,11 +3986,17 @@ function mergeRouteSchemas(routeChain, key) {
3880
3986
  return schemas[0];
3881
3987
  }
3882
3988
  if (schemas.some((schema) => !isTypeBoxObjectSchema(schema))) {
3883
- 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.`);
3989
+ 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.`);
3884
3990
  }
3885
3991
  const properties = Object.assign({}, ...schemas.map((schema) => schema.properties));
3886
3992
  const options = Object.assign({}, ...schemas.map((schema) => Object.fromEntries(Object.entries(schema).filter(([name]) => !TOBJECT_STRUCTURAL_KEYS.has(name)))));
3887
- return t.Object(properties, options);
3993
+ const required = Object.keys(properties).filter((name) => {
3994
+ const property = properties[name];
3995
+ return !(property["~optional"] || property[TYPEBOX_OPTIONAL]);
3996
+ });
3997
+ return Object.defineProperty({ ...options, properties, required, type: "object" }, "~kind", {
3998
+ value: "Object"
3999
+ });
3888
4000
  }
3889
4001
 
3890
4002
  // src/server/router/schemas.ts
@@ -3944,10 +4056,11 @@ function unwrapTSExpression(node) {
3944
4056
  init_patterns();
3945
4057
  var ROUTES_NAMESPACE_PREFIX = "furin-routes";
3946
4058
  var ROUTES_REGISTRY_SPECIFIER = "furin/routes?registry";
3947
- var ROUTES_REGISTRY_FILTER = /^furin\/routes\?registry$/;
4059
+ var COMPOSABLE_ROUTES_REGISTRY_SPECIFIER = "furin/routes?registry=composable";
4060
+ var ROUTES_REGISTRY_FILTER = /^furin\/routes\?registry(?:=composable)?$/;
3948
4061
  var ROUTE_FILE_FILTER = /^furin-route-file:.+$/;
3949
4062
  var ROUTE_FILES_NAMESPACE = "furin-route-files";
3950
- var ROUTES_REGISTRY_FILE_FILTER = /[\\/]\.furin-routes-registry\.ts\?furin-virtual$/;
4063
+ var ROUTES_REGISTRY_FILE_FILTER = /[\\/]\.furin-routes-registry(?:-composable)?\.ts\?furin-virtual$/;
3951
4064
  var CLIENT_ROUTES_NAMESPACE = "furin-routes-client";
3952
4065
  var CLIENT_ROUTES_FILTER = /^(?:@teyik0\/furin|furin)\/routes$/;
3953
4066
  var SERVER_ROUTES_FILTER = /^(?:@teyik0\/furin|furin)\/routes\?instance=.+$/;
@@ -3958,11 +4071,14 @@ var DEV_ROUTES_APPS_SYMBOL = Symbol.for("@teyik0/furin/dev-routes-apps");
3958
4071
  var DEV_ROUTE_WATCHERS_SYMBOL = Symbol.for("@teyik0/furin/dev-route-watchers");
3959
4072
  var devInstancesBySpecifier = new Map;
3960
4073
  function instanceKey(instance) {
3961
- return `${resolve2(instance.pagesDir)}\x00${instance.prefix}`;
4074
+ return `${resolve3(instance.pagesDir)}\x00${instance.prefix}`;
3962
4075
  }
3963
4076
  function routeModuleSpecifier(instance) {
3964
4077
  return `@teyik0/furin/routes?instance=${Bun.hash(instanceKey(instance)).toString(16)}`;
3965
4078
  }
4079
+ function composableRouteModuleSpecifier(instance) {
4080
+ return `${routeModuleSpecifier(instance)}&composable`;
4081
+ }
3966
4082
  function instanceNamespace(instance) {
3967
4083
  return `${ROUTES_NAMESPACE_PREFIX}-${Bun.hash(instanceKey(instance)).toString(16)}`;
3968
4084
  }
@@ -3972,7 +4088,7 @@ function scanRouteFiles(directory, directorySegments, files) {
3972
4088
  if (entry.name.startsWith("_")) {
3973
4089
  continue;
3974
4090
  }
3975
- scanRouteFiles(join4(directory, entry.name), [...directorySegments, entry.name], files);
4091
+ scanRouteFiles(join5(directory, entry.name), [...directorySegments, entry.name], files);
3976
4092
  continue;
3977
4093
  }
3978
4094
  const extension = extname(entry.name);
@@ -3980,7 +4096,7 @@ function scanRouteFiles(directory, directorySegments, files) {
3980
4096
  continue;
3981
4097
  }
3982
4098
  const base = entry.name.slice(0, -extension.length);
3983
- const sourcePath = join4(directory, entry.name);
4099
+ const sourcePath = join5(directory, entry.name);
3984
4100
  for (const segment of [...directorySegments, base]) {
3985
4101
  parseDynamicRouteSegment(segment, sourcePath);
3986
4102
  }
@@ -4069,9 +4185,9 @@ function collectRouteFiles(root) {
4069
4185
  }
4070
4186
  function routeSourcePaths(instance) {
4071
4187
  const instanceId = Bun.hash(instanceKey(instance)).toString(16);
4072
- return collectRouteFiles(buildRouteTree(instance.pagesDir, instanceId)).map(({ sourcePath }) => resolve2(sourcePath)).toSorted((left, right) => left.localeCompare(right));
4188
+ return collectRouteFiles(buildRouteTree(instance.pagesDir, instanceId)).map(({ sourcePath }) => resolve3(sourcePath)).toSorted((left, right) => left.localeCompare(right));
4073
4189
  }
4074
- function emitRouteNode(node, indentation) {
4190
+ function emitRouteNode(node, indentation, includeRootCatchAll) {
4075
4191
  const childIndentation = `${indentation} `;
4076
4192
  const prefix = node.name ? `/${segmentPath(node.name)}` : "";
4077
4193
  const head = `new Elysia({ prefix: ${JSON.stringify(prefix)} })`;
@@ -4079,13 +4195,13 @@ function emitRouteNode(node, indentation) {
4079
4195
  if (node.indexRoute) {
4080
4196
  content.push(`${childIndentation}.use(new Elysia({ prefix: "" }).use(${node.indexRoute.id}.elysia))`);
4081
4197
  }
4082
- for (const route of node.fileRoutes) {
4198
+ for (const route of node.fileRoutes.filter((file) => includeRootCatchAll || file.path !== "/*")) {
4083
4199
  const segment = route.path.slice(route.path.lastIndexOf("/") + 1);
4084
4200
  content.push(`${childIndentation}.use(new Elysia({ prefix: ${JSON.stringify(`/${segment}`)} }).use(${route.id}.elysia))`);
4085
4201
  }
4086
4202
  for (const child of node.children) {
4087
4203
  content.push(`${childIndentation}.use(`);
4088
- content.push(emitRouteNode(child, `${childIndentation} `));
4204
+ content.push(emitRouteNode(child, `${childIndentation} `, includeRootCatchAll));
4089
4205
  content.push(`${childIndentation})`);
4090
4206
  }
4091
4207
  if (node.layout) {
@@ -4118,28 +4234,28 @@ async function retainComposableRoutes(node) {
4118
4234
  node.fileRoutes = composableRoutes;
4119
4235
  await Promise.all(node.children.map((child) => retainComposableRoutes(child)));
4120
4236
  }
4121
- async function generateServerInstance(instance, routeFilesBySpecifier) {
4237
+ async function generateServerInstance(instance, routeFilesBySpecifier, materialized, includeRootCatchAll) {
4122
4238
  const instanceId = Bun.hash(instanceKey(instance)).toString(16);
4123
4239
  const tree = buildRouteTree(instance.pagesDir, instanceId);
4124
4240
  await retainComposableRoutes(tree);
4125
4241
  const imports = collectRouteFiles(tree).sort((left, right) => left.sourcePath.localeCompare(right.sourcePath)).map((route) => {
4126
- const specifier = routeFileSpecifier(route);
4242
+ const specifier = materialized ? resolve3(route.sourcePath).replaceAll("\\", "/") : routeFileSpecifier(route);
4127
4243
  routeFilesBySpecifier.set(specifier, {
4128
4244
  routePath: route.path,
4129
- sourcePath: resolve2(route.sourcePath)
4245
+ sourcePath: resolve3(route.sourcePath)
4130
4246
  });
4131
4247
  return `import { route as ${route.id} } from ${JSON.stringify(specifier)};`;
4132
4248
  }).join(`
4133
4249
  `);
4134
4250
  return {
4135
- appExpression: emitRouteNode(tree, ""),
4251
+ appExpression: emitRouteNode(tree, "", includeRootCatchAll),
4136
4252
  exportName: `furinApp_${instanceId}`,
4137
4253
  imports
4138
4254
  };
4139
4255
  }
4140
- async function serverRegistrySource(instances, routeFilesBySpecifier) {
4256
+ async function serverRegistrySource(instances, routeFilesBySpecifier, materialized, includeRootCatchAll) {
4141
4257
  routeFilesBySpecifier.clear();
4142
- const generated = await Promise.all(instances.map((instance) => generateServerInstance(instance, routeFilesBySpecifier)));
4258
+ const generated = await Promise.all(instances.map((instance) => generateServerInstance(instance, routeFilesBySpecifier, materialized, includeRootCatchAll)));
4143
4259
  return `import { Elysia } from "elysia";
4144
4260
  ${generated.map(({ imports }) => imports).join(`
4145
4261
  `)}
@@ -4148,6 +4264,15 @@ ${generated.map(({ appExpression, exportName }) => `export const ${exportName} =
4148
4264
  `)}
4149
4265
  `;
4150
4266
  }
4267
+ async function materializedRouteModuleSource(instance) {
4268
+ const routeFilesBySpecifier = new Map;
4269
+ const source = await serverRegistrySource([instance], routeFilesBySpecifier, true, false);
4270
+ await validateRouteModules(routeFilesBySpecifier.values());
4271
+ const exportName = `furinApp_${Bun.hash(instanceKey(instance)).toString(16)}`;
4272
+ return `${source}
4273
+ export { ${exportName} as furinApp };
4274
+ `;
4275
+ }
4151
4276
  function validateRouteParams(path, schemas) {
4152
4277
  const pathParams = path.split("/").filter((segment) => segment === "*" || segment.startsWith(":")).map((segment) => segment === "*" ? segment : segment.slice(1));
4153
4278
  if (pathParams.length === 0) {
@@ -4170,19 +4295,19 @@ function routeModuleCache() {
4170
4295
  return cache;
4171
4296
  }
4172
4297
  function findPackageRoot(sourcePath) {
4173
- const fallback = dirname3(sourcePath);
4298
+ const fallback = dirname5(sourcePath);
4174
4299
  let directory = fallback;
4175
- while (dirname3(directory) !== directory) {
4176
- if (existsSync4(join4(directory, "package.json"))) {
4300
+ while (dirname5(directory) !== directory) {
4301
+ if (existsSync5(join5(directory, "package.json"))) {
4177
4302
  return directory;
4178
4303
  }
4179
- directory = dirname3(directory);
4304
+ directory = dirname5(directory);
4180
4305
  }
4181
- return existsSync4(join4(directory, "package.json")) ? directory : fallback;
4306
+ return existsSync5(join5(directory, "package.json")) ? directory : fallback;
4182
4307
  }
4183
4308
  function isWithinDirectory(path, directory) {
4184
- const relativePath = relative3(directory, path);
4185
- return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute(relativePath));
4309
+ const relativePath = relative4(directory, path);
4310
+ return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute2(relativePath));
4186
4311
  }
4187
4312
  function isFurinPackageImport(specifier) {
4188
4313
  return specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/");
@@ -4199,8 +4324,8 @@ function resolveRouteModuleImports(dependencyPath, packageRoot) {
4199
4324
  continue;
4200
4325
  }
4201
4326
  try {
4202
- const resolvedImport = realpathSync(Bun.resolveSync(imported.path, dirname3(dependencyPath)));
4203
- if (isAbsolute(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot)) {
4327
+ const resolvedImport = realpathSync(Bun.resolveSync(imported.path, dirname5(dependencyPath)));
4328
+ if (isAbsolute2(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot)) {
4204
4329
  resolvedImports.push(resolvedImport);
4205
4330
  }
4206
4331
  } catch {}
@@ -4289,18 +4414,30 @@ function primaryInstance(instances) {
4289
4414
  }
4290
4415
  return instance;
4291
4416
  }
4292
- function serverProxySource(instance) {
4417
+ function serverProxySource(instance, includeRootCatchAll) {
4293
4418
  const exportName = `furinApp_${Bun.hash(instanceKey(instance)).toString(16)}`;
4294
- return `export { ${exportName} as furinApp } from ${JSON.stringify(ROUTES_REGISTRY_SPECIFIER)};
4419
+ const registry = includeRootCatchAll ? ROUTES_REGISTRY_SPECIFIER : COMPOSABLE_ROUTES_REGISTRY_SPECIFIER;
4420
+ return `export { ${exportName} as furinApp } from ${JSON.stringify(registry)};
4295
4421
  `;
4296
4422
  }
4297
4423
  function createRoutesPlugin(options) {
4298
4424
  const routeFilesBySpecifier = new Map;
4299
4425
  const routeFilesByResolvedPath = new Map;
4300
- const registryVirtualPath = join4(resolve2(primaryInstance(options.instances).pagesDir), ".furin-routes-registry.ts?furin-virtual");
4301
- const instancesBySpecifier = new Map(options.instances.map((instance) => [
4302
- routeModuleSpecifier(instance),
4303
- { instance, namespace: instanceNamespace(instance) }
4426
+ const registryVirtualPath = join5(resolve3(primaryInstance(options.instances).pagesDir), ".furin-routes-registry.ts?furin-virtual");
4427
+ const composableRegistryVirtualPath = join5(resolve3(primaryInstance(options.instances).pagesDir), ".furin-routes-registry-composable.ts?furin-virtual");
4428
+ const instancesBySpecifier = new Map(options.instances.flatMap((instance) => [
4429
+ [
4430
+ routeModuleSpecifier(instance),
4431
+ { includeRootCatchAll: true, instance, namespace: instanceNamespace(instance) }
4432
+ ],
4433
+ [
4434
+ composableRouteModuleSpecifier(instance),
4435
+ {
4436
+ includeRootCatchAll: false,
4437
+ instance,
4438
+ namespace: `${instanceNamespace(instance)}-composable`
4439
+ }
4440
+ ]
4304
4441
  ]));
4305
4442
  return {
4306
4443
  name: `furin-routes-${options.target}`,
@@ -4321,12 +4458,12 @@ function createRoutesPlugin(options) {
4321
4458
  }
4322
4459
  return { namespace: registered.namespace, path };
4323
4460
  });
4324
- build.onResolve({ filter: ROUTES_REGISTRY_FILTER }, () => ({
4461
+ build.onResolve({ filter: ROUTES_REGISTRY_FILTER }, ({ path }) => ({
4325
4462
  namespace: "file",
4326
- path: registryVirtualPath
4463
+ path: path === ROUTES_REGISTRY_SPECIFIER ? registryVirtualPath : composableRegistryVirtualPath
4327
4464
  }));
4328
- build.onLoad({ filter: ROUTES_REGISTRY_FILE_FILTER, namespace: "file" }, async () => {
4329
- const contents = await serverRegistrySource(options.instances, routeFilesBySpecifier);
4465
+ build.onLoad({ filter: ROUTES_REGISTRY_FILE_FILTER, namespace: "file" }, async ({ path }) => {
4466
+ const contents = await serverRegistrySource(options.instances, routeFilesBySpecifier, false, path === registryVirtualPath);
4330
4467
  await validateRouteModules(routeFilesBySpecifier.values());
4331
4468
  return { contents, loader: "ts" };
4332
4469
  });
@@ -4347,12 +4484,12 @@ function createRoutesPlugin(options) {
4347
4484
  return {
4348
4485
  contents: await Bun.file(routeFile.sourcePath).text(),
4349
4486
  loader: detectLoaderFromPath(routeFile.sourcePath),
4350
- resolveDir: dirname3(routeFile.sourcePath)
4487
+ resolveDir: dirname5(routeFile.sourcePath)
4351
4488
  };
4352
4489
  });
4353
- for (const { instance, namespace } of instancesBySpecifier.values()) {
4490
+ for (const { instance, namespace, includeRootCatchAll } of instancesBySpecifier.values()) {
4354
4491
  build.onLoad({ filter: VIRTUAL_ROUTES_FILTER, namespace }, () => ({
4355
- contents: serverProxySource(instance),
4492
+ contents: serverProxySource(instance, includeRootCatchAll),
4356
4493
  loader: "ts"
4357
4494
  }));
4358
4495
  }
@@ -4360,6 +4497,44 @@ function createRoutesPlugin(options) {
4360
4497
  };
4361
4498
  }
4362
4499
 
4500
+ // src/build/server-app-entry.ts
4501
+ async function materializeServerAppEntry(options) {
4502
+ ensureDir(options.outDir);
4503
+ const apps = await Promise.all(options.apps.map(async (app, index) => {
4504
+ const instance = options.instances[index];
4505
+ if (!instance) {
4506
+ throw new Error(`[furin] Missing route instance for server app ${index}.`);
4507
+ }
4508
+ const routePath = join6(options.outDir, `_furin-routes-${index}.ts`);
4509
+ writeFileSync(routePath, await materializedRouteModuleSource(instance));
4510
+ return { ...app, nativeRoutes: toPosixPath(routePath) };
4511
+ }));
4512
+ const entryPath = join6(options.outDir, "_furin-app.ts");
4513
+ writeFileSync(entryPath, buildEntrySource({
4514
+ apps,
4515
+ headerComment: options.headerComment,
4516
+ mode: "app",
4517
+ serverEntry: options.serverEntry
4518
+ }));
4519
+ return entryPath;
4520
+ }
4521
+ function serverBootSource(appEntry) {
4522
+ return `// Auto-generated by furin build - do not edit
4523
+ import { startProductionServer } from "@teyik0/furin/production-server";
4524
+ import app, { idleTimeout, onShutdown, port, startServer } from ${JSON.stringify(toPosixPath(appEntry))};
4525
+
4526
+ if (typeof startServer === "function") {
4527
+ await startServer();
4528
+ } else if (app && typeof app.listen === "function" && !app.server) {
4529
+ const serverPort = process.env.PORT === undefined
4530
+ ? typeof port === "number" ? port : 3000
4531
+ : Number(process.env.PORT);
4532
+ startProductionServer({ app, idleTimeout, onShutdown, port: serverPort });
4533
+ console.log(\`[furin] Server running at http://localhost:\${app.server?.port}\`);
4534
+ }
4535
+ `;
4536
+ }
4537
+
4363
4538
  // ../../node_modules/.bun/magic-string@1.2.3/node_modules/magic-string/dist/index.mjs
4364
4539
  init_sourcemap_codec();
4365
4540
  var BitSet = class BitSet {
@@ -6815,13 +6990,13 @@ function assertNoPrefixSlugCollisions(prefixes) {
6815
6990
  }
6816
6991
 
6817
6992
  // src/adapter/runtime-build.ts
6818
- import { existsSync as existsSync6, writeFileSync as writeFileSync3 } from "fs";
6819
- import { basename as basename4, dirname as dirname6, join as join7, relative as relative4, resolve as resolve3 } from "path";
6993
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
6994
+ import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute3, join as join9, relative as relative6, resolve as resolve5 } from "path";
6820
6995
  import { fileURLToPath as fileURLToPath5 } from "url";
6821
6996
 
6822
6997
  // src/build/client.ts
6823
- import { existsSync as existsSync5, mkdirSync as mkdirSync2, writeFileSync } from "fs";
6824
- import { basename as basename2, dirname as dirname4, join as join5 } from "path";
6998
+ import { existsSync as existsSync6, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
6999
+ import { basename as basename2, dirname as dirname6, join as join7, resolve as resolve4 } from "path";
6825
7000
 
6826
7001
  // src/plugin/transform-client.ts
6827
7002
  var FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
@@ -7642,6 +7817,7 @@ const _match = routes.find((r) => r.regex.test(pathname));
7642
7817
  // a matched loader threw notFound(). The latter still has a _match; the
7643
7818
  // former does not \u2014 so the two cases fork on _match below.
7644
7819
  const dataEl = document.getElementById("__FURIN_DATA__");
7820
+ const frameTemplate = document.getElementById("__FURIN_ROUTE_FRAMES__") as HTMLTemplateElement | null;
7645
7821
  let loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
7646
7822
  const syncEl = document.getElementById("__FURIN_SYNC__");
7647
7823
  const syncConfig = syncEl ? JSON.parse(syncEl.textContent || "{}") : {};
@@ -7658,6 +7834,7 @@ const documentState: DocumentState = {
7658
7834
  assets: {
7659
7835
  buildId,
7660
7836
  entryModule: entryEl?.getAttribute("src") ?? undefined,
7837
+ extensionErrorFilterScript: document.querySelector("[data-furin-extension-error-filter]")?.textContent ?? undefined,
7661
7838
  faviconHref,
7662
7839
  frameworkModules,
7663
7840
  staticMode: document.querySelector('meta[name="furin-mode"][content="static"]') !== null,
@@ -7667,6 +7844,9 @@ const documentState: DocumentState = {
7667
7844
  },
7668
7845
  dataJson: dataEl?.textContent ?? undefined,
7669
7846
  head,
7847
+ routeFrames: frameTemplate?.hasAttribute("data-furin-document-state")
7848
+ ? (frameTemplate.content.textContent ?? "")
7849
+ : undefined,
7670
7850
  syncJson: syncEl?.textContent ?? undefined,
7671
7851
  };
7672
7852
 
@@ -7741,7 +7921,6 @@ if (__deferred && __deferred._chunks) {
7741
7921
  // Wrapped in an async IIFE to avoid top-level await, which causes Bun's HTML
7742
7922
  // bundler to misidentify which chunk to reference as the entry in index.html.
7743
7923
  (async () => {
7744
- const frameTemplate = document.getElementById("__FURIN_ROUTE_FRAMES__") as HTMLTemplateElement | null;
7745
7924
  if (frameTemplate) {
7746
7925
  const payload = frameTemplate.content.textContent || "";
7747
7926
  const routeFrameStream = (window as unknown as { __FURIN_ROUTE_FRAME_STREAM__?: FurinRouteFrameStream })
@@ -7871,6 +8050,7 @@ if (__deferred && __deferred._chunks) {
7871
8050
 
7872
8051
  // src/build/client.ts
7873
8052
  var SCRIPT_FILE_FILTER2 = /\.(tsx?|jsx?)$/;
8053
+ var ROUTER_PROVIDER_PATH = resolve4(import.meta.dir, "../client/router/provider.tsx");
7874
8054
  function resolveClientModuleSpecifiers(code) {
7875
8055
  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));
7876
8056
  }
@@ -7888,15 +8068,15 @@ async function buildClient(routes, {
7888
8068
  pagesDir
7889
8069
  }) {
7890
8070
  const dirName = clientDirName ?? "client";
7891
- const clientDir = join5(outDir, dirName);
7892
- if (!existsSync5(outDir)) {
8071
+ const clientDir = join7(outDir, dirName);
8072
+ if (!existsSync6(outDir)) {
7893
8073
  mkdirSync2(outDir, { recursive: true });
7894
8074
  }
7895
- if (!existsSync5(clientDir)) {
8075
+ if (!existsSync6(clientDir)) {
7896
8076
  mkdirSync2(clientDir, { recursive: true });
7897
8077
  }
7898
8078
  const hydrateCode = resolveClientModuleSpecifiers(generateHydrateEntry(routes, rootLayout, basePath, clientLogging));
7899
- const hydratePath = join5(outDir, dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`);
8079
+ const hydratePath = join7(outDir, dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`);
7900
8080
  const hydrateEntry = createVirtualBuildEntry(hydratePath, hydrateCode, "tsx");
7901
8081
  console.log("[furin] Building production client bundle\u2026");
7902
8082
  const transformPlugin = {
@@ -7917,6 +8097,20 @@ async function buildClient(routes, {
7917
8097
  });
7918
8098
  }
7919
8099
  };
8100
+ const routerLoggerPlugin = {
8101
+ name: "furin-client-router-logger",
8102
+ setup(build) {
8103
+ build.onResolve({ filter: /^evlog$/ }, ({ importer }) => {
8104
+ if (importer === ROUTER_PROVIDER_PATH) {
8105
+ return { namespace: "furin-client-router-logger", path: "router-logger" };
8106
+ }
8107
+ });
8108
+ build.onLoad({ filter: /.*/, namespace: "furin-client-router-logger" }, () => ({
8109
+ contents: "export const log = { warn: console.warn, error: console.error };",
8110
+ loader: "js"
8111
+ }));
8112
+ }
8113
+ };
7920
8114
  const clientBuildConfig = {
7921
8115
  entrypoints: [hydrateEntry.entrypoint],
7922
8116
  files: hydrateEntry.files,
@@ -7938,6 +8132,7 @@ async function buildClient(routes, {
7938
8132
  plugins: [
7939
8133
  hydrateEntry.plugin,
7940
8134
  ...plugins ?? [],
8135
+ ...!clientLogging ? [routerLoggerPlugin] : [],
7941
8136
  ...pagesDir ? [createRoutesPlugin({ instances: [{ pagesDir, prefix: basePath }], target: "client" })] : [],
7942
8137
  environmentGuardPlugin("client"),
7943
8138
  transformPlugin
@@ -7956,8 +8151,8 @@ async function buildClient(routes, {
7956
8151
  if (result.metafile === undefined) {
7957
8152
  throw new Error("[furin] client build did not produce the requested metafile");
7958
8153
  }
7959
- mkdirSync2(dirname4(metafilePath), { recursive: true });
7960
- writeFileSync(metafilePath, `${JSON.stringify(result.metafile, null, 2)}
8154
+ mkdirSync2(dirname6(metafilePath), { recursive: true });
8155
+ writeFileSync2(metafilePath, `${JSON.stringify(result.metafile, null, 2)}
7961
8156
  `);
7962
8157
  console.log(`[furin] Client metafile: ${metafilePath}`);
7963
8158
  }
@@ -9805,6 +10000,10 @@ function HeadContent() {
9805
10000
  }
9806
10001
  return /* @__PURE__ */ jsxDEV(Fragment, {
9807
10002
  children: [
10003
+ state.assets.extensionErrorFilterScript === undefined ? null : /* @__PURE__ */ jsxDEV("script", {
10004
+ dangerouslySetInnerHTML: { __html: state.assets.extensionErrorFilterScript },
10005
+ "data-furin-extension-error-filter": ""
10006
+ }, undefined, false, undefined, this),
9808
10007
  /* @__PURE__ */ jsxDEV("meta", {
9809
10008
  charSet: "utf-8",
9810
10009
  "data-furin-head": ""
@@ -9862,6 +10061,13 @@ function Scripts() {
9862
10061
  id: "__FURIN_DATA__",
9863
10062
  type: "application/json"
9864
10063
  }, undefined, false, undefined, this),
10064
+ state.routeFrames === undefined ? null : /* @__PURE__ */ jsxDEV("template", {
10065
+ dangerouslySetInnerHTML: {
10066
+ __html: state.routeFrames.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
10067
+ },
10068
+ "data-furin-document-state": "",
10069
+ id: "__FURIN_ROUTE_FRAMES__"
10070
+ }, undefined, false, undefined, this),
9865
10071
  /* @__PURE__ */ jsxDEV("script", {
9866
10072
  dangerouslySetInnerHTML: { __html: serializeJson(state.head ?? {}) },
9867
10073
  "data-furin-scripts": "",
@@ -10142,6 +10348,21 @@ function cyrb53(input) {
10142
10348
  return 4294967296 * (2097151 & h2) + (4294967295 & h1);
10143
10349
  }
10144
10350
 
10351
+ // src/shared/production-build.ts
10352
+ var productionBuildScope;
10353
+ var productionBuildScopePromise;
10354
+ async function withProductionBuild(build) {
10355
+ productionBuildScopePromise ??= import("async_hooks").then(({ AsyncLocalStorage }) => {
10356
+ productionBuildScope = new AsyncLocalStorage;
10357
+ return productionBuildScope;
10358
+ });
10359
+ const scope = await productionBuildScopePromise;
10360
+ return scope.run(true, build);
10361
+ }
10362
+ function isProductionBuild() {
10363
+ return productionBuildScope?.getStore() === true || typeof process !== "undefined" && false;
10364
+ }
10365
+
10145
10366
  // src/rsc/shared.tsx
10146
10367
  import {
10147
10368
  Children,
@@ -10167,7 +10388,7 @@ var FRAME_VERSION = 3;
10167
10388
  var MAX_FRAME_BYTES = 1024 * 1024;
10168
10389
  var MAX_ROUTE_FRAME_STREAM_BYTES = 8 * 1024 * 1024;
10169
10390
  var RSC_DESCRIPTOR = "__furinRsc";
10170
- function isPlainObject3(value) {
10391
+ function isPlainObject4(value) {
10171
10392
  const prototype = Object.getPrototypeOf(value);
10172
10393
  return prototype === Object.prototype || prototype === null;
10173
10394
  }
@@ -10196,7 +10417,7 @@ function extractRscSources(value, sources, seen, idPrefix) {
10196
10417
  }
10197
10418
  return result;
10198
10419
  }
10199
- if (!isPlainObject3(value)) {
10420
+ if (!isPlainObject4(value)) {
10200
10421
  return value;
10201
10422
  }
10202
10423
  const result = {};
@@ -10276,7 +10497,7 @@ function containsRscSourceInner(value, seen) {
10276
10497
  if (Array.isArray(value)) {
10277
10498
  return value.some((entry) => containsRscSourceInner(entry, seen));
10278
10499
  }
10279
- return isPlainObject3(value) && Object.values(value).some((entry) => containsRscSourceInner(entry, seen));
10500
+ return isPlainObject4(value) && Object.values(value).some((entry) => containsRscSourceInner(entry, seen));
10280
10501
  }
10281
10502
  function serializeRouteFrames(data, deferredKeys) {
10282
10503
  const sources = [];
@@ -10317,10 +10538,12 @@ function withDocumentState(element, assets, head, data) {
10317
10538
  ...assets,
10318
10539
  frameworkModules: [browserEventsClientPath, ...assets.frameworkModules]
10319
10540
  };
10541
+ const routeFrames = data !== undefined && containsRscSource(data) ? serializeRouteFrames(data, undefined) : undefined;
10320
10542
  const state = {
10321
10543
  assets: resolvedAssets,
10322
- dataJson: data === undefined ? undefined : safeJson(data),
10544
+ dataJson: data === undefined || routeFrames !== undefined ? undefined : safeJson(data),
10323
10545
  head,
10546
+ routeFrames,
10324
10547
  syncJson: syncPath === undefined ? undefined : safeJson({ path: syncPath })
10325
10548
  };
10326
10549
  return createElement3(DocumentProvider, { value: state }, element);
@@ -11076,7 +11299,9 @@ function errorStack(error) {
11076
11299
  return error instanceof Error ? error.stack : undefined;
11077
11300
  }
11078
11301
  function renderErrorMessage(options) {
11079
- if (typeof process !== "undefined" && false) {}
11302
+ if (isProductionBuild()) {
11303
+ return `[furin/rsc] Server Component rendering failed inside ${options.operation}().`;
11304
+ }
11080
11305
  if (options.hook !== undefined && options.component !== undefined) {
11081
11306
  const diagnostic = `[furin/rsc] A component rendered inside ${options.operation}()
11082
11307
  used a client-only React hook.
@@ -11180,13 +11405,17 @@ function injectInstrumentationClient(html, prefix) {
11180
11405
  var REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
11181
11406
  var FURIN_RESERVED_KEY_PREFIX = "__furin";
11182
11407
  var ROUTE_CTX_RESERVED_KEYS = new Set([
11408
+ "catch",
11183
11409
  "children",
11410
+ "finally",
11184
11411
  "key",
11185
11412
  "params",
11186
11413
  "path",
11187
11414
  "query",
11188
11415
  "ref",
11189
- "requestData"
11416
+ "requestData",
11417
+ "then",
11418
+ "toJSON"
11190
11419
  ]);
11191
11420
  function assertPublicLoaderKey(key) {
11192
11421
  if (key.startsWith(FURIN_RESERVED_KEY_PREFIX)) {
@@ -11220,7 +11449,7 @@ function createLoaderCtx(ctx, accumulatedParentPromise) {
11220
11449
  if (prop === "then" || prop === "catch" || prop === "finally" || prop === "toJSON") {
11221
11450
  return Reflect.get(target, prop);
11222
11451
  }
11223
- if (Object.hasOwn(target, prop)) {
11452
+ if (Object.hasOwn(target, prop) || prop in target && !Object.hasOwn(Object.prototype, prop)) {
11224
11453
  return target[prop];
11225
11454
  }
11226
11455
  let entry = cache.get(prop);
@@ -11262,7 +11491,7 @@ function createRequestLoaderContext(ctx) {
11262
11491
  get: (name) => headers.get(name),
11263
11492
  has: (name) => headers.has(name)
11264
11493
  }),
11265
- log: useLogger3(),
11494
+ log: getLogger(),
11266
11495
  params: ctx.params,
11267
11496
  path: ctx.path,
11268
11497
  query: ctx.query,
@@ -11387,7 +11616,7 @@ async function normalizeLoaderError(err, headers) {
11387
11616
  return { error: err, headers, message, status, type: "error" };
11388
11617
  }
11389
11618
  if (isFurinRscRenderError(err)) {
11390
- useLogger3().error(err);
11619
+ getLogger().error(err);
11391
11620
  return {
11392
11621
  error: err,
11393
11622
  headers,
@@ -11407,7 +11636,7 @@ async function normalizeLoaderError(err, headers) {
11407
11636
  async function runLoadersInternal(route, ctx, includeRequestData) {
11408
11637
  try {
11409
11638
  const requestData = includeRequestData ? runRequestLoaderData(route, ctx) : undefined;
11410
- const ctxRecord = includeRequestData ? { ...ctx, log: useLogger3() } : createPublicLoaderContext(ctx);
11639
+ const ctxRecord = includeRequestData ? Object.assign(Object.create(Object.getPrototypeOf(ctx)), ctx, { log: getLogger() }) : createPublicLoaderContext(ctx);
11411
11640
  const loaderMap = new Map;
11412
11641
  let accumulatedParentPromise = Promise.resolve({});
11413
11642
  let loaderIndex = 0;
@@ -11422,7 +11651,7 @@ async function runLoadersInternal(route, ctx, includeRequestData) {
11422
11651
  if (IS_DEV) {
11423
11652
  for (const key of Object.keys(own)) {
11424
11653
  if (Object.hasOwn(acc, key)) {
11425
- useLogger3().warn(`[furin] Loader data collision on "${key}" for ${ctx.path}: a deeper loader overwrites the value inherited from its layout chain (deepest wins).`);
11654
+ getLogger().warn(`[furin] Loader data collision on "${key}" for ${ctx.path}: a deeper loader overwrites the value inherited from its layout chain (deepest wins).`);
11426
11655
  }
11427
11656
  }
11428
11657
  }
@@ -11466,7 +11695,7 @@ function createPublicLoaderContext(ctx) {
11466
11695
  Object.defineProperties(publicContext, {
11467
11696
  cookie: { enumerable: true, get: fail },
11468
11697
  headers: { enumerable: true, get: fail },
11469
- log: { enumerable: true, value: useLogger3() },
11698
+ log: { enumerable: true, value: getLogger() },
11470
11699
  params: { enumerable: true, value: ctx.params },
11471
11700
  path: { enumerable: true, value: ctx.path },
11472
11701
  query: { enumerable: true, value: ctx.query },
@@ -11602,7 +11831,11 @@ async function getDevDocumentAssets(origin) {
11602
11831
  if (state.devAssets && Date.now() - state.devAssets.ts < DEV_TEMPLATE_TTL_MS) {
11603
11832
  return state.devAssets.assets;
11604
11833
  }
11605
- const assets = documentAssetsFromTemplate(await getDevTemplate(origin));
11834
+ await Promise.resolve().then(() => init_plugin2());
11835
+ const assets = {
11836
+ ...documentAssetsFromTemplate(await getDevTemplate(origin)),
11837
+ extensionErrorFilterScript
11838
+ };
11606
11839
  state.devAssets = { assets, ts: Date.now() };
11607
11840
  return assets;
11608
11841
  }
@@ -11884,7 +12117,7 @@ function renderForPath(route, params, root, origin, mode, basePath, searchRoutes
11884
12117
  if (prepared instanceof Response) {
11885
12118
  return prepared;
11886
12119
  }
11887
- useLogger3().set({
12120
+ getLogger().set({
11888
12121
  furin: {
11889
12122
  cache: mode === "isr" ? "revalidated" : "miss",
11890
12123
  loader_ms: prepared.loader_ms,
@@ -11918,6 +12151,118 @@ async function serializeLoaderDataNdjson(syncData, deferredPromises) {
11918
12151
  `;
11919
12152
  }
11920
12153
 
12154
+ // src/server/render/static-params.ts
12155
+ import { dirname as dirname8, relative as relative5 } from "path";
12156
+ init_patterns();
12157
+ var STATIC_PARAMS_CONCURRENCY = 4;
12158
+ function collectStaticParamsStages(route) {
12159
+ const stages = [];
12160
+ for (const [index, entry] of route.routeChain.entries()) {
12161
+ if (entry.staticParams) {
12162
+ stages.push({ ancestors: route.routeChain.slice(0, index), run: entry.staticParams });
12163
+ }
12164
+ }
12165
+ if (route.page.staticParams) {
12166
+ stages.push({ ancestors: route.routeChain, run: route.page.staticParams });
12167
+ }
12168
+ return stages;
12169
+ }
12170
+ function ancestorPattern(route, ancestors) {
12171
+ const rootSourcePath = route.routeChain[0]?.sourcePath;
12172
+ const ancestorSourcePath = ancestors.at(-1)?.sourcePath;
12173
+ if (rootSourcePath === undefined || ancestorSourcePath === undefined) {
12174
+ return route.pattern;
12175
+ }
12176
+ const pagesDir = dirname8(rootSourcePath);
12177
+ const ancestorDir = dirname8(ancestorSourcePath);
12178
+ if (ancestorDir === pagesDir) {
12179
+ return "/";
12180
+ }
12181
+ return filePathToPattern(`${relative5(pagesDir, ancestorDir)}/index.tsx`);
12182
+ }
12183
+ function createBuildContext(pattern, params, origin) {
12184
+ const path = resolvePath(pattern, params);
12185
+ return {
12186
+ cookie: {},
12187
+ headers: {},
12188
+ params,
12189
+ path,
12190
+ query: {},
12191
+ redirect: (url, status) => new Response(null, { headers: { Location: url }, status: status ?? 302 }),
12192
+ request: new Request(new URL(path, origin)),
12193
+ set: { headers: {} }
12194
+ };
12195
+ }
12196
+ async function runAncestorLoaders(route, ancestors, params, origin) {
12197
+ const pattern = ancestorPattern(route, ancestors);
12198
+ const result = await runPublicLoaders({
12199
+ ...route,
12200
+ page: { ...route.page, loader: undefined },
12201
+ pattern,
12202
+ routeChain: ancestors
12203
+ }, createBuildContext(pattern, params, origin));
12204
+ if (result.type === "redirect") {
12205
+ throw result.response;
12206
+ }
12207
+ if (result.type === "not-found") {
12208
+ throw result.error;
12209
+ }
12210
+ if (result.type === "error") {
12211
+ throw result.error;
12212
+ }
12213
+ const data = {};
12214
+ for (const [key, value] of Object.entries(result.syncData)) {
12215
+ if (key !== "params" && key !== "path" && key !== "query") {
12216
+ data[key] = value;
12217
+ }
12218
+ }
12219
+ Object.assign(data, result.deferredPromises);
12220
+ return data;
12221
+ }
12222
+ function createStaticParamsContext(route, ancestors, params, origin) {
12223
+ const target = { params };
12224
+ const fields = new Map;
12225
+ let parentData;
12226
+ return new Proxy(target, {
12227
+ get(context, property) {
12228
+ if (typeof property !== "string" || Object.hasOwn(context, property)) {
12229
+ return Reflect.get(context, property);
12230
+ }
12231
+ if (property === "then" || property === "catch" || property === "finally" || property === "toJSON") {
12232
+ return;
12233
+ }
12234
+ let field = fields.get(property);
12235
+ if (!field) {
12236
+ parentData ??= runAncestorLoaders(route, ancestors, params, origin);
12237
+ field = parentData.then((data) => data[property]);
12238
+ fields.set(property, field);
12239
+ }
12240
+ return field;
12241
+ }
12242
+ });
12243
+ }
12244
+ function hasStaticParams(route) {
12245
+ return route.page.staticParams !== undefined || route.routeChain.some((entry) => entry.staticParams !== undefined);
12246
+ }
12247
+ async function resolveStaticParams(route, origin) {
12248
+ const stages = collectStaticParamsStages(route);
12249
+ if (stages.length === 0) {
12250
+ return;
12251
+ }
12252
+ let branches = [{}];
12253
+ for (const stage of stages) {
12254
+ const branchValues = await mapWithConcurrency(branches, STATIC_PARAMS_CONCURRENCY, async (params) => {
12255
+ const values = await stage.run(createStaticParamsContext(route, stage.ancestors, params, origin));
12256
+ if (!Array.isArray(values)) {
12257
+ throw new TypeError(`[furin] staticParams() for "${route.pattern}" must return an array.`);
12258
+ }
12259
+ return values.map((value) => ({ ...params, ...value }));
12260
+ });
12261
+ branches = branchValues.flat();
12262
+ }
12263
+ return branches;
12264
+ }
12265
+
11921
12266
  // src/server/render/ssg.ts
11922
12267
  async function prerenderRoute(route, params, root, origin, mode, basePath, searchRoutes, requestContext) {
11923
12268
  const renderResult = await renderForPath(route, params, root, origin, mode, basePath, searchRoutes, undefined, requestContext);
@@ -11970,12 +12315,8 @@ async function buildRoutePrerenders(routes, root, origin, basePath) {
11970
12315
  let paramSets;
11971
12316
  if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
11972
12317
  paramSets = [{}];
11973
- } else if (route.page.staticParams) {
11974
- const resolvedParams = await route.page.staticParams();
11975
- if (!Array.isArray(resolvedParams)) {
11976
- throw new TypeError(`[furin] staticParams() for "${route.pattern}" must return an array.`);
11977
- }
11978
- paramSets = resolvedParams;
12318
+ } else if (hasStaticParams(route)) {
12319
+ paramSets = await resolveStaticParams(route, origin) ?? [];
11979
12320
  } else {
11980
12321
  continue;
11981
12322
  }
@@ -11998,10 +12339,10 @@ async function buildSSGCacheSnapshot(routes, root, origin, basePath) {
11998
12339
  const snapshot = {};
11999
12340
  const searchRoutes = createSearchRouteMetadata(routes);
12000
12341
  for (const route of routes) {
12001
- if (route.mode !== "ssg" || !route.page.staticParams || hasRequestLoader(route)) {
12342
+ if (route.mode !== "ssg" || !hasStaticParams(route) || hasRequestLoader(route)) {
12002
12343
  continue;
12003
12344
  }
12004
- const paramSets = await route.page.staticParams();
12345
+ const paramSets = await resolveStaticParams(route, origin) ?? [];
12005
12346
  for (const params of paramSets) {
12006
12347
  const result = await prerenderSSG(route, params, root, origin, basePath, searchRoutes);
12007
12348
  if (!(result instanceof Response)) {
@@ -12013,8 +12354,8 @@ async function buildSSGCacheSnapshot(routes, root, origin, basePath) {
12013
12354
  }
12014
12355
 
12015
12356
  // src/rsc/build/index.ts
12016
- import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync2 } from "fs";
12017
- import { basename as basename3, join as join6 } from "path";
12357
+ import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "fs";
12358
+ import { basename as basename3, join as join8 } from "path";
12018
12359
  import { fileURLToPath as fileURLToPath4 } from "url";
12019
12360
 
12020
12361
  // src/rsc/version.ts
@@ -12062,7 +12403,7 @@ function assertInstalledRscVersions() {
12062
12403
  // src/rsc/build/index.ts
12063
12404
  async function buildRscGraph(apps, outDir, buildId, userPlugins) {
12064
12405
  await assertInstalledRscVersions();
12065
- const graphDir = join6(outDir, "rsc");
12406
+ const graphDir = join8(outDir, "rsc");
12066
12407
  mkdirSync3(graphDir, { recursive: true });
12067
12408
  const rscEntry = fileURLToPath4(import.meta.resolve("../../rsc-server.tsx"));
12068
12409
  const entrypoints = [
@@ -12124,13 +12465,13 @@ ${codecResult.logs.map((log) => log.message).join(`
12124
12465
  }
12125
12466
  const css = result.outputs.filter((output) => output.path.endsWith(".css")).map((output) => ({ href: `/_rsc/${basename3(output.path)}` }));
12126
12467
  const manifest = { buildId, clientReferences: [], css };
12127
- writeFileSync2(join6(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
12468
+ writeFileSync3(join8(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
12128
12469
  return manifest;
12129
12470
  }
12130
12471
 
12131
12472
  // src/adapter/runtime-build.ts
12132
- var _pkgRoot2 = dirname6(dirname6(fileURLToPath5(import.meta.resolve("@teyik0/furin"))));
12133
- var _pkgSrcDir2 = existsSync6(join7(_pkgRoot2, "src", "furin.ts")) ? join7(_pkgRoot2, "src") : join7(_pkgRoot2, "dist");
12473
+ var _pkgRoot2 = dirname9(dirname9(fileURLToPath5(import.meta.resolve("@teyik0/furin"))));
12474
+ var _pkgSrcDir2 = existsSync7(join9(_pkgRoot2, "src", "furin.ts")) ? join9(_pkgRoot2, "src") : join9(_pkgRoot2, "dist");
12134
12475
  var _ext2 = ".ts";
12135
12476
  var PPR_ROUTE_IMPORT_RE = /ppr-route(?:\.ts)?$/;
12136
12477
  var ANY_MODULE_RE = /.*/;
@@ -12190,13 +12531,13 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
12190
12531
  }
12191
12532
  }
12192
12533
  for (const path of BUILD_ID_INPUT_PATHS) {
12193
- if (!existsSync6(path)) {
12534
+ if (!existsSync7(path)) {
12194
12535
  console.warn(`[furin] Warning: build fingerprint input "${toPosixPath(path)}" is missing \u2014 ` + "the generated build ID may not reflect all framework changes.");
12195
12536
  }
12196
12537
  fingerprintPaths.add(path);
12197
12538
  }
12198
12539
  const fileParts = await Promise.all([...fingerprintPaths].toSorted().map(async (path) => {
12199
- const content = existsSync6(path) ? await Bun.file(path).text() : "";
12540
+ const content = existsSync7(path) ? await Bun.file(path).text() : "";
12200
12541
  return `${stableFingerprintPath(path, projectRoot)}:${content}`;
12201
12542
  }));
12202
12543
  const routeParts = routes.map((route) => JSON.stringify({
@@ -12208,12 +12549,12 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
12208
12549
  `);
12209
12550
  }
12210
12551
  function stableFingerprintPath(path, projectRoot) {
12211
- const projectPath = relative4(projectRoot, path);
12212
- if (projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
12552
+ const projectPath = relative6(projectRoot, path);
12553
+ if (!isAbsolute3(projectPath) && projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
12213
12554
  return `app/${toPosixPath(projectPath)}`;
12214
12555
  }
12215
- const frameworkPath = relative4(_pkgRoot2, path);
12216
- if (frameworkPath !== ".." && !frameworkPath.startsWith("../") && !frameworkPath.startsWith("..\\")) {
12556
+ const frameworkPath = relative6(_pkgRoot2, path);
12557
+ if (!isAbsolute3(frameworkPath) && frameworkPath !== ".." && !frameworkPath.startsWith("../") && !frameworkPath.startsWith("..\\")) {
12217
12558
  return `furin/${toPosixPath(frameworkPath)}`;
12218
12559
  }
12219
12560
  return `external/${basename4(path)}`;
@@ -12238,7 +12579,7 @@ function buildCompileMetadata(root, routes) {
12238
12579
  }
12239
12580
  function pprRuntimePlugin(apps) {
12240
12581
  const enabled = apps.some((app) => app.routes.some((route) => route.mode !== "ssr" && (app.root.route.requestLoader !== undefined || hasRequestLoader(route))));
12241
- const pprPath = resolve3(_pkgSrcDir2, "server/render/ppr-route.ts");
12582
+ const pprPath = resolve5(_pkgSrcDir2, "server/render/ppr-route.ts");
12242
12583
  const reactServerPath = fileURLToPath5(import.meta.resolve(enabled ? "react-dom/server.edge" : "react-dom/server"));
12243
12584
  const reactStaticPath = fileURLToPath5(import.meta.resolve("react-dom/static.edge"));
12244
12585
  return {
@@ -12250,7 +12591,7 @@ function pprRuntimePlugin(apps) {
12250
12591
  return;
12251
12592
  }
12252
12593
  build.onResolve({ filter: PPR_ROUTE_IMPORT_RE }, ({ path, importer }) => {
12253
- const absolute = resolve3(dirname6(importer.split("?")[0]), path);
12594
+ const absolute = resolve5(dirname9(importer.split("?")[0]), path);
12254
12595
  if (absolute !== pprPath && `${absolute}.ts` !== pprPath) {
12255
12596
  return;
12256
12597
  }
@@ -12270,7 +12611,7 @@ function isFrameworkRuntimeImporter(importer) {
12270
12611
  if (importer === "") {
12271
12612
  return false;
12272
12613
  }
12273
- const fromRuntimeRoot = relative4(_pkgSrcDir2, importer.split("?")[0]);
12614
+ const fromRuntimeRoot = relative6(_pkgSrcDir2, importer.split("?")[0]);
12274
12615
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
12275
12616
  }
12276
12617
  async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options, targetName) {
@@ -12282,7 +12623,7 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
12282
12623
  basePath: prefix,
12283
12624
  clientDirName,
12284
12625
  clientLogging: options.clientLogging ?? false,
12285
- metafilePath: options.analyze ? join7(dirname6(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
12626
+ metafilePath: options.analyze ? join9(dirname9(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
12286
12627
  optimizeImports: options.optimizeImports,
12287
12628
  outDir: targetDir,
12288
12629
  pagesDir: app.pagesDir,
@@ -12294,9 +12635,9 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
12294
12635
  const buildFingerprint = await createBuildFingerprint(`${prefix}
12295
12636
  ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
12296
12637
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
12297
- const clientDir = join7(targetDir, clientDirName);
12638
+ const clientDir = join9(targetDir, clientDirName);
12298
12639
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
12299
- writeFileSync3(join7(clientDir, "index.html"), indexHtml);
12640
+ writeFileSync4(join9(clientDir, "index.html"), indexHtml);
12300
12641
  setProductionTemplateContent(indexHtml);
12301
12642
  ssgRouteCache().clear();
12302
12643
  let ssgCache;
@@ -12316,9 +12657,10 @@ ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
12316
12657
  entryApp: {
12317
12658
  buildId,
12318
12659
  clientLogging: options.clientLogging ?? false,
12660
+ deploymentTarget: targetName === "vercel" ? "vercel" : undefined,
12319
12661
  embed: options.compile === "embed" ? { clientDir } : undefined,
12320
12662
  modulePaths,
12321
- nativeRoutes: routeModuleSpecifier(app),
12663
+ nativeRoutes: composableRouteModuleSpecifier(app),
12322
12664
  prefix,
12323
12665
  rootConventions,
12324
12666
  rootPath: root.path,
@@ -12353,15 +12695,10 @@ async function buildRuntimeAppsSequentially(apps, projectRoot, targetDir, server
12353
12695
  }
12354
12696
 
12355
12697
  // src/adapter/bun.ts
12356
- function generateDiskEntry(options) {
12357
- ensureDir(options.outDir);
12358
- const source = buildEntrySource({
12359
- apps: options.apps.map(({ embed: _embed, ...context }) => context),
12360
- headerComment: "// Auto-generated by furin build - do not edit",
12361
- serverEntry: options.serverEntry
12362
- });
12363
- const entryPath = join8(options.outDir, "server.ts");
12364
- return createVirtualBuildEntry(entryPath, source, "ts");
12698
+ function generateBootEntry(appEntry, outDir, filename) {
12699
+ ensureDir(outDir);
12700
+ const entryPath = join10(outDir, filename);
12701
+ return createVirtualBuildEntry(entryPath, serverBootSource(appEntry), "ts");
12365
12702
  }
12366
12703
  function collectEmbeddedAssets(entryApps, publicDir, compile) {
12367
12704
  if (compile !== "embed") {
@@ -12373,6 +12710,70 @@ function collectEmbeddedAssets(entryApps, publicDir, compile) {
12373
12710
  }
12374
12711
  return assets;
12375
12712
  }
12713
+ function compiledServerFilename(platform) {
12714
+ return platform === "win32" ? "server.exe" : "server";
12715
+ }
12716
+ function serverSourcemapMode(enabled) {
12717
+ return enabled ? "external" : "none";
12718
+ }
12719
+ function relocateServerMaps(build, enabled, targetDir, buildRoot) {
12720
+ if (!enabled) {
12721
+ return;
12722
+ }
12723
+ movePrivateServerSourceMaps(targetDir, join10(buildRoot, "private", "server-sourcemaps", "bun"), build.outputs.filter((output) => output.kind === "sourcemap").map((output) => output.path));
12724
+ }
12725
+ function writeServerMetafile(build, analyze, buildRoot) {
12726
+ if (!analyze) {
12727
+ return;
12728
+ }
12729
+ if (build.metafile === undefined) {
12730
+ throw new Error("[furin] Bun server build did not produce the requested metafile.");
12731
+ }
12732
+ const analysisDir = join10(buildRoot, "analysis");
12733
+ ensureDir(analysisDir);
12734
+ const metafilePath = join10(analysisDir, "bun-server.json");
12735
+ writeFileSync5(metafilePath, `${JSON.stringify(build.metafile, null, 2)}
12736
+ `);
12737
+ console.log(`[furin] Server metafile: ${toPosixPath(metafilePath)}`);
12738
+ }
12739
+ function finalizeEmbeddedAssets(compile, apps, targetDir, manifest) {
12740
+ if (compile !== "embed") {
12741
+ return;
12742
+ }
12743
+ for (const app of apps) {
12744
+ rmSync2(join10(targetDir, clientDirNameForPrefix(app.prefix)), {
12745
+ force: true,
12746
+ recursive: true
12747
+ });
12748
+ }
12749
+ manifest.clientDir = null;
12750
+ manifest.templatePath = null;
12751
+ }
12752
+ async function createBunAppEntry(apps, entryApps, options, publicDir, serverEntry, targetDir) {
12753
+ if (!serverEntry) {
12754
+ return;
12755
+ }
12756
+ const contexts = options.compile ? prepareCompileEntryApps({
12757
+ apps: entryApps,
12758
+ outDir: targetDir,
12759
+ publicDir,
12760
+ serverEntry
12761
+ }) : entryApps.map(({ embed: _embed, ...context }) => ({
12762
+ ...context,
12763
+ extraContext: [
12764
+ ...context.extraContext ?? [],
12765
+ ` clientDir: import.meta.dir + ${JSON.stringify(`/${clientDirNameForPrefix(context.prefix ?? "")}`)},`
12766
+ ],
12767
+ templateHtml: readFileSync4(join10(targetDir, clientDirNameForPrefix(context.prefix ?? ""), "index.html"), "utf8")
12768
+ }));
12769
+ return await materializeServerAppEntry({
12770
+ apps: contexts,
12771
+ headerComment: "// Auto-generated by furin build - do not edit",
12772
+ instances: apps,
12773
+ outDir: targetDir,
12774
+ serverEntry
12775
+ });
12776
+ }
12376
12777
  async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12377
12778
  if (options.compile && !serverEntry) {
12378
12779
  throw new Error(`[furin] \`compile: "${options.compile}"\` requires a server entry point. ` + "Create src/server.ts or set `serverEntry` in your furin.config.ts.");
@@ -12382,35 +12783,37 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12382
12783
  }
12383
12784
  const target = "bun";
12384
12785
  const targetManifest = buildTargetManifest(rootDir, buildRoot, target, serverEntry);
12385
- const targetDir = resolve4(rootDir, targetManifest.targetDir);
12786
+ const targetDir = resolve6(rootDir, targetManifest.targetDir);
12386
12787
  rmSync2(targetDir, { force: true, recursive: true });
12788
+ rmSync2(join10(buildRoot, "private", "server-sourcemaps", "bun"), {
12789
+ force: true,
12790
+ recursive: true
12791
+ });
12387
12792
  ensureDir(targetDir);
12388
- const publicDir = existsSync7(join8(rootDir, "public")) ? join8(rootDir, "public") : undefined;
12793
+ const publicDir = existsSync8(join10(rootDir, "public")) ? join10(rootDir, "public") : undefined;
12389
12794
  const { entryApps, headlineBuildId } = await buildRuntimeAppsSequentially(apps, rootDir, targetDir, serverEntry, options, "bun");
12390
12795
  targetManifest.buildId = headlineBuildId;
12391
12796
  if (serverEntry) {
12392
- targetManifest.rscManifestPath = toPosixPath(join8(targetManifest.targetDir, "rsc", "manifest.json"));
12797
+ targetManifest.rscManifestPath = toPosixPath(join10(targetManifest.targetDir, "rsc", "manifest.json"));
12393
12798
  }
12394
- const targetPublicDir = publicDir ? join8(targetDir, "public") : undefined;
12799
+ const targetPublicDir = publicDir ? join10(targetDir, "public") : undefined;
12395
12800
  if (publicDir && targetPublicDir && options.compile !== "embed") {
12396
12801
  copyDirRecursive(publicDir, targetPublicDir);
12397
12802
  }
12398
- if (options.compile && serverEntry) {
12399
- const outfile = join8(targetDir, "server");
12400
- const entry = generateCompileEntry({
12401
- apps: entryApps,
12402
- outDir: targetDir,
12403
- publicDir,
12404
- serverEntry
12405
- });
12803
+ const appEntry = await createBunAppEntry(apps, entryApps, options, publicDir, serverEntry, targetDir);
12804
+ if (options.compile && serverEntry && appEntry) {
12805
+ const serverFilename = compiledServerFilename(process.platform);
12806
+ const outfile = join10(targetDir, serverFilename);
12807
+ const entry = generateBootEntry(appEntry, targetDir, "_compile-entry.ts");
12406
12808
  const embeddedAssets = collectEmbeddedAssets(entryApps, publicDir, options.compile);
12407
- await runBunBuild({
12809
+ const serverBuild = await runBunBuild({
12408
12810
  bytecode: true,
12409
12811
  compile: { assets: embeddedAssets, outfile },
12410
12812
  define: { "process.env.NODE_ENV": JSON.stringify("production") },
12411
12813
  entrypoints: [entry.entrypoint],
12412
12814
  files: entry.files,
12413
12815
  format: "esm",
12816
+ metafile: options.analyze,
12414
12817
  minify: true,
12415
12818
  plugins: [
12416
12819
  entry.plugin,
@@ -12419,33 +12822,24 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12419
12822
  ...options.plugins ?? [],
12420
12823
  createRoutesPlugin({ instances: apps, target: "server" }),
12421
12824
  isomorphicTransformPlugin("server"),
12422
- environmentGuardPlugin("ssr")
12825
+ environmentGuardPlugin("ssr"),
12826
+ elysiaAot(appEntry)
12423
12827
  ],
12424
- sourcemap: "none",
12828
+ sourcemap: serverSourcemapMode(options.serverSourceMaps),
12425
12829
  splitting: true,
12426
12830
  target: "bun"
12427
12831
  });
12832
+ relocateServerMaps(serverBuild, options.serverSourceMaps, targetDir, buildRoot);
12833
+ writeServerMetafile(serverBuild, options.analyze, buildRoot);
12428
12834
  console.log(`[furin] Server binary: ${outfile}`);
12429
- targetManifest.serverPath = toPosixPath(join8(targetManifest.targetDir, "server"));
12430
- if (options.compile === "embed") {
12431
- for (const app of apps) {
12432
- rmSync2(join8(targetDir, clientDirNameForPrefix(app.prefix)), {
12433
- force: true,
12434
- recursive: true
12435
- });
12436
- }
12437
- targetManifest.clientDir = null;
12438
- targetManifest.templatePath = null;
12439
- }
12440
- } else if (serverEntry) {
12441
- const entry = generateDiskEntry({
12442
- apps: entryApps,
12443
- outDir: targetDir,
12444
- serverEntry
12445
- });
12446
- await runBunBuild({
12835
+ targetManifest.serverPath = toPosixPath(join10(targetManifest.targetDir, serverFilename));
12836
+ finalizeEmbeddedAssets(options.compile, apps, targetDir, targetManifest);
12837
+ } else if (serverEntry && appEntry) {
12838
+ const entry = generateBootEntry(appEntry, targetDir, "server.ts");
12839
+ const serverBuild = await runBunBuild({
12447
12840
  entrypoints: [entry.entrypoint],
12448
12841
  files: entry.files,
12842
+ metafile: options.analyze,
12449
12843
  minify: true,
12450
12844
  naming: { chunk: "[name]-[hash].[ext]", entry: "[name].[ext]" },
12451
12845
  outdir: targetDir,
@@ -12456,30 +12850,33 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12456
12850
  ...options.plugins ?? [],
12457
12851
  createRoutesPlugin({ instances: apps, target: "server" }),
12458
12852
  isomorphicTransformPlugin("server"),
12459
- environmentGuardPlugin("ssr")
12853
+ environmentGuardPlugin("ssr"),
12854
+ elysiaAot(appEntry)
12460
12855
  ],
12461
- sourcemap: "none",
12856
+ sourcemap: serverSourcemapMode(options.serverSourceMaps),
12462
12857
  target: "bun"
12463
12858
  });
12464
- console.log(`[furin] Server bundle: ${toPosixPath(join8(targetManifest.targetDir, "server.js"))}`);
12465
- targetManifest.serverPath = toPosixPath(join8(targetManifest.targetDir, "server.js"));
12859
+ relocateServerMaps(serverBuild, options.serverSourceMaps, targetDir, buildRoot);
12860
+ writeServerMetafile(serverBuild, options.analyze, buildRoot);
12861
+ console.log(`[furin] Server bundle: ${toPosixPath(join10(targetManifest.targetDir, "server.js"))}`);
12862
+ targetManifest.serverPath = toPosixPath(join10(targetManifest.targetDir, "server.js"));
12466
12863
  }
12467
12864
  return targetManifest;
12468
12865
  }
12469
12866
 
12470
12867
  // src/adapter/package.ts
12471
- import { existsSync as existsSync8, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
12472
- import { join as join9, relative as relative5, resolve as resolve5 } from "path";
12868
+ import { existsSync as existsSync9, rmSync as rmSync3, writeFileSync as writeFileSync6 } from "fs";
12869
+ import { join as join11, relative as relative7, resolve as resolve7 } from "path";
12473
12870
  async function buildPackageTarget(app, rootDir, buildRoot, options) {
12474
12871
  const { prefix, root, routes, pagesDir } = app;
12475
12872
  const modulePaths = routeSourcePaths(app);
12476
- const targetDir = join9(buildRoot, "package");
12873
+ const targetDir = join11(buildRoot, "package");
12477
12874
  rmSync3(targetDir, { force: true, recursive: true });
12478
12875
  ensureDir(targetDir);
12479
12876
  const { entryChunk, cssChunks } = await buildClient(routes, {
12480
12877
  basePath: prefix,
12481
12878
  clientLogging: options.clientLogging ?? false,
12482
- metafilePath: options.analyze ? join9(buildRoot, "analysis", "package-client.json") : undefined,
12879
+ metafilePath: options.analyze ? join11(buildRoot, "analysis", "package-client.json") : undefined,
12483
12880
  optimizeImports: options.optimizeImports,
12484
12881
  outDir: targetDir,
12485
12882
  pagesDir,
@@ -12491,13 +12888,13 @@ async function buildPackageTarget(app, rootDir, buildRoot, options) {
12491
12888
  const buildFingerprint = await createBuildFingerprint(`${prefix}
12492
12889
  ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12493
12890
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
12494
- const clientDir = join9(targetDir, "client");
12495
- const publicDir = join9(rootDir, "public");
12496
- if (existsSync8(publicDir)) {
12497
- copyDirRecursive(publicDir, join9(targetDir, "public"));
12891
+ const clientDir = join11(targetDir, "client");
12892
+ const publicDir = join11(rootDir, "public");
12893
+ if (existsSync9(publicDir)) {
12894
+ copyDirRecursive(publicDir, join11(targetDir, "public"));
12498
12895
  }
12499
12896
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
12500
- writeFileSync4(join9(clientDir, "index.html"), indexHtml);
12897
+ writeFileSync6(join11(clientDir, "index.html"), indexHtml);
12501
12898
  setProductionTemplateContent(indexHtml);
12502
12899
  ssgRouteCache().clear();
12503
12900
  const ssgCache = await buildSSGCacheSnapshot(routes, root, "http://localhost", prefix);
@@ -12522,7 +12919,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12522
12919
  buildId,
12523
12920
  clientLogging: options.clientLogging ?? false,
12524
12921
  modulePaths,
12525
- nativeRoutes: routeModuleSpecifier(app),
12922
+ nativeRoutes: composableRouteModuleSpecifier(app),
12526
12923
  prefix,
12527
12924
  rootConventions,
12528
12925
  rootPath: root.path,
@@ -12534,7 +12931,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12534
12931
  headerComment: "// Auto-generated by `furin build --target package` \u2014 do not edit",
12535
12932
  mode: "register"
12536
12933
  });
12537
- const registerEntry = join9(targetDir, "register.ts");
12934
+ const registerEntry = join11(targetDir, "register.ts");
12538
12935
  const register = createVirtualBuildEntry(registerEntry, registerSource, "ts");
12539
12936
  const result = await runBunBuild({
12540
12937
  entrypoints: [register.entrypoint],
@@ -12554,7 +12951,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12554
12951
  if (!result.success) {
12555
12952
  throw new AggregateError(result.logs, "[furin] package register build failed");
12556
12953
  }
12557
- const relativePagesDir = toPosixPath(relative5(targetDir, resolve5(rootDir, pagesDir)));
12954
+ const relativePagesDir = toPosixPath(relative7(targetDir, resolve7(rootDir, pagesDir)));
12558
12955
  const factorySource = `// Auto-generated by \`furin build --target package\` \u2014 do not edit
12559
12956
  import { fileURLToPath } from "node:url";
12560
12957
  import { furin } from "@teyik0/furin";
@@ -12581,7 +12978,7 @@ export function createFurinApp(options = {}) {
12581
12978
 
12582
12979
  export const prefix = ${JSON.stringify(prefix)};
12583
12980
  `;
12584
- writeFileSync4(join9(targetDir, "index.js"), factorySource);
12981
+ writeFileSync6(join11(targetDir, "index.js"), factorySource);
12585
12982
  const dtsSource = `import type { FurinOptions, furin } from "@teyik0/furin";
12586
12983
 
12587
12984
  /** Extra furin() options \u2014 pagesDir/prefix/clientDir are baked into the package and cannot be overridden. */
@@ -12589,29 +12986,29 @@ export type CreateFurinAppOptions = Omit<FurinOptions, "pagesDir" | "prefix" | "
12589
12986
  export declare function createFurinApp(options?: CreateFurinAppOptions): ReturnType<typeof furin>;
12590
12987
  export declare const prefix: string;
12591
12988
  `;
12592
- writeFileSync4(join9(targetDir, "index.d.ts"), dtsSource);
12593
- console.log(`[furin] Package artifact: ${toPosixPath(relative5(rootDir, targetDir))}`);
12989
+ writeFileSync6(join11(targetDir, "index.d.ts"), dtsSource);
12990
+ console.log(`[furin] Package artifact: ${toPosixPath(relative7(rootDir, targetDir))}`);
12594
12991
  return {
12595
12992
  buildId,
12596
12993
  generatedAt: new Date().toISOString(),
12597
12994
  prefix,
12598
- targetDir: toPosixPath(relative5(rootDir, targetDir))
12995
+ targetDir: toPosixPath(relative7(rootDir, targetDir))
12599
12996
  };
12600
12997
  }
12601
12998
 
12602
12999
  // src/adapter/static.ts
12603
- import { cpSync as cpSync2, existsSync as existsSync9, rmSync as rmSync4, writeFileSync as writeFileSync5 } from "fs";
12604
- import { dirname as dirname7, isAbsolute as isAbsolute2, join as join10, relative as relative6, resolve as resolve6, sep as sep2 } from "path";
13000
+ import { cpSync as cpSync2, existsSync as existsSync10, rmSync as rmSync4, writeFileSync as writeFileSync7 } from "fs";
13001
+ import { dirname as dirname10, isAbsolute as isAbsolute4, join as join12, parse as parse3, relative as relative8, resolve as resolve8, sep as sep2, win32 } from "path";
12605
13002
  var STATIC_CONCURRENCY = 4;
12606
13003
  var DYNAMIC_SEGMENT_RE2 = /\/:[^/]+|\/\*/;
12607
13004
  var TRAILING_SLASHES_RE = /\/+$/;
12608
13005
  var STATIC_RENDER_ORIGIN = "http://localhost";
12609
13006
  function pathToOutputFile(urlPath, outDir, fileName) {
12610
- const normalizedOutDir = resolve6(outDir);
13007
+ const normalizedOutDir = resolve8(outDir);
12611
13008
  if (urlPath === "/" || urlPath === "") {
12612
- return join10(normalizedOutDir, fileName);
13009
+ return join12(normalizedOutDir, fileName);
12613
13010
  }
12614
- const resolved = resolve6(normalizedOutDir, urlPath.slice(1), fileName);
13011
+ const resolved = resolve8(normalizedOutDir, urlPath.slice(1), fileName);
12615
13012
  if (!resolved.startsWith(`${normalizedOutDir}${sep2}`)) {
12616
13013
  throw new Error(`[furin] static: unsafe output path detected for URL "${urlPath}" \u2014 path traversal via ".." is not allowed.`);
12617
13014
  }
@@ -12684,22 +13081,22 @@ async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, sk
12684
13081
  throw new Error(`[furin] static: route "${route.pattern}" returned a response that cannot be exported.`);
12685
13082
  }
12686
13083
  const staticLocation = resolveStaticRedirectLocation(location, basePath, urlPath);
12687
- ensureDir(dirname7(htmlOutputFile));
12688
- writeFileSync5(htmlOutputFile, createStaticRedirectHtml(staticLocation.html));
13084
+ ensureDir(dirname10(htmlOutputFile));
13085
+ writeFileSync7(htmlOutputFile, createStaticRedirectHtml(staticLocation.html));
12689
13086
  if (staticLocation.spa !== null) {
12690
13087
  const serializedRedirect = await toCrossJSONAsync({
12691
13088
  __furinRedirect: staticLocation.spa
12692
13089
  });
12693
- writeFileSync5(dataOutputFile, `${JSON.stringify(serializedRedirect)}
13090
+ writeFileSync7(dataOutputFile, `${JSON.stringify(serializedRedirect)}
12694
13091
  `);
12695
13092
  }
12696
13093
  renderedRoutes.push(urlPath);
12697
13094
  console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)} (redirects to ${staticLocation.html})`);
12698
13095
  return;
12699
13096
  }
12700
- ensureDir(dirname7(htmlOutputFile));
12701
- writeFileSync5(htmlOutputFile, entry.html);
12702
- writeFileSync5(dataOutputFile, entry.ndjson);
13097
+ ensureDir(dirname10(htmlOutputFile));
13098
+ writeFileSync7(htmlOutputFile, entry.html);
13099
+ writeFileSync7(dataOutputFile, entry.ndjson);
12703
13100
  renderedRoutes.push(urlPath);
12704
13101
  console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)}`);
12705
13102
  } catch (err) {
@@ -12732,13 +13129,13 @@ async function buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRo
12732
13129
  if (!DYNAMIC_SEGMENT_RE2.test(route.pattern)) {
12733
13130
  return { paramSets: [{}], route };
12734
13131
  }
12735
- if (!route.page.staticParams) {
13132
+ if (!hasStaticParams(route)) {
12736
13133
  console.warn(`[furin] static: skipping dynamic route "${route.pattern}" \u2014 no staticParams() defined.`);
12737
13134
  skippedRoutes.push(route.pattern);
12738
13135
  return { paramSets: null, route };
12739
13136
  }
12740
13137
  try {
12741
- const paramSets = await route.page.staticParams() ?? [];
13138
+ const paramSets = await resolveStaticParams(route, STATIC_RENDER_ORIGIN) ?? [];
12742
13139
  return { paramSets, route };
12743
13140
  } catch (err) {
12744
13141
  return { error: err, paramSets: null, route };
@@ -12805,15 +13202,16 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
12805
13202
  if (basePath && !basePath.startsWith("/")) {
12806
13203
  throw new Error(`[furin] static: basePath must start with "/" (received "${rawBasePath}"). ` + `Use "" for root deployments or "/sub-path" for sub-path deployments.`);
12807
13204
  }
12808
- const outDir = resolve6(rootDir, staticConfig.outDir ?? "dist");
12809
- const normalizedRoot = resolve6(rootDir);
12810
- const normalizedBuildRoot = resolve6(buildRoot);
12811
- if (outDir === normalizedRoot || outDir === normalizedBuildRoot || outDir === "/" || outDir === ".") {
13205
+ const rawOutDir = staticConfig.outDir ?? "dist";
13206
+ const outDir = resolve8(rootDir, rawOutDir);
13207
+ const normalizedRoot = resolve8(rootDir);
13208
+ const normalizedBuildRoot = resolve8(buildRoot);
13209
+ if (outDir === normalizedRoot || outDir === normalizedBuildRoot || outDir === parse3(outDir).root || rawOutDir === win32.parse(rawOutDir).root) {
12812
13210
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
12813
13211
  }
12814
13212
  function isOutsideOutDir(target) {
12815
- const rel = relative6(outDir, target);
12816
- return rel.startsWith("..") || isAbsolute2(rel);
13213
+ const rel = relative8(outDir, target);
13214
+ return rel.startsWith("..") || isAbsolute4(rel);
12817
13215
  }
12818
13216
  if (!(isOutsideOutDir(normalizedRoot) && isOutsideOutDir(normalizedBuildRoot))) {
12819
13217
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
@@ -12829,36 +13227,36 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
12829
13227
  const afterQueueCount = skippedRoutes.length;
12830
13228
  rmSync4(outDir, { force: true, recursive: true });
12831
13229
  ensureDir(outDir);
12832
- const targetDir = join10(buildRoot, "static");
13230
+ const targetDir = join12(buildRoot, "static");
12833
13231
  rmSync4(targetDir, { force: true, recursive: true });
12834
13232
  ensureDir(targetDir);
12835
13233
  const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
12836
13234
  basePath,
12837
13235
  clientLogging: Boolean(options.clientLogging),
12838
- metafilePath: options.analyze ? join10(buildRoot, "analysis", "static-client.json") : undefined,
13236
+ metafilePath: options.analyze ? join12(buildRoot, "analysis", "static-client.json") : undefined,
12839
13237
  optimizeImports: options.optimizeImports,
12840
13238
  outDir: targetDir,
12841
- pagesDir: dirname7(root.path),
13239
+ pagesDir: dirname10(root.path),
12842
13240
  plugins: options.plugins,
12843
13241
  publicPath,
12844
13242
  reactCompiler: options.reactCompiler,
12845
13243
  rootLayout: root.path
12846
13244
  });
12847
- const publicFavicon = join10(rootDir, "public", "favicon.ico");
12848
- const faviconHref = existsSync9(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
13245
+ const publicFavicon = join12(rootDir, "public", "favicon.ico");
13246
+ const faviconHref = existsSync10(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
12849
13247
  const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref, true);
12850
13248
  setProductionTemplateContent(shellHtml);
12851
- const publicSrcDir = join10(rootDir, "public");
12852
- if (existsSync9(publicSrcDir)) {
13249
+ const publicSrcDir = join12(rootDir, "public");
13250
+ if (existsSync10(publicSrcDir)) {
12853
13251
  cpSync2(publicSrcDir, outDir, { recursive: true });
12854
13252
  }
12855
- const clientSrcDir = join10(targetDir, "client");
12856
- if (existsSync9(clientSrcDir)) {
12857
- cpSync2(clientSrcDir, join10(outDir, "_client"), { recursive: true });
13253
+ const clientSrcDir = join12(targetDir, "client");
13254
+ if (existsSync10(clientSrcDir)) {
13255
+ cpSync2(clientSrcDir, join12(outDir, "_client"), { recursive: true });
12858
13256
  }
12859
13257
  await runWithConcurrency(tasks, STATIC_CONCURRENCY);
12860
13258
  assertNoPrerenderSkips(onSSR, skippedRoutes, afterQueueCount);
12861
- writeFileSync5(join10(outDir, "404.html"), shellHtml);
13259
+ writeFileSync7(join12(outDir, "404.html"), shellHtml);
12862
13260
  console.log("[furin] static: wrote 404.html (SPA shell fallback)");
12863
13261
  rmSync4(targetDir, { force: true, recursive: true });
12864
13262
  console.log(`[furin] static: export complete \u2192 ${toPosixPath(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
@@ -12872,32 +13270,24 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
12872
13270
  }
12873
13271
 
12874
13272
  // src/adapter/vercel.ts
12875
- import {
12876
- cpSync as cpSync3,
12877
- existsSync as existsSync10,
12878
- readFileSync as readFileSync4,
12879
- rmSync as rmSync5,
12880
- statSync as statSync3,
12881
- symlinkSync,
12882
- writeFileSync as writeFileSync6
12883
- } from "fs";
12884
- import { basename as basename5, dirname as dirname8, extname as extname3, join as join11, relative as relative7 } from "path";
13273
+ import { cpSync as cpSync3, existsSync as existsSync11, readFileSync as readFileSync5, rmSync as rmSync5, symlinkSync, writeFileSync as writeFileSync8 } from "fs";
13274
+ import { basename as basename5, dirname as dirname11, extname as extname3, join as join13, relative as relative9 } from "path";
12885
13275
  import { fileURLToPath as fileURLToPath6, pathToFileURL as pathToFileURL2 } from "url";
12886
13276
  init_patterns();
12887
13277
  var ISR_PATH_PARAM = "__furin_path";
12888
13278
  var DYNAMIC_SEGMENT_RE3 = /\/:[^/]+|\/\*/;
12889
- var ELYSIA_STATIC_IMPORT_RE = /^@elysiajs\/static$/;
13279
+ var ELYSIA_STATIC_IMPORT_RE = /^@elysia\/static$/;
12890
13280
  var MATCH_ALL_RE = /.*/;
12891
13281
  var REGEX_META_RE = /[.*+?^${}()|[\]\\]/;
12892
13282
  var UNSAFE_FUNCTION_PATH_RE = /[^a-zA-Z0-9_.[\]/-]/g;
12893
13283
  var VERCEL_FUNCTIONS_PATH = fileURLToPath6(import.meta.resolve("@vercel/functions"));
12894
13284
  var VERCEL_RUNTIME_STUB_NAMESPACE = "furin-vercel-runtime-stub";
12895
- var FURIN_RUNTIME_ROOT2 = dirname8(import.meta.dir);
13285
+ var FURIN_RUNTIME_ROOT2 = dirname11(import.meta.dir);
12896
13286
  function isFurinRuntimeImporter(importer) {
12897
13287
  if (importer === "") {
12898
13288
  return false;
12899
13289
  }
12900
- const fromRuntimeRoot = relative7(FURIN_RUNTIME_ROOT2, importer.split("?")[0]);
13290
+ const fromRuntimeRoot = relative9(FURIN_RUNTIME_ROOT2, importer.split("?")[0]);
12901
13291
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
12902
13292
  }
12903
13293
  function vercelRuntimePlugin() {
@@ -12906,11 +13296,11 @@ function vercelRuntimePlugin() {
12906
13296
  setup(build) {
12907
13297
  build.onResolve({ filter: ELYSIA_STATIC_IMPORT_RE }, ({ importer }) => {
12908
13298
  if (!isFurinRuntimeImporter(importer)) {
12909
- throw new Error("[furin] Application @elysiajs/static mounts are not supported by the Vercel target. Put CDN assets under public/ instead.");
13299
+ throw new Error("[furin] Application @elysia/static mounts are not supported by the Vercel target. Put CDN assets under public/ instead.");
12910
13300
  }
12911
13301
  return {
12912
13302
  namespace: VERCEL_RUNTIME_STUB_NAMESPACE,
12913
- path: "@elysiajs/static"
13303
+ path: "@elysia/static"
12914
13304
  };
12915
13305
  });
12916
13306
  build.onLoad({ filter: MATCH_ALL_RE, namespace: VERCEL_RUNTIME_STUB_NAMESPACE }, () => ({
@@ -12923,8 +13313,8 @@ function vercelRuntimePlugin() {
12923
13313
  };
12924
13314
  }
12925
13315
  function frameworkVersion() {
12926
- const packageRoot = dirname8(dirname8(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
12927
- const packageJson = JSON.parse(readFileSync4(join11(packageRoot, "package.json"), "utf8"));
13316
+ const packageRoot = dirname11(dirname11(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
13317
+ const packageJson = JSON.parse(readFileSync5(join13(packageRoot, "package.json"), "utf8"));
12928
13318
  return packageJson.version;
12929
13319
  }
12930
13320
  function serverEntryLoader(serverEntry) {
@@ -12942,10 +13332,15 @@ function serverEntryLoader(serverEntry) {
12942
13332
  }
12943
13333
  function assertDefaultServerExport(serverEntry) {
12944
13334
  const transpiler = new Bun.Transpiler({ loader: serverEntryLoader(serverEntry) });
12945
- const { exports } = transpiler.scan(readFileSync4(serverEntry, "utf8"));
13335
+ const { exports, imports } = transpiler.scan(readFileSync5(serverEntry, "utf8"));
12946
13336
  if (!exports.includes("default")) {
12947
13337
  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.");
12948
13338
  }
13339
+ if (imports.some(({ path }) => ELYSIA_STATIC_IMPORT_RE.test(path))) {
13340
+ throw new AggregateError([
13341
+ new Error("[furin] Application @elysia/static mounts are not supported by the Vercel target. Put CDN assets under public/ instead.")
13342
+ ], "[furin] Vercel build rejected application static mounts.");
13343
+ }
12949
13344
  }
12950
13345
  function escapeRegex(value) {
12951
13346
  let escaped = "";
@@ -13035,9 +13430,9 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
13035
13430
  body = result.html;
13036
13431
  ({ status } = result);
13037
13432
  }
13038
- const fallbackPath = join11(dirname8(join11(functionsDir, spec.functionName)), fallback);
13039
- ensureDir(dirname8(fallbackPath));
13040
- writeFileSync6(fallbackPath, body);
13433
+ const fallbackPath = join13(dirname11(join13(functionsDir, spec.functionName)), fallback);
13434
+ ensureDir(dirname11(fallbackPath));
13435
+ writeFileSync8(fallbackPath, body);
13041
13436
  spec.config.fallback = fallback;
13042
13437
  spec.config.initialHeaders = {
13043
13438
  "content-type": contentType,
@@ -13048,9 +13443,9 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
13048
13443
  spec.config.initialStatus = status;
13049
13444
  }
13050
13445
  function createFunctionAlias(functionsDir, serverFunctionDir, functionName) {
13051
- const aliasPath = join11(functionsDir, `${functionName}.func`);
13052
- ensureDir(dirname8(aliasPath));
13053
- const target = relative7(dirname8(aliasPath), serverFunctionDir);
13446
+ const aliasPath = join13(functionsDir, `${functionName}.func`);
13447
+ ensureDir(dirname11(aliasPath));
13448
+ const target = relative9(dirname11(aliasPath), serverFunctionDir);
13054
13449
  symlinkSync(target, aliasPath, process.platform === "win32" ? "junction" : "dir");
13055
13450
  }
13056
13451
  function createExactPrerenderSpec(prerender, routePath) {
@@ -13120,7 +13515,7 @@ async function createPrerenderSpecs(apps, builds, functionsDir, pprResumeKey) {
13120
13515
  return compareRouteSpecificity(right.pattern, left.pattern);
13121
13516
  });
13122
13517
  }
13123
- function vercelEntrySource(apps, builds, prerenderSpecs, serverEntry, pprResumeKey) {
13518
+ function vercelEntrySource(apps, builds, prerenderSpecs, appEntry, pprResumeKey) {
13124
13519
  const routeCount = builds.reduce((count, build) => count + build.entryApp.routes.length, 0);
13125
13520
  const prerenderAliases = prerenderSpecs.map((spec) => [
13126
13521
  `/${spec.functionName}`,
@@ -13137,15 +13532,6 @@ function vercelEntrySource(apps, builds, prerenderSpecs, serverEntry, pprResumeK
13137
13532
  source: `^(?:${routePatternSource(app.prefix, route.pattern)})$`,
13138
13533
  tags: route.tags ?? []
13139
13534
  }))).sort((left, right) => compareRouteSpecificity(right.pattern, left.pattern)).map(({ source, tags }) => [source, tags]);
13140
- const contextSource = buildEntrySource({
13141
- apps: builds.map(({ entryApp, indexHtml }) => ({
13142
- ...entryApp,
13143
- embed: undefined,
13144
- serveAssets: false,
13145
- templateHtml: indexHtml
13146
- })),
13147
- headerComment: "// Auto-generated by `furin build --target vercel` \u2014 do not edit"
13148
- });
13149
13535
  return `import {
13150
13536
  addCacheTag,
13151
13537
  getCache as getVercelCache,
@@ -13158,12 +13544,11 @@ import {
13158
13544
  markExternalPrerenderRequest,
13159
13545
  restorePprResumeRequest,
13160
13546
  setCacheTagPurger,
13547
+ setRuntimeEvlogWaitUntil,
13161
13548
  setRuntimeCacheProvider,
13162
13549
  waitForPendingISRRevalidations,
13163
13550
  } from "@teyik0/furin/internal";
13164
13551
 
13165
- ${contextSource}
13166
-
13167
13552
  const prerenderAliases = new Map(
13168
13553
  ${JSON.stringify(prerenderAliases)}.map(([alias, source]) => [alias, new RegExp(source)])
13169
13554
  );
@@ -13183,6 +13568,7 @@ function encodeCacheTag(value) {
13183
13568
  setRuntimeCacheProvider({
13184
13569
  getCache: (options) => getVercelCache(options),
13185
13570
  });
13571
+ setRuntimeEvlogWaitUntil(waitUntil);
13186
13572
 
13187
13573
  async function purgeCacheTags(paths) {
13188
13574
  const purge = Promise.all([
@@ -13196,7 +13582,7 @@ setCachePurger(purgeCacheTags);
13196
13582
  setCacheTagPurger(purgeCacheTags);
13197
13583
 
13198
13584
  const serverInitStartedAt = performance.now();
13199
- const serverModule = await import(${JSON.stringify(toPosixPath(serverEntry))});
13585
+ const serverModule = await import(${JSON.stringify(toPosixPath(appEntry))});
13200
13586
  const app = serverModule.default;
13201
13587
  if (!app || typeof app.handle !== "function") {
13202
13588
  throw new TypeError("[furin] Vercel server entry must export the Elysia app as default.");
@@ -13281,10 +13667,10 @@ async function buildPprFallbacks(apps, builds, specs, functionsDir, rootDir, tar
13281
13667
  if (jobs.length === 0) {
13282
13668
  return;
13283
13669
  }
13284
- const resultPath = join11(targetDir, "ppr-results.json");
13670
+ const resultPath = join13(targetDir, "ppr-results.json");
13285
13671
  const requests = jobs.map(({ path, spec }) => `http://localhost/${spec.functionName}?${ISR_PATH_PARAM}=${encodeURIComponent(path)}`);
13286
13672
  const script = `
13287
- const handler = (await import(${JSON.stringify(pathToFileURL2(join11(functionsDir, "__server.func/index.js")).href)})).default;
13673
+ const handler = (await import(${JSON.stringify(pathToFileURL2(join13(functionsDir, "__server.func/index.js")).href)})).default;
13288
13674
  const results = [];
13289
13675
  for (const url of ${JSON.stringify(requests)}) {
13290
13676
  const response = await handler.fetch(new Request(url));
@@ -13311,7 +13697,7 @@ process.exit(0);
13311
13697
  ${stderr}
13312
13698
  ${stdout}`);
13313
13699
  }
13314
- const results = JSON.parse(readFileSync4(resultPath, "utf8"));
13700
+ const results = JSON.parse(readFileSync5(resultPath, "utf8"));
13315
13701
  for (const [index, job] of jobs.entries()) {
13316
13702
  const result = results[index];
13317
13703
  await addPrerenderFallback(job.spec, job.path, {
@@ -13383,6 +13769,7 @@ async function handle(request) {
13383
13769
  \`furin_server_init;dur=\${initialization.server_init_ms}\`,
13384
13770
  \`furin_handler_wait;dur=\${requestWaitMs}\`,
13385
13771
  \`furin_handler;dur=\${handlerMs}\`,
13772
+ ...(isFirstRequest ? ["furin_instance_first_request"] : []),
13386
13773
  ].join(", ");
13387
13774
  return appendServerTiming(response, serverTiming);
13388
13775
  }
@@ -13392,32 +13779,57 @@ export default { fetch: handle };
13392
13779
  }
13393
13780
  async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options) {
13394
13781
  assertDefaultServerExport(serverEntry);
13395
- const targetDir = join11(buildRoot, "vercel");
13396
- const outputDir = join11(rootDir, ".vercel", "output");
13397
- const staticDir = join11(outputDir, "static");
13398
- const functionsDir = join11(outputDir, "functions");
13399
- const serverFunctionDir = join11(functionsDir, "__server.func");
13782
+ const targetDir = join13(buildRoot, "vercel");
13783
+ const outputDir = join13(rootDir, ".vercel", "output");
13784
+ const staticDir = join13(outputDir, "static");
13785
+ const functionsDir = join13(outputDir, "functions");
13786
+ const serverFunctionDir = join13(functionsDir, "__server.func");
13400
13787
  rmSync5(targetDir, { force: true, recursive: true });
13788
+ rmSync5(join13(buildRoot, "private", "server-sourcemaps", "vercel"), {
13789
+ force: true,
13790
+ recursive: true
13791
+ });
13401
13792
  rmSync5(outputDir, { force: true, recursive: true });
13402
13793
  ensureDir(targetDir);
13403
13794
  ensureDir(staticDir);
13404
13795
  ensureDir(serverFunctionDir);
13405
13796
  const { builds, headlineBuildId } = await buildRuntimeAppsSequentially(apps, rootDir, targetDir, serverEntry, options, "vercel");
13406
- cpSync3(join11(targetDir, "server-codec.js"), join11(serverFunctionDir, "server-codec.js"));
13407
- const publicDir = join11(rootDir, "public");
13408
- if (existsSync10(publicDir)) {
13797
+ cpSync3(join13(targetDir, "server-codec.js"), join13(serverFunctionDir, "server-codec.js"));
13798
+ const publicDir = join13(rootDir, "public");
13799
+ if (existsSync11(publicDir)) {
13409
13800
  cpSync3(publicDir, staticDir, { recursive: true });
13801
+ for (const app of apps) {
13802
+ const appStaticDir = join13(staticDir, app.prefix.slice(1));
13803
+ const appPublicDir = join13(appStaticDir, "public");
13804
+ cpSync3(publicDir, appPublicDir, { recursive: true });
13805
+ const favicon = join13(publicDir, "favicon.ico");
13806
+ if (app.prefix !== "" && existsSync11(favicon)) {
13807
+ cpSync3(favicon, join13(appStaticDir, "favicon.ico"));
13808
+ }
13809
+ }
13410
13810
  }
13411
13811
  for (let appIndex = 0;appIndex < apps.length; appIndex += 1) {
13412
13812
  const app = apps[appIndex];
13413
13813
  const build = builds[appIndex];
13414
- const clientOutputDir = join11(staticDir, app.prefix.slice(1), "_client");
13814
+ const clientOutputDir = join13(staticDir, app.prefix.slice(1), "_client");
13415
13815
  cpSync3(build.clientDir, clientOutputDir, { recursive: true });
13416
13816
  }
13417
13817
  const pprResumeKey = crypto.randomUUID();
13418
13818
  const prerenderSpecs = await createPrerenderSpecs(apps, builds, functionsDir, pprResumeKey);
13419
- const entryPath = join11(serverFunctionDir, "_vercel-handler.ts");
13420
- const entry = createVirtualBuildEntry(entryPath, vercelEntrySource(apps, builds, prerenderSpecs, serverEntry, pprResumeKey), "ts");
13819
+ const appEntry = await materializeServerAppEntry({
13820
+ apps: builds.map(({ entryApp, indexHtml }) => ({
13821
+ ...entryApp,
13822
+ embed: undefined,
13823
+ serveAssets: false,
13824
+ templateHtml: indexHtml
13825
+ })),
13826
+ headerComment: "// Auto-generated by `furin build --target vercel` \u2014 do not edit",
13827
+ instances: apps,
13828
+ outDir: serverFunctionDir,
13829
+ serverEntry
13830
+ });
13831
+ const entryPath = join13(serverFunctionDir, "_vercel-handler.ts");
13832
+ const entry = createVirtualBuildEntry(entryPath, vercelEntrySource(apps, builds, prerenderSpecs, appEntry, pprResumeKey), "ts");
13421
13833
  const serverBuild = await runBunBuild({
13422
13834
  define: { "process.env.NODE_ENV": JSON.stringify("production") },
13423
13835
  entrypoints: [entry.entrypoint],
@@ -13435,26 +13847,30 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13435
13847
  ...options.plugins ?? [],
13436
13848
  createRoutesPlugin({ instances: apps, target: "server" }),
13437
13849
  isomorphicTransformPlugin("server"),
13438
- environmentGuardPlugin("ssr")
13850
+ environmentGuardPlugin("ssr"),
13851
+ elysiaAot(appEntry)
13439
13852
  ],
13440
- sourcemap: "none",
13853
+ sourcemap: options.serverSourceMaps ? "external" : "none",
13854
+ splitting: true,
13441
13855
  target: "bun"
13442
13856
  });
13857
+ if (options.serverSourceMaps) {
13858
+ movePrivateServerSourceMaps(serverFunctionDir, join13(buildRoot, "private", "server-sourcemaps", "vercel"), serverBuild.outputs.filter((output) => output.kind === "sourcemap").map((output) => output.path));
13859
+ }
13443
13860
  if (options.analyze) {
13444
13861
  if (serverBuild.metafile === undefined) {
13445
13862
  throw new Error("[furin] Vercel server build did not produce the requested metafile.");
13446
13863
  }
13447
- const metafilePath = join11(buildRoot, "analysis", "vercel-server.json");
13448
- ensureDir(dirname8(metafilePath));
13449
- writeFileSync6(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}
13864
+ const metafilePath = join13(buildRoot, "analysis", "vercel-server.json");
13865
+ ensureDir(dirname11(metafilePath));
13866
+ writeFileSync8(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}
13450
13867
  `);
13451
13868
  console.log(`[furin] Server metafile: ${toPosixPath(metafilePath)}`);
13452
13869
  }
13453
- const handlerPath = join11(serverFunctionDir, "handler.js");
13454
- const serverBundleBytes = existsSync10(handlerPath) ? statSync3(handlerPath).size : 0;
13455
- writeFileSync6(join11(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
13870
+ const serverBundleBytes = serverBuild.outputs.filter((output) => output.path.endsWith(".js")).reduce((total, output) => total + output.size, 0);
13871
+ writeFileSync8(join13(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
13456
13872
  await buildPprFallbacks(apps, builds, prerenderSpecs, functionsDir, rootDir, targetDir);
13457
- writeFileSync6(join11(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
13873
+ writeFileSync8(join13(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
13458
13874
  handler: "index.js",
13459
13875
  launcherType: "Nodejs",
13460
13876
  ...options.vercelConfig?.regions === undefined ? {} : { regions: options.vercelConfig.regions },
@@ -13465,7 +13881,7 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13465
13881
  `);
13466
13882
  for (const spec of prerenderSpecs) {
13467
13883
  createFunctionAlias(functionsDir, serverFunctionDir, spec.functionName);
13468
- writeFileSync6(join11(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
13884
+ writeFileSync8(join13(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
13469
13885
  `);
13470
13886
  }
13471
13887
  const assetRoutes = apps.map((app) => ({
@@ -13495,48 +13911,71 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13495
13911
  ],
13496
13912
  version: 3
13497
13913
  };
13498
- writeFileSync6(join11(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
13914
+ writeFileSync8(join13(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
13499
13915
  `);
13500
13916
  const ssgRoutes = builds.flatMap((build, index) => build.prerenders.filter((prerender) => prerender.route.mode === "ssg").map((prerender) => physicalPath(apps[index].prefix, prerender.path))).toSorted();
13501
13917
  const isrRoutes = apps.flatMap((app) => app.routes.filter((route) => route.mode === "isr").map((route) => physicalPath(app.prefix, route.pattern))).toSorted();
13502
- console.log(`[furin] Vercel output: ${toPosixPath(relative7(rootDir, outputDir))}`);
13918
+ console.log(`[furin] Vercel output: ${toPosixPath(relative9(rootDir, outputDir))}`);
13503
13919
  return {
13504
13920
  buildId: headlineBuildId,
13505
13921
  generatedAt: new Date().toISOString(),
13506
13922
  isrRoutes,
13507
- outputDir: toPosixPath(relative7(rootDir, outputDir)),
13508
- serverPath: toPosixPath(relative7(rootDir, serverFunctionDir)),
13923
+ outputDir: toPosixPath(relative9(rootDir, outputDir)),
13924
+ serverPath: toPosixPath(relative9(rootDir, serverFunctionDir)),
13509
13925
  ssgRoutes
13510
13926
  };
13511
13927
  }
13512
13928
 
13513
13929
  // src/config.ts
13514
- import { t as t2 } from "elysia";
13515
- var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare", "static", "package"];
13516
- var buildTargetSchema = t2.Union(BUILD_TARGETS.map((v) => t2.Literal(v)));
13517
- var compileTargetSchema = t2.Union([t2.Literal("server"), t2.Literal("embed")]);
13518
- var configSchema = t2.Object({
13519
- apps: t2.Optional(t2.Array(t2.Object({
13520
- pagesDir: t2.String(),
13521
- prefix: t2.Optional(t2.String())
13930
+ import { t } from "elysia";
13931
+ var BUILD_TARGETS = ["bun", "vercel", "static", "package"];
13932
+ var VERCEL_REGIONS = [
13933
+ "arn1",
13934
+ "bom1",
13935
+ "cdg1",
13936
+ "cle1",
13937
+ "cpt1",
13938
+ "dub1",
13939
+ "dxb1",
13940
+ "fra1",
13941
+ "gru1",
13942
+ "hkg1",
13943
+ "hnd1",
13944
+ "iad1",
13945
+ "icn1",
13946
+ "kix1",
13947
+ "lhr1",
13948
+ "pdx1",
13949
+ "sfo1",
13950
+ "sin1",
13951
+ "syd1",
13952
+ "yul1"
13953
+ ];
13954
+ var buildTargetSchema = t.Union(BUILD_TARGETS.map((v) => t.Literal(v)));
13955
+ var compileTargetSchema = t.Union([t.Literal("server"), t.Literal("embed")]);
13956
+ var configSchema = t.Object({
13957
+ apps: t.Optional(t.Array(t.Object({
13958
+ pagesDir: t.String(),
13959
+ prefix: t.Optional(t.String())
13522
13960
  }))),
13523
- bun: t2.Optional(t2.Object({
13524
- compile: t2.Optional(compileTargetSchema)
13961
+ bun: t.Optional(t.Object({
13962
+ compile: t.Optional(compileTargetSchema)
13525
13963
  })),
13526
- clientLogging: t2.Optional(t2.Boolean()),
13527
- optimizeImports: t2.Optional(t2.Array(t2.String())),
13528
- pagesDir: t2.Optional(t2.String()),
13529
- reactCompiler: t2.Optional(t2.Boolean()),
13530
- rootDir: t2.Optional(t2.String()),
13531
- serverEntry: t2.Optional(t2.String()),
13532
- static: t2.Optional(t2.Object({
13533
- basePath: t2.Optional(t2.String()),
13534
- onSSR: t2.Optional(t2.Union([t2.Literal("error"), t2.Literal("skip")])),
13535
- outDir: t2.Optional(t2.String())
13964
+ clientLogging: t.Optional(t.Boolean()),
13965
+ optimizeImports: t.Optional(t.Array(t.String())),
13966
+ pagesDir: t.Optional(t.String()),
13967
+ reactCompiler: t.Optional(t.Boolean()),
13968
+ rootDir: t.Optional(t.String()),
13969
+ serverEntry: t.Optional(t.String()),
13970
+ serverSourceMaps: t.Optional(t.Boolean()),
13971
+ static: t.Optional(t.Object({
13972
+ basePath: t.Optional(t.String()),
13973
+ onSSR: t.Optional(t.Union([t.Literal("error"), t.Literal("skip")])),
13974
+ outDir: t.Optional(t.String())
13536
13975
  })),
13537
- targets: t2.Optional(t2.Array(buildTargetSchema)),
13538
- vercel: t2.Optional(t2.Object({
13539
- regions: t2.Optional(t2.Array(t2.String({ pattern: "^[a-z]{3}[1-9][0-9]*$" }), {
13976
+ targets: t.Optional(t.Array(buildTargetSchema)),
13977
+ vercel: t.Optional(t.Object({
13978
+ regions: t.Optional(t.Array(t.Enum(VERCEL_REGIONS), {
13540
13979
  minItems: 1,
13541
13980
  uniqueItems: true
13542
13981
  }))
@@ -13547,9 +13986,9 @@ var configSchema = t2.Object({
13547
13986
  init_instance();
13548
13987
 
13549
13988
  // src/server/router/discovery.ts
13550
- import { existsSync as existsSync11 } from "fs";
13989
+ import { existsSync as existsSync12 } from "fs";
13551
13990
  import { readdir } from "fs/promises";
13552
- import { join as join12, parse as parse3 } from "path";
13991
+ import { join as join14, parse as parse4 } from "path";
13553
13992
 
13554
13993
  // src/server/internal.ts
13555
13994
  var _compileContexts = new Map;
@@ -13634,6 +14073,7 @@ function adaptDefinedLayout(route, parent, sourcePath) {
13634
14073
  requestLoader: route.requestLoader,
13635
14074
  revalidate: route.revalidate,
13636
14075
  sourcePath,
14076
+ staticParams: route.staticParams,
13637
14077
  tags: copyTags(route.tags)
13638
14078
  };
13639
14079
  }
@@ -13698,7 +14138,7 @@ async function scanPages(pagesDir) {
13698
14138
  async function scanRootLayout(pagesDir) {
13699
14139
  const rootPath = `${pagesDir}/root.tsx`;
13700
14140
  const ctx = getCompileContext();
13701
- if (!(existsSync11(rootPath) || ctx?.modules[rootPath])) {
14141
+ if (!(existsSync12(rootPath) || ctx?.modules[rootPath])) {
13702
14142
  throw new Error("[furin] root.tsx: not found.");
13703
14143
  }
13704
14144
  const mod = ctx?.modules[rootPath] ?? await import(rootPath);
@@ -13738,8 +14178,8 @@ function getSourceModuleCandidates(dir, name) {
13738
14178
  async function loadConventionComponent(dir, name) {
13739
14179
  const ctx = getCompileContext();
13740
14180
  for (const filePath of getSourceModuleCandidates(dir, name)) {
13741
- if (existsSync11(filePath) || ctx?.modules[filePath]) {
13742
- const moduleSpecifier = IS_DEV && existsSync11(filePath) ? `${filePath}?furin-server&t=${routeModuleSourceVersion(filePath)}` : filePath;
14181
+ if (existsSync12(filePath) || ctx?.modules[filePath]) {
14182
+ const moduleSpecifier = IS_DEV && existsSync12(filePath) ? `${filePath}?furin-server&t=${routeModuleSourceVersion(filePath)}` : filePath;
13743
14183
  const mod = ctx?.modules[filePath] ?? await import(moduleSpecifier);
13744
14184
  if (mod.default) {
13745
14185
  return { component: mod.default, path: filePath };
@@ -13757,7 +14197,7 @@ async function scanPageFiles(pagesDir, root) {
13757
14197
  continue;
13758
14198
  }
13759
14199
  const relativePath = routeRelativePath(pagesDir, absolutePath);
13760
- const fileName = parse3(relativePath).name;
14200
+ const fileName = parse4(relativePath).name;
13761
14201
  if (fileName.startsWith("_") || fileName === "root" || isConventionFileName(fileName)) {
13762
14202
  continue;
13763
14203
  }
@@ -13822,10 +14262,10 @@ async function resolveDefinedLayoutParent(pagePath, pagesDir, rootRoute) {
13822
14262
  for (const segment of segments) {
13823
14263
  directory = `${directory}/${segment}`;
13824
14264
  for (const candidate of getSourceModuleCandidates(directory, "_route")) {
13825
- if (!existsSync11(candidate)) {
14265
+ if (!existsSync12(candidate)) {
13826
14266
  continue;
13827
14267
  }
13828
- const layoutModule = await import(candidate);
14268
+ const layoutModule = await (IS_DEV ? import(`${candidate}?furin-server&t=${routeModuleSourceVersion(candidate)}`) : import(candidate));
13829
14269
  const layout = layoutModule.route;
13830
14270
  if (isDefinedRouteTerminal(layout) && typeof layout.layout === "function") {
13831
14271
  parent = adaptDefinedLayout(layout, parent, candidate);
@@ -13922,7 +14362,7 @@ async function collectPageFilePaths(dir) {
13922
14362
  const files = [];
13923
14363
  const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
13924
14364
  const resolved = await mapWithConcurrency(entries, DIR_SCAN_CONCURRENCY, async (entry) => {
13925
- const absolutePath = toPosixPath2(join12(dir, entry.name));
14365
+ const absolutePath = toPosixPath2(join14(dir, entry.name));
13926
14366
  if (entry.isDirectory()) {
13927
14367
  return await collectPageFilePaths(absolutePath);
13928
14368
  }
@@ -13939,9 +14379,9 @@ async function collectPageFilePaths(dir) {
13939
14379
 
13940
14380
  // src/build/scan-server.ts
13941
14381
  init_instance();
13942
- import { readFileSync as readFileSync5 } from "fs";
14382
+ import { readFileSync as readFileSync6 } from "fs";
13943
14383
  function scanFurinInstances(serverEntryPath) {
13944
- const code = readFileSync5(serverEntryPath, "utf8");
14384
+ const code = readFileSync6(serverEntryPath, "utf8");
13945
14385
  const lang = detectLangFromPath(serverEntryPath);
13946
14386
  if (lang === "dts") {
13947
14387
  return [];
@@ -14022,39 +14462,42 @@ function registerIsomorphicRuntimePlugin() {
14022
14462
  function resolveAppSpecs(options, serverEntry, rootDir) {
14023
14463
  if (options.apps && options.apps.length > 0) {
14024
14464
  return options.apps.map((app) => ({
14025
- pagesDir: resolve7(rootDir, app.pagesDir),
14465
+ pagesDir: resolve9(rootDir, app.pagesDir),
14026
14466
  prefix: normalizePrefix(app.prefix)
14027
14467
  }));
14028
14468
  }
14029
14469
  if (options.pagesDir) {
14030
- return [{ pagesDir: resolve7(rootDir, options.pagesDir), prefix: "" }];
14470
+ return [{ pagesDir: resolve9(rootDir, options.pagesDir), prefix: "" }];
14031
14471
  }
14032
14472
  if (serverEntry) {
14033
14473
  const detected = scanFurinInstances(serverEntry);
14034
14474
  if (detected.length > 0) {
14035
14475
  return detected.map((app) => ({
14036
- pagesDir: resolve7(rootDir, app.pagesDir),
14476
+ pagesDir: resolve9(rootDir, app.pagesDir),
14037
14477
  prefix: app.prefix
14038
14478
  }));
14039
14479
  }
14040
14480
  }
14041
- return [{ pagesDir: resolve7(rootDir, "src/pages"), prefix: "" }];
14481
+ return [{ pagesDir: resolve9(rootDir, "src/pages"), prefix: "" }];
14042
14482
  }
14043
14483
  async function buildApp(options) {
14044
- const rootDir = resolve7(options.rootDir ?? process.cwd());
14045
- const buildRoot = join13(rootDir, BUILD_OUTPUT_DIR);
14484
+ return withProductionBuild(() => buildAppInternal(options));
14485
+ }
14486
+ async function buildAppInternal(options) {
14487
+ const rootDir = resolve9(options.rootDir ?? process.cwd());
14488
+ const buildRoot = join15(rootDir, BUILD_OUTPUT_DIR);
14046
14489
  const serverEntry = (() => {
14047
14490
  if (options.target === "static" || options.target === "package") {
14048
14491
  return null;
14049
14492
  }
14050
14493
  if (options.serverEntry) {
14051
- const resolved = resolve7(rootDir, options.serverEntry);
14052
- if (existsSync12(resolved)) {
14494
+ const resolved = resolve9(rootDir, options.serverEntry);
14495
+ if (existsSync13(resolved)) {
14053
14496
  return resolved;
14054
14497
  }
14055
14498
  }
14056
- const entry = resolve7(rootDir, "src/server.ts");
14057
- if (!existsSync12(entry)) {
14499
+ const entry = resolve9(rootDir, "src/server.ts");
14500
+ if (!existsSync13(entry)) {
14058
14501
  throw new Error("[furin] Entrypoint server.ts not found");
14059
14502
  }
14060
14503
  return entry;
@@ -14094,12 +14537,12 @@ async function buildApp(options) {
14094
14537
  version: 1,
14095
14538
  generatedAt: new Date().toISOString(),
14096
14539
  rootDir: toPosixPath(rootDir),
14097
- pagesDir: toPosixPath(relative8(rootDir, primaryApp.pagesDir)),
14098
- rootPath: toPosixPath(relative8(rootDir, primaryApp.root.path)),
14099
- serverEntry: serverEntry ? toPosixPath(relative8(rootDir, serverEntry)) : null,
14540
+ pagesDir: toPosixPath(relative10(rootDir, primaryApp.pagesDir)),
14541
+ rootPath: toPosixPath(relative10(rootDir, primaryApp.root.path)),
14542
+ serverEntry: serverEntry ? toPosixPath(relative10(rootDir, serverEntry)) : null,
14100
14543
  routes: primaryApp.routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
14101
14544
  apps: apps.map((app) => ({
14102
- pagesDir: toPosixPath(relative8(rootDir, app.pagesDir)),
14545
+ pagesDir: toPosixPath(relative10(rootDir, app.pagesDir)),
14103
14546
  prefix: app.prefix,
14104
14547
  routes: app.routes.map((route) => toBuildRouteManifestEntry(route, rootDir))
14105
14548
  })),
@@ -14131,14 +14574,11 @@ async function buildApp(options) {
14131
14574
  }
14132
14575
  manifest.targets.vercel = await buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options);
14133
14576
  break;
14134
- case "node":
14135
- case "cloudflare":
14136
- throw new Error(`[furin] \`--target ${target}\` is planned but not implemented yet in this branch.`);
14137
14577
  default:
14138
14578
  throw new Error(`[furin] Unsupported build target "${target}"`);
14139
14579
  }
14140
14580
  }
14141
- writeFileSync7(join13(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
14581
+ writeFileSync9(join15(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
14142
14582
  `);
14143
14583
  return {
14144
14584
  manifest,
@@ -14150,18 +14590,19 @@ async function buildApp(options) {
14150
14590
  init_instance();
14151
14591
 
14152
14592
  // src/cli/config.ts
14153
- import { existsSync as existsSync13 } from "fs";
14154
- import { resolve as resolve8 } from "path";
14593
+ import { existsSync as existsSync14 } from "fs";
14594
+ import { resolve as resolve10 } from "path";
14155
14595
  import { pathToFileURL as pathToFileURL3 } from "url";
14156
- var compiledConfigSchema = TypeCompiler.Compile(configSchema);
14596
+ import { Validator as Validator2 } from "elysia";
14597
+ var compiledConfigSchema = Validator2.create(configSchema);
14157
14598
  var DEFAULT_CONFIG_FILENAMES = [
14158
14599
  "furin.config.ts",
14159
14600
  "furin.config.js",
14160
14601
  "furin.config.mjs"
14161
14602
  ];
14162
14603
  async function loadCliConfig(cwd, explicitConfigPath) {
14163
- const rootDir = resolve8(cwd);
14164
- const configPath = explicitConfigPath ? resolve8(rootDir, explicitConfigPath) : DEFAULT_CONFIG_FILENAMES.map((filename) => resolve8(rootDir, filename)).find((path) => existsSync13(path));
14604
+ const rootDir = resolve10(cwd);
14605
+ const configPath = explicitConfigPath ? resolve10(rootDir, explicitConfigPath) : DEFAULT_CONFIG_FILENAMES.map((filename) => resolve10(rootDir, filename)).find((path) => existsSync14(path));
14165
14606
  if (!configPath) {
14166
14607
  return {
14167
14608
  configPath: null,
@@ -14176,21 +14617,21 @@ async function loadCliConfig(cwd, explicitConfigPath) {
14176
14617
  }
14177
14618
  if (!compiledConfigSchema.Check(configToValidate)) {
14178
14619
  const [firstError] = compiledConfigSchema.Errors(configToValidate);
14179
- throw new Error(`[furin] Invalid config at ${configPath}: ${firstError?.message ?? "unknown error"} (path: ${firstError?.path ?? "/"})`);
14620
+ throw new Error(`[furin] Invalid config at ${configPath}: ${firstError?.message ?? "unknown error"} (path: ${firstError?.instancePath ?? "/"})`);
14180
14621
  }
14181
- const resolvedRootDir = resolve8(rootDir, configToValidate.rootDir ?? ".");
14622
+ const resolvedRootDir = resolve10(rootDir, configToValidate.rootDir ?? ".");
14182
14623
  return {
14183
14624
  ...configToValidate,
14184
14625
  configPath,
14185
- pagesDir: configToValidate.pagesDir ? resolve8(resolvedRootDir, configToValidate.pagesDir) : undefined,
14626
+ pagesDir: configToValidate.pagesDir ? resolve10(resolvedRootDir, configToValidate.pagesDir) : undefined,
14186
14627
  plugins,
14187
14628
  rootDir: resolvedRootDir
14188
14629
  };
14189
14630
  }
14190
14631
 
14191
14632
  // src/cli/preview.ts
14192
- import { existsSync as existsSync14 } from "fs";
14193
- import { isAbsolute as isAbsolute3, join as join14, relative as relative9, resolve as resolve9 } from "path";
14633
+ import { existsSync as existsSync15 } from "fs";
14634
+ import { isAbsolute as isAbsolute5, join as join16, relative as relative11, resolve as resolve11 } from "path";
14194
14635
  var LEADING_SLASHES_RE = /^\/+/;
14195
14636
  var TRAILING_SLASHES_RE2 = /\/+$/;
14196
14637
  function normalizeStaticPreviewBasePath(basePath) {
@@ -14208,15 +14649,15 @@ function startStaticPreview({
14208
14649
  port
14209
14650
  }) {
14210
14651
  const basePath = normalizeStaticPreviewBasePath(rawBasePath);
14211
- const distDir = resolve9(rawDistDir);
14212
- const indexPath = join14(distDir, "index.html");
14213
- const notFoundPath = join14(distDir, "404.html");
14214
- const faviconPath = join14(distDir, "favicon.ico");
14215
- if (!(existsSync14(indexPath) && existsSync14(notFoundPath))) {
14652
+ const distDir = resolve11(rawDistDir);
14653
+ const indexPath = join16(distDir, "index.html");
14654
+ const notFoundPath = join16(distDir, "404.html");
14655
+ const faviconPath = join16(distDir, "favicon.ico");
14656
+ if (!(existsSync15(indexPath) && existsSync15(notFoundPath))) {
14216
14657
  throw new Error(`[furin] preview: "${distDir}" is not a Furin static export. Run \`furin build --target static\` first.`);
14217
14658
  }
14218
14659
  const notFound = () => new Response(Bun.file(notFoundPath), { status: 404 });
14219
- const clientDir = join14(distDir, "_client");
14660
+ const clientDir = join16(distDir, "_client");
14220
14661
  const fetchStaticFile = async (request) => {
14221
14662
  const encodedPathname = new URL(request.url).pathname;
14222
14663
  let pathname;
@@ -14229,16 +14670,16 @@ function startStaticPreview({
14229
14670
  return notFound();
14230
14671
  }
14231
14672
  const logicalPath = pathname.slice(basePath.length).replace(LEADING_SLASHES_RE, "");
14232
- const exactPath = resolve9(distDir, logicalPath);
14233
- const relativePath = relative9(distDir, exactPath);
14234
- if (relativePath.startsWith("..") || isAbsolute3(relativePath)) {
14673
+ const exactPath = resolve11(distDir, logicalPath);
14674
+ const relativePath = relative11(distDir, exactPath);
14675
+ if (relativePath.startsWith("..") || isAbsolute5(relativePath)) {
14235
14676
  return notFound();
14236
14677
  }
14237
14678
  const exactFile = Bun.file(exactPath);
14238
14679
  if (!pathname.endsWith("/") && await exactFile.exists()) {
14239
14680
  return new Response(exactFile);
14240
14681
  }
14241
- const indexFile = Bun.file(join14(exactPath, "index.html"));
14682
+ const indexFile = Bun.file(join16(exactPath, "index.html"));
14242
14683
  if (await indexFile.exists()) {
14243
14684
  return new Response(indexFile);
14244
14685
  }
@@ -14254,7 +14695,7 @@ function startStaticPreview({
14254
14695
  routes: {
14255
14696
  ...entryRoutes,
14256
14697
  [`${basePath}/_client/*`]: { dir: clientDir },
14257
- "/favicon.ico": existsSync14(faviconPath) ? Bun.file(faviconPath) : notFound()
14698
+ "/favicon.ico": existsSync15(faviconPath) ? Bun.file(faviconPath) : notFound()
14258
14699
  }
14259
14700
  });
14260
14701
  }
@@ -14329,10 +14770,10 @@ if (command === "preview") {
14329
14770
  const values = rawValues;
14330
14771
  const config = await loadCliConfig(process.cwd(), values.config);
14331
14772
  const port = values.port === undefined ? 3000 : Number(values.port);
14332
- if (!(Number.isInteger(port) && port > 0 && port <= 65535)) {
14333
- bail(`Invalid preview port "${values.port}". Expected an integer between 1 and 65535.`);
14773
+ if (values.port !== undefined && !/^\d+$/.test(values.port) || !(Number.isInteger(port) && port >= 0 && port <= 65535)) {
14774
+ bail(`Invalid preview port "${values.port}". Expected an integer between 0 and 65535.`);
14334
14775
  }
14335
- const distDir = resolve10(config.rootDir, values.dir ?? config.static?.outDir ?? "dist");
14776
+ const distDir = resolve12(config.rootDir, values.dir ?? config.static?.outDir ?? "dist");
14336
14777
  const basePath = normalizeStaticPreviewBasePath(values.basePath ?? config.static?.basePath ?? "");
14337
14778
  const server = startStaticPreview({ basePath, distDir, port });
14338
14779
  log("Static preview ready");
@@ -14367,8 +14808,8 @@ if (command === "preview") {
14367
14808
  const config = await loadCliConfig(process.cwd(), values.config);
14368
14809
  const isServerlessTarget = target === "static" || target === "package";
14369
14810
  const resolvedServerEntry = isServerlessTarget ? undefined : (() => {
14370
- const entry = resolve10(config.rootDir, config.serverEntry ?? "src/server.ts");
14371
- if (!existsSync15(entry)) {
14811
+ const entry = resolve12(config.rootDir, config.serverEntry ?? "src/server.ts");
14812
+ if (!existsSync16(entry)) {
14372
14813
  const expected = config.serverEntry ?? "src/server.ts";
14373
14814
  throw new Error(`[furin] Entrypoint ${expected} not found`);
14374
14815
  }
@@ -14391,6 +14832,7 @@ if (command === "preview") {
14391
14832
  reactCompiler: config.reactCompiler,
14392
14833
  rootDir: config.rootDir,
14393
14834
  serverEntry: resolvedServerEntry,
14835
+ serverSourceMaps: config.serverSourceMaps,
14394
14836
  staticConfig: config.static,
14395
14837
  target,
14396
14838
  vercelConfig: config.vercel