@teyik0/furin 0.5.0-alpha.1 → 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 (61) hide show
  1. package/dist/build/entry-template.ts +3 -1
  2. package/dist/build/index.js +360 -219
  3. package/dist/build/private-server-sourcemaps.d.ts +2 -0
  4. package/dist/build/types.d.ts +2 -0
  5. package/dist/cli/index.js +363 -221
  6. package/dist/client/document.d.ts +2 -0
  7. package/dist/client/link.js +11 -0
  8. package/dist/client.js +11 -0
  9. package/dist/config.d.ts +7 -2
  10. package/dist/config.js +24 -1
  11. package/dist/furin.js +217 -82
  12. package/dist/rsc-client.js +9 -1
  13. package/dist/rsc.js +19 -7
  14. package/dist/server/browser-events/shutdown.d.ts +3 -0
  15. package/dist/server/cache/redis/index.d.ts +2 -0
  16. package/dist/server/cache/redis/index.js +67 -12
  17. package/dist/server/cache/redis/scripts.d.ts +5 -5
  18. package/dist/server/dev/plugin.d.ts +1 -0
  19. package/dist/server/evlog.d.ts +1 -1
  20. package/dist/server/internal.js +3 -1
  21. package/dist/server/production-server.d.ts +13 -0
  22. package/dist/server/production-server.js +2906 -0
  23. package/dist/server/router/hmr.d.ts +6 -0
  24. package/dist/server/router/hmr.production.d.ts +5 -0
  25. package/dist/server/router/plugin.d.ts +5 -1
  26. package/dist/server/sync/index.js +5 -2
  27. package/dist/server/sync/stream.d.ts +4 -0
  28. package/dist/shared/production-build.d.ts +2 -0
  29. package/package.json +8 -3
  30. package/src/adapter/bun.ts +74 -15
  31. package/src/adapter/vercel.ts +15 -1
  32. package/src/build/elysia-aot.ts +1 -1
  33. package/src/build/entry-template.ts +3 -1
  34. package/src/build/hydrate.ts +5 -1
  35. package/src/build/index.ts +5 -0
  36. package/src/build/private-server-sourcemaps.ts +20 -0
  37. package/src/build/server-app-entry.ts +3 -2
  38. package/src/build/types.ts +2 -0
  39. package/src/cli/index.ts +1 -0
  40. package/src/client/document.tsx +19 -0
  41. package/src/config.ts +30 -2
  42. package/src/furin.ts +37 -12
  43. package/src/rsc/codec.ts +11 -6
  44. package/src/rsc/render-error.ts +3 -1
  45. package/src/server/browser-events/plugin.ts +7 -0
  46. package/src/server/browser-events/shutdown.ts +32 -0
  47. package/src/server/cache/redis/index.ts +19 -2
  48. package/src/server/cache/redis/scripts.ts +47 -7
  49. package/src/server/dev/plugin.ts +10 -1
  50. package/src/server/evlog.ts +11 -4
  51. package/src/server/production-server.ts +135 -0
  52. package/src/server/render/document.tsx +7 -1
  53. package/src/server/render/ssr.ts +2 -1
  54. package/src/server/render/template.ts +5 -1
  55. package/src/server/router/discovery.ts +3 -1
  56. package/src/server/router/hmr.production.ts +11 -0
  57. package/src/server/router/hmr.ts +84 -77
  58. package/src/server/router/plugin.ts +76 -17
  59. package/src/server/router/schema-merge.ts +9 -2
  60. package/src/server/sync/stream.ts +43 -2
  61. package/src/shared/production-build.ts +20 -0
