@teyik0/furin 0.2.0-alpha.4 → 0.2.0-alpha.5

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 (67) hide show
  1. package/dist/adapter/bun.d.ts +17 -1
  2. package/dist/adapter/package.d.ts +26 -0
  3. package/dist/build/client.d.ts +1 -1
  4. package/dist/build/compile-entry.d.ts +3 -3
  5. package/dist/build/compile-entry.ts +88 -83
  6. package/dist/build/entry-template.d.ts +35 -9
  7. package/dist/build/entry-template.ts +106 -56
  8. package/dist/build/hydrate.d.ts +1 -1
  9. package/dist/build/index.js +643 -247
  10. package/dist/build/scan-server.d.ts +10 -4
  11. package/dist/build/server-routes-entry.d.ts +3 -3
  12. package/dist/build/server-routes-entry.ts +5 -11
  13. package/dist/build/ssg-cache.d.ts +1 -1
  14. package/dist/build/types.d.ts +36 -1
  15. package/dist/cli/config.d.ts +6 -1
  16. package/dist/cli/index.js +662 -260
  17. package/dist/config.d.ts +11 -2
  18. package/dist/config.js +5 -1
  19. package/dist/furin.d.ts +36 -18
  20. package/dist/furin.js +630 -310
  21. package/dist/server/auto-invalidate/registry.d.ts +8 -1
  22. package/dist/server/cache/dev-loader.d.ts +3 -2
  23. package/dist/server/cache/invalidation.d.ts +19 -0
  24. package/dist/server/cache/isr.d.ts +6 -2
  25. package/dist/server/cache/registry.d.ts +3 -3
  26. package/dist/server/cache/ssg.d.ts +6 -2
  27. package/dist/server/cache/store-view.d.ts +11 -0
  28. package/dist/server/instance.d.ts +86 -0
  29. package/dist/server/internal.d.ts +16 -1
  30. package/dist/server/internal.js +72 -5
  31. package/dist/server/render/template.d.ts +3 -2
  32. package/dist/server/sync/config.d.ts +11 -0
  33. package/dist/server/sync/stream.d.ts +8 -1
  34. package/dist/shared/prefix.d.ts +15 -0
  35. package/package.json +6 -1
  36. package/src/adapter/bun.ts +113 -50
  37. package/src/adapter/package.ts +206 -0
  38. package/src/build/client.ts +9 -3
  39. package/src/build/compile-entry.ts +88 -83
  40. package/src/build/entry-template.ts +106 -56
  41. package/src/build/hydrate.ts +4 -2
  42. package/src/build/index.ts +99 -28
  43. package/src/build/scan-server.ts +23 -7
  44. package/src/build/server-routes-entry.ts +5 -11
  45. package/src/build/ssg-cache.ts +6 -2
  46. package/src/build/types.ts +37 -1
  47. package/src/cli/config.ts +9 -3
  48. package/src/cli/index.ts +21 -3
  49. package/src/config.ts +14 -1
  50. package/src/furin.ts +297 -143
  51. package/src/server/auto-invalidate/registry.ts +23 -1
  52. package/src/server/auto-invalidate/runtime.ts +29 -4
  53. package/src/server/cache/dev-loader.ts +77 -38
  54. package/src/server/cache/invalidation.ts +71 -30
  55. package/src/server/cache/isr.ts +20 -5
  56. package/src/server/cache/registry.ts +17 -20
  57. package/src/server/cache/ssg.ts +19 -4
  58. package/src/server/cache/store-view.ts +30 -0
  59. package/src/server/instance.ts +252 -0
  60. package/src/server/internal.ts +100 -5
  61. package/src/server/render/not-found.ts +9 -3
  62. package/src/server/render/ssr.ts +16 -4
  63. package/src/server/render/template.ts +57 -24
  64. package/src/server/sync/config.ts +32 -1
  65. package/src/server/sync/plugin.ts +4 -5
  66. package/src/server/sync/stream.ts +19 -9
  67. package/src/shared/prefix.ts +38 -0
@@ -1,7 +1,7 @@
1
1
  // @bun
2
2
  // src/build/index.ts
3
- import { existsSync as existsSync10, writeFileSync as writeFileSync8 } from "fs";
4
- import { join as join11, relative as relative4, resolve as resolve3 } from "path";
3
+ import { existsSync as existsSync11, writeFileSync as writeFileSync9 } from "fs";
4
+ import { join as join12, relative as relative5, resolve as resolve4 } from "path";
5
5
 
6
6
  // src/adapter/bun.ts
7
7
  import { existsSync as existsSync8, rmSync as rmSync2, writeFileSync as writeFileSync6 } from "fs";
@@ -1660,10 +1660,127 @@ function validateRouteChain(chain, root, pagePath) {
1660
1660
  }
1661
1661
  }
1662
1662
 
1663
+ // src/server/instance.ts
1664
+ import { AsyncLocalStorage } from "async_hooks";
1665
+ var _requestScope = new AsyncLocalStorage;
1666
+ var WHITESPACE_RE = /\s/;
1667
+ var _instances = new Map;
1668
+ var _defaultInstance = null;
1669
+ function createInstance(prefix, pagesDir) {
1670
+ return {
1671
+ prefix,
1672
+ pagesDir,
1673
+ syncStreamPath: undefined,
1674
+ buildId: "",
1675
+ registrationEpoch: 0,
1676
+ state: new Map
1677
+ };
1678
+ }
1679
+ function defaultInstance() {
1680
+ if (!_defaultInstance) {
1681
+ _defaultInstance = createInstance("", "");
1682
+ }
1683
+ return _defaultInstance;
1684
+ }
1685
+ function defaultInstanceBucket() {
1686
+ return defaultInstance();
1687
+ }
1688
+ function normalizePrefix(prefix) {
1689
+ if (prefix === undefined || prefix === "" || prefix === "/") {
1690
+ return "";
1691
+ }
1692
+ if (!prefix.startsWith("/")) {
1693
+ throw new Error(`[furin] prefix must start with "/" (got "${prefix}").`);
1694
+ }
1695
+ if (prefix.includes("//") || WHITESPACE_RE.test(prefix)) {
1696
+ throw new Error(`[furin] invalid prefix "${prefix}".`);
1697
+ }
1698
+ return prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
1699
+ }
1700
+ function currentInstance() {
1701
+ const scope = _requestScope.getStore();
1702
+ if (scope) {
1703
+ return scope.instance;
1704
+ }
1705
+ if (_instances.size === 1) {
1706
+ const only = _instances.values().next().value;
1707
+ if (only) {
1708
+ return only;
1709
+ }
1710
+ }
1711
+ return defaultInstance();
1712
+ }
1713
+ function instanceSlot(init) {
1714
+ const key = Symbol("furin-instance-slot");
1715
+ return (instance) => {
1716
+ const target = instance ?? currentInstance();
1717
+ if (target.state.has(key)) {
1718
+ return target.state.get(key);
1719
+ }
1720
+ const value = init(target);
1721
+ target.state.set(key, value);
1722
+ return value;
1723
+ };
1724
+ }
1725
+
1663
1726
  // src/server/internal.ts
1664
- var _compileCtx = null;
1665
- function getCompileContext() {
1666
- return _compileCtx;
1727
+ var _compileContexts = new Map;
1728
+ function normalizeContextKey(path) {
1729
+ return path.replaceAll("\\", "/");
1730
+ }
1731
+ function pagesDirOf(ctx) {
1732
+ const rootPath = normalizeContextKey(ctx.rootPath);
1733
+ const lastSlash = rootPath.lastIndexOf("/");
1734
+ return lastSlash === -1 ? rootPath : rootPath.slice(0, lastSlash);
1735
+ }
1736
+ function contextKey(pagesDir, prefix) {
1737
+ return `${pagesDir}\x00${prefix}`;
1738
+ }
1739
+ function getCompileContext(pagesDir, prefix) {
1740
+ if (pagesDir !== undefined) {
1741
+ const dir = normalizeContextKey(pagesDir);
1742
+ if (prefix !== undefined) {
1743
+ const exact = _compileContexts.get(contextKey(dir, prefix));
1744
+ if (exact) {
1745
+ return exact;
1746
+ }
1747
+ }
1748
+ const dirMatch = soleContextForPagesDir(dir);
1749
+ if (dirMatch) {
1750
+ return dirMatch;
1751
+ }
1752
+ }
1753
+ if (prefix !== undefined) {
1754
+ const prefixMatch = contextForPrefix(prefix);
1755
+ if (prefixMatch) {
1756
+ return prefixMatch;
1757
+ }
1758
+ }
1759
+ if (_compileContexts.size === 1) {
1760
+ return _compileContexts.values().next().value ?? null;
1761
+ }
1762
+ return null;
1763
+ }
1764
+ function soleContextForPagesDir(dir) {
1765
+ let match = null;
1766
+ for (const ctx of _compileContexts.values()) {
1767
+ if (pagesDirOf(ctx) !== dir) {
1768
+ continue;
1769
+ }
1770
+ if (match) {
1771
+ return null;
1772
+ }
1773
+ match = ctx;
1774
+ }
1775
+ return match;
1776
+ }
1777
+ function contextForPrefix(prefix) {
1778
+ for (const ctx of _compileContexts.values()) {
1779
+ if ((ctx.prefix ?? "") === prefix) {
1780
+ return ctx;
1781
+ }
1782
+ }
1783
+ return null;
1667
1784
  }
1668
1785
 
1669
1786
  // src/server/runtime-env.ts
@@ -2507,7 +2624,7 @@ const rootEl = document.getElementById("root") as HTMLElement;
2507
2624
  });