@@ -2832,7 +2832,7 @@ var init_toolkit = __esm(() => {
2832
2832
 
2833
2833
  // src/server/evlog.ts
2834
2834
  import { Elysia as Elysia2 } from "elysia";
2835
- var loggerStorage, integration, getRequestLogger;
2835
+ var loggerStorage, integration, getRequestLogger, runtimeWaitUntil;
2836
2836
  var init_evlog = __esm(() => {
2837
2837
  init_toolkit();
2838
2838
  loggerStorage = createLoggerStorage("Furin request context. Make sure the Furin plugin is registered before your routes.", "@teyik0/furin:evlog");
@@ -2853,6 +2853,7 @@ var init_evlog = __esm(() => {
2853
2853
  storage: loggerStorage.storage
2854
2854
  });
2855
2855
  getRequestLogger = loggerStorage.useLogger;
2856
+ runtimeWaitUntil = new Set;
2856
2857
  });
2857
2858
 
2858
2859
  // src/server/context-logger.ts
@@ -2899,7 +2900,7 @@ var IS_DEV = true;
2899
2900
  // src/server/dev/graph.ts
2900
2901
  import { randomUUID } from "crypto";
2901
2902
  import { readFileSync as readFileSync4, statSync as statSync2 } from "fs";
2902
- import { dirname as dirname6, extname as extname3 } from "path";
2903
+ import { dirname as dirname7, extname as extname3 } from "path";
2903
2904
  function normalizeModulePath(path) {
2904
2905
  return path.replaceAll("\\", "/");
2905
2906
  }
@@ -2908,7 +2909,7 @@ function resolveDevSourceImports(source, path, loader) {
2908
2909
  const transpiler = new Bun.Transpiler({ loader });
2909
2910
  for (const imported of transpiler.scanImports(source)) {
2910
2911
  try {
2911
- const resolved = normalizeModulePath(Bun.resolveSync(imported.path, dirname6(path)));
2912
+ const resolved = normalizeModulePath(Bun.resolveSync(imported.path, dirname7(path)));
2912
2913
  if (!resolved.includes("/node_modules/")) {
2913
2914
  imports.push(resolved);
2914
2915
  }
@@ -3383,15 +3384,23 @@ function injectDevDiagnosticClient(html, basePath) {
3383
3384
  }
3384
3385
  return html.includes("</head>") ? html.replace("</head>", `${script}</head>`) : `${script}${html}`;
3385
3386
  }
3387
+ var extensionErrorFilterScript = `window.addEventListener("unhandledrejection", (event) => {
3388
+ const stack = event.reason?.stack;
3389
+ if (typeof stack !== "string") return;
3390
+ const firstFrame = stack.match(/^(?:\\s*at [^\\n]*|[^\\n]*@[^\\n]*)/m)?.[0];
3391
+ if (firstFrame && /\\b(?:chrome|moz)-extension:\\/\\//.test(firstFrame)) {
3392
+ event.stopImmediatePropagation();
3393
+ }
3394
+ }, true);`;
3386
3395
  var init_plugin2 = () => {};
3387
3396
 
3388
3397
  // src/build/index.ts
3389
- import { existsSync as existsSync14, writeFileSync as writeFileSync10 } from "fs";
3390
- import { join as join16, relative as relative10, resolve as resolve9 } from "path";
3398
+ import { existsSync as existsSync15, writeFileSync as writeFileSync11 } from "fs";
3399
+ import { join as join17, relative as relative11, resolve as resolve9 } from "path";
3391
3400
 
3392
3401
  // src/adapter/bun.ts
3393
- import { existsSync as existsSync9, readFileSync as readFileSync6, rmSync as rmSync2 } from "fs";
3394
- import { join as join11, resolve as resolve6 } from "path";
3402
+ import { existsSync as existsSync10, readFileSync as readFileSync6, rmSync as rmSync2, writeFileSync as writeFileSync7 } from "fs";
3403
+ import { join as join12, resolve as resolve6 } from "path";
3395
3404
 
3396
3405
  // src/build/bun-build.ts
3397
3406
  function runBunBuild(config) {
@@ -3509,7 +3518,7 @@ function buildEntrySource(options) {
3509
3518
  "",
3510
3519
  "// Force production mode \u2014 Bun may inline process.env.NODE_ENV at bundle time.",
3511
3520
  "__setDevMode(false);",
3512
- 'process.env.NODE_ENV = "production";'
3521
+ ...mode === "boot" ? ['process.env.NODE_ENV = "production";'] : []
3513
3522
  ] : [],
3514
3523
  ...contextBlocks,
3515
3524
  "",
@@ -3535,7 +3544,9 @@ function buildEntrySource(options) {
3535
3544
  `const __serverModule = await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
3536
3545
  "export const app = __serverModule.default;",
3537
3546
  "export const port = __serverModule.port;",
3547
+ "export const idleTimeout = __serverModule.idleTimeout;",
3538
3548
  "export const startServer = __serverModule.startServer;",
3549
+ "export const onShutdown = __serverModule.onShutdown;",
3539
3550
  "export default __serverModule.default;",
3540
3551
  ""
3541
3552
  ] : []
@@ -3668,7 +3679,7 @@ export function handleWSResponse(){return e()}
3668
3679
  }
3669
3680
  function elysiaAot(entry) {
3670
3681
  const entryPath = resolve(entry);
3671
- const hooks = aotFactory({ entry, strip: "auto", target: "bun" });
3682
+ const hooks = aotFactory({ entry, strip: false, target: "bun" });
3672
3683
  return {
3673
3684
  name: "elysia-aot",
3674
3685
  async setup(build) {
@@ -3721,8 +3732,23 @@ function elysiaAot(entry) {
3721
3732
  };
3722
3733
  }
3723
3734
 
3735
+ // src/build/private-server-sourcemaps.ts
3736
+ import { existsSync as existsSync4, renameSync } from "fs";
3737
+ import { dirname as dirname3, isAbsolute, join as join4, relative as relative2 } from "path";
3738
+ function movePrivateServerSourceMaps(outputDir, privateDir, filenames) {
3739
+ for (const filename of filenames) {
3740
+ const source = isAbsolute(filename) ? filename : join4(outputDir, filename);
3741
+ if (!existsSync4(source)) {
3742
+ continue;
3743
+ }
3744
+ const destination = join4(privateDir, relative2(outputDir, source));
3745
+ ensureDir(dirname3(destination));
3746
+ renameSync(source, destination);
3747
+ }
3748
+ }
3749
+
3724
3750
  // src/build/production-instrumentation.ts
3725
- import { dirname as dirname3, relative as relative2, resolve as resolve2 } from "path";
3751
+ import { dirname as dirname4, relative as relative3, resolve as resolve2 } from "path";
3726
3752
  var INSTRUMENTATION_IMPORT = /(?:^|[/\\])devtools[/\\]instrumentation(?:\.ts|\.js)?$/;
3727
3753
  var DEV_PAGE_PLUGIN_IMPORT = /(?:^|[/\\])server[/\\]dev-page-plugin(?:\.ts|\.js)?$/;
3728
3754
  var DEV_RUNTIME_IMPORT = /(?:^|[/\\])server[/\\]dev[/\\](?:browser-events|diagnostics|graph|plugin)(?:\.ts|\.js)?$/;
@@ -3732,7 +3758,7 @@ var PRODUCTION_BOUNDARY_IMPORT = /(?:browser-events|instrumentation|dev-page-plu
3732
3758
  var PRODUCTION_STUB_NAMESPACE = "furin-production-runtime-stub";
3733
3759
  var FURIN_RUNTIME_ROOT = resolve2(import.meta.dir, "..");
3734
3760
  function isFurinRuntimePath(path) {
3735
- const fromRuntimeRoot = relative2(FURIN_RUNTIME_ROOT, path);
3761
+ const fromRuntimeRoot = relative3(FURIN_RUNTIME_ROOT, path);
3736
3762
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
3737
3763
  }
3738
3764
  function devBuildExport(path) {
@@ -3743,7 +3769,7 @@ function productionInstrumentationPlugin() {
3743
3769
  name: "furin-production-instrumentation",
3744
3770
  setup(build) {
3745
3771
  build.onResolve({ filter: PRODUCTION_BOUNDARY_IMPORT }, (args) => {
3746
- const importPath = resolve2(dirname3(args.importer), args.path);
3772
+ const importPath = resolve2(dirname4(args.importer), args.path);
3747
3773
  if (!isFurinRuntimePath(importPath)) {
3748
3774
  return;
3749
3775
  }
@@ -3777,18 +3803,18 @@ function productionInstrumentationPlugin() {
3777
3803
 
3778
3804
  // src/build/server-app-entry.ts
3779
3805
  import { writeFileSync } from "fs";
3780
- import { join as join5 } from "path";
3806
+ import { join as join6 } from "path";
3781
3807
 
3782
3808
  // src/plugin/routes.ts
3783
3809
  import {
3784
- existsSync as existsSync4,
3810
+ existsSync as existsSync5,
3785
3811
  readdirSync as readdirSync2,
3786
3812
  readFileSync,
3787
3813
  realpathSync,
3788
3814
  statSync,
3789
3815
  watch
3790
3816
  } from "fs";
3791
- import { dirname as dirname4, extname, isAbsolute, join as join4, relative as relative3, resolve as resolve3, sep } from "path";
3817
+ import { dirname as dirname5, extname, isAbsolute as isAbsolute2, join as join5, relative as relative4, resolve as resolve3, sep } from "path";
3792
3818
  import { pathToFileURL } from "url";
3793
3819
  import { Elysia } from "elysia";
3794
3820
 
@@ -3943,8 +3969,8 @@ function findSearchDefaultsForRouteTarget(to, routes) {
3943
3969
  init_patterns();
3944
3970
 
3945
3971
  // src/server/router/schema-merge.ts
3946
- import { t } from "elysia";
3947
3972
  var TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
3973
+ var TYPEBOX_OPTIONAL = Symbol.for("TypeBox.Optional");
3948
3974
  function mergeRouteSchemas(routeChain, key) {
3949
3975
  const schemas = routeChain.flatMap((route) => route[key] ? [route[key]] : []);
3950
3976
  if (schemas.length === 0) {
@@ -3958,7 +3984,13 @@ function mergeRouteSchemas(routeChain, key) {
3958
3984
  }
3959
3985
  const properties = Object.assign({}, ...schemas.map((schema) => schema.properties));
3960
3986
  const options = Object.assign({}, ...schemas.map((schema) => Object.fromEntries(Object.entries(schema).filter(([name]) => !TOBJECT_STRUCTURAL_KEYS.has(name)))));
3961
- return t.Object(properties, options);
3987
+ const required = Object.keys(properties).filter((name) => {
3988
+ const property = properties[name];
3989
+ return !(property["~optional"] || property[TYPEBOX_OPTIONAL]);
3990
+ });
3991
+ return Object.defineProperty({ ...options, properties, required, type: "object" }, "~kind", {
3992
+ value: "Object"
3993
+ });
3962
3994
  }
3963
3995
 
3964
3996
  // src/server/router/schemas.ts
@@ -4050,7 +4082,7 @@ function scanRouteFiles(directory, directorySegments, files) {
4050
4082
  if (entry.name.startsWith("_")) {
4051
4083
  continue;
4052
4084
  }
4053
- scanRouteFiles(join4(directory, entry.name), [...directorySegments, entry.name], files);
4085
+ scanRouteFiles(join5(directory, entry.name), [...directorySegments, entry.name], files);
4054
4086
  continue;
4055
4087
  }
4056
4088
  const extension = extname(entry.name);
@@ -4058,7 +4090,7 @@ function scanRouteFiles(directory, directorySegments, files) {
4058
4090
  continue;
4059
4091
  }
4060
4092
  const base = entry.name.slice(0, -extension.length);
4061
- const sourcePath = join4(directory, entry.name);
4093
+ const sourcePath = join5(directory, entry.name);
4062
4094
  for (const segment of [...directorySegments, base]) {
4063
4095
  parseDynamicRouteSegment(segment, sourcePath);
4064
4096
  }
@@ -4257,19 +4289,19 @@ function routeModuleCache() {
4257
4289
  return cache;
4258
4290
  }
4259
4291
  function findPackageRoot(sourcePath) {
4260
- const fallback = dirname4(sourcePath);
4292
+ const fallback = dirname5(sourcePath);
4261
4293
  let directory = fallback;
4262
- while (dirname4(directory) !== directory) {
4263
- if (existsSync4(join4(directory, "package.json"))) {
4294
+ while (dirname5(directory) !== directory) {
4295
+ if (existsSync5(join5(directory, "package.json"))) {
4264
4296
  return directory;
4265
4297
  }
4266
- directory = dirname4(directory);
4298
+ directory = dirname5(directory);
4267
4299
  }
4268
- return existsSync4(join4(directory, "package.json")) ? directory : fallback;
4300
+ return existsSync5(join5(directory, "package.json")) ? directory : fallback;
4269
4301
  }
4270
4302
  function isWithinDirectory(path, directory) {
4271
- const relativePath = relative3(directory, path);
4272
- return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute(relativePath));
4303
+ const relativePath = relative4(directory, path);
4304
+ return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute2(relativePath));
4273
4305
  }
4274
4306
  function isFurinPackageImport(specifier) {
4275
4307
  return specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/");
@@ -4286,8 +4318,8 @@ function resolveRouteModuleImports(dependencyPath, packageRoot) {
4286
4318
  continue;
4287
4319
  }
4288
4320
  try {
4289
- const resolvedImport = realpathSync(Bun.resolveSync(imported.path, dirname4(dependencyPath)));
4290
- if (isAbsolute(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot)) {
4321
+ const resolvedImport = realpathSync(Bun.resolveSync(imported.path, dirname5(dependencyPath)));
4322
+ if (isAbsolute2(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot)) {
4291
4323
  resolvedImports.push(resolvedImport);
4292
4324
  }
4293
4325
  } catch {}
@@ -4385,8 +4417,8 @@ function serverProxySource(instance, includeRootCatchAll) {
4385
4417
  function createRoutesPlugin(options) {
4386
4418
  const routeFilesBySpecifier = new Map;
4387
4419
  const routeFilesByResolvedPath = new Map;
4388
- const registryVirtualPath = join4(resolve3(primaryInstance(options.instances).pagesDir), ".furin-routes-registry.ts?furin-virtual");
4389
- const composableRegistryVirtualPath = join4(resolve3(primaryInstance(options.instances).pagesDir), ".furin-routes-registry-composable.ts?furin-virtual");
4420
+ const registryVirtualPath = join5(resolve3(primaryInstance(options.instances).pagesDir), ".furin-routes-registry.ts?furin-virtual");
4421
+ const composableRegistryVirtualPath = join5(resolve3(primaryInstance(options.instances).pagesDir), ".furin-routes-registry-composable.ts?furin-virtual");
4390
4422
  const instancesBySpecifier = new Map(options.instances.flatMap((instance) => [
4391
4423
  [
4392
4424
  routeModuleSpecifier(instance),
@@ -4446,7 +4478,7 @@ function createRoutesPlugin(options) {
4446
4478
  return {
4447
4479
  contents: await Bun.file(routeFile.sourcePath).text(),
4448
4480
  loader: detectLoaderFromPath(routeFile.sourcePath),
4449
- resolveDir: dirname4(routeFile.sourcePath)
4481
+ resolveDir: dirname5(routeFile.sourcePath)
4450
4482
  };
4451
4483
  });
4452
4484
  for (const { instance, namespace, includeRootCatchAll } of instancesBySpecifier.values()) {
@@ -4467,11 +4499,11 @@ async function materializeServerAppEntry(options) {
4467
4499
  if (!instance) {
4468
4500
  throw new Error(`[furin] Missing route instance for server app ${index}.`);
4469
4501
  }
4470
- const routePath = join5(options.outDir, `_furin-routes-${index}.ts`);
4502
+ const routePath = join6(options.outDir, `_furin-routes-${index}.ts`);
4471
4503
  writeFileSync(routePath, await materializedRouteModuleSource(instance));
4472
4504
  return { ...app, nativeRoutes: toPosixPath(routePath) };
4473
4505
  }));
4474
- const entryPath = join5(options.outDir, "_furin-app.ts");
4506
+ const entryPath = join6(options.outDir, "_furin-app.ts");
4475
4507
  writeFileSync(entryPath, buildEntrySource({
4476
4508
  apps,
4477
4509
  headerComment: options.headerComment,
@@ -4482,7 +4514,8 @@ async function materializeServerAppEntry(options) {
4482
4514
  }
4483
4515
  function serverBootSource(appEntry) {
4484
4516
  return `// Auto-generated by furin build - do not edit
4485
- import app, { port, startServer } from ${JSON.stringify(toPosixPath(appEntry))};
4517
+ import { startProductionServer } from "@teyik0/furin/production-server";
4518
+ import app, { idleTimeout, onShutdown, port, startServer } from ${JSON.stringify(toPosixPath(appEntry))};
4486
4519
 
4487
4520
  if (typeof startServer === "function") {
4488
4521
  await startServer();
@@ -4490,7 +4523,7 @@ if (typeof startServer === "function") {
4490
4523
  const serverPort = process.env.PORT === undefined
4491
4524
  ? typeof port === "number" ? port : 3000
4492
4525
  : Number(process.env.PORT);
4493
- app.listen(serverPort);
4526
+ startProductionServer({ app, idleTimeout, onShutdown, port: serverPort });
4494
4527
  console.log(\`[furin] Server running at http://localhost:\${app.server?.port}\`);
4495
4528
  }
4496
4529
  `;
@@ -6951,13 +6984,13 @@ function assertNoPrefixSlugCollisions(prefixes) {
6951
6984
  }
6952
6985
 
6953
6986
  // src/adapter/runtime-build.ts
6954
- import { existsSync as existsSync8, writeFileSync as writeFileSync6 } from "fs";
6955
- import { basename as basename4, dirname as dirname8, isAbsolute as isAbsolute2, join as join10, relative as relative6, resolve as resolve5 } from "path";
6987
+ import { existsSync as existsSync9, writeFileSync as writeFileSync6 } from "fs";
6988
+ import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute3, join as join11, relative as relative7, resolve as resolve5 } from "path";
6956
6989
  import { fileURLToPath as fileURLToPath5 } from "url";
6957
6990
 
6958
6991
  // src/build/client.ts
6959
- import { existsSync as existsSync7, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "fs";
6960
- import { basename as basename2, dirname as dirname5, join as join8, resolve as resolve4 } from "path";
6992
+ import { existsSync as existsSync8, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "fs";
6993
+ import { basename as basename2, dirname as dirname6, join as join9, resolve as resolve4 } from "path";
6961
6994
 
6962
6995
  // src/plugin/transform-client.ts
6963
6996
  var FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
@@ -7594,8 +7627,8 @@ if (import.meta.hot && route?.component) {
7594
7627
  }
7595
7628
 
7596
7629
  // src/build/hydrate.ts
7597
- import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
7598
- import { join as join7 } from "path";
7630
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
7631
+ import { join as join8 } from "path";
7599
7632
 
7600
7633
  // src/server/render/shell.ts
7601
7634
  function escapeHtml(str) {
@@ -7649,8 +7682,8 @@ ${buildIdMeta}${modeMeta}${faviconLink}${cssLinks ? `${cssLinks}
7649
7682
  init_patterns();
7650
7683
 
7651
7684
  // src/build/route-types.ts
7652
- import { existsSync as existsSync5, readFileSync as readFileSync2, renameSync, writeFileSync as writeFileSync2 } from "fs";
7653
- import { extname as extname2, join as join6, relative as relative4 } from "path";
7685
+ import { existsSync as existsSync6, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "fs";
7686
+ import { extname as extname2, join as join7, relative as relative5 } from "path";
7654
7687
 
7655
7688
  // src/shared/route-map.ts
7656
7689
  function routeTypeProperty(pattern) {
@@ -7697,7 +7730,7 @@ function writeRouteTypes(routes, projectRoot) {
7697
7730
  const entries = routes.map((route) => {
7698
7731
  const extension = extname2(route.path);
7699
7732
  const sourcePath = extension ? route.path.slice(0, -extension.length) : route.path;
7700
- const relativePath = relative4(projectRoot, sourcePath).replaceAll("\\", "/");
7733
+ const relativePath = relative5(projectRoot, sourcePath).replaceAll("\\", "/");
7701
7734
  const specifier = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
7702
7735
  return { importSpecifier: specifier, pattern: route.pattern };
7703
7736
  });
@@ -7716,14 +7749,14 @@ import "@teyik0/furin/routes";
7716
7749
 
7717
7750
  ${routeMapDeclaration(entries)}${tagBlock}
7718
7751
  `;
7719
- const typesPath = join6(projectRoot, "furin-env.d.ts");
7720
- const existing = existsSync5(typesPath) ? readFileSync2(typesPath, "utf8") : "";
7752
+ const typesPath = join7(projectRoot, "furin-env.d.ts");
7753
+ const existing = existsSync6(typesPath) ? readFileSync2(typesPath, "utf8") : "";
7721
7754
  if (content === existing) {
7722
7755
  return false;
7723
7756
  }
7724
7757
  const temporaryPath = `${typesPath}.${process.pid}.${Bun.nanoseconds()}.tmp`;
7725
7758
  writeFileSync2(temporaryPath, content);
7726
- renameSync(temporaryPath, typesPath);
7759
+ renameSync2(temporaryPath, typesPath);
7727
7760
  return true;
7728
7761
  }
7729
7762
 
@@ -7863,6 +7896,7 @@ const _match = routes.find((r) => r.regex.test(pathname));
7863
7896
  // a matched loader threw notFound(). The latter still has a _match; the
7864
7897
  // former does not \u2014 so the two cases fork on _match below.
7865
7898
  const dataEl = document.getElementById("__FURIN_DATA__");
7899
+ const frameTemplate = document.getElementById("__FURIN_ROUTE_FRAMES__") as HTMLTemplateElement | null;
7866
7900
  let loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
7867
7901
  const syncEl = document.getElementById("__FURIN_SYNC__");
7868
7902
  const syncConfig = syncEl ? JSON.parse(syncEl.textContent || "{}") : {};
@@ -7879,6 +7913,7 @@ const documentState: DocumentState = {
7879
7913
  assets: {
7880
7914
  buildId,
7881
7915
  entryModule: entryEl?.getAttribute("src") ?? undefined,
7916
+ extensionErrorFilterScript: document.querySelector("[data-furin-extension-error-filter]")?.textContent ?? undefined,
7882
7917
  faviconHref,
7883
7918
  frameworkModules,
7884
7919
  staticMode: document.querySelector('meta[name="furin-mode"][content="static"]') !== null,
@@ -7888,6 +7923,9 @@ const documentState: DocumentState = {
7888
7923
  },
7889
7924
  dataJson: dataEl?.textContent ?? undefined,
7890
7925
  head,
7926
+ routeFrames: frameTemplate?.hasAttribute("data-furin-document-state")
7927
+ ? (frameTemplate.content.textContent ?? "")
7928
+ : undefined,
7891
7929
  syncJson: syncEl?.textContent ?? undefined,
7892
7930
  };
7893
7931
 
@@ -7962,7 +8000,6 @@ if (__deferred && __deferred._chunks) {
7962
8000
  // Wrapped in an async IIFE to avoid top-level await, which causes Bun's HTML
7963
8001
  // bundler to misidentify which chunk to reference as the entry in index.html.
7964
8002
  (async () => {
7965
- const frameTemplate = document.getElementById("__FURIN_ROUTE_FRAMES__") as HTMLTemplateElement | null;
7966
8003
  if (frameTemplate) {
7967
8004
  const payload = frameTemplate.content.textContent || "";
7968
8005
  const routeFrameStream = (window as unknown as { __FURIN_ROUTE_FRAME_STREAM__?: FurinRouteFrameStream })
@@ -8090,20 +8127,20 @@ if (__deferred && __deferred._chunks) {
8090
8127
  `;
8091
8128
  }
8092
8129
  function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging, skipRouteTypes }, projectRoot) {
8093
- if (!existsSync6(outDir)) {
8130
+ if (!existsSync7(outDir)) {
8094
8131
  mkdirSync2(outDir, { recursive: true });
8095
8132
  }
8096
8133
  const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
8097
- const hydratePath = join7(outDir, "_hydrate.tsx");
8098
- const existingHydrate = existsSync6(hydratePath) ? readFileSync3(hydratePath, "utf8") : "";
8134
+ const hydratePath = join8(outDir, "_hydrate.tsx");
8135
+ const existingHydrate = existsSync7(hydratePath) ? readFileSync3(hydratePath, "utf8") : "";
8099
8136
  let changed = false;
8100
8137
  if (hydrateCode !== existingHydrate) {
8101
8138
  writeFileSync3(hydratePath, hydrateCode);
8102
8139
  changed = true;
8103
8140
  }
8104
8141
  const indexHtml = generateIndexHtml();
8105
- const indexPath = join7(outDir, "index.html");
8106
- const existingIndex = existsSync6(indexPath) ? readFileSync3(indexPath, "utf8") : "";
8142
+ const indexPath = join8(outDir, "index.html");
8143
+ const existingIndex = existsSync7(indexPath) ? readFileSync3(indexPath, "utf8") : "";
8107
8144
  if (indexHtml !== existingIndex) {
8108
8145
  writeFileSync3(indexPath, indexHtml);
8109
8146
  changed = true;
@@ -8136,15 +8173,15 @@ async function buildClient(routes, {
8136
8173
  pagesDir
8137
8174
  }) {
8138
8175
  const dirName = clientDirName ?? "client";
8139
- const clientDir = join8(outDir, dirName);
8140
- if (!existsSync7(outDir)) {
8176
+ const clientDir = join9(outDir, dirName);
8177
+ if (!existsSync8(outDir)) {
8141
8178
  mkdirSync3(outDir, { recursive: true });
8142
8179
  }
8143
- if (!existsSync7(clientDir)) {
8180
+ if (!existsSync8(clientDir)) {
8144
8181
  mkdirSync3(clientDir, { recursive: true });
8145
8182
  }
8146
8183
  const hydrateCode = resolveClientModuleSpecifiers(generateHydrateEntry(routes, rootLayout, basePath, clientLogging));
8147
- const hydratePath = join8(outDir, dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`);
8184
+ const hydratePath = join9(outDir, dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`);
8148
8185
  const hydrateEntry = createVirtualBuildEntry(hydratePath, hydrateCode, "tsx");
8149
8186
  console.log("[furin] Building production client bundle\u2026");
8150
8187
  const transformPlugin = {
@@ -8219,7 +8256,7 @@ async function buildClient(routes, {
8219
8256
  if (result.metafile === undefined) {
8220
8257
  throw new Error("[furin] client build did not produce the requested metafile");
8221
8258
  }
8222
- mkdirSync3(dirname5(metafilePath), { recursive: true });
8259
+ mkdirSync3(dirname6(metafilePath), { recursive: true });
8223
8260
  writeFileSync4(metafilePath, `${JSON.stringify(result.metafile, null, 2)}
8224
8261
  `);
8225
8262
  console.log(`[furin] Client metafile: ${metafilePath}`);
@@ -10068,6 +10105,10 @@ function HeadContent() {
10068
10105
  }
10069
10106
  return /* @__PURE__ */ jsxDEV(Fragment, {
10070
10107
  children: [
10108
+ state.assets.extensionErrorFilterScript === undefined ? null : /* @__PURE__ */ jsxDEV("script", {
10109
+ dangerouslySetInnerHTML: { __html: state.assets.extensionErrorFilterScript },
10110
+ "data-furin-extension-error-filter": ""
10111
+ }, undefined, false, undefined, this),
10071
10112
  /* @__PURE__ */ jsxDEV("meta", {
10072
10113
  charSet: "utf-8",
10073
10114
  "data-furin-head": ""
@@ -10125,6 +10166,13 @@ function Scripts() {
10125
10166
  id: "__FURIN_DATA__",
10126
10167
  type: "application/json"
10127
10168
  }, undefined, false, undefined, this),
10169
+ state.routeFrames === undefined ? null : /* @__PURE__ */ jsxDEV("template", {
10170
+ dangerouslySetInnerHTML: {
10171
+ __html: state.routeFrames.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
10172
+ },
10173
+ "data-furin-document-state": "",
10174
+ id: "__FURIN_ROUTE_FRAMES__"
10175
+ }, undefined, false, undefined, this),
10128
10176
  /* @__PURE__ */ jsxDEV("script", {
10129
10177
  dangerouslySetInnerHTML: { __html: serializeJson(state.head ?? {}) },
10130
10178
  "data-furin-scripts": "",
@@ -10405,6 +10453,21 @@ function cyrb53(input) {
10405
10453
  return 4294967296 * (2097151 & h2) + (4294967295 & h1);
10406
10454
  }
10407
10455
 
10456
+ // src/shared/production-build.ts
10457
+ var productionBuildScope;
10458
+ var productionBuildScopePromise;
10459
+ async function withProductionBuild(build) {
10460
+ productionBuildScopePromise ??= import("async_hooks").then(({ AsyncLocalStorage }) => {
10461
+ productionBuildScope = new AsyncLocalStorage;
10462
+ return productionBuildScope;
10463
+ });
10464
+ const scope = await productionBuildScopePromise;
10465
+ return scope.run(true, build);
10466
+ }
10467
+ function isProductionBuild() {
10468
+ return productionBuildScope?.getStore() === true || typeof process !== "undefined" && false;
10469
+ }
10470
+
10408
10471
  // src/rsc/shared.tsx
10409
10472
  import {
10410
10473
  Children,
@@ -10580,10 +10643,12 @@ function withDocumentState(element, assets, head, data) {
10580
10643
  ...assets,
10581
10644
  frameworkModules: [browserEventsClientPath, ...assets.frameworkModules]
10582
10645
  };
10646
+ const routeFrames = data !== undefined && containsRscSource(data) ? serializeRouteFrames(data, undefined) : undefined;
10583
10647
  const state = {
10584
10648
  assets: resolvedAssets,
10585
- dataJson: data === undefined ? undefined : safeJson(data),
10649
+ dataJson: data === undefined || routeFrames !== undefined ? undefined : safeJson(data),
10586
10650
  head,
10651
+ routeFrames,
10587
10652
  syncJson: syncPath === undefined ? undefined : safeJson({ path: syncPath })
10588
10653
  };
10589
10654
  return createElement3(DocumentProvider, { value: state }, element);
@@ -11339,7 +11404,9 @@ function errorStack(error) {
11339
11404
  return error instanceof Error ? error.stack : undefined;
11340
11405
  }
11341
11406
  function renderErrorMessage(options) {
11342
- if (typeof process !== "undefined" && false) {}
11407
+ if (isProductionBuild()) {
11408
+ return `[furin/rsc] Server Component rendering failed inside ${options.operation}().`;
11409
+ }
11343
11410
  if (options.hook !== undefined && options.component !== undefined) {
11344
11411
  const diagnostic = `[furin/rsc] A component rendered inside ${options.operation}()
11345
11412
  used a client-only React hook.
@@ -11869,7 +11936,11 @@ async function getDevDocumentAssets(origin) {
11869
11936
  if (state.devAssets && Date.now() - state.devAssets.ts < DEV_TEMPLATE_TTL_MS) {
11870
11937
  return state.devAssets.assets;
11871
11938
  }
11872
- const assets = documentAssetsFromTemplate(await getDevTemplate(origin));
11939
+ await Promise.resolve().then(() => init_plugin2());
11940
+ const assets = {
11941
+ ...documentAssetsFromTemplate(await getDevTemplate(origin)),
11942
+ extensionErrorFilterScript
11943
+ };
11873
11944
  state.devAssets = { assets, ts: Date.now() };
11874
11945
  return assets;
11875
11946
  }
@@ -12186,7 +12257,7 @@ async function serializeLoaderDataNdjson(syncData, deferredPromises) {
12186
12257
  }
12187
12258
 
12188
12259
  // src/server/render/static-params.ts
12189
- import { dirname as dirname7, relative as relative5 } from "path";
12260
+ import { dirname as dirname8, relative as relative6 } from "path";
12190
12261
  init_patterns();
12191
12262
  var STATIC_PARAMS_CONCURRENCY = 4;
12192
12263
  function collectStaticParamsStages(route) {
@@ -12207,12 +12278,12 @@ function ancestorPattern(route, ancestors) {
12207
12278
  if (rootSourcePath === undefined || ancestorSourcePath === undefined) {
12208
12279
  return route.pattern;
12209
12280
  }
12210
- const pagesDir = dirname7(rootSourcePath);
12211
- const ancestorDir = dirname7(ancestorSourcePath);
12281
+ const pagesDir = dirname8(rootSourcePath);
12282
+ const ancestorDir = dirname8(ancestorSourcePath);
12212
12283
  if (ancestorDir === pagesDir) {
12213
12284
  return "/";
12214
12285
  }
12215
- return filePathToPattern(`${relative5(pagesDir, ancestorDir)}/index.tsx`);
12286
+ return filePathToPattern(`${relative6(pagesDir, ancestorDir)}/index.tsx`);
12216
12287
  }
12217
12288
  function createBuildContext(pattern, params, origin) {
12218
12289
  const path = resolvePath(pattern, params);
@@ -12389,7 +12460,7 @@ async function buildSSGCacheSnapshot(routes, root, origin, basePath) {
12389
12460
 
12390
12461
  // src/rsc/build/index.ts
12391
12462
  import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync5 } from "fs";
12392
- import { basename as basename3, join as join9 } from "path";
12463
+ import { basename as basename3, join as join10 } from "path";
12393
12464
  import { fileURLToPath as fileURLToPath4 } from "url";
12394
12465
 
12395
12466
  // src/rsc/version.ts
@@ -12437,7 +12508,7 @@ function assertInstalledRscVersions() {
12437
12508
  // src/rsc/build/index.ts
12438
12509
  async function buildRscGraph(apps, outDir, buildId, userPlugins) {
12439
12510
  await assertInstalledRscVersions();
12440
- const graphDir = join9(outDir, "rsc");
12511
+ const graphDir = join10(outDir, "rsc");
12441
12512
  mkdirSync4(graphDir, { recursive: true });
12442
12513
  const rscEntry = fileURLToPath4(import.meta.resolve("../../rsc-server.tsx"));
12443
12514
  const entrypoints = [
@@ -12499,13 +12570,13 @@ ${codecResult.logs.map((log) => log.message).join(`
12499
12570
  }
12500
12571
  const css = result.outputs.filter((output) => output.path.endsWith(".css")).map((output) => ({ href: `/_rsc/${basename3(output.path)}` }));
12501
12572
  const manifest = { buildId, clientReferences: [], css };
12502
- writeFileSync5(join9(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
12573
+ writeFileSync5(join10(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
12503
12574
  return manifest;
12504
12575
  }
12505
12576
 
12506
12577
  // src/adapter/runtime-build.ts
12507
- var _pkgRoot2 = dirname8(dirname8(fileURLToPath5(import.meta.resolve("@teyik0/furin"))));
12508
- var _pkgSrcDir2 = existsSync8(join10(_pkgRoot2, "src", "furin.ts")) ? join10(_pkgRoot2, "src") : join10(_pkgRoot2, "dist");
12578
+ var _pkgRoot2 = dirname9(dirname9(fileURLToPath5(import.meta.resolve("@teyik0/furin"))));
12579
+ var _pkgSrcDir2 = existsSync9(join11(_pkgRoot2, "src", "furin.ts")) ? join11(_pkgRoot2, "src") : join11(_pkgRoot2, "dist");
12509
12580
  var _ext2 = ".ts";
12510
12581
  var PPR_ROUTE_IMPORT_RE = /ppr-route(?:\.ts)?$/;
12511
12582
  var ANY_MODULE_RE = /.*/;
@@ -12565,13 +12636,13 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
12565
12636
  }
12566
12637
  }
12567
12638
  for (const path of BUILD_ID_INPUT_PATHS) {
12568
- if (!existsSync8(path)) {
12639
+ if (!existsSync9(path)) {
12569
12640
  console.warn(`[furin] Warning: build fingerprint input "${toPosixPath(path)}" is missing \u2014 ` + "the generated build ID may not reflect all framework changes.");
12570
12641
  }
12571
12642
  fingerprintPaths.add(path);
12572
12643
  }
12573
12644
  const fileParts = await Promise.all([...fingerprintPaths].toSorted().map(async (path) => {
12574
- const content = existsSync8(path) ? await Bun.file(path).text() : "";
12645
+ const content = existsSync9(path) ? await Bun.file(path).text() : "";
12575
12646
  return `${stableFingerprintPath(path, projectRoot)}:${content}`;
12576
12647
  }));
12577
12648
  const routeParts = routes.map((route) => JSON.stringify({
@@ -12583,12 +12654,12 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
12583
12654
  `);
12584
12655
  }
12585
12656
  function stableFingerprintPath(path, projectRoot) {
12586
- const projectPath = relative6(projectRoot, path);
12587
- if (!isAbsolute2(projectPath) && projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
12657
+ const projectPath = relative7(projectRoot, path);
12658
+ if (!isAbsolute3(projectPath) && projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
12588
12659
  return `app/${toPosixPath(projectPath)}`;
12589
12660
  }
12590
- const frameworkPath = relative6(_pkgRoot2, path);
12591
- if (!isAbsolute2(frameworkPath) && frameworkPath !== ".." && !frameworkPath.startsWith("../") && !frameworkPath.startsWith("..\\")) {
12661
+ const frameworkPath = relative7(_pkgRoot2, path);
12662
+ if (!isAbsolute3(frameworkPath) && frameworkPath !== ".." && !frameworkPath.startsWith("../") && !frameworkPath.startsWith("..\\")) {
12592
12663
  return `furin/${toPosixPath(frameworkPath)}`;
12593
12664
  }
12594
12665
  return `external/${basename4(path)}`;
@@ -12625,7 +12696,7 @@ function pprRuntimePlugin(apps) {
12625
12696
  return;
12626
12697
  }
12627
12698
  build.onResolve({ filter: PPR_ROUTE_IMPORT_RE }, ({ path, importer }) => {
12628
- const absolute = resolve5(dirname8(importer.split("?")[0]), path);
12699
+ const absolute = resolve5(dirname9(importer.split("?")[0]), path);
12629
12700
  if (absolute !== pprPath && `${absolute}.ts` !== pprPath) {
12630
12701
  return;
12631
12702
  }
@@ -12645,7 +12716,7 @@ function isFrameworkRuntimeImporter(importer) {
12645
12716
  if (importer === "") {
12646
12717
  return false;
12647
12718
  }
12648
- const fromRuntimeRoot = relative6(_pkgSrcDir2, importer.split("?")[0]);
12719
+ const fromRuntimeRoot = relative7(_pkgSrcDir2, importer.split("?")[0]);
12649
12720
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
12650
12721
  }
12651
12722
  async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options, targetName) {
@@ -12657,7 +12728,7 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
12657
12728
  basePath: prefix,
12658
12729
  clientDirName,
12659
12730
  clientLogging: options.clientLogging ?? false,
12660
- metafilePath: options.analyze ? join10(dirname8(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
12731
+ metafilePath: options.analyze ? join11(dirname9(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
12661
12732
  optimizeImports: options.optimizeImports,
12662
12733
  outDir: targetDir,
12663
12734
  pagesDir: app.pagesDir,
@@ -12669,9 +12740,9 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
12669
12740
  const buildFingerprint = await createBuildFingerprint(`${prefix}
12670
12741
  ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
12671
12742
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
12672
- const clientDir = join10(targetDir, clientDirName);
12743
+ const clientDir = join11(targetDir, clientDirName);
12673
12744
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
12674
- writeFileSync6(join10(clientDir, "index.html"), indexHtml);
12745
+ writeFileSync6(join11(clientDir, "index.html"), indexHtml);
12675
12746
  setProductionTemplateContent(indexHtml);
12676
12747
  ssgRouteCache().clear();
12677
12748
  let ssgCache;
@@ -12731,7 +12802,7 @@ async function buildRuntimeAppsSequentially(apps, projectRoot, targetDir, server
12731
12802
  // src/adapter/bun.ts
12732
12803
  function generateBootEntry(appEntry, outDir, filename) {
12733
12804
  ensureDir(outDir);
12734
- const entryPath = join11(outDir, filename);
12805
+ const entryPath = join12(outDir, filename);
12735
12806
  return createVirtualBuildEntry(entryPath, serverBootSource(appEntry), "ts");
12736
12807
  }
12737
12808
  function collectEmbeddedAssets(entryApps, publicDir, compile) {
@@ -12747,6 +12818,42 @@ function collectEmbeddedAssets(entryApps, publicDir, compile) {
12747
12818
  function compiledServerFilename(platform) {
12748
12819
  return platform === "win32" ? "server.exe" : "server";
12749
12820
  }
12821
+ function serverSourcemapMode(enabled) {
12822
+ return enabled ? "external" : "none";
12823
+ }
12824
+ function relocateServerMaps(build, enabled, targetDir, buildRoot) {
12825
+ if (!enabled) {
12826
+ return;
12827
+ }
12828
+ movePrivateServerSourceMaps(targetDir, join12(buildRoot, "private", "server-sourcemaps", "bun"), build.outputs.filter((output) => output.kind === "sourcemap").map((output) => output.path));
12829
+ }
12830
+ function writeServerMetafile(build, analyze, buildRoot) {
12831
+ if (!analyze) {
12832
+ return;
12833
+ }
12834
+ if (build.metafile === undefined) {
12835
+ throw new Error("[furin] Bun server build did not produce the requested metafile.");
12836
+ }
12837
+ const analysisDir = join12(buildRoot, "analysis");
12838
+ ensureDir(analysisDir);
12839
+ const metafilePath = join12(analysisDir, "bun-server.json");
12840
+ writeFileSync7(metafilePath, `${JSON.stringify(build.metafile, null, 2)}
12841
+ `);
12842
+ console.log(`[furin] Server metafile: ${toPosixPath(metafilePath)}`);
12843
+ }
12844
+ function finalizeEmbeddedAssets(compile, apps, targetDir, manifest) {
12845
+ if (compile !== "embed") {
12846
+ return;
12847
+ }
12848
+ for (const app of apps) {
12849
+ rmSync2(join12(targetDir, clientDirNameForPrefix(app.prefix)), {
12850
+ force: true,
12851
+ recursive: true
12852
+ });
12853
+ }
12854
+ manifest.clientDir = null;
12855
+ manifest.templatePath = null;
12856
+ }
12750
12857
  async function createBunAppEntry(apps, entryApps, options, publicDir, serverEntry, targetDir) {
12751
12858
  if (!serverEntry) {
12752
12859
  return;
@@ -12762,7 +12869,7 @@ async function createBunAppEntry(apps, entryApps, options, publicDir, serverEntr
12762
12869
  ...context.extraContext ?? [],
12763
12870
  ` clientDir: import.meta.dir + ${JSON.stringify(`/${clientDirNameForPrefix(context.prefix ?? "")}`)},`
12764
12871
  ],
12765
- templateHtml: readFileSync6(join11(targetDir, clientDirNameForPrefix(context.prefix ?? ""), "index.html"), "utf8")
12872
+ templateHtml: readFileSync6(join12(targetDir, clientDirNameForPrefix(context.prefix ?? ""), "index.html"), "utf8")
12766
12873
  }));
12767
12874
  return await materializeServerAppEntry({
12768
12875
  apps: contexts,
@@ -12783,30 +12890,35 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12783
12890
  const targetManifest = buildTargetManifest(rootDir, buildRoot, target, serverEntry);
12784
12891
  const targetDir = resolve6(rootDir, targetManifest.targetDir);
12785
12892
  rmSync2(targetDir, { force: true, recursive: true });
12893
+ rmSync2(join12(buildRoot, "private", "server-sourcemaps", "bun"), {
12894
+ force: true,
12895
+ recursive: true
12896
+ });
12786
12897
  ensureDir(targetDir);
12787
- const publicDir = existsSync9(join11(rootDir, "public")) ? join11(rootDir, "public") : undefined;
12898
+ const publicDir = existsSync10(join12(rootDir, "public")) ? join12(rootDir, "public") : undefined;
12788
12899
  const { entryApps, headlineBuildId } = await buildRuntimeAppsSequentially(apps, rootDir, targetDir, serverEntry, options, "bun");
12789
12900
  targetManifest.buildId = headlineBuildId;
12790
12901
  if (serverEntry) {
12791
- targetManifest.rscManifestPath = toPosixPath(join11(targetManifest.targetDir, "rsc", "manifest.json"));
12902
+ targetManifest.rscManifestPath = toPosixPath(join12(targetManifest.targetDir, "rsc", "manifest.json"));
12792
12903
  }
12793
- const targetPublicDir = publicDir ? join11(targetDir, "public") : undefined;
12904
+ const targetPublicDir = publicDir ? join12(targetDir, "public") : undefined;
12794
12905
  if (publicDir && targetPublicDir && options.compile !== "embed") {
12795
12906
  copyDirRecursive(publicDir, targetPublicDir);
12796
12907
  }
12797
12908
  const appEntry = await createBunAppEntry(apps, entryApps, options, publicDir, serverEntry, targetDir);
12798
12909
  if (options.compile && serverEntry && appEntry) {
12799
12910
  const serverFilename = compiledServerFilename(process.platform);
12800
- const outfile = join11(targetDir, serverFilename);
12911
+ const outfile = join12(targetDir, serverFilename);
12801
12912
  const entry = generateBootEntry(appEntry, targetDir, "_compile-entry.ts");
12802
12913
  const embeddedAssets = collectEmbeddedAssets(entryApps, publicDir, options.compile);
12803
- await runBunBuild({
12914
+ const serverBuild = await runBunBuild({
12804
12915
  bytecode: true,
12805
12916
  compile: { assets: embeddedAssets, outfile },
12806
12917
  define: { "process.env.NODE_ENV": JSON.stringify("production") },
12807
12918
  entrypoints: [entry.entrypoint],
12808
12919
  files: entry.files,
12809
12920
  format: "esm",
12921
+ metafile: options.analyze,
12810
12922
  minify: true,
12811
12923
  plugins: [
12812
12924
  entry.plugin,
@@ -12818,27 +12930,21 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12818
12930
  environmentGuardPlugin("ssr"),
12819
12931
  elysiaAot(appEntry)
12820
12932
  ],
12821
- sourcemap: "none",
12933
+ sourcemap: serverSourcemapMode(options.serverSourceMaps),
12822
12934
  splitting: true,
12823
12935
  target: "bun"
12824
12936
  });
12937
+ relocateServerMaps(serverBuild, options.serverSourceMaps, targetDir, buildRoot);
12938
+ writeServerMetafile(serverBuild, options.analyze, buildRoot);
12825
12939
  console.log(`[furin] Server binary: ${outfile}`);
12826
- targetManifest.serverPath = toPosixPath(join11(targetManifest.targetDir, serverFilename));
12827
- if (options.compile === "embed") {
12828
- for (const app of apps) {
12829
- rmSync2(join11(targetDir, clientDirNameForPrefix(app.prefix)), {
12830
- force: true,
12831
- recursive: true
12832
- });
12833
- }
12834
- targetManifest.clientDir = null;
12835
- targetManifest.templatePath = null;
12836
- }
12940
+ targetManifest.serverPath = toPosixPath(join12(targetManifest.targetDir, serverFilename));
12941
+ finalizeEmbeddedAssets(options.compile, apps, targetDir, targetManifest);
12837
12942
  } else if (serverEntry && appEntry) {
12838
12943
  const entry = generateBootEntry(appEntry, targetDir, "server.ts");
12839
- await runBunBuild({
12944
+ const serverBuild = await runBunBuild({
12840
12945
  entrypoints: [entry.entrypoint],
12841
12946
  files: entry.files,
12947
+ metafile: options.analyze,
12842
12948
  minify: true,
12843
12949
  naming: { chunk: "[name]-[hash].[ext]", entry: "[name].[ext]" },
12844
12950
  outdir: targetDir,
@@ -12852,28 +12958,30 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
12852
12958
  environmentGuardPlugin("ssr"),
12853
12959
  elysiaAot(appEntry)
12854
12960
  ],
12855
- sourcemap: "none",
12961
+ sourcemap: serverSourcemapMode(options.serverSourceMaps),
12856
12962
  target: "bun"
12857
12963
  });
12858
- console.log(`[furin] Server bundle: ${toPosixPath(join11(targetManifest.targetDir, "server.js"))}`);
12859
- targetManifest.serverPath = toPosixPath(join11(targetManifest.targetDir, "server.js"));
12964
+ relocateServerMaps(serverBuild, options.serverSourceMaps, targetDir, buildRoot);
12965
+ writeServerMetafile(serverBuild, options.analyze, buildRoot);
12966
+ console.log(`[furin] Server bundle: ${toPosixPath(join12(targetManifest.targetDir, "server.js"))}`);
12967
+ targetManifest.serverPath = toPosixPath(join12(targetManifest.targetDir, "server.js"));
12860
12968
  }
12861
12969
  return targetManifest;
12862
12970
  }
12863
12971
 
12864
12972
  // src/adapter/package.ts
12865
- import { existsSync as existsSync10, rmSync as rmSync3, writeFileSync as writeFileSync7 } from "fs";
12866
- import { join as join12, relative as relative7, resolve as resolve7 } from "path";
12973
+ import { existsSync as existsSync11, rmSync as rmSync3, writeFileSync as writeFileSync8 } from "fs";
12974
+ import { join as join13, relative as relative8, resolve as resolve7 } from "path";
12867
12975
  async function buildPackageTarget(app, rootDir, buildRoot, options) {
12868
12976
  const { prefix, root, routes, pagesDir } = app;
12869
12977
  const modulePaths = routeSourcePaths(app);
12870
- const targetDir = join12(buildRoot, "package");
12978
+ const targetDir = join13(buildRoot, "package");
12871
12979
  rmSync3(targetDir, { force: true, recursive: true });
12872
12980
  ensureDir(targetDir);
12873
12981
  const { entryChunk, cssChunks } = await buildClient(routes, {
12874
12982
  basePath: prefix,
12875
12983
  clientLogging: options.clientLogging ?? false,
12876
- metafilePath: options.analyze ? join12(buildRoot, "analysis", "package-client.json") : undefined,
12984
+ metafilePath: options.analyze ? join13(buildRoot, "analysis", "package-client.json") : undefined,
12877
12985
  optimizeImports: options.optimizeImports,
12878
12986
  outDir: targetDir,
12879
12987
  pagesDir,
@@ -12885,13 +12993,13 @@ async function buildPackageTarget(app, rootDir, buildRoot, options) {
12885
12993
  const buildFingerprint = await createBuildFingerprint(`${prefix}
12886
12994
  ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12887
12995
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
12888
- const clientDir = join12(targetDir, "client");
12889
- const publicDir = join12(rootDir, "public");
12890
- if (existsSync10(publicDir)) {
12891
- copyDirRecursive(publicDir, join12(targetDir, "public"));
12996
+ const clientDir = join13(targetDir, "client");
12997
+ const publicDir = join13(rootDir, "public");
12998
+ if (existsSync11(publicDir)) {
12999
+ copyDirRecursive(publicDir, join13(targetDir, "public"));
12892
13000
  }
12893
13001
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
12894
- writeFileSync7(join12(clientDir, "index.html"), indexHtml);
13002
+ writeFileSync8(join13(clientDir, "index.html"), indexHtml);
12895
13003
  setProductionTemplateContent(indexHtml);
12896
13004
  ssgRouteCache().clear();
12897
13005
  const ssgCache = await buildSSGCacheSnapshot(routes, root, "http://localhost", prefix);
@@ -12928,7 +13036,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12928
13036
  headerComment: "// Auto-generated by `furin build --target package` \u2014 do not edit",
12929
13037
  mode: "register"
12930
13038
  });
12931
- const registerEntry = join12(targetDir, "register.ts");
13039
+ const registerEntry = join13(targetDir, "register.ts");
12932
13040
  const register = createVirtualBuildEntry(registerEntry, registerSource, "ts");
12933
13041
  const result = await runBunBuild({
12934
13042
  entrypoints: [register.entrypoint],
@@ -12948,7 +13056,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
12948
13056
  if (!result.success) {
12949
13057
  throw new AggregateError(result.logs, "[furin] package register build failed");
12950
13058
  }
12951
- const relativePagesDir = toPosixPath(relative7(targetDir, resolve7(rootDir, pagesDir)));
13059
+ const relativePagesDir = toPosixPath(relative8(targetDir, resolve7(rootDir, pagesDir)));
12952
13060
  const factorySource = `// Auto-generated by \`furin build --target package\` \u2014 do not edit
12953
13061
  import { fileURLToPath } from "node:url";
12954
13062
  import { furin } from "@teyik0/furin";
@@ -12975,7 +13083,7 @@ export function createFurinApp(options = {}) {
12975
13083
 
12976
13084
  export const prefix = ${JSON.stringify(prefix)};
12977
13085
  `;
12978
- writeFileSync7(join12(targetDir, "index.js"), factorySource);
13086
+ writeFileSync8(join13(targetDir, "index.js"), factorySource);
12979
13087
  const dtsSource = `import type { FurinOptions, furin } from "@teyik0/furin";
12980
13088
 
12981
13089
  /** Extra furin() options \u2014 pagesDir/prefix/clientDir are baked into the package and cannot be overridden. */
@@ -12983,19 +13091,19 @@ export type CreateFurinAppOptions = Omit<FurinOptions, "pagesDir" | "prefix" | "
12983
13091
  export declare function createFurinApp(options?: CreateFurinAppOptions): ReturnType<typeof furin>;
12984
13092
  export declare const prefix: string;
12985
13093
  `;
12986
- writeFileSync7(join12(targetDir, "index.d.ts"), dtsSource);
12987
- console.log(`[furin] Package artifact: ${toPosixPath(relative7(rootDir, targetDir))}`);
13094
+ writeFileSync8(join13(targetDir, "index.d.ts"), dtsSource);
13095
+ console.log(`[furin] Package artifact: ${toPosixPath(relative8(rootDir, targetDir))}`);
12988
13096
  return {
12989
13097
  buildId,
12990
13098
  generatedAt: new Date().toISOString(),
12991
13099
  prefix,
12992
- targetDir: toPosixPath(relative7(rootDir, targetDir))
13100
+ targetDir: toPosixPath(relative8(rootDir, targetDir))
12993
13101
  };
12994
13102
  }
12995
13103
 
12996
13104
  // src/adapter/static.ts
12997
- import { cpSync as cpSync2, existsSync as existsSync11, rmSync as rmSync4, writeFileSync as writeFileSync8 } from "fs";
12998
- import { dirname as dirname9, isAbsolute as isAbsolute3, join as join13, parse as parse3, relative as relative8, resolve as resolve8, sep as sep2, win32 } from "path";
13105
+ import { cpSync as cpSync2, existsSync as existsSync12, rmSync as rmSync4, writeFileSync as writeFileSync9 } from "fs";
13106
+ import { dirname as dirname10, isAbsolute as isAbsolute4, join as join14, parse as parse3, relative as relative9, resolve as resolve8, sep as sep2, win32 } from "path";
12999
13107
  var STATIC_CONCURRENCY = 4;
13000
13108
  var DYNAMIC_SEGMENT_RE2 = /\/:[^/]+|\/\*/;
13001
13109
  var TRAILING_SLASHES_RE = /\/+$/;
@@ -13003,7 +13111,7 @@ var STATIC_RENDER_ORIGIN = "http://localhost";
13003
13111
  function pathToOutputFile(urlPath, outDir, fileName) {
13004
13112
  const normalizedOutDir = resolve8(outDir);
13005
13113
  if (urlPath === "/" || urlPath === "") {
13006
- return join13(normalizedOutDir, fileName);
13114
+ return join14(normalizedOutDir, fileName);
13007
13115
  }
13008
13116
  const resolved = resolve8(normalizedOutDir, urlPath.slice(1), fileName);
13009
13117
  if (!resolved.startsWith(`${normalizedOutDir}${sep2}`)) {
@@ -13078,22 +13186,22 @@ async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, sk
13078
13186
  throw new Error(`[furin] static: route "${route.pattern}" returned a response that cannot be exported.`);
13079
13187
  }
13080
13188
  const staticLocation = resolveStaticRedirectLocation(location, basePath, urlPath);
13081
- ensureDir(dirname9(htmlOutputFile));
13082
- writeFileSync8(htmlOutputFile, createStaticRedirectHtml(staticLocation.html));
13189
+ ensureDir(dirname10(htmlOutputFile));
13190
+ writeFileSync9(htmlOutputFile, createStaticRedirectHtml(staticLocation.html));
13083
13191
  if (staticLocation.spa !== null) {
13084
13192
  const serializedRedirect = await toCrossJSONAsync({
13085
13193
  __furinRedirect: staticLocation.spa
13086
13194
  });
13087
- writeFileSync8(dataOutputFile, `${JSON.stringify(serializedRedirect)}
13195
+ writeFileSync9(dataOutputFile, `${JSON.stringify(serializedRedirect)}
13088
13196
  `);
13089
13197
  }
13090
13198
  renderedRoutes.push(urlPath);
13091
13199
  console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)} (redirects to ${staticLocation.html})`);
13092
13200
  return;
13093
13201
  }
13094
- ensureDir(dirname9(htmlOutputFile));
13095
- writeFileSync8(htmlOutputFile, entry.html);
13096
- writeFileSync8(dataOutputFile, entry.ndjson);
13202
+ ensureDir(dirname10(htmlOutputFile));
13203
+ writeFileSync9(htmlOutputFile, entry.html);
13204
+ writeFileSync9(dataOutputFile, entry.ndjson);
13097
13205
  renderedRoutes.push(urlPath);
13098
13206
  console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)}`);
13099
13207
  } catch (err) {
@@ -13207,8 +13315,8 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
13207
13315
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
13208
13316
  }
13209
13317
  function isOutsideOutDir(target) {
13210
- const rel = relative8(outDir, target);
13211
- return rel.startsWith("..") || isAbsolute3(rel);
13318
+ const rel = relative9(outDir, target);
13319
+ return rel.startsWith("..") || isAbsolute4(rel);
13212
13320
  }
13213
13321
  if (!(isOutsideOutDir(normalizedRoot) && isOutsideOutDir(normalizedBuildRoot))) {
13214
13322
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
@@ -13224,36 +13332,36 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
13224
13332
  const afterQueueCount = skippedRoutes.length;
13225
13333
  rmSync4(outDir, { force: true, recursive: true });
13226
13334
  ensureDir(outDir);
13227
- const targetDir = join13(buildRoot, "static");
13335
+ const targetDir = join14(buildRoot, "static");
13228
13336
  rmSync4(targetDir, { force: true, recursive: true });
13229
13337
  ensureDir(targetDir);
13230
13338
  const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
13231
13339
  basePath,
13232
13340
  clientLogging: Boolean(options.clientLogging),
13233
- metafilePath: options.analyze ? join13(buildRoot, "analysis", "static-client.json") : undefined,
13341
+ metafilePath: options.analyze ? join14(buildRoot, "analysis", "static-client.json") : undefined,
13234
13342
  optimizeImports: options.optimizeImports,
13235
13343
  outDir: targetDir,
13236
- pagesDir: dirname9(root.path),
13344
+ pagesDir: dirname10(root.path),
13237
13345
  plugins: options.plugins,
13238
13346
  publicPath,
13239
13347
  reactCompiler: options.reactCompiler,
13240
13348
  rootLayout: root.path
13241
13349
  });
13242
- const publicFavicon = join13(rootDir, "public", "favicon.ico");
13243
- const faviconHref = existsSync11(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
13350
+ const publicFavicon = join14(rootDir, "public", "favicon.ico");
13351
+ const faviconHref = existsSync12(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
13244
13352
  const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref, true);
13245
13353
  setProductionTemplateContent(shellHtml);
13246
- const publicSrcDir = join13(rootDir, "public");
13247
- if (existsSync11(publicSrcDir)) {
13354
+ const publicSrcDir = join14(rootDir, "public");
13355
+ if (existsSync12(publicSrcDir)) {
13248
13356
  cpSync2(publicSrcDir, outDir, { recursive: true });
13249
13357
  }
13250
- const clientSrcDir = join13(targetDir, "client");
13251
- if (existsSync11(clientSrcDir)) {
13252
- cpSync2(clientSrcDir, join13(outDir, "_client"), { recursive: true });
13358
+ const clientSrcDir = join14(targetDir, "client");
13359
+ if (existsSync12(clientSrcDir)) {
13360
+ cpSync2(clientSrcDir, join14(outDir, "_client"), { recursive: true });
13253
13361
  }
13254
13362
  await runWithConcurrency(tasks, STATIC_CONCURRENCY);
13255
13363
  assertNoPrerenderSkips(onSSR, skippedRoutes, afterQueueCount);
13256
- writeFileSync8(join13(outDir, "404.html"), shellHtml);
13364
+ writeFileSync9(join14(outDir, "404.html"), shellHtml);
13257
13365
  console.log("[furin] static: wrote 404.html (SPA shell fallback)");
13258
13366
  rmSync4(targetDir, { force: true, recursive: true });
13259
13367
  console.log(`[furin] static: export complete \u2192 ${toPosixPath(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
@@ -13267,8 +13375,8 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
13267
13375
  }
13268
13376
 
13269
13377
  // src/adapter/vercel.ts
13270
- import { cpSync as cpSync3, existsSync as existsSync12, readFileSync as readFileSync7, rmSync as rmSync5, symlinkSync, writeFileSync as writeFileSync9 } from "fs";
13271
- import { basename as basename5, dirname as dirname10, extname as extname4, join as join14, relative as relative9 } from "path";
13378
+ import { cpSync as cpSync3, existsSync as existsSync13, readFileSync as readFileSync7, rmSync as rmSync5, symlinkSync, writeFileSync as writeFileSync10 } from "fs";
13379
+ import { basename as basename5, dirname as dirname11, extname as extname4, join as join15, relative as relative10 } from "path";
13272
13380
  import { fileURLToPath as fileURLToPath6, pathToFileURL as pathToFileURL2 } from "url";
13273
13381
  init_patterns();
13274
13382
  var ISR_PATH_PARAM = "__furin_path";
@@ -13279,12 +13387,12 @@ var REGEX_META_RE = /[.*+?^${}()|[\]\\]/;
13279
13387
  var UNSAFE_FUNCTION_PATH_RE = /[^a-zA-Z0-9_.[\]/-]/g;
13280
13388
  var VERCEL_FUNCTIONS_PATH = fileURLToPath6(import.meta.resolve("@vercel/functions"));
13281
13389
  var VERCEL_RUNTIME_STUB_NAMESPACE = "furin-vercel-runtime-stub";
13282
- var FURIN_RUNTIME_ROOT2 = dirname10(import.meta.dir);
13390
+ var FURIN_RUNTIME_ROOT2 = dirname11(import.meta.dir);
13283
13391
  function isFurinRuntimeImporter(importer) {
13284
13392
  if (importer === "") {
13285
13393
  return false;
13286
13394
  }
13287
- const fromRuntimeRoot = relative9(FURIN_RUNTIME_ROOT2, importer.split("?")[0]);
13395
+ const fromRuntimeRoot = relative10(FURIN_RUNTIME_ROOT2, importer.split("?")[0]);
13288
13396
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
13289
13397
  }
13290
13398
  function vercelRuntimePlugin() {
@@ -13310,8 +13418,8 @@ function vercelRuntimePlugin() {
13310
13418
  };
13311
13419
  }
13312
13420
  function frameworkVersion() {
13313
- const packageRoot = dirname10(dirname10(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
13314
- const packageJson = JSON.parse(readFileSync7(join14(packageRoot, "package.json"), "utf8"));
13421
+ const packageRoot = dirname11(dirname11(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
13422
+ const packageJson = JSON.parse(readFileSync7(join15(packageRoot, "package.json"), "utf8"));
13315
13423
  return packageJson.version;
13316
13424
  }
13317
13425
  function serverEntryLoader(serverEntry) {
@@ -13427,9 +13535,9 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
13427
13535
  body = result.html;
13428
13536
  ({ status } = result);
13429
13537
  }
13430
- const fallbackPath = join14(dirname10(join14(functionsDir, spec.functionName)), fallback);
13431
- ensureDir(dirname10(fallbackPath));
13432
- writeFileSync9(fallbackPath, body);
13538
+ const fallbackPath = join15(dirname11(join15(functionsDir, spec.functionName)), fallback);
13539
+ ensureDir(dirname11(fallbackPath));
13540
+ writeFileSync10(fallbackPath, body);
13433
13541
  spec.config.fallback = fallback;
13434
13542
  spec.config.initialHeaders = {
13435
13543
  "content-type": contentType,
@@ -13440,9 +13548,9 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
13440
13548
  spec.config.initialStatus = status;
13441
13549
  }
13442
13550
  function createFunctionAlias(functionsDir, serverFunctionDir, functionName) {
13443
- const aliasPath = join14(functionsDir, `${functionName}.func`);
13444
- ensureDir(dirname10(aliasPath));
13445
- const target = relative9(dirname10(aliasPath), serverFunctionDir);
13551
+ const aliasPath = join15(functionsDir, `${functionName}.func`);
13552
+ ensureDir(dirname11(aliasPath));
13553
+ const target = relative10(dirname11(aliasPath), serverFunctionDir);
13446
13554
  symlinkSync(target, aliasPath, process.platform === "win32" ? "junction" : "dir");
13447
13555
  }
13448
13556
  function createExactPrerenderSpec(prerender, routePath) {
@@ -13664,10 +13772,10 @@ async function buildPprFallbacks(apps, builds, specs, functionsDir, rootDir, tar
13664
13772
  if (jobs.length === 0) {
13665
13773
  return;
13666
13774
  }
13667
- const resultPath = join14(targetDir, "ppr-results.json");
13775
+ const resultPath = join15(targetDir, "ppr-results.json");
13668
13776
  const requests = jobs.map(({ path, spec }) => `http://localhost/${spec.functionName}?${ISR_PATH_PARAM}=${encodeURIComponent(path)}`);
13669
13777
  const script = `
13670
- const handler = (await import(${JSON.stringify(pathToFileURL2(join14(functionsDir, "__server.func/index.js")).href)})).default;
13778
+ const handler = (await import(${JSON.stringify(pathToFileURL2(join15(functionsDir, "__server.func/index.js")).href)})).default;
13671
13779
  const results = [];
13672
13780
  for (const url of ${JSON.stringify(requests)}) {
13673
13781
  const response = await handler.fetch(new Request(url));
@@ -13776,35 +13884,39 @@ export default { fetch: handle };
13776
13884
  }
13777
13885
  async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options) {
13778
13886
  assertDefaultServerExport(serverEntry);
13779
- const targetDir = join14(buildRoot, "vercel");
13780
- const outputDir = join14(rootDir, ".vercel", "output");
13781
- const staticDir = join14(outputDir, "static");
13782
- const functionsDir = join14(outputDir, "functions");
13783
- const serverFunctionDir = join14(functionsDir, "__server.func");
13887
+ const targetDir = join15(buildRoot, "vercel");
13888
+ const outputDir = join15(rootDir, ".vercel", "output");
13889
+ const staticDir = join15(outputDir, "static");
13890
+ const functionsDir = join15(outputDir, "functions");
13891
+ const serverFunctionDir = join15(functionsDir, "__server.func");
13784
13892
  rmSync5(targetDir, { force: true, recursive: true });
13893
+ rmSync5(join15(buildRoot, "private", "server-sourcemaps", "vercel"), {
13894
+ force: true,
13895
+ recursive: true
13896
+ });
13785
13897
  rmSync5(outputDir, { force: true, recursive: true });
13786
13898
  ensureDir(targetDir);
13787
13899
  ensureDir(staticDir);
13788
13900
  ensureDir(serverFunctionDir);
13789
13901
  const { builds, headlineBuildId } = await buildRuntimeAppsSequentially(apps, rootDir, targetDir, serverEntry, options, "vercel");
13790
- cpSync3(join14(targetDir, "server-codec.js"), join14(serverFunctionDir, "server-codec.js"));
13791
- const publicDir = join14(rootDir, "public");
13792
- if (existsSync12(publicDir)) {
13902
+ cpSync3(join15(targetDir, "server-codec.js"), join15(serverFunctionDir, "server-codec.js"));
13903
+ const publicDir = join15(rootDir, "public");
13904
+ if (existsSync13(publicDir)) {
13793
13905
  cpSync3(publicDir, staticDir, { recursive: true });
13794
13906
  for (const app of apps) {
13795
- const appStaticDir = join14(staticDir, app.prefix.slice(1));
13796
- const appPublicDir = join14(appStaticDir, "public");
13907
+ const appStaticDir = join15(staticDir, app.prefix.slice(1));
13908
+ const appPublicDir = join15(appStaticDir, "public");
13797
13909
  cpSync3(publicDir, appPublicDir, { recursive: true });
13798
- const favicon = join14(publicDir, "favicon.ico");
13799
- if (app.prefix !== "" && existsSync12(favicon)) {
13800
- cpSync3(favicon, join14(appStaticDir, "favicon.ico"));
13910
+ const favicon = join15(publicDir, "favicon.ico");
13911
+ if (app.prefix !== "" && existsSync13(favicon)) {
13912
+ cpSync3(favicon, join15(appStaticDir, "favicon.ico"));
13801
13913
  }
13802
13914
  }
13803
13915
  }
13804
13916
  for (let appIndex = 0;appIndex < apps.length; appIndex += 1) {
13805
13917
  const app = apps[appIndex];
13806
13918
  const build = builds[appIndex];
13807
- const clientOutputDir = join14(staticDir, app.prefix.slice(1), "_client");
13919
+ const clientOutputDir = join15(staticDir, app.prefix.slice(1), "_client");
13808
13920
  cpSync3(build.clientDir, clientOutputDir, { recursive: true });
13809
13921
  }
13810
13922
  const pprResumeKey = crypto.randomUUID();
@@ -13821,7 +13933,7 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13821
13933
  outDir: serverFunctionDir,
13822
13934
  serverEntry
13823
13935
  });
13824
- const entryPath = join14(serverFunctionDir, "_vercel-handler.ts");
13936
+ const entryPath = join15(serverFunctionDir, "_vercel-handler.ts");
13825
13937
  const entry = createVirtualBuildEntry(entryPath, vercelEntrySource(apps, builds, prerenderSpecs, appEntry, pprResumeKey), "ts");
13826
13938
  const serverBuild = await runBunBuild({
13827
13939
  define: { "process.env.NODE_ENV": JSON.stringify("production") },
@@ -13843,24 +13955,27 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13843
13955
  environmentGuardPlugin("ssr"),
13844
13956
  elysiaAot(appEntry)
13845
13957
  ],
13846
- sourcemap: "none",
13958
+ sourcemap: options.serverSourceMaps ? "external" : "none",
13847
13959
  splitting: true,
13848
13960
  target: "bun"
13849
13961
  });
13962
+ if (options.serverSourceMaps) {
13963
+ movePrivateServerSourceMaps(serverFunctionDir, join15(buildRoot, "private", "server-sourcemaps", "vercel"), serverBuild.outputs.filter((output) => output.kind === "sourcemap").map((output) => output.path));
13964
+ }
13850
13965
  if (options.analyze) {
13851
13966
  if (serverBuild.metafile === undefined) {
13852
13967
  throw new Error("[furin] Vercel server build did not produce the requested metafile.");
13853
13968
  }
13854
- const metafilePath = join14(buildRoot, "analysis", "vercel-server.json");
13855
- ensureDir(dirname10(metafilePath));
13856
- writeFileSync9(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}
13969
+ const metafilePath = join15(buildRoot, "analysis", "vercel-server.json");
13970
+ ensureDir(dirname11(metafilePath));
13971
+ writeFileSync10(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}
13857
13972
  `);
13858
13973
  console.log(`[furin] Server metafile: ${toPosixPath(metafilePath)}`);
13859
13974
  }
13860
13975
  const serverBundleBytes = serverBuild.outputs.filter((output) => output.path.endsWith(".js")).reduce((total, output) => total + output.size, 0);
13861
- writeFileSync9(join14(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
13976
+ writeFileSync10(join15(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
13862
13977
  await buildPprFallbacks(apps, builds, prerenderSpecs, functionsDir, rootDir, targetDir);
13863
- writeFileSync9(join14(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
13978
+ writeFileSync10(join15(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
13864
13979
  handler: "index.js",
13865
13980
  launcherType: "Nodejs",
13866
13981
  ...options.vercelConfig?.regions === undefined ? {} : { regions: options.vercelConfig.regions },
@@ -13871,7 +13986,7 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13871
13986
  `);
13872
13987
  for (const spec of prerenderSpecs) {
13873
13988
  createFunctionAlias(functionsDir, serverFunctionDir, spec.functionName);
13874
- writeFileSync9(join14(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
13989
+ writeFileSync10(join15(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
13875
13990
  `);
13876
13991
  }
13877
13992
  const assetRoutes = apps.map((app) => ({
@@ -13901,48 +14016,71 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
13901
14016
  ],
13902
14017
  version: 3
13903
14018
  };
13904
- writeFileSync9(join14(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
14019
+ writeFileSync10(join15(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
13905
14020
  `);
13906
14021
  const ssgRoutes = builds.flatMap((build, index) => build.prerenders.filter((prerender) => prerender.route.mode === "ssg").map((prerender) => physicalPath(apps[index].prefix, prerender.path))).toSorted();
13907
14022
  const isrRoutes = apps.flatMap((app) => app.routes.filter((route) => route.mode === "isr").map((route) => physicalPath(app.prefix, route.pattern))).toSorted();
13908
- console.log(`[furin] Vercel output: ${toPosixPath(relative9(rootDir, outputDir))}`);
14023
+ console.log(`[furin] Vercel output: ${toPosixPath(relative10(rootDir, outputDir))}`);
13909
14024
  return {
13910
14025
  buildId: headlineBuildId,
13911
14026
  generatedAt: new Date().toISOString(),
13912
14027
  isrRoutes,
13913
- outputDir: toPosixPath(relative9(rootDir, outputDir)),
13914
- serverPath: toPosixPath(relative9(rootDir, serverFunctionDir)),
14028
+ outputDir: toPosixPath(relative10(rootDir, outputDir)),
14029
+ serverPath: toPosixPath(relative10(rootDir, serverFunctionDir)),
13915
14030
  ssgRoutes
13916
14031
  };
13917
14032
  }
13918
14033
 
13919
14034
  // src/config.ts
13920
- import { t as t2 } from "elysia";
14035
+ import { t } from "elysia";
13921
14036
  var BUILD_TARGETS = ["bun", "vercel", "static", "package"];
13922
- var buildTargetSchema = t2.Union(BUILD_TARGETS.map((v) => t2.Literal(v)));
13923
- var compileTargetSchema = t2.Union([t2.Literal("server"), t2.Literal("embed")]);
13924
- var configSchema = t2.Object({
13925
- apps: t2.Optional(t2.Array(t2.Object({
13926
- pagesDir: t2.String(),
13927
- prefix: t2.Optional(t2.String())
14037
+ var VERCEL_REGIONS = [
14038
+ "arn1",
14039
+ "bom1",
14040
+ "cdg1",
14041
+ "cle1",
14042
+ "cpt1",
14043
+ "dub1",
14044
+ "dxb1",
14045
+ "fra1",
14046
+ "gru1",
14047
+ "hkg1",
14048
+ "hnd1",
14049
+ "iad1",
14050
+ "icn1",
14051
+ "kix1",
14052
+ "lhr1",
14053
+ "pdx1",
14054
+ "sfo1",
14055
+ "sin1",
14056
+ "syd1",
14057
+ "yul1"
14058
+ ];
14059
+ var buildTargetSchema = t.Union(BUILD_TARGETS.map((v) => t.Literal(v)));
14060
+ var compileTargetSchema = t.Union([t.Literal("server"), t.Literal("embed")]);
14061
+ var configSchema = t.Object({
14062
+ apps: t.Optional(t.Array(t.Object({
14063
+ pagesDir: t.String(),
14064
+ prefix: t.Optional(t.String())
13928
14065
  }))),
13929
- bun: t2.Optional(t2.Object({
13930
- compile: t2.Optional(compileTargetSchema)
14066
+ bun: t.Optional(t.Object({
14067
+ compile: t.Optional(compileTargetSchema)
13931
14068
  })),
13932
- clientLogging: t2.Optional(t2.Boolean()),
13933
- optimizeImports: t2.Optional(t2.Array(t2.String())),
13934
- pagesDir: t2.Optional(t2.String()),
13935
- reactCompiler: t2.Optional(t2.Boolean()),
13936
- rootDir: t2.Optional(t2.String()),
13937
- serverEntry: t2.Optional(t2.String()),
13938
- static: t2.Optional(t2.Object({
13939
- basePath: t2.Optional(t2.String()),
13940
- onSSR: t2.Optional(t2.Union([t2.Literal("error"), t2.Literal("skip")])),
13941
- outDir: t2.Optional(t2.String())
14069
+ clientLogging: t.Optional(t.Boolean()),
14070
+ optimizeImports: t.Optional(t.Array(t.String())),
14071
+ pagesDir: t.Optional(t.String()),
14072
+ reactCompiler: t.Optional(t.Boolean()),
14073
+ rootDir: t.Optional(t.String()),
14074
+ serverEntry: t.Optional(t.String()),
14075
+ serverSourceMaps: t.Optional(t.Boolean()),
14076
+ static: t.Optional(t.Object({
14077
+ basePath: t.Optional(t.String()),
14078
+ onSSR: t.Optional(t.Union([t.Literal("error"), t.Literal("skip")])),
14079
+ outDir: t.Optional(t.String())
13942
14080
  })),
13943
- targets: t2.Optional(t2.Array(buildTargetSchema)),
13944
- vercel: t2.Optional(t2.Object({
13945
- regions: t2.Optional(t2.Array(t2.String({ pattern: "^[a-z]{3}[1-9][0-9]*$" }), {
14081
+ targets: t.Optional(t.Array(buildTargetSchema)),
14082
+ vercel: t.Optional(t.Object({
14083
+ regions: t.Optional(t.Array(t.Enum(VERCEL_REGIONS), {
13946
14084
  minItems: 1,
13947
14085
  uniqueItems: true
13948
14086
  }))
@@ -13953,9 +14091,9 @@ var configSchema = t2.Object({
13953
14091
  init_instance();
13954
14092
 
13955
14093
  // src/server/router/discovery.ts
13956
- import { existsSync as existsSync13 } from "fs";
14094
+ import { existsSync as existsSync14 } from "fs";
13957
14095
  import { readdir } from "fs/promises";
13958
- import { join as join15, parse as parse4 } from "path";
14096
+ import { join as join16, parse as parse4 } from "path";
13959
14097
 
13960
14098
  // src/server/internal.ts
13961
14099
  var _compileContexts = new Map;
@@ -14105,7 +14243,7 @@ async function scanPages(pagesDir) {
14105
14243
  async function scanRootLayout(pagesDir) {
14106
14244
  const rootPath = `${pagesDir}/root.tsx`;
14107
14245
  const ctx = getCompileContext();
14108
- if (!(existsSync13(rootPath) || ctx?.modules[rootPath])) {
14246
+ if (!(existsSync14(rootPath) || ctx?.modules[rootPath])) {
14109
14247
  throw new Error("[furin] root.tsx: not found.");
14110
14248
  }
14111
14249
  const mod = ctx?.modules[rootPath] ?? await import(rootPath);
@@ -14145,8 +14283,8 @@ function getSourceModuleCandidates(dir, name) {
14145
14283
  async function loadConventionComponent(dir, name) {
14146
14284
  const ctx = getCompileContext();
14147
14285
  for (const filePath of getSourceModuleCandidates(dir, name)) {
14148
- if (existsSync13(filePath) || ctx?.modules[filePath]) {
14149
- const moduleSpecifier = IS_DEV && existsSync13(filePath) ? `${filePath}?furin-server&t=${routeModuleSourceVersion(filePath)}` : filePath;
14286
+ if (existsSync14(filePath) || ctx?.modules[filePath]) {
14287
+ const moduleSpecifier = IS_DEV && existsSync14(filePath) ? `${filePath}?furin-server&t=${routeModuleSourceVersion(filePath)}` : filePath;
14150
14288
  const mod = ctx?.modules[filePath] ?? await import(moduleSpecifier);
14151
14289
  if (mod.default) {
14152
14290
  return { component: mod.default, path: filePath };
@@ -14229,10 +14367,10 @@ async function resolveDefinedLayoutParent(pagePath, pagesDir, rootRoute) {
14229
14367
  for (const segment of segments) {
14230
14368
  directory = `${directory}/${segment}`;
14231
14369
  for (const candidate of getSourceModuleCandidates(directory, "_route")) {
14232
- if (!existsSync13(candidate)) {
14370
+ if (!existsSync14(candidate)) {
14233
14371
  continue;
14234
14372
  }
14235
- const layoutModule = await import(candidate);
14373
+ const layoutModule = await (IS_DEV ? import(`${candidate}?furin-server&t=${routeModuleSourceVersion(candidate)}`) : import(candidate));
14236
14374
  const layout = layoutModule.route;
14237
14375
  if (isDefinedRouteTerminal(layout) && typeof layout.layout === "function") {
14238
14376
  parent = adaptDefinedLayout(layout, parent, candidate);
@@ -14329,7 +14467,7 @@ async function collectPageFilePaths(dir) {
14329
14467
  const files = [];
14330
14468
  const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
14331
14469
  const resolved = await mapWithConcurrency(entries, DIR_SCAN_CONCURRENCY, async (entry) => {
14332
- const absolutePath = toPosixPath2(join15(dir, entry.name));
14470
+ const absolutePath = toPosixPath2(join16(dir, entry.name));
14333
14471
  if (entry.isDirectory()) {
14334
14472
  return await collectPageFilePaths(absolutePath);
14335
14473
  }
@@ -14448,20 +14586,23 @@ function resolveAppSpecs(options, serverEntry, rootDir) {
14448
14586
  return [{ pagesDir: resolve9(rootDir, "src/pages"), prefix: "" }];
14449
14587
  }
14450
14588
  async function buildApp(options) {
14589
+ return withProductionBuild(() => buildAppInternal(options));
14590
+ }
14591
+ async function buildAppInternal(options) {
14451
14592
  const rootDir = resolve9(options.rootDir ?? process.cwd());
14452
- const buildRoot = join16(rootDir, BUILD_OUTPUT_DIR);
14593
+ const buildRoot = join17(rootDir, BUILD_OUTPUT_DIR);
14453
14594
  const serverEntry = (() => {
14454
14595
  if (options.target === "static" || options.target === "package") {
14455
14596
  return null;
14456
14597
  }
14457
14598
  if (options.serverEntry) {
14458
14599
  const resolved = resolve9(rootDir, options.serverEntry);
14459
- if (existsSync14(resolved)) {
14600
+ if (existsSync15(resolved)) {
14460
14601
  return resolved;
14461
14602
  }
14462
14603
  }
14463
14604
  const entry = resolve9(rootDir, "src/server.ts");
14464
- if (!existsSync14(entry)) {
14605
+ if (!existsSync15(entry)) {
14465
14606
  throw new Error("[furin] Entrypoint server.ts not found");
14466
14607
  }
14467
14608
  return entry;
@@ -14501,12 +14642,12 @@ async function buildApp(options) {
14501
14642
  version: 1,
14502
14643
  generatedAt: new Date().toISOString(),
14503
14644
  rootDir: toPosixPath(rootDir),
14504
- pagesDir: toPosixPath(relative10(rootDir, primaryApp.pagesDir)),
14505
- rootPath: toPosixPath(relative10(rootDir, primaryApp.root.path)),
14506
- serverEntry: serverEntry ? toPosixPath(relative10(rootDir, serverEntry)) : null,
14645
+ pagesDir: toPosixPath(relative11(rootDir, primaryApp.pagesDir)),
14646
+ rootPath: toPosixPath(relative11(rootDir, primaryApp.root.path)),
14647
+ serverEntry: serverEntry ? toPosixPath(relative11(rootDir, serverEntry)) : null,
14507
14648
  routes: primaryApp.routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
14508
14649
  apps: apps.map((app) => ({
14509
- pagesDir: toPosixPath(relative10(rootDir, app.pagesDir)),
14650
+ pagesDir: toPosixPath(relative11(rootDir, app.pagesDir)),
14510
14651
  prefix: app.prefix,
14511
14652
  routes: app.routes.map((route) => toBuildRouteManifestEntry(route, rootDir))
14512
14653
  })),
@@ -14542,7 +14683,7 @@ async function buildApp(options) {
14542
14683
  throw new Error(`[furin] Unsupported build target "${target}"`);
14543
14684
  }
14544
14685
  }
14545
- writeFileSync10(join16(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
14686
+ writeFileSync11(join17(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
14546
14687
  `);
14547
14688
  return {
14548
14689
  manifest,