2508
2625
  `;
2509
2626
  }
2510
- function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging }, projectRoot) {
2627
+ function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging, skipRouteTypes }, projectRoot) {
2511
2628
  if (!existsSync3(outDir)) {
2512
2629
  mkdirSync(outDir, { recursive: true });
2513
2630
  }
@@ -2523,7 +2640,9 @@ function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging },
2523
2640
  if (indexHtml !== existingIndex) {
2524
2641
  writeFileSync2(indexPath, indexHtml);
2525
2642
  }
2526
- writeRouteTypes(routes, projectRoot);
2643
+ if (!skipRouteTypes) {
2644
+ writeRouteTypes(routes, projectRoot);
2645
+ }
2527
2646
  console.log("[furin] Dev files written (.furin/_hydrate.tsx + .furin/index.html + furin-env.d.ts)");
2528
2647
  }
2529
2648
 
@@ -2586,8 +2705,9 @@ function buildTargetManifest(rootDir, buildRoot, target, serverEntry) {
2586
2705
 
2587
2706
  // src/build/client.ts
2588
2707
  var TS_FILE_FILTER = /\.(tsx|ts)$/;
2589
- async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, basePath, clientLogging }) {
2590
- const clientDir = join5(outDir, "client");
2708
+ async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, basePath, clientLogging, clientDirName }) {
2709
+ const dirName = clientDirName ?? "client";
2710
+ const clientDir = join5(outDir, dirName);
2591
2711
  if (!existsSync5(outDir)) {
2592
2712
  mkdirSync3(outDir, { recursive: true });
2593
2713
  }
@@ -2595,7 +2715,7 @@ async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, ba
2595
2715
  mkdirSync3(clientDir, { recursive: true });
2596
2716
  }
2597
2717
  const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
2598
- const hydratePath = join5(outDir, "_hydrate.tsx");
2718
+ const hydratePath = join5(outDir, dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`);
2599
2719
  writeFileSync3(hydratePath, hydrateCode);
2600
2720
  console.log("[furin] Building production client bundle\u2026");
2601
2721
  const transformPlugin = {
@@ -2701,55 +2821,29 @@ function collectConventionPaths(rootConventions, routeMetadata) {
2701
2821
  }
2702
2822
  return [...new Set(paths)];
2703
2823
  }
2704
- function buildEntrySource(options) {
2705
- const {
2706
- buildId,
2707
- headerComment,
2708
- rootPath,
2709
- routes,
2710
- serverEntry,
2711
- rootConventions,
2712
- routeMetadata,
2713
- ssgCache
2714
- } = options;
2715
- let { extraImports, extraContext } = options;
2716
- if (extraImports === undefined) {
2717
- extraImports = [];
2718
- }
2719
- if (extraContext === undefined) {
2720
- extraContext = [];
2721
- }
2824
+ function buildAppContextBlock(app, varPrefix) {
2722
2825
  const allModulePaths = [
2723
- rootPath,
2724
- ...routes.map((r) => r.path),
2725
- ...collectConventionPaths(rootConventions, routeMetadata)
2826
+ app.rootPath,
2827
+ ...app.routes.map((r) => r.path),
2828
+ ...collectConventionPaths(app.rootConventions, app.routeMetadata)
2726
2829
  ];
2727
- const moduleImports = [];
2830
+ const importLines = [];
2728
2831
  const moduleEntries = [];
2729
2832
  for (let i = 0;i < allModulePaths.length; i++) {
2730
2833
  const absPath = allModulePaths[i].replace(/\\/g, "/");
2731
- const varName = `_mod${i}`;
2732
- moduleImports.push(`import * as ${varName} from ${JSON.stringify(absPath)};`);
2834
+ const varName = `${varPrefix}mod${i}`;
2835
+ importLines.push(`import * as ${varName} from ${JSON.stringify(absPath)};`);
2733
2836
  moduleEntries.push(` ${JSON.stringify(absPath)}: ${varName},`);
2734
2837
  }
2735
- const routeEntries = routes.map((r) => ` { pattern: ${JSON.stringify(r.pattern)}, path: ${JSON.stringify(r.path.replace(/\\/g, "/"))}, mode: ${JSON.stringify(r.mode)} },`);
2736
- const rootConventionsLine = rootConventions ? ` rootConventions: ${JSON.stringify(rootConventions)},` : "";
2737
- const routeMetadataLine = routeMetadata ? ` routeMetadata: ${JSON.stringify(routeMetadata)},` : "";
2738
- const ssgCacheLine = ssgCache ? ` ssgCache: ${JSON.stringify(ssgCache)},` : "";
2739
- const lines = [
2740
- headerComment,
2741
- `import { __setCompileContext } from ${JSON.stringify(INTERNAL_MODULE_PATH)};`,
2742
- `import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`,
2743
- ...moduleImports,
2744
- ...extraImports.length > 0 ? ["", ...extraImports] : [],
2745
- "",
2746
- "// Force production mode \u2014 Bun may inline process.env.NODE_ENV at bundle time.",
2747
- "__setDevMode(false);",
2748
- 'process.env.NODE_ENV = "production";',
2749
- "",
2838
+ const routeEntries = app.routes.map((r) => ` { pattern: ${JSON.stringify(r.pattern)}, path: ${JSON.stringify(r.path.replace(/\\/g, "/"))}, mode: ${JSON.stringify(r.mode)} },`);
2839
+ const rootConventionsLine = app.rootConventions ? ` rootConventions: ${JSON.stringify(app.rootConventions)},` : "";
2840
+ const routeMetadataLine = app.routeMetadata ? ` routeMetadata: ${JSON.stringify(app.routeMetadata)},` : "";
2841
+ const ssgCacheLine = app.ssgCache ? ` ssgCache: ${JSON.stringify(app.ssgCache)},` : "";
2842
+ const contextLines = [
2750
2843
  "__setCompileContext({",
2751
- ` buildId: ${JSON.stringify(buildId ?? "")},`,
2752
- ` rootPath: ${JSON.stringify(rootPath.replace(/\\/g, "/"))},`,
2844
+ ` buildId: ${JSON.stringify(app.buildId ?? "")},`,
2845
+ ` prefix: ${JSON.stringify(app.prefix ?? "")},`,
2846
+ ` rootPath: ${JSON.stringify(app.rootPath.replace(/\\/g, "/"))},`,
2753
2847
  rootConventionsLine,
2754
2848
  " modules: {",
2755
2849
  ...moduleEntries,
@@ -2759,87 +2853,113 @@ function buildEntrySource(options) {
2759
2853
  " ],",
2760
2854
  routeMetadataLine,
2761
2855
  ssgCacheLine,
2762
- ...extraContext,
2763
- "});",
2856
+ ...app.extraContext ?? [],
2857
+ "});"
2858
+ ];
2859
+ return { contextLines, importLines };
2860
+ }
2861
+ function buildEntrySource(options) {
2862
+ const { apps, headerComment, serverEntry } = options;
2863
+ const mode = options.mode ?? "boot";
2864
+ const internalSpecifier = mode === "register" ? "@teyik0/furin/internal" : INTERNAL_MODULE_PATH;
2865
+ const importLines = [];
2866
+ const contextBlocks = [];
2867
+ for (let appIndex = 0;appIndex < apps.length; appIndex++) {
2868
+ const app = apps[appIndex];
2869
+ const varPrefix = apps.length === 1 ? "_" : `_a${appIndex}_`;
2870
+ const block = buildAppContextBlock(app, varPrefix);
2871
+ importLines.push(...block.importLines);
2872
+ if (app.extraImports && app.extraImports.length > 0) {
2873
+ importLines.push("", ...app.extraImports);
2874
+ }
2875
+ contextBlocks.push("", ...block.contextLines);
2876
+ }
2877
+ const lines = [
2878
+ headerComment,
2879
+ `import { __setCompileContext } from ${JSON.stringify(internalSpecifier)};`,
2880
+ ...mode === "boot" ? [`import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`] : [],
2881
+ ...importLines,
2882
+ ...mode === "boot" ? [
2883
+ "",
2884
+ "// Force production mode \u2014 Bun may inline process.env.NODE_ENV at bundle time.",
2885
+ "__setDevMode(false);",
2886
+ 'process.env.NODE_ENV = "production";'
2887
+ ] : [],
2888
+ ...contextBlocks,
2764
2889
  "",
2765
- `await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
2766
- ""
2890
+ ...serverEntry ? [`await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`, ""] : []
2767
2891
  ];
2768
2892
  return lines.join(`
2769
2893
  `);
2770
2894
  }
2771
2895
 
2772
2896
  // src/build/compile-entry.ts
2773
- function generateCompileEntry(options) {
2774
- const {
2775
- buildId,
2776
- outDir,
2777
- rootPath,
2778
- routes,
2779
- serverEntry,
2780
- embed,
2781
- publicDir,
2782
- rootConventions,
2783
- routeMetadata,
2784
- ssgCache
2785
- } = options;
2786
- ensureDir(outDir);
2897
+ function buildEmbeddedAssets(outDir, clientDir, publicDir, varPrefix) {
2898
+ if (!existsSync7(clientDir)) {
2899
+ throw new Error(`[furin] Client directory not found: ${clientDir}. Run the client build first.`);
2900
+ }
2901
+ const clientFiles = collectFilesRecursive(clientDir).filter((file) => !file.endsWith(".map"));
2787
2902
  const assetImports = [];
2788
- let embeddedBlock = [];
2789
- if (embed) {
2790
- if (!existsSync7(embed.clientDir)) {
2791
- throw new Error(`[furin] Client directory not found: ${embed.clientDir}. Run the client build first.`);
2792
- }
2793
- const clientFiles = collectFilesRecursive(embed.clientDir).filter((file) => !file.endsWith(".map"));
2794
- const assetEntries = [];
2795
- let templateVarName = null;
2796
- let assetIndex = 0;
2797
- for (const file of clientFiles) {
2798
- const varName = `_asset${assetIndex++}`;
2799
- const relPath = toPosixPath2(relative2(outDir, file));
2800
- const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
2801
- assetImports.push(`import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`);
2802
- const clientRelativePath = toPosixPath2(relative2(embed.clientDir, file));
2803
- if (clientRelativePath === "index.html") {
2804
- templateVarName = varName;
2805
- } else {
2806
- assetEntries.push(` ${JSON.stringify(`/_client/${clientRelativePath}`)}: ${varName},`);
2807
- }
2903
+ const assetEntries = [];
2904
+ let templateVarName = null;
2905
+ let assetIndex = 0;
2906
+ const importAsset = (file) => {
2907
+ const varName = `${varPrefix}asset${assetIndex++}`;
2908
+ const relPath = toPosixPath2(relative2(outDir, file));
2909
+ const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
2910
+ assetImports.push(`import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`);
2911
+ return varName;
2912
+ };
2913
+ for (const file of clientFiles) {
2914
+ const varName = importAsset(file);
2915
+ const clientRelativePath = toPosixPath2(relative2(clientDir, file));
2916
+ if (clientRelativePath === "index.html") {
2917
+ templateVarName = varName;
2918
+ } else {
2919
+ assetEntries.push(` ${JSON.stringify(`/_client/${clientRelativePath}`)}: ${varName},`);
2808
2920
  }
2809
- if (templateVarName === null) {
2810
- throw new Error(`[furin] Embed mode requires a client index.html at ${join7(embed.clientDir, "index.html")}. Run the client build first.`);
2811
- }
2812
- if (publicDir && existsSync7(publicDir)) {
2813
- const publicFiles = collectFilesRecursive(publicDir);
2814
- for (const file of publicFiles) {
2815
- const varName = `_asset${assetIndex++}`;
2816
- const relPath = toPosixPath2(relative2(outDir, file));
2817
- const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
2818
- assetImports.push(`import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`);
2819
- const publicRelativePath = toPosixPath2(relative2(publicDir, file));
2820
- assetEntries.push(` ${JSON.stringify(`/public/${publicRelativePath}`)}: ${varName},`);
2821
- }
2921
+ }
2922
+ if (templateVarName === null) {
2923
+ throw new Error(`[furin] Embed mode requires a client index.html at ${join7(clientDir, "index.html")}. Run the client build first.`);
2924
+ }
2925
+ if (publicDir && existsSync7(publicDir)) {
2926
+ const publicFiles = collectFilesRecursive(publicDir);
2927
+ for (const file of publicFiles) {
2928
+ const varName = importAsset(file);
2929
+ const publicRelativePath = toPosixPath2(relative2(publicDir, file));
2930
+ assetEntries.push(` ${JSON.stringify(`/public/${publicRelativePath}`)}: ${varName},`);
2822
2931
  }
2823
- embeddedBlock = [
2824
- " embedded: {",
2825
- ` template: ${templateVarName},`,
2826
- " assets: {",
2827
- ...assetEntries,
2828
- " },",
2829
- " },"
2830
- ];
2831
2932
  }
2933
+ const extraContext = [
2934
+ " embedded: {",
2935
+ ` template: ${templateVarName},`,
2936
+ " assets: {",
2937
+ ...assetEntries,
2938
+ " },",
2939
+ " },"
2940
+ ];
2941
+ return { extraContext, extraImports: assetImports };
2942
+ }
2943
+ function generateCompileEntry(options) {
2944
+ const { apps, outDir, serverEntry, publicDir } = options;
2945
+ ensureDir(outDir);
2946
+ const preparedApps = apps.map((app, appIndex) => {
2947
+ const { embed, ...context } = app;
2948
+ if (!embed) {
2949
+ return context;
2950
+ }
2951
+ const varPrefix = apps.length === 1 ? "_" : `_a${appIndex}_`;
2952
+ const embedded = buildEmbeddedAssets(outDir, embed.clientDir, publicDir, varPrefix);
2953
+ return {
2954
+ ...context,
2955
+ extraContext: [...context.extraContext ?? [], ...embedded.extraContext],
2956
+ extraImports: [...context.extraImports ?? [], ...embedded.extraImports]
2957
+ };
2958
+ });
2832
2959
  const source = buildEntrySource({
2833
- buildId,
2834
- headerComment: "// Auto-generated by furin compile \u2014 do not edit",
2835
- rootPath,
2836
- routes,
2837
- serverEntry,
2838
- extraImports: assetImports,
2839
- extraContext: embeddedBlock,
2840
- rootConventions,
2841
- routeMetadata,
2842
- ssgCache
2960
+ apps: preparedApps,
2961
+ headerComment: options.headerComment ?? "// Auto-generated by furin compile \u2014 do not edit",
2962
+ serverEntry
2843
2963
  });
2844
2964
  const entryPath = join7(outDir, "_compile-entry.ts");
2845
2965
  writeFileSync4(entryPath, source);
@@ -2850,17 +2970,12 @@ function generateCompileEntry(options) {
2850
2970
  import { writeFileSync as writeFileSync5 } from "fs";
2851
2971
  import { join as join8 } from "path";
2852
2972
  function generateServerRoutesEntry(options) {
2853
- const { buildId, outDir, rootPath, routes, serverEntry, rootConventions, routeMetadata, ssgCache } = options;
2973
+ const { apps, outDir, serverEntry } = options;
2854
2974
  ensureDir(outDir);
2855
2975
  const source = buildEntrySource({
2856
- buildId,
2976
+ apps: apps.map(({ embed: _embed, ...context }) => context),
2857
2977
  headerComment: "// Auto-generated by furin build \u2014 do not edit",
2858
- rootPath,
2859
- routes,
2860
- serverEntry,
2861
- rootConventions,
2862
- routeMetadata,
2863
- ssgCache
2978
+ serverEntry
2864
2979
  });
2865
2980
  const entryPath = join8(outDir, "server.ts");
2866
2981
  writeFileSync5(entryPath, source);
@@ -2918,7 +3033,13 @@ class AutoInvalidateRegistry {
2918
3033
  this.tagToPaths.clear();
2919
3034
  }
2920
3035
  }
2921
- var autoInvalidateRegistry = new AutoInvalidateRegistry;
3036
+ var instanceAutoInvalidateRegistry = instanceSlot(() => new AutoInvalidateRegistry);
3037
+ var autoInvalidateRegistry = {
3038
+ registerLoaderTags: (urlPath, tags) => instanceAutoInvalidateRegistry().registerLoaderTags(urlPath, tags),
3039
+ pathsForTags: (tags) => instanceAutoInvalidateRegistry().pathsForTags(tags),
3040
+ unregisterPath: (urlPath) => instanceAutoInvalidateRegistry().unregisterPath(urlPath),
3041
+ reset: () => instanceAutoInvalidateRegistry().reset()
3042
+ };
2922
3043
 
2923
3044
  // src/server/cache/route-cache.ts
2924
3045
  function defaultPathFromKey(key) {
@@ -3022,19 +3143,60 @@ function createHtmlRouteCache(mode) {
3022
3143
  });
3023
3144
  }
3024
3145
 
3146
+ // src/server/cache/registry.ts
3147
+ var instanceInvalidators = instanceSlot(() => new Map);
3148
+ function registerCacheInvalidator(invalidator, instance) {
3149
+ const invalidators = instanceInvalidators(instance);
3150
+ const existing = invalidators.get(invalidator.name);
3151
+ if (existing !== undefined && existing !== invalidator) {
3152
+ throw new Error(`Cache invalidator "${invalidator.name}" is already registered for this furin instance with a different invalidator object.`);
3153
+ }
3154
+ invalidators.set(invalidator.name, invalidator);
3155
+ return () => {
3156
+ if (invalidators.get(invalidator.name) === invalidator) {
3157
+ invalidators.delete(invalidator.name);
3158
+ }
3159
+ };
3160
+ }
3161
+
3162
+ // src/server/cache/store-view.ts
3163
+ function createStoreView(resolve) {
3164
+ return {
3165
+ clear: () => resolve().clear(),
3166
+ delete: (key) => resolve().delete(key),
3167
+ entries: () => resolve().entries(),
3168
+ get: (key) => resolve().get(key),
3169
+ has: (key) => resolve().has(key),
3170
+ keys: () => resolve().keys(),
3171
+ set: (key, entry) => {
3172
+ resolve().set(key, entry);
3173
+ },
3174
+ get size() {
3175
+ return resolve().size;
3176
+ }
3177
+ };
3178
+ }
3179
+
3025
3180
  // src/server/cache/ssg.ts
3026
- var ssgRouteCache = createHtmlRouteCache("ssg");
3027
- var ssgCache = ssgRouteCache.store;
3181
+ var instanceSsgCache = instanceSlot((instance) => {
3182
+ const cache = createHtmlRouteCache("ssg");
3183
+ registerCacheInvalidator(cache, instance);
3184
+ return cache;
3185
+ });
3186
+ function ssgRouteCache(instance) {
3187
+ return instanceSsgCache(instance);
3188
+ }
3189
+ var ssgCache = createStoreView(() => instanceSsgCache().store);
3028
3190
  function getSSGCache(key) {
3029
- return ssgRouteCache.get(key);
3191
+ return instanceSsgCache().get(key);
3030
3192
  }
3031
3193
  function setSSGCache(key, entry) {
3032
- ssgRouteCache.set(key, entry);
3194
+ instanceSsgCache().set(key, entry);
3033
3195
  autoInvalidateRegistry.registerLoaderTags(key, entry.tags);
3034
3196
  }
3035
3197
 
3036
3198
  // src/server/context-logger.ts
3037
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
3199
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
3038
3200
  // ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/utils.mjs
3039
3201
  function formatDuration(ms) {
3040
3202
  if (ms < 1000)
@@ -5223,9 +5385,9 @@ function defineFrameworkIntegration(spec) {
5223
5385
  }
5224
5386
 
5225
5387
  // ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/elysia/index.mjs
5226
- import { AsyncLocalStorage } from "async_hooks";
5388
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
5227
5389
  import { Elysia } from "elysia";
5228
- var storage = new AsyncLocalStorage;
5390
+ var storage = new AsyncLocalStorage2;
5229
5391
  var activeLoggers = /* @__PURE__ */ new WeakSet;
5230
5392
  function useLogger2() {
5231
5393
  const logger = storage.getStore();
@@ -5269,7 +5431,7 @@ var noopLogger2 = {
5269
5431
  getContext: () => ({}),
5270
5432
  fork: (_label, fn) => fn()
5271
5433
  };
5272
- var syntheticRenderStorage = new AsyncLocalStorage2;
5434
+ var syntheticRenderStorage = new AsyncLocalStorage3;
5273
5435
  function useLogger3() {
5274
5436
  try {
5275
5437
  return useLogger2();
@@ -5291,10 +5453,14 @@ async function runInSyntheticRenderScope(fn, initialContext) {
5291
5453
  }
5292
5454
 
5293
5455
  // src/server/sync/config.ts
5294
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
5295
- var requestSyncStreamPath = new AsyncLocalStorage3;
5456
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
5457
+ var requestSyncStreamPath = new AsyncLocalStorage4;
5296
5458
  function getSyncStreamPath() {
5297
- return requestSyncStreamPath.getStore();
5459
+ const override = requestSyncStreamPath.getStore();
5460
+ if (override !== undefined) {
5461
+ return override;
5462
+ }
5463
+ return currentInstance().syncStreamPath;
5298
5464
  }
5299
5465
 
5300
5466
  // src/server/render/assemble.ts
@@ -6435,6 +6601,12 @@ function normalizeHref(href) {
6435
6601
  }
6436
6602
  return pathname + url.search + url.hash;
6437
6603
  }
6604
+ function toLogical(physicalPathname, basePath) {
6605
+ if (basePath && physicalPathname.startsWith(basePath) && (physicalPathname.length === basePath.length || physicalPathname[basePath.length] === "/")) {
6606
+ return physicalPathname.slice(basePath.length) || "/";
6607
+ }
6608
+ return physicalPathname;
6609
+ }
6438
6610
  // src/client/router/search-store.ts
6439
6611
  import { createContext as createContext2 } from "react";
6440
6612
  function searchSnapshotChanged(a, b) {
@@ -7341,36 +7513,46 @@ async function runLoaders(route, ctx) {
7341
7513
 
7342
7514
  // src/server/render/template.ts
7343
7515
  import { readFileSync as readFileSync3 } from "fs";
7344
- var _prodTemplatePath = null;
7345
- var _prodTemplateContent = null;
7346
- var _devTemplateCache = null;
7516
+ var instanceTemplateState = instanceSlot(() => ({ devCache: null, prodContent: null, prodPath: null }));
7347
7517
  var DEV_TEMPLATE_TTL_MS = 1000;
7348
7518
  async function getDevTemplate(origin) {
7349
- if (_devTemplateCache && Date.now() - _devTemplateCache.ts < DEV_TEMPLATE_TTL_MS) {
7350
- return _devTemplateCache.html;
7519
+ const instance = currentInstance();
7520
+ const state = instanceTemplateState(instance);
7521
+ if (state.devCache && Date.now() - state.devCache.ts < DEV_TEMPLATE_TTL_MS) {
7522
+ return state.devCache.html;
7351
7523
  }
7352
- const r = await fetch(`${origin}/_bun_hmr_entry`);
7524
+ const entryPath = `${instance.prefix}/_bun_hmr_entry`;
7525
+ const r = await fetch(`${origin}${entryPath}`);
7353
7526
  if (!r.ok) {
7354
- throw new Error(`/_bun_hmr_entry returned ${r.status}`);
7527
+ throw new Error(`${entryPath} returned ${r.status}`);
7355
7528
  }
7356
7529
  const html = await r.text();
7357
- _devTemplateCache = { html, ts: Date.now() };
7530
+ state.devCache = { html, ts: Date.now() };
7358
7531
  return html;
7359
7532
  }
7360
- function setProductionTemplateContent(content) {
7361
- _prodTemplatePath = null;
7362
- _prodTemplateContent = content;
7533
+ function setProductionTemplateContent(content, instance) {
7534
+ const state = instanceTemplateState(instance);
7535
+ state.prodPath = null;
7536
+ state.prodContent = content;
7363
7537
  }
7364
7538
  function getProductionTemplate() {
7365
- if (_prodTemplateContent !== null) {
7366
- return _prodTemplateContent;
7539
+ const own = readTemplate(instanceTemplateState());
7540
+ if (own !== null) {
7541
+ return own;
7542
+ }
7543
+ const fallback = instanceTemplateState(defaultInstanceBucket());
7544
+ return readTemplate(fallback);
7545
+ }
7546
+ function readTemplate(state) {
7547
+ if (state.prodContent !== null) {
7548
+ return state.prodContent;
7367
7549
  }
7368
- if (!_prodTemplatePath) {
7550
+ if (!state.prodPath) {
7369
7551
  return null;
7370
7552
  }
7371
7553
  try {
7372
- _prodTemplateContent = readFileSync3(_prodTemplatePath, "utf8");
7373
- return _prodTemplateContent;
7554
+ state.prodContent = readFileSync3(state.prodPath, "utf8");
7555
+ return state.prodContent;
7374
7556
  } catch {
7375
7557
  return null;
7376
7558
  }
@@ -7385,10 +7567,10 @@ function assertDeferredModeAllowed(route, deferredPromises) {
7385
7567
  throw new Error(`[furin] page "${route.pattern}" returned defer() but the route is rendered in "${route.mode}" mode. ` + "defer() streams data progressively and is only supported in SSR. " + "Return the data directly (await it inside the loader) or switch the route to SSR mode.");
7386
7568
  }
7387
7569
  }
7388
- function currentHrefFromContext(ctx) {
7570
+ function currentHrefFromContext(ctx, basePath) {
7389
7571
  const pathUrl = new URL(ctx.path, "http://furin.local");
7390
7572
  const requestUrl = new URL(ctx.request.url);
7391
- return normalizeHref(pathUrl.pathname) + (pathUrl.search || requestUrl.search);
7573
+ return normalizeHref(toLogical(pathUrl.pathname, basePath)) + (pathUrl.search || requestUrl.search);
7392
7574
  }
7393
7575
  function buildSuccessRender(route, root, componentProps, throwOnFailure) {
7394
7576
  try {
@@ -7450,9 +7632,10 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
7450
7632
  errorDigest = success.errorDigest;
7451
7633
  status = success.status;
7452
7634
  }
7635
+ const resolvedBasePath = basePath ?? currentInstance().prefix;
7453
7636
  const ssrContext = {
7454
- basePath: basePath ?? "",
7455
- currentHref: currentHrefFromContext(ctx),
7637
+ basePath: resolvedBasePath,
7638
+ currentHref: currentHrefFromContext(ctx, resolvedBasePath),
7456
7639
  search: ctx.query ?? {},
7457
7640
  searchRoutes: searchRoutes ?? [],
7458
7641
  navigate: (_href, _opts) => Promise.resolve(),
@@ -7556,7 +7739,7 @@ async function prerenderSSG(route, params, root, origin, basePath, searchRoutes)
7556
7739
  return entry;
7557
7740
  }
7558
7741
  // src/build/ssg-cache.ts
7559
- async function buildSSGCacheSnapshot(routes, root, origin) {
7742
+ async function buildSSGCacheSnapshot(routes, root, origin, basePath) {
7560
7743
  const snapshot = {};
7561
7744
  const searchRoutes = createSearchRouteMetadata(routes);
7562
7745
  for (const route of routes) {
@@ -7565,7 +7748,7 @@ async function buildSSGCacheSnapshot(routes, root, origin) {
7565
7748
  }
7566
7749
  const paramSets = await route.page.staticParams();
7567
7750
  for (const params of paramSets) {
7568
- const entry = await prerenderSSG(route, params, root, origin, undefined, searchRoutes);
7751
+ const entry = await prerenderSSG(route, params, root, origin, basePath, searchRoutes);
7569
7752
  if (entry instanceof Response) {
7570
7753
  continue;
7571
7754
  }
@@ -7575,6 +7758,25 @@ async function buildSSGCacheSnapshot(routes, root, origin) {
7575
7758
  return snapshot;
7576
7759
  }
7577
7760
 
7761
+ // src/shared/prefix.ts
7762
+ function clientDirNameForPrefix(prefix) {
7763
+ return prefix === "" ? "client" : `client-${prefixSlug(prefix)}`;
7764
+ }
7765
+ function prefixSlug(prefix) {
7766
+ return prefix.slice(1).replaceAll("/", "-");
7767
+ }
7768
+ function assertNoPrefixSlugCollisions(prefixes) {
7769
+ const byDirName = new Map;
7770
+ for (const prefix of prefixes) {
7771
+ const dirName = clientDirNameForPrefix(prefix);
7772
+ const existing = byDirName.get(dirName);
7773
+ if (existing !== undefined && existing !== prefix) {
7774
+ throw new Error(`[furin] prefixes "${existing}" and "${prefix}" both map to the client directory ` + `"${dirName}" \u2014 rename one of them so their slugs (\`/\` \u2192 \`-\`) no longer collide.`);
7775
+ }
7776
+ byDirName.set(dirName, prefix);
7777
+ }
7778
+ }
7779
+
7578
7780
  // src/adapter/bun.ts
7579
7781
  var _pkgRoot2 = dirname2(dirname2(fileURLToPath3(import.meta.resolve("@teyik0/furin"))));
7580
7782
  var _pkgSrcDir2 = existsSync8(join9(_pkgRoot2, "src", "furin.ts")) ? join9(_pkgRoot2, "src") : join9(_pkgRoot2, "dist");
@@ -7640,52 +7842,79 @@ function buildCompileMetadata(root, routes) {
7640
7842
  }
7641
7843
  return { rootConventions, routeMetadata };
7642
7844
  }
7643
- async function buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, options) {
7644
- if (options.compile && !serverEntry) {
7645
- throw new Error(`[furin] \`compile: "${options.compile}"\` requires a server entry point. ` + "Create src/server.ts or set `serverEntry` in your furin.config.ts.");
7646
- }
7647
- const target = "bun";
7648
- const targetManifest = buildTargetManifest(rootDir, buildRoot, target, serverEntry);
7649
- const targetDir = resolve(rootDir, targetManifest.targetDir);
7650
- rmSync2(targetDir, { force: true, recursive: true });
7651
- ensureDir(targetDir);
7845
+ async function buildOneApp(app, targetDir, serverEntry, options) {
7846
+ const { prefix, root, routes } = app;
7847
+ const clientDirName = clientDirNameForPrefix(prefix);
7848
+ const label = prefix === "" ? "root app" : `app "${prefix}"`;
7652
7849
  const { entryChunk, cssChunks } = await buildClient(routes, {
7653
7850
  outDir: targetDir,
7654
7851
  rootLayout: root.path,
7655
7852
  plugins: options.plugins,
7656
- publicPath: "/_client/",
7657
- basePath: "",
7658
- clientLogging: options.clientLogging ?? false
7853
+ publicPath: `${prefix}/_client/`,
7854
+ basePath: prefix,
7855
+ clientLogging: options.clientLogging ?? false,
7856
+ clientDirName
7659
7857
  });
7660
- const buildFingerprint = await createBuildFingerprint(entryChunk, cssChunks, routes, root, serverEntry);
7858
+ const buildFingerprint = await createBuildFingerprint(`${prefix}
7859
+ ${entryChunk}`, cssChunks, routes, root, serverEntry);
7661
7860
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
7662
- targetManifest.buildId = buildId;
7663
- const clientDir = join9(targetDir, "client");
7861
+ const clientDir = join9(targetDir, clientDirName);
7664
7862
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
7665
7863
  writeFileSync6(join9(clientDir, "index.html"), indexHtml);
7666
7864
  setProductionTemplateContent(indexHtml);
7667
- const routeManifest = routes.map((r) => ({ pattern: r.pattern, path: r.path, mode: r.mode }));
7668
- const ssgCache2 = serverEntry ? await buildSSGCacheSnapshot(routes, root, "http://localhost") : undefined;
7865
+ ssgRouteCache().clear();
7866
+ const ssgCache2 = serverEntry ? await buildSSGCacheSnapshot(routes, root, "http://localhost", prefix) : undefined;
7867
+ const { rootConventions, routeMetadata } = buildCompileMetadata(root, routes);
7868
+ console.log(`[furin] Built ${label} (buildId ${buildId})`);
7869
+ return {
7870
+ buildId,
7871
+ entryApp: {
7872
+ buildId,
7873
+ prefix,
7874
+ rootPath: root.path,
7875
+ routes: routes.map((r) => ({ pattern: r.pattern, path: r.path, mode: r.mode })),
7876
+ rootConventions,
7877
+ routeMetadata,
7878
+ ssgCache: ssgCache2,
7879
+ embed: options.compile === "embed" ? { clientDir } : undefined
7880
+ },
7881
+ hydrateIntermediate: clientDirName === "client" ? "_hydrate.tsx" : `_hydrate-${clientDirName}.tsx`
7882
+ };
7883
+ }
7884
+ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
7885
+ if (options.compile && !serverEntry) {
7886
+ throw new Error(`[furin] \`compile: "${options.compile}"\` requires a server entry point. ` + "Create src/server.ts or set `serverEntry` in your furin.config.ts.");
7887
+ }
7888
+ if (apps.length === 0) {
7889
+ throw new Error("[furin] buildBunTarget requires at least one app.");
7890
+ }
7891
+ const target = "bun";
7892
+ const targetManifest = buildTargetManifest(rootDir, buildRoot, target, serverEntry);
7893
+ const targetDir = resolve(rootDir, targetManifest.targetDir);
7894
+ rmSync2(targetDir, { force: true, recursive: true });
7895
+ ensureDir(targetDir);
7669
7896
  const publicDir = existsSync8(join9(rootDir, "public")) ? join9(rootDir, "public") : undefined;
7897
+ const entryApps = [];
7898
+ const hydrateIntermediates = [];
7899
+ for (const app of apps) {
7900
+ const built = await buildOneApp(app, targetDir, serverEntry, options);
7901
+ entryApps.push(built.entryApp);
7902
+ hydrateIntermediates.push(built.hydrateIntermediate);
7903
+ if (app.prefix === "" || targetManifest.buildId === "") {
7904
+ targetManifest.buildId = built.buildId;
7905
+ }
7906
+ }
7670
7907
  const targetPublicDir = publicDir ? join9(targetDir, "public") : undefined;
7671
7908
  if (publicDir && targetPublicDir && options.compile !== "embed") {
7672
7909
  copyDirRecursive(publicDir, targetPublicDir);
7673
7910
  }
7674
- const { rootConventions, routeMetadata } = buildCompileMetadata(root, routes);
7675
7911
  if (options.compile && serverEntry) {
7676
- const clientDir2 = join9(targetDir, "client");
7677
7912
  const outfile = join9(targetDir, "server");
7678
7913
  const entryPath = generateCompileEntry({
7679
- buildId,
7680
- rootPath: root.path,
7681
- routes: routeManifest,
7914
+ apps: entryApps,
7682
7915
  serverEntry,
7683
7916
  outDir: targetDir,
7684
- embed: options.compile === "embed" ? { clientDir: clientDir2 } : undefined,
7685
- publicDir,
7686
- rootConventions,
7687
- routeMetadata,
7688
- ssgCache: ssgCache2
7917
+ publicDir
7689
7918
  });
7690
7919
  await Bun.build({
7691
7920
  entrypoints: [entryPath],
@@ -7698,20 +7927,20 @@ async function buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, opt
7698
7927
  console.log(`[furin] Server binary: ${outfile}`);
7699
7928
  targetManifest.serverPath = toPosixPath2(join9(targetManifest.targetDir, "server"));
7700
7929
  if (options.compile === "embed") {
7701
- rmSync2(clientDir2, { force: true, recursive: true });
7930
+ for (const app of apps) {
7931
+ rmSync2(join9(targetDir, clientDirNameForPrefix(app.prefix)), {
7932
+ force: true,
7933
+ recursive: true
7934
+ });
7935
+ }
7702
7936
  targetManifest.clientDir = null;
7703
7937
  targetManifest.templatePath = null;
7704
7938
  }
7705
7939
  } else if (serverEntry) {
7706
7940
  const entryPath = generateServerRoutesEntry({
7707
- buildId,
7708
- rootPath: root.path,
7709
- routes: routeManifest,
7941
+ apps: entryApps,
7710
7942
  serverEntry,
7711
- outDir: targetDir,
7712
- rootConventions,
7713
- routeMetadata,
7714
- ssgCache: ssgCache2
7943
+ outDir: targetDir
7715
7944
  });
7716
7945
  await Bun.build({
7717
7946
  entrypoints: [entryPath],
@@ -7728,25 +7957,147 @@ async function buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, opt
7728
7957
  "_compile-entry.ts",
7729
7958
  "_compile-entry.js.map",
7730
7959
  "server.ts",
7731
- "_hydrate.tsx"
7960
+ ...hydrateIntermediates
7732
7961
  ]) {
7733
7962
  rmSync2(join9(targetDir, file), { force: true });
7734
7963
  }
7735
7964
  return targetManifest;
7736
7965
  }
7737
7966
 
7967
+ // src/adapter/package.ts
7968
+ import { existsSync as existsSync9, rmSync as rmSync3, writeFileSync as writeFileSync7 } from "fs";
7969
+ import { join as join10, relative as relative3, resolve as resolve2 } from "path";
7970
+ async function buildPackageTarget(app, rootDir, buildRoot, options) {
7971
+ const { prefix, root, routes, pagesDir } = app;
7972
+ const targetDir = join10(buildRoot, "package");
7973
+ rmSync3(targetDir, { force: true, recursive: true });
7974
+ ensureDir(targetDir);
7975
+ const { entryChunk, cssChunks } = await buildClient(routes, {
7976
+ outDir: targetDir,
7977
+ rootLayout: root.path,
7978
+ plugins: options.plugins,
7979
+ publicPath: `${prefix}/_client/`,
7980
+ basePath: prefix,
7981
+ clientLogging: options.clientLogging ?? false
7982
+ });
7983
+ const buildFingerprint = await createBuildFingerprint(`${prefix}
7984
+ ${entryChunk}`, cssChunks, routes, root, null);
7985
+ const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
7986
+ const clientDir = join10(targetDir, "client");
7987
+ const publicDir = join10(rootDir, "public");
7988
+ if (existsSync9(publicDir)) {
7989
+ copyDirRecursive(publicDir, join10(targetDir, "public"));
7990
+ }
7991
+ const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
7992
+ writeFileSync7(join10(clientDir, "index.html"), indexHtml);
7993
+ setProductionTemplateContent(indexHtml);
7994
+ ssgRouteCache().clear();
7995
+ const ssgCache2 = await buildSSGCacheSnapshot(routes, root, "http://localhost", prefix);
7996
+ const rootConventions = root.errorPath || root.notFoundPath ? {
7997
+ errorPath: root.errorPath ? toPosixPath2(root.errorPath) : undefined,
7998
+ notFoundPath: root.notFoundPath ? toPosixPath2(root.notFoundPath) : undefined
7999
+ } : undefined;
8000
+ const routeMetadata = {};
8001
+ for (const route of routes) {
8002
+ routeMetadata[toPosixPath2(route.path)] = {
8003
+ segmentBoundaries: route.segmentBoundaries.map((b) => ({
8004
+ depth: b.depth,
8005
+ path: toPosixPath2(b.path),
8006
+ errorPath: b.errorPath ? toPosixPath2(b.errorPath) : undefined,
8007
+ notFoundPath: b.notFoundPath ? toPosixPath2(b.notFoundPath) : undefined
8008
+ }))
8009
+ };
8010
+ }
8011
+ const registerSource = buildEntrySource({
8012
+ apps: [
8013
+ {
8014
+ buildId,
8015
+ prefix,
8016
+ rootPath: root.path,
8017
+ routes: routes.map((r) => ({ pattern: r.pattern, path: r.path, mode: r.mode })),
8018
+ rootConventions,
8019
+ routeMetadata,
8020
+ ssgCache: ssgCache2
8021
+ }
8022
+ ],
8023
+ headerComment: "// Auto-generated by `furin build --target package` \u2014 do not edit",
8024
+ mode: "register"
8025
+ });
8026
+ const registerEntry = join10(targetDir, "register.ts");
8027
+ writeFileSync7(registerEntry, registerSource);
8028
+ const result = await Bun.build({
8029
+ entrypoints: [registerEntry],
8030
+ outdir: targetDir,
8031
+ target: "bun",
8032
+ packages: "external",
8033
+ naming: { entry: "[name].[ext]", chunk: "[name]-[hash].[ext]" },
8034
+ sourcemap: "none",
8035
+ minify: false,
8036
+ plugins: options.plugins
8037
+ });
8038
+ if (!result.success) {
8039
+ throw new AggregateError(result.logs, "[furin] package register build failed");
8040
+ }
8041
+ rmSync3(registerEntry, { force: true });
8042
+ rmSync3(join10(targetDir, "_hydrate.tsx"), { force: true });
8043
+ const relativePagesDir = toPosixPath2(relative3(targetDir, resolve2(rootDir, pagesDir)));
8044
+ const factorySource = `// Auto-generated by \`furin build --target package\` \u2014 do not edit
8045
+ import { fileURLToPath } from "node:url";
8046
+ import { furin } from "@teyik0/furin";
8047
+ import "./register.js";
8048
+
8049
+ const PAGES_DIR = fileURLToPath(new URL(${JSON.stringify(`./${relativePagesDir}`)}, import.meta.url));
8050
+ const CLIENT_DIR = fileURLToPath(new URL("./client", import.meta.url));
8051
+
8052
+ /**
8053
+ * Mounts this packaged furin app as an Elysia plugin.
8054
+ *
8055
+ * @param {object} [options] Extra furin() options (logger, sync, ...) \u2014
8056
+ * pagesDir/prefix/clientDir are baked into the package and cannot be overridden.
8057
+ * @returns {Promise<import("elysia").Elysia>}
8058
+ */
8059
+ export function createFurinApp(options = {}) {
8060
+ return furin({
8061
+ ...options,
8062
+ pagesDir: PAGES_DIR,
8063
+ prefix: ${JSON.stringify(prefix)},
8064
+ clientDir: CLIENT_DIR,
8065
+ });
8066
+ }
8067
+
8068
+ export const prefix = ${JSON.stringify(prefix)};
8069
+ `;
8070
+ writeFileSync7(join10(targetDir, "index.js"), factorySource);
8071
+ const dtsSource = `import type { Elysia } from "elysia";
8072
+ import type { FurinOptions } from "@teyik0/furin";
8073
+
8074
+ /** Extra furin() options \u2014 pagesDir/prefix/clientDir are baked into the package and cannot be overridden. */
8075
+ export type CreateFurinAppOptions = Omit<FurinOptions, "pagesDir" | "prefix" | "clientDir">;
8076
+ export declare function createFurinApp(options?: CreateFurinAppOptions): Promise<Elysia>;
8077
+ export declare const prefix: string;
8078
+ `;
8079
+ writeFileSync7(join10(targetDir, "index.d.ts"), dtsSource);
8080
+ console.log(`[furin] Package artifact: ${toPosixPath2(relative3(rootDir, targetDir))}`);
8081
+ return {
8082
+ buildId,
8083
+ generatedAt: new Date().toISOString(),
8084
+ prefix,
8085
+ targetDir: toPosixPath2(relative3(rootDir, targetDir))
8086
+ };
8087
+ }
8088
+
7738
8089
  // src/adapter/static.ts
7739
- import { cpSync as cpSync2, existsSync as existsSync9, rmSync as rmSync3, writeFileSync as writeFileSync7 } from "fs";
7740
- import { dirname as dirname3, isAbsolute, join as join10, relative as relative3, resolve as resolve2, sep } from "path";
8090
+ import { cpSync as cpSync2, existsSync as existsSync10, rmSync as rmSync4, writeFileSync as writeFileSync8 } from "fs";
8091
+ import { dirname as dirname3, isAbsolute, join as join11, relative as relative4, resolve as resolve3, sep } from "path";
7741
8092
  var STATIC_CONCURRENCY = 4;
7742
8093
  var DYNAMIC_SEGMENT_RE = /\/:[^/]+|\/\*/;
7743
8094
  var TRAILING_SLASHES_RE2 = /\/+$/;
7744
8095
  function pathToOutputFile(urlPath, outDir, fileName) {
7745
- const normalizedOutDir = resolve2(outDir);
8096
+ const normalizedOutDir = resolve3(outDir);
7746
8097
  if (urlPath === "/" || urlPath === "") {
7747
- return join10(normalizedOutDir, fileName);
8098
+ return join11(normalizedOutDir, fileName);
7748
8099
  }
7749
- const resolved = resolve2(normalizedOutDir, urlPath.slice(1), fileName);
8100
+ const resolved = resolve3(normalizedOutDir, urlPath.slice(1), fileName);
7750
8101
  if (!resolved.startsWith(`${normalizedOutDir}${sep}`)) {
7751
8102
  throw new Error(`[furin] static: unsafe output path detected for URL "${urlPath}" \u2014 path traversal via ".." is not allowed.`);
7752
8103
  }
@@ -7763,8 +8114,8 @@ async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, sk
7763
8114
  return;
7764
8115
  }
7765
8116
  ensureDir(dirname3(htmlOutputFile));
7766
- writeFileSync7(htmlOutputFile, entry.html);
7767
- writeFileSync7(dataOutputFile, entry.ndjson);
8117
+ writeFileSync8(htmlOutputFile, entry.html);
8118
+ writeFileSync8(dataOutputFile, entry.ndjson);
7768
8119
  renderedRoutes.push(urlPath);
7769
8120
  console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath2(htmlOutputFile)}`);
7770
8121
  } catch (err) {
@@ -7852,14 +8203,14 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
7852
8203
  if (basePath && !basePath.startsWith("/")) {
7853
8204
  throw new Error(`[furin] static: basePath must start with "/" (received "${rawBasePath}"). ` + `Use "" for root deployments or "/sub-path" for sub-path deployments.`);
7854
8205
  }
7855
- const outDir = resolve2(rootDir, staticConfig.outDir ?? "dist");
7856
- const normalizedRoot = resolve2(rootDir);
7857
- const normalizedBuildRoot = resolve2(buildRoot);
8206
+ const outDir = resolve3(rootDir, staticConfig.outDir ?? "dist");
8207
+ const normalizedRoot = resolve3(rootDir);
8208
+ const normalizedBuildRoot = resolve3(buildRoot);
7858
8209
  if (outDir === normalizedRoot || outDir === normalizedBuildRoot || outDir === "/" || outDir === ".") {
7859
8210
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
7860
8211
  }
7861
8212
  function isOutsideOutDir(target) {
7862
- const rel = relative3(outDir, target);
8213
+ const rel = relative4(outDir, target);
7863
8214
  return rel.startsWith("..") || isAbsolute(rel);
7864
8215
  }
7865
8216
  if (!(isOutsideOutDir(normalizedRoot) && isOutsideOutDir(normalizedBuildRoot))) {
@@ -7871,10 +8222,10 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
7871
8222
  const skippedRoutes = [];
7872
8223
  const ssgRoutes = collectSsgRoutes(routes, onSSR, skippedRoutes);
7873
8224
  const searchRoutes = createSearchRouteMetadata(ssgRoutes);
7874
- rmSync3(outDir, { force: true, recursive: true });
8225
+ rmSync4(outDir, { force: true, recursive: true });
7875
8226
  ensureDir(outDir);
7876
- const targetDir = join10(buildRoot, "static");
7877
- rmSync3(targetDir, { force: true, recursive: true });
8227
+ const targetDir = join11(buildRoot, "static");
8228
+ rmSync4(targetDir, { force: true, recursive: true });
7878
8229
  ensureDir(targetDir);
7879
8230
  const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
7880
8231
  outDir: targetDir,
@@ -7884,17 +8235,17 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
7884
8235
  basePath,
7885
8236
  clientLogging: Boolean(options.clientLogging)
7886
8237
  });
7887
- const publicFavicon = join10(rootDir, "public", "favicon.ico");
7888
- const faviconHref = existsSync9(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
8238
+ const publicFavicon = join11(rootDir, "public", "favicon.ico");
8239
+ const faviconHref = existsSync10(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
7889
8240
  const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref, true);
7890
8241
  setProductionTemplateContent(shellHtml);
7891
- const publicSrcDir = join10(rootDir, "public");
7892
- if (existsSync9(publicSrcDir)) {
8242
+ const publicSrcDir = join11(rootDir, "public");
8243
+ if (existsSync10(publicSrcDir)) {
7893
8244
  cpSync2(publicSrcDir, outDir, { recursive: true });
7894
8245
  }
7895
- const clientSrcDir = join10(targetDir, "client");
7896
- if (existsSync9(clientSrcDir)) {
7897
- cpSync2(clientSrcDir, join10(outDir, "_client"), { recursive: true });
8246
+ const clientSrcDir = join11(targetDir, "client");
8247
+ if (existsSync10(clientSrcDir)) {
8248
+ cpSync2(clientSrcDir, join11(outDir, "_client"), { recursive: true });
7898
8249
  }
7899
8250
  const tasks = await buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath, searchRoutes);
7900
8251
  const afterQueueCount = skippedRoutes.length;
@@ -7907,9 +8258,9 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
7907
8258
  ${list}
7908
8259
  ` + `Set \`onSSR: "skip"\` in your static config to suppress this error.`);
7909
8260
  }
7910
- writeFileSync7(join10(outDir, "404.html"), shellHtml);
8261
+ writeFileSync8(join11(outDir, "404.html"), shellHtml);
7911
8262
  console.log("[furin] static: wrote 404.html (SPA shell fallback)");
7912
- rmSync3(targetDir, { force: true, recursive: true });
8263
+ rmSync4(targetDir, { force: true, recursive: true });
7913
8264
  console.log(`[furin] static: export complete \u2192 ${toPosixPath2(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
7914
8265
  return {
7915
8266
  basePath,
@@ -7922,12 +8273,16 @@ ${list}
7922
8273
 
7923
8274
  // src/config.ts
7924
8275
  import { t as t2 } from "elysia";
7925
- var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare", "static"];
8276
+ var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare", "static", "package"];
7926
8277
  var buildTargetSchema = t2.Union(BUILD_TARGETS.map((v) => t2.Literal(v)));
7927
8278
  var compileTargetSchema = t2.Union([t2.Literal("server"), t2.Literal("embed")]);
7928
8279
  var configSchema = t2.Object({
7929
8280
  rootDir: t2.Optional(t2.String()),
7930
8281
  pagesDir: t2.Optional(t2.String()),
8282
+ apps: t2.Optional(t2.Array(t2.Object({
8283
+ pagesDir: t2.String(),
8284
+ prefix: t2.Optional(t2.String())
8285
+ }))),
7931
8286
  serverEntry: t2.Optional(t2.String()),
7932
8287
  clientLogging: t2.Optional(t2.Boolean()),
7933
8288
  targets: t2.Optional(t2.Array(buildTargetSchema)),
@@ -7979,9 +8334,13 @@ function checkFurinCall(node, out) {
7979
8334
  }
7980
8335
  const pagesDir = extractStringProperty(firstArg, "pagesDir");
7981
8336
  if (pagesDir !== null) {
7982
- out.push(pagesDir);
8337
+ const prefix = extractStringProperty(firstArg, "prefix");
8338
+ out.push({ pagesDir, prefix: normalizeScannedPrefix(prefix) });
7983
8339
  }
7984
8340
  }
8341
+ function normalizeScannedPrefix(prefix) {
8342
+ return normalizePrefix(prefix ?? undefined);
8343
+ }
7985
8344
  function isObjectExpressionNode2(node) {
7986
8345
  return node.type === "ObjectExpression";
7987
8346
  }
@@ -8011,31 +8370,42 @@ function getStringPropertyValue(prop, propName) {
8011
8370
  // src/build/index.ts
8012
8371
  var IMPLEMENTED_TARGETS = ["bun", "static"];
8013
8372
  var BUILD_OUTPUT_DIR = ".furin/build";
8014
- function resolvePagesDirFromServer(serverEntry, rootDir) {
8015
- if (!serverEntry) {
8016
- return null;
8373
+ function resolveAppSpecs(options, serverEntry, rootDir) {
8374
+ if (options.apps && options.apps.length > 0) {
8375
+ return options.apps.map((app) => ({
8376
+ pagesDir: resolve4(rootDir, app.pagesDir),
8377
+ prefix: normalizePrefix(app.prefix)
8378
+ }));
8017
8379
  }
8018
- const detected = scanFurinInstances(serverEntry);
8019
- if (detected.length === 0) {
8020
- return null;
8380
+ if (options.pagesDir) {
8381
+ return [{ pagesDir: resolve4(rootDir, options.pagesDir), prefix: "" }];
8382
+ }
8383
+ if (serverEntry) {
8384
+ const detected = scanFurinInstances(serverEntry);
8385
+ if (detected.length > 0) {
8386
+ return detected.map((app) => ({
8387
+ pagesDir: resolve4(rootDir, app.pagesDir),
8388
+ prefix: app.prefix
8389
+ }));
8390
+ }
8021
8391
  }
8022
- return resolve3(rootDir, detected[0]);
8392
+ return [{ pagesDir: resolve4(rootDir, "src/pages"), prefix: "" }];
8023
8393
  }
8024
8394
  async function buildApp(options) {
8025
- const rootDir = resolve3(options.rootDir ?? process.cwd());
8026
- const buildRoot = join11(rootDir, BUILD_OUTPUT_DIR);
8395
+ const rootDir = resolve4(options.rootDir ?? process.cwd());
8396
+ const buildRoot = join12(rootDir, BUILD_OUTPUT_DIR);
8027
8397
  const serverEntry = (() => {
8028
- if (options.target === "static") {
8398
+ if (options.target === "static" || options.target === "package") {
8029
8399
  return null;
8030
8400
  }
8031
8401
  if (options.serverEntry) {
8032
- const resolved = resolve3(rootDir, options.serverEntry);
8033
- if (existsSync10(resolved)) {
8402
+ const resolved = resolve4(rootDir, options.serverEntry);
8403
+ if (existsSync11(resolved)) {
8034
8404
  return resolved;
8035
8405
  }
8036
8406
  }
8037
- const entry = resolve3(rootDir, "src/server.ts");
8038
- if (!existsSync10(entry)) {
8407
+ const entry = resolve4(rootDir, "src/server.ts");
8408
+ if (!existsSync11(entry)) {
8039
8409
  throw new Error("[furin] Entrypoint server.ts not found");
8040
8410
  }
8041
8411
  return entry;
@@ -8051,33 +8421,59 @@ async function buildApp(options) {
8051
8421
  console.debug("[furin] Skipped plugin at runtime:", err);
8052
8422
  }
8053
8423
  }
8054
- const rawPagesDir = options.pagesDir ?? resolvePagesDirFromServer(serverEntry, rootDir) ?? "src/pages";
8055
- const pagesDir = resolve3(rootDir, rawPagesDir);
8424
+ const appSpecs = resolveAppSpecs(options, serverEntry, rootDir);
8425
+ const duplicatePrefix = appSpecs.find((spec, index) => appSpecs.findIndex((other) => other.prefix === spec.prefix) !== index);
8426
+ if (duplicatePrefix) {
8427
+ throw new Error(`[furin] Two apps are configured with the prefix "${duplicatePrefix.prefix || "/"}" \u2014 give each app a unique prefix.`);
8428
+ }
8429
+ assertNoPrefixSlugCollisions(appSpecs.map((spec) => spec.prefix));
8056
8430
  const requestedTargets = options.target === "all" ? [...IMPLEMENTED_TARGETS] : [options.target].map((target) => {
8057
8431
  if (!BUILD_TARGETS.includes(target)) {
8058
8432
  throw new Error(`[furin] Unsupported build target "${target}"`);
8059
8433
  }
8060
8434
  return target;
8061
8435
  });
8062
- const { root, routes } = await scanPages(pagesDir);
8436
+ const apps = [];
8437
+ for (const spec of appSpecs) {
8438
+ const { root, routes } = await scanPages(spec.pagesDir);
8439
+ apps.push({ pagesDir: spec.pagesDir, prefix: spec.prefix, root, routes });
8440
+ }
8441
+ const primaryApp = apps.find((app) => app.prefix === "") ?? apps[0];
8063
8442
  ensureDir(buildRoot);
8064
8443
  const manifest = {
8065
8444
  version: 1,
8066
8445
  generatedAt: new Date().toISOString(),
8067
8446
  rootDir: toPosixPath2(rootDir),
8068
- pagesDir: toPosixPath2(relative4(rootDir, pagesDir)),
8069
- rootPath: toPosixPath2(relative4(rootDir, root.path)),
8070
- serverEntry: serverEntry ? toPosixPath2(relative4(rootDir, serverEntry)) : null,
8071
- routes: routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
8447
+ pagesDir: toPosixPath2(relative5(rootDir, primaryApp.pagesDir)),
8448
+ rootPath: toPosixPath2(relative5(rootDir, primaryApp.root.path)),
8449
+ serverEntry: serverEntry ? toPosixPath2(relative5(rootDir, serverEntry)) : null,
8450
+ routes: primaryApp.routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
8451
+ apps: apps.map((app) => ({
8452
+ pagesDir: toPosixPath2(relative5(rootDir, app.pagesDir)),
8453
+ prefix: app.prefix,
8454
+ routes: app.routes.map((route) => toBuildRouteManifestEntry(route, rootDir))
8455
+ })),
8072
8456
  targets: {}
8073
8457
  };
8074
8458
  for (const target of requestedTargets) {
8075
8459
  switch (target) {
8076
8460
  case "bun":
8077
- manifest.targets.bun = await buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, options);
8461
+ manifest.targets.bun = await buildBunTarget(apps, rootDir, buildRoot, serverEntry, options);
8078
8462
  break;
8079
8463
  case "static":
8080
- manifest.targets.static = await buildStaticTarget(routes, rootDir, buildRoot, root, options);
8464
+ if (apps.length > 1) {
8465
+ console.warn("[furin] `--target static` exports the root-mounted app only \u2014 prefixed apps are skipped.");
8466
+ }
8467
+ if (primaryApp.prefix !== "") {
8468
+ console.warn(`[furin] \`--target static\` exports an app mounted at "${primaryApp.prefix}", but the ` + `static export ignores the mount prefix \u2014 set \`static.basePath\` to "${primaryApp.prefix}" ` + "(or the sub-path the site is served from) so asset URLs resolve correctly.");
8469
+ }
8470
+ manifest.targets.static = await buildStaticTarget(primaryApp.routes, rootDir, buildRoot, primaryApp.root, options);
8471
+ break;
8472
+ case "package":
8473
+ if (apps.length > 1) {
8474
+ throw new Error("[furin] `--target package` builds exactly one app \u2014 configure a single pagesDir/prefix.");
8475
+ }
8476
+ manifest.targets.package = await buildPackageTarget(primaryApp, rootDir, buildRoot, options);
8081
8477
  break;
8082
8478
  case "node":
8083
8479
  case "vercel":
@@ -8087,7 +8483,7 @@ async function buildApp(options) {
8087
8483
  throw new Error(`[furin] Unsupported build target "${target}"`);
8088
8484
  }
8089
8485
  }
8090
- writeFileSync8(join11(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
8486
+ writeFileSync9(join12(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
8091
8487
  `);
8092
8488
  return {
8093
8489
  manifest,