@teyik0/furin 0.6.0-alpha.1 → 0.7.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 (197) hide show
  1. package/dist/adapter/runtime-build.d.ts +1 -1
  2. package/dist/build/client.d.ts +4 -1
  3. package/dist/build/elysia-aot-worker.d.ts +22 -0
  4. package/dist/build/elysia-aot.d.ts +1 -1
  5. package/dist/build/entry-template.d.ts +3 -0
  6. package/dist/build/entry-template.ts +7 -0
  7. package/dist/build/hydrate.d.ts +1 -1
  8. package/dist/build/index.js +1880 -401
  9. package/dist/build/preload-manifest.d.ts +17 -0
  10. package/dist/build/types.d.ts +6 -0
  11. package/dist/cli/index.js +1878 -408
  12. package/dist/client/client-module.d.ts +26 -0
  13. package/dist/client/define-route.d.ts +9 -0
  14. package/dist/client/document.d.ts +2 -0
  15. package/dist/client/internal/runtime-types.d.ts +2 -0
  16. package/dist/client/link.js +942 -122
  17. package/dist/client/mutation.d.ts +38 -0
  18. package/dist/client/query-store.d.ts +85 -0
  19. package/dist/client/query.d.ts +14 -0
  20. package/dist/client/route-api.d.ts +11 -0
  21. package/dist/client/router/context.d.ts +3 -2
  22. package/dist/client/router/index.d.ts +1 -1
  23. package/dist/client/router/link-utils.d.ts +8 -1
  24. package/dist/client/router/navigation.d.ts +2 -9
  25. package/dist/client/router/optimistic.d.ts +41 -0
  26. package/dist/client/router/search/index.d.ts +3 -3
  27. package/dist/client/router/search-store.d.ts +1 -0
  28. package/dist/client/router/sync-catch-up.d.ts +3 -0
  29. package/dist/client/router/types.d.ts +51 -7
  30. package/dist/client/sync.d.ts +39 -22
  31. package/dist/client.d.ts +11 -33
  32. package/dist/client.js +1219 -59
  33. package/dist/config.d.ts +7 -0
  34. package/dist/config.js +1 -0
  35. package/dist/define-route.d.ts +78 -32
  36. package/dist/env.d.ts +2 -2
  37. package/dist/furin.d.ts +1 -2
  38. package/dist/furin.js +2484 -708
  39. package/dist/plugin/hmr-dependencies.d.ts +2 -0
  40. package/dist/plugin/index.js +349 -18
  41. package/dist/plugin/transform-client-module.d.ts +16 -0
  42. package/dist/plugin/transform-client.d.ts +2 -0
  43. package/dist/plugin/transform-isomorphic.d.ts +1 -1
  44. package/dist/routes.d.ts +6 -0
  45. package/dist/rsc-client.js +87 -16
  46. package/dist/rsc.js +87 -16
  47. package/dist/server/auto-invalidate/registry.d.ts +1 -0
  48. package/dist/server/auto-invalidate/types.d.ts +2 -0
  49. package/dist/server/cache/isr.d.ts +2 -4
  50. package/dist/server/cache/route-cache.d.ts +5 -0
  51. package/dist/server/dev/graph.d.ts +1 -0
  52. package/dist/server/dev-page-plugin.d.ts +5 -19
  53. package/dist/server/internal.d.ts +3 -0
  54. package/dist/server/internal.js +55 -35
  55. package/dist/server/production-server.js +54 -34
  56. package/dist/server/render/loaders.d.ts +4 -2
  57. package/dist/server/render/react-stream.d.ts +3 -0
  58. package/dist/server/render/ssr.d.ts +2 -1
  59. package/dist/server/render/template.d.ts +4 -0
  60. package/dist/server/router/defined-route.d.ts +2 -0
  61. package/dist/server/router/hmr.d.ts +1 -1
  62. package/dist/server/router/patterns.d.ts +2 -0
  63. package/dist/server/router/types.d.ts +1 -1
  64. package/dist/server/sync/adapter.d.ts +25 -4
  65. package/dist/server/sync/atomic.d.ts +25 -0
  66. package/dist/server/sync/drizzle/index.d.ts +45 -0
  67. package/dist/server/sync/drizzle/index.js +540 -0
  68. package/dist/server/sync/execution-error.d.ts +2 -0
  69. package/dist/server/sync/index.d.ts +2 -1
  70. package/dist/server/sync/index.js +533 -105
  71. package/dist/server/sync/mutation-handler.d.ts +4 -0
  72. package/dist/server/sync/plugin.d.ts +34 -11
  73. package/dist/server/sync/postgres/execute.d.ts +3 -0
  74. package/dist/server/sync/postgres/index.d.ts +12 -1
  75. package/dist/server/sync/postgres/index.js +34 -13
  76. package/dist/server/sync/postgres/sql.d.ts +8 -0
  77. package/dist/server/sync/prisma/index.d.ts +24 -0
  78. package/dist/server/sync/prisma/index.js +340 -0
  79. package/dist/server/sync/queries.d.ts +21 -0
  80. package/dist/server/sync/query-context.d.ts +5 -0
  81. package/dist/server/sync/redis/index.js +3 -3
  82. package/dist/server/sync/redis/scripts.d.ts +1 -1
  83. package/dist/server/sync/response.d.ts +1 -0
  84. package/dist/server/sync/sqlite/index.d.ts +3 -0
  85. package/dist/server/sync/sqlite/index.js +10 -4
  86. package/dist/server/sync/stream.d.ts +2 -5
  87. package/dist/server/sync/validation.d.ts +4 -0
  88. package/dist/shared/defer.d.ts +31 -0
  89. package/dist/shared/error.d.ts +2 -2
  90. package/dist/shared/page-key.d.ts +7 -0
  91. package/dist/shared/query-bindings.d.ts +12 -0
  92. package/dist/shared/route-frame.d.ts +1 -0
  93. package/dist/shared/sync-query.d.ts +40 -0
  94. package/package.json +29 -6
  95. package/src/adapter/package.ts +12 -2
  96. package/src/adapter/runtime-build.ts +63 -12
  97. package/src/adapter/static.ts +7 -2
  98. package/src/adapter/vercel.ts +15 -13
  99. package/src/build/client.ts +23 -5
  100. package/src/build/elysia-aot-worker.ts +51 -0
  101. package/src/build/elysia-aot.ts +83 -19
  102. package/src/build/entry-template.ts +7 -0
  103. package/src/build/hydrate.ts +21 -3
  104. package/src/build/preload-manifest.ts +100 -0
  105. package/src/build/production-instrumentation.ts +6 -3
  106. package/src/build/types.ts +4 -0
  107. package/src/cli/index.ts +1 -0
  108. package/src/client/browser-events-runtime.ts +4 -0
  109. package/src/client/client-module.ts +57 -0
  110. package/src/client/define-route.ts +11 -1
  111. package/src/client/document.tsx +28 -18
  112. package/src/client/hmr.ts +2 -1
  113. package/src/client/internal/runtime-types.ts +2 -0
  114. package/src/client/link.tsx +8 -8
  115. package/src/client/mutation.ts +136 -0
  116. package/src/client/query-store.ts +418 -0
  117. package/src/client/query.tsx +67 -0
  118. package/src/client/route-api.tsx +75 -0
  119. package/src/client/router/boundary-tree.tsx +19 -12
  120. package/src/client/router/context.ts +57 -4
  121. package/src/client/router/index.ts +3 -0
  122. package/src/client/router/link-utils.ts +29 -1
  123. package/src/client/router/navigation.ts +3 -50
  124. package/src/client/router/optimistic.ts +233 -0
  125. package/src/client/router/provider.tsx +306 -46
  126. package/src/client/router/search/index.ts +37 -17
  127. package/src/client/router/search-store.ts +4 -0
  128. package/src/client/router/sync-catch-up.ts +7 -0
  129. package/src/client/router/types.ts +73 -9
  130. package/src/client/sync.ts +438 -65
  131. package/src/client.ts +20 -60
  132. package/src/config.ts +5 -0
  133. package/src/define-route.ts +113 -55
  134. package/src/env.d.ts +2 -2
  135. package/src/furin.ts +75 -13
  136. package/src/plugin/hmr-dependencies.ts +58 -0
  137. package/src/plugin/index.ts +38 -2
  138. package/src/plugin/routes.ts +28 -16
  139. package/src/plugin/transform-client-module.ts +123 -0
  140. package/src/plugin/transform-client.ts +293 -13
  141. package/src/plugin/transform-isomorphic.ts +11 -5
  142. package/src/routes.ts +8 -0
  143. package/src/rsc/shared.tsx +104 -18
  144. package/src/server/auto-invalidate/registry.ts +4 -0
  145. package/src/server/auto-invalidate/runtime.ts +17 -0
  146. package/src/server/auto-invalidate/types.ts +6 -0
  147. package/src/server/cache/isr.ts +6 -34
  148. package/src/server/cache/route-cache.ts +40 -4
  149. package/src/server/dev/graph.ts +16 -2
  150. package/src/server/dev-page-plugin.ts +93 -59
  151. package/src/server/internal.ts +3 -0
  152. package/src/server/render/document.tsx +10 -1
  153. package/src/server/render/element.tsx +21 -11
  154. package/src/server/render/isr.ts +61 -29
  155. package/src/server/render/loaders.ts +118 -47
  156. package/src/server/render/mixed-cache.ts +33 -4
  157. package/src/server/render/not-found.ts +4 -7
  158. package/src/server/render/ppr-document.ts +2 -1
  159. package/src/server/render/ppr-route.ts +30 -10
  160. package/src/server/render/react-stream.ts +17 -0
  161. package/src/server/render/route-frame-transport.ts +3 -0
  162. package/src/server/render/ssg.ts +51 -18
  163. package/src/server/render/ssr.ts +53 -8
  164. package/src/server/render/template.ts +23 -0
  165. package/src/server/router/defined-route.ts +3 -0
  166. package/src/server/router/discovery.ts +25 -9
  167. package/src/server/router/hmr.ts +3 -2
  168. package/src/server/router/patterns.ts +16 -0
  169. package/src/server/router/plugin.ts +27 -12
  170. package/src/server/router/types.ts +1 -1
  171. package/src/server/sync/adapter.ts +41 -4
  172. package/src/server/sync/atomic.ts +303 -0
  173. package/src/server/sync/drizzle/index.ts +145 -0
  174. package/src/server/sync/execution-error.ts +1 -0
  175. package/src/server/sync/fingerprint.ts +2 -6
  176. package/src/server/sync/index.ts +6 -0
  177. package/src/server/sync/mutation-handler.ts +69 -0
  178. package/src/server/sync/plugin.ts +177 -60
  179. package/src/server/sync/postgres/execute.ts +20 -0
  180. package/src/server/sync/postgres/index.ts +52 -16
  181. package/src/server/sync/postgres/sql.ts +20 -0
  182. package/src/server/sync/prisma/index.ts +70 -0
  183. package/src/server/sync/queries.ts +75 -0
  184. package/src/server/sync/query-context.ts +85 -0
  185. package/src/server/sync/redis/index.ts +7 -3
  186. package/src/server/sync/redis/scripts.ts +1 -1
  187. package/src/server/sync/response.ts +21 -0
  188. package/src/server/sync/sqlite/index.ts +19 -8
  189. package/src/server/sync/stream.ts +14 -22
  190. package/src/server/sync/validation.ts +34 -0
  191. package/src/shared/defer.ts +48 -0
  192. package/src/shared/error.ts +2 -2
  193. package/src/shared/page-key.ts +36 -0
  194. package/src/shared/query-bindings.ts +138 -0
  195. package/src/shared/route-frame.ts +13 -1
  196. package/src/shared/route-map.ts +12 -2
  197. package/src/shared/sync-query.ts +138 -0
@@ -0,0 +1,2 @@
1
+ /** Fingerprint server imports without importing their code into the client bundle. */
2
+ export declare function hmrDependencySignature(imports: Set<string>, filename: string): string | undefined;
@@ -1,4 +1,31 @@
1
1
  // @bun
2
+ // src/plugin/index.ts
3
+ import { dirname as dirname3, isAbsolute as isAbsolute2, resolve as resolve2 } from "path";
4
+
5
+ // src/rsc/build/environment.ts
6
+ import { fileURLToPath } from "url";
7
+ var SERVER_ONLY_RE = /^(?:@teyik0\/)?furin\/server-only$/;
8
+ var CLIENT_ONLY_RE = /^(?:@teyik0\/)?furin\/client-only$/;
9
+ function environmentGuardPlugin(graph) {
10
+ return {
11
+ name: `furin-environment-${graph}`,
12
+ setup(build) {
13
+ build.onResolve({ filter: SERVER_ONLY_RE }, (args) => {
14
+ if (graph === "client") {
15
+ throw new Error(`[furin] ${args.importer} imports furin/server-only from the client graph.`);
16
+ }
17
+ return { path: fileURLToPath(import.meta.resolve("../../server-only.ts")) };
18
+ });
19
+ build.onResolve({ filter: CLIENT_ONLY_RE }, (args) => {
20
+ if (graph !== "client") {
21
+ throw new Error(`[furin] ${args.importer} imports furin/client-only from the ${graph} graph.`);
22
+ }
23
+ return { path: fileURLToPath(import.meta.resolve("../../client-only.ts")) };
24
+ });
25
+ }
26
+ };
27
+ }
28
+
2
29
  // src/server/lang-detect.ts
3
30
  function detectLangFromPath(filePath) {
4
31
  if (filePath.endsWith(".d.ts")) {
@@ -2593,6 +2620,124 @@ function deadCodeElimination(transformed, originalCode, lang) {
2593
2620
  return pruned;
2594
2621
  }
2595
2622
 
2623
+ // src/plugin/hmr-dependencies.ts
2624
+ import { readFileSync } from "fs";
2625
+ import { dirname, isAbsolute, resolve } from "path";
2626
+ var SCRIPT_FILE = /\.[cm]?[jt]sx?$/;
2627
+ function hmrDependencySignature(imports, filename) {
2628
+ const routePath = resolve(filename);
2629
+ const visited = new Set;
2630
+ const hash = new Bun.CryptoHasher("sha256");
2631
+ const visit = (specifier, importer) => {
2632
+ if (specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/")) {
2633
+ return true;
2634
+ }
2635
+ const path = Bun.resolveSync(specifier, dirname(importer));
2636
+ if (path === routePath) {
2637
+ return false;
2638
+ }
2639
+ hash.update(JSON.stringify([specifier, path]));
2640
+ if (!isAbsolute(path) || path.replaceAll("\\", "/").includes("/node_modules/") || visited.has(path)) {
2641
+ return true;
2642
+ }
2643
+ visited.add(path);
2644
+ const source = readFileSync(path, "utf8");
2645
+ hash.update(source);
2646
+ if (SCRIPT_FILE.test(path)) {
2647
+ const transpiler = new Bun.Transpiler({ loader: detectLoaderFromPath(path) });
2648
+ for (const dependency of transpiler.scanImports(source)) {
2649
+ if (!visit(dependency.path, path)) {
2650
+ return false;
2651
+ }
2652
+ }
2653
+ }
2654
+ return true;
2655
+ };
2656
+ try {
2657
+ for (const specifier of imports) {
2658
+ if (!visit(specifier, routePath)) {
2659
+ return;
2660
+ }
2661
+ }
2662
+ return hash.digest("hex");
2663
+ } catch {}
2664
+ }
2665
+
2666
+ // src/plugin/transform-client-module.ts
2667
+ import { realpathSync } from "fs";
2668
+ import { dirname as dirname2 } from "path";
2669
+ var FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
2670
+ var SERVER_LOAD = '() => Promise.reject(new Error("[furin] clientModule() can only be loaded in the browser."))';
2671
+ function clientModuleKey(modulePath) {
2672
+ const realPath = realpathSync(modulePath).replaceAll("\\", "/");
2673
+ return `__FURIN_CLIENT_MODULE_${Bun.hash(realPath).toString(36)}__`;
2674
+ }
2675
+ function collectClientModuleBindings(program) {
2676
+ const bindings = new Set;
2677
+ for (const statement of program.body) {
2678
+ if (statement.type !== "ImportDeclaration") {
2679
+ continue;
2680
+ }
2681
+ const declaration = statement;
2682
+ if (declaration.importKind === "type" || !FURIN_CLIENT_MODULES.has(String(declaration.source.value))) {
2683
+ continue;
2684
+ }
2685
+ for (const specifier of declaration.specifiers) {
2686
+ const imported = specifier.imported;
2687
+ const local = specifier.local;
2688
+ if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && imported?.name === "clientModule" && typeof local?.name === "string") {
2689
+ bindings.add(local.name);
2690
+ }
2691
+ }
2692
+ }
2693
+ return bindings;
2694
+ }
2695
+ function dynamicImportSpecifier(loader) {
2696
+ if (loader.type !== "ArrowFunctionExpression" || loader.params.length > 0) {
2697
+ return null;
2698
+ }
2699
+ const body = loader.body;
2700
+ const source = body.type === "ImportExpression" ? body.source : null;
2701
+ return source?.type === "Literal" && typeof source.value === "string" ? source.value : null;
2702
+ }
2703
+ function transformClientModules(source, filename, environment) {
2704
+ if (!source.includes("clientModule")) {
2705
+ return source;
2706
+ }
2707
+ const { program } = parseSource(source, detectLangFromPath(filename));
2708
+ const bindings = collectClientModuleBindings(program);
2709
+ if (bindings.size === 0) {
2710
+ return source;
2711
+ }
2712
+ const transformed = new MagicString(source);
2713
+ walk(program, {
2714
+ CallExpression(node, context) {
2715
+ const call = node;
2716
+ const [loader, ...rest] = call.arguments;
2717
+ if (call.callee.type !== "Identifier" || !bindings.has(call.callee.name) || hasShadowingDeclaration(call.callee.name, context.ancestors()) || !loader || rest.length > 0) {
2718
+ return;
2719
+ }
2720
+ const unwrapped = unwrapTSExpression(loader);
2721
+ const specifier = dynamicImportSpecifier(unwrapped);
2722
+ if (specifier === null) {
2723
+ return;
2724
+ }
2725
+ let key;
2726
+ try {
2727
+ key = JSON.stringify(clientModuleKey(Bun.resolveSync(specifier, dirname2(filename))));
2728
+ } catch (error) {
2729
+ throw new Error(`[furin] Cannot resolve clientModule import ${JSON.stringify(specifier)} in ${filename}`, { cause: error });
2730
+ }
2731
+ if (environment === "client") {
2732
+ transformed.appendLeft(loader.end, `, ${key}`);
2733
+ } else {
2734
+ transformed.overwrite(loader.start, loader.end, `${SERVER_LOAD}, ${key}`);
2735
+ }
2736
+ }
2737
+ });
2738
+ return transformed.toString();
2739
+ }
2740
+
2596
2741
  // src/plugin/transform-isomorphic.ts
2597
2742
  var FURIN_MODULES = new Set(["@teyik0/furin", "furin"]);
2598
2743
  function importedName(specifier) {
@@ -2814,11 +2959,13 @@ function assertStaticEnvironmentMethods(source, filename, program, bindings, bui
2814
2959
  }
2815
2960
  });
2816
2961
  }
2817
- function transformIsomorphicFunctions(source, filename, environment) {
2962
+ function transformIsomorphicFunctions(input, filename, environment) {
2818
2963
  const lang = detectLangFromPath(filename);
2819
2964
  if (lang === "dts") {
2820
- return { code: source, map: null, transformed: false };
2965
+ return { code: input, map: null, transformed: false };
2821
2966
  }
2967
+ const source = transformClientModules(input, filename, environment);
2968
+ const clientModulesTransformed = source !== input;
2822
2969
  const { program, diagnostics } = parseSource(source, lang);
2823
2970
  const firstError = diagnostics.find((diagnostic) => diagnostic.severity === "error");
2824
2971
  if (firstError) {
@@ -2830,7 +2977,7 @@ function transformIsomorphicFunctions(source, filename, environment) {
2830
2977
  assertNoSplitChains(source, filename, program, builders);
2831
2978
  const candidates = collectCandidates(source, filename, program, bindings);
2832
2979
  if (candidates.length === 0) {
2833
- return { code: source, map: null, transformed: false };
2980
+ return { code: source, map: null, transformed: clientModulesTransformed };
2834
2981
  }
2835
2982
  const transformed = new MagicString(source);
2836
2983
  for (const candidate of candidates) {
@@ -2846,12 +2993,13 @@ function transformIsomorphicFunctions(source, filename, environment) {
2846
2993
  }
2847
2994
 
2848
2995
  // src/plugin/transform-client.ts
2849
- var FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
2996
+ var FURIN_CLIENT_MODULES2 = new Set(["@teyik0/furin/client", "furin/client"]);
2850
2997
  var FURIN_SERVER_MODULES = new Set(["@teyik0/furin", "furin"]);
2851
2998
  var REACT_COMPONENT_WRAPPERS = new Set(["forwardRef", "memo"]);
2852
2999
  var SERVER_ONLY_METHODS = new Set(["config", "head", "loader", "requestLoader", "staticParams"]);
2853
3000
  var REACT_HOOK_NAME_RE = /^use[A-Z0-9]/;
2854
3001
  var HMR_DATA_SIGNATURE = "furin.hmr.data-signature";
3002
+ var HMR_SOURCE_SIGNATURE = "furin.hmr.source-signature";
2855
3003
  var TYPESCRIPT_RUNTIME_WRAPPERS = new Map([
2856
3004
  ["TSAsExpression", ["expression"]],
2857
3005
  ["TSInstantiationExpression", ["expression"]],
@@ -2861,7 +3009,7 @@ var TYPESCRIPT_RUNTIME_WRAPPERS = new Map([
2861
3009
  ["TSTypeAssertion", ["expression"]]
2862
3010
  ]);
2863
3011
  function isFurinRouteModule(source) {
2864
- return typeof source === "string" && (FURIN_SERVER_MODULES.has(source) || FURIN_CLIENT_MODULES.has(source));
3012
+ return typeof source === "string" && (FURIN_SERVER_MODULES.has(source) || FURIN_CLIENT_MODULES2.has(source));
2865
3013
  }
2866
3014
  function importedName2(specifier) {
2867
3015
  const { imported } = specifier;
@@ -2961,8 +3109,51 @@ function chainRootIsDefineRoute(node, bindings, ancestors) {
2961
3109
  }
2962
3110
  return false;
2963
3111
  }
2964
- function removeChainedServerCalls(source, program, bindings) {
3112
+ function assertCompleteRouteChains(program, bindings, filename) {
3113
+ const namespaces = new Set;
3114
+ for (const statement of program.body) {
3115
+ if (statement.type !== "ImportDeclaration") {
3116
+ continue;
3117
+ }
3118
+ const declaration = statement;
3119
+ if (!isFurinRouteModule(declaration.source.value) || declaration.importKind === "type") {
3120
+ continue;
3121
+ }
3122
+ for (const specifier of declaration.specifiers) {
3123
+ const name = localName2(specifier);
3124
+ if (name && specifier.type === "ImportNamespaceSpecifier") {
3125
+ namespaces.add(name);
3126
+ }
3127
+ }
3128
+ }
3129
+ walk(program, {
3130
+ MemberExpression(node, context) {
3131
+ const object = asAstNode(node.object);
3132
+ const property = asAstNode(node.property);
3133
+ const method = property?.type === "Identifier" ? property.name : property?.value;
3134
+ if (object?.type === "Identifier" && typeof object.name === "string" && namespaces.has(object.name) && (method === "defineRoute" || method === "defineRootRoute") && !hasShadowingDeclaration(object.name, context.ancestors())) {
3135
+ throw new Error(`[furin] ${filename}: route builders require a named import.`);
3136
+ }
3137
+ if (node.computed && context.parent?.type === "CallExpression" && chainRootIsDefineRoute(node.object, bindings, context.ancestors())) {
3138
+ throw new Error(`[furin] ${filename}: route builders require static builder methods.`);
3139
+ }
3140
+ },
3141
+ VariableDeclarator(node, context) {
3142
+ const initializer = asAstNode(node.init);
3143
+ if (!(initializer && chainRootIsDefineRoute(initializer, bindings, context.ancestors()))) {
3144
+ return;
3145
+ }
3146
+ const callee = initializer.type === "CallExpression" ? asAstNode(initializer.callee) : null;
3147
+ const method = callee?.type === "MemberExpression" ? asAstNode(callee.property) : null;
3148
+ if (method?.type !== "Identifier" || method.name !== "page" && method.name !== "layout") {
3149
+ throw new Error(`[furin] ${filename}: route builders must use one fluent chain ending in .page() or .layout().`);
3150
+ }
3151
+ }
3152
+ });
3153
+ }
3154
+ function removeChainedServerCalls(source, program, bindings, configBindings, filename) {
2965
3155
  let transformed = rewriteClientImports(source, program, bindings);
3156
+ const { declarations } = collectModuleBindings(program);
2966
3157
  walk(program, {
2967
3158
  CallExpression(call, context) {
2968
3159
  const callee = asAstNode(call.callee);
@@ -2977,12 +3168,93 @@ function removeChainedServerCalls(source, program, bindings) {
2977
3168
  if (!object) {
2978
3169
  return;
2979
3170
  }
3171
+ if (property.name === "config" && Array.isArray(call.arguments)) {
3172
+ const config = asAstNode(call.arguments[0]);
3173
+ if (config?.type === "ObjectExpression" && Array.isArray(config.properties)) {
3174
+ collectConfigBindings(config, declarations, configBindings);
3175
+ const remount = resolveRemountProperty(config, declarations, configBindings, new Set, filename);
3176
+ if (remount) {
3177
+ source.update(object.end, call.end, `.config({ ${source.original.slice(remount.start, remount.end)} })`);
3178
+ transformed = true;
3179
+ return;
3180
+ }
3181
+ }
3182
+ }
2980
3183
  source.remove(object.end, call.end);
2981
3184
  transformed = true;
2982
3185
  }
2983
3186
  });
2984
3187
  return transformed;
2985
3188
  }
3189
+ function collectConfigBindings(config, declarations, names) {
3190
+ if (config?.type === "Identifier" && typeof config.name === "string" && !names.has(config.name)) {
3191
+ names.add(config.name);
3192
+ const declaration = declarations.get(config.name);
3193
+ collectConfigBindings(asAstNode(declaration?.init), declarations, names);
3194
+ } else if (config?.type === "ObjectExpression" && Array.isArray(config.properties)) {
3195
+ for (const property of config.properties) {
3196
+ const entry = asAstNode(property);
3197
+ if (entry?.type === "SpreadElement") {
3198
+ collectConfigBindings(asAstNode(entry.argument), declarations, names);
3199
+ }
3200
+ }
3201
+ }
3202
+ }
3203
+ function resolveRemountProperty(config, declarations, configBindings, visiting, filename) {
3204
+ if (config?.type === "Identifier" && typeof config.name === "string" && !visiting.has(config.name)) {
3205
+ visiting.add(config.name);
3206
+ configBindings.add(config.name);
3207
+ const declaration = declarations.get(config.name);
3208
+ const result = resolveRemountProperty(asAstNode(declaration?.init), declarations, configBindings, visiting, filename);
3209
+ visiting.delete(config.name);
3210
+ return result;
3211
+ }
3212
+ if (config?.type !== "ObjectExpression" || !Array.isArray(config.properties)) {
3213
+ throw new Error(`[furin] ${filename}: route config spreads must resolve to local object literals; declare remountDeps after dynamic spreads.`);
3214
+ }
3215
+ for (let index = config.properties.length - 1;index >= 0; index -= 1) {
3216
+ const entry = asAstNode(config.properties[index]);
3217
+ if (entry?.type === "SpreadElement") {
3218
+ const remount = resolveRemountProperty(asAstNode(entry.argument), declarations, configBindings, visiting, filename);
3219
+ if (remount) {
3220
+ return remount;
3221
+ }
3222
+ } else if (entry?.type === "Property") {
3223
+ const key = asAstNode(entry.key);
3224
+ if (key?.type === "Identifier" && entry.computed !== true && key.name === "remountDeps" || key?.type === "Literal" && key.value === "remountDeps") {
3225
+ return entry;
3226
+ }
3227
+ }
3228
+ }
3229
+ return null;
3230
+ }
3231
+ function pruneUnusedConfigBindings(source, filename, names) {
3232
+ let result = source;
3233
+ let pruned = true;
3234
+ while (pruned) {
3235
+ pruned = false;
3236
+ const code = result.toString();
3237
+ const { program } = parseSource(code, detectLangFromPath(filename));
3238
+ const references = new Set;
3239
+ walkWithAncestors(program, [], (node, ancestors) => {
3240
+ if (node.type === "Identifier" && typeof node.name === "string" && isReferenceIdentifier(node, ancestors)) {
3241
+ references.add(node.name);
3242
+ }
3243
+ });
3244
+ result = new MagicString(code);
3245
+ for (const statement of program.body) {
3246
+ if (statement.type !== "VariableDeclaration") {
3247
+ continue;
3248
+ }
3249
+ const retained = statement.declarations.filter((declaration) => declaration.id.type !== "Identifier" || !names.has(declaration.id.name) || references.has(declaration.id.name));
3250
+ if (retained.length !== statement.declarations.length) {
3251
+ result.update(statement.start, statement.end, retained.length ? `${statement.kind} ${retained.map((node) => code.slice(node.start, node.end)).join(", ")};` : "");
3252
+ pruned = true;
3253
+ }
3254
+ }
3255
+ }
3256
+ return result;
3257
+ }
2986
3258
  function collectBindingNames(pattern, names) {
2987
3259
  const node = asAstNode(pattern);
2988
3260
  if (!node) {
@@ -3034,13 +3306,13 @@ function collectDeclarationBindings(declaration, declarations) {
3034
3306
  }
3035
3307
  function collectModuleBindings(program) {
3036
3308
  const declarations = new Map;
3037
- const imports = new Set;
3309
+ const imports = new Map;
3038
3310
  for (const statement of program.body) {
3039
3311
  if (statement.type === "ImportDeclaration" && Array.isArray(statement.specifiers)) {
3040
3312
  for (const specifier of statement.specifiers) {
3041
3313
  const local = localName2(specifier);
3042
3314
  if (local) {
3043
- imports.add(local);
3315
+ imports.set(local, statement);
3044
3316
  }
3045
3317
  }
3046
3318
  continue;
@@ -3128,13 +3400,16 @@ function walkWithAncestors(value, ancestors, visitor) {
3128
3400
  }
3129
3401
  }
3130
3402
  function collectDependencyIdentifier(child, ancestors, trackImports, state) {
3131
- if (child.type !== "Identifier" || typeof child.name !== "string" || !isReferenceIdentifier(child, ancestors) || hasShadowingDeclaration(child.name, ancestors)) {
3403
+ const parent = ancestors.at(-1);
3404
+ const jsxReference = child.type === "JSXIdentifier" && (parent?.type === "JSXOpeningElement" && parent.name === child && typeof child.name === "string" && child.name[0] === child.name[0]?.toUpperCase() || parent?.type === "JSXMemberExpression" && parent.object === child);
3405
+ if (!(child.type === "Identifier" || jsxReference) || typeof child.name !== "string" || !isReferenceIdentifier(child, ancestors) || hasShadowingDeclaration(child.name, ancestors)) {
3132
3406
  return;
3133
3407
  }
3134
3408
  const declaration = state.moduleBindings.declarations.get(child.name);
3135
3409
  if (!declaration) {
3136
- if (trackImports && state.moduleBindings.imports.has(child.name)) {
3137
- state.hasUnresolvedImport = true;
3410
+ const imported = state.moduleBindings.imports.get(child.name);
3411
+ if (trackImports && imported) {
3412
+ state.imports.add(imported);
3138
3413
  }
3139
3414
  return;
3140
3415
  }
@@ -3155,13 +3430,20 @@ function collectDependencyIdentifier(child, ancestors, trackImports, state) {
3155
3430
  function collectDependencies(node, trackImports, state) {
3156
3431
  walkWithAncestors(node, [], (child, ancestors) => {
3157
3432
  collectDependencyIdentifier(child, ancestors, trackImports, state);
3433
+ if (trackImports && child.type === "ImportExpression") {
3434
+ const specifier = asAstNode(child.source)?.value;
3435
+ if (typeof specifier === "string") {
3436
+ state.dynamicImports.add(specifier);
3437
+ }
3438
+ }
3158
3439
  });
3159
3440
  }
3160
- function createHmrDataSignature(code, program, bindings) {
3441
+ function createHmrDataSignature(code, program, bindings, filename) {
3161
3442
  const serverStages = [];
3162
3443
  const dependencyState = {
3163
3444
  dependencies: new Map,
3164
- hasUnresolvedImport: false,
3445
+ dynamicImports: new Set,
3446
+ imports: new Set,
3165
3447
  importTrackedDependencies: new Set,
3166
3448
  moduleBindings: collectModuleBindings(program)
3167
3449
  };
@@ -3195,6 +3477,10 @@ function createHmrDataSignature(code, program, bindings) {
3195
3477
  });
3196
3478
  const dataSource = [
3197
3479
  ...serverStages,
3480
+ ...[...dependencyState.imports].map((imported) => ({
3481
+ source: code.slice(imported.start, imported.end),
3482
+ start: imported.start
3483
+ })),
3198
3484
  ...[...dependencyState.dependencies.values()].map((dependency) => ({
3199
3485
  source: code.slice(dependency.start, dependency.end),
3200
3486
  start: dependency.start
@@ -3202,7 +3488,14 @@ function createHmrDataSignature(code, program, bindings) {
3202
3488
  ].sort((left, right) => left.start - right.start).map((entry) => entry.source).join(`
3203
3489
  `);
3204
3490
  const hash = new Bun.CryptoHasher("sha256").update(dataSource).digest("hex");
3205
- return dependencyState.hasUnresolvedImport ? `external:${hash}` : hash;
3491
+ if (dependencyState.imports.size === 0 && dependencyState.dynamicImports.size === 0) {
3492
+ return hash;
3493
+ }
3494
+ const dependencies = hmrDependencySignature(new Set([
3495
+ ...[...dependencyState.imports].map((imported) => imported.source.value),
3496
+ ...dependencyState.dynamicImports
3497
+ ]), filename);
3498
+ return dependencies === undefined ? `external:${hash}` : `imports:${hash}:${dependencies}`;
3206
3499
  }
3207
3500
  function calledHookName(call) {
3208
3501
  const callee = asAstNode(call.callee);
@@ -3420,9 +3713,14 @@ function transformForClient(code, filename) {
3420
3713
  }
3421
3714
  let source = new MagicString(clientSource);
3422
3715
  const routeBindings = collectDefineRouteBindings(program);
3423
- const removedRouteCode = removeChainedServerCalls(source, program, routeBindings);
3716
+ assertCompleteRouteChains(program, routeBindings, filename);
3717
+ const configBindings = new Set;
3718
+ const removedRouteCode = removeChainedServerCalls(source, program, routeBindings, configBindings, filename);
3424
3719
  const removedServerCode = isomorphicResult.transformed || removedRouteCode;
3425
3720
  if (removedServerCode) {
3721
+ if (configBindings.size > 0) {
3722
+ source = pruneUnusedConfigBindings(source, filename, configBindings);
3723
+ }
3426
3724
  source = deadCodeElimination(source, code, lang);
3427
3725
  }
3428
3726
  const transformedCode = source.toString();
@@ -3441,11 +3739,16 @@ function transformForClient(code, filename) {
3441
3739
  if (originalError) {
3442
3740
  throw new Error(`Failed to parse ${filename}: ${originalError.message}`);
3443
3741
  }
3444
- const hmrDataSignature = createHmrDataSignature(code, originalParse.program, collectDefineRouteBindings(originalParse.program));
3742
+ const hmrDataSignature = createHmrDataSignature(code, originalParse.program, collectDefineRouteBindings(originalParse.program), filename);
3445
3743
  const signatureValue = Array.isArray(hookSignature) ? JSON.stringify(hookSignature) : 'route.component[Symbol.for("furin.hmr.hook-signature")] ?? [String(route.component)]';
3446
3744
  source.append(`
3447
3745
  if (import.meta.hot && route?.component) {
3448
3746
  const previousDataSignature = ${JSON.stringify(hmrDataSignature)};
3747
+ const previousSourceSignature = ${JSON.stringify(Bun.hash(code).toString(16))};
3748
+ Object.defineProperty(route, Symbol.for(${JSON.stringify(HMR_SOURCE_SIGNATURE)}), {
3749
+ configurable: true,
3750
+ value: previousSourceSignature,
3751
+ });
3449
3752
  Object.defineProperty(route, Symbol.for(${JSON.stringify(HMR_DATA_SIGNATURE)}), {
3450
3753
  configurable: true,
3451
3754
  value: previousDataSignature,
@@ -3461,10 +3764,14 @@ if (import.meta.hot && route?.component) {
3461
3764
  updatedRoute,
3462
3765
  Symbol.for(${JSON.stringify(HMR_DATA_SIGNATURE)})
3463
3766
  );
3767
+ // An unchanged source can be re-evaluated by Bun after an import edit
3768
+ // without rerunning this transform. Its embedded dependency hash is stale.
3464
3769
  const dataChanged =
3465
3770
  previousDataSignature.startsWith("external:") ||
3466
3771
  typeof updatedDataSignature !== "string" ||
3467
3772
  updatedDataSignature.startsWith("external:") ||
3773
+ (updatedDataSignature.startsWith("imports:") &&
3774
+ Reflect.get(updatedRoute, Symbol.for(${JSON.stringify(HMR_SOURCE_SIGNATURE)})) === previousSourceSignature) ||
3468
3775
  updatedDataSignature !== previousDataSignature;
3469
3776
  window.__FURIN_HMR_UPDATE__?.(${JSON.stringify(filename)}, updatedRoute.component, dataChanged);
3470
3777
  }
@@ -3492,6 +3799,9 @@ export default {};
3492
3799
  var plugin = {
3493
3800
  name: "furin-strip-server",
3494
3801
  setup(build) {
3802
+ environmentGuardPlugin("client").setup(build);
3803
+ const topologyPaths = new Set;
3804
+ const loadedSources = new Map;
3495
3805
  build.onResolve({ filter: ELYSIA_FILTER }, () => ({
3496
3806
  namespace: "furin-stubs",
3497
3807
  path: "elysia-stub"
@@ -3508,12 +3818,33 @@ var plugin = {
3508
3818
  if (args.path.includes("node_modules")) {
3509
3819
  return;
3510
3820
  }
3511
- const source = await Bun.file(args.path).text();
3821
+ let source;
3822
+ try {
3823
+ source = await Bun.file(args.path).text();
3824
+ } catch (error) {
3825
+ const loaded = loadedSources.get(args.path);
3826
+ if (loaded?.isRouteModule && error instanceof Error && "code" in error && error.code === "ENOENT") {
3827
+ return loaded;
3828
+ }
3829
+ throw error;
3830
+ }
3831
+ const normalizedPath = args.path.replaceAll("\\", "/");
3832
+ if (normalizedPath.includes("/.furin/") && normalizedPath.endsWith("/_hydrate.tsx")) {
3833
+ const transpiler = new Bun.Transpiler({ loader: "tsx" });
3834
+ for (const imported of transpiler.scanImports(source)) {
3835
+ if (isAbsolute2(imported.path) || imported.path.startsWith(".")) {
3836
+ topologyPaths.add(resolve2(dirname3(args.path), imported.path));
3837
+ }
3838
+ }
3839
+ }
3512
3840
  const result = transformForClient(source, args.path);
3513
- return {
3841
+ const loaded = {
3514
3842
  contents: result.code,
3843
+ isRouteModule: topologyPaths.has(args.path),
3515
3844
  loader: detectLoaderFromPath(args.path)
3516
3845
  };
3846
+ loadedSources.set(args.path, loaded);
3847
+ return loaded;
3517
3848
  });
3518
3849
  }
3519
3850
  };
@@ -0,0 +1,16 @@
1
+ import type { IsomorphicEnvironment } from "./transform-isomorphic.ts";
2
+ /**
3
+ * Stable key shared by the `clientModule()` transform and the client build's
4
+ * preload manifest. It is an opaque ASCII token so it survives minification
5
+ * unchanged and can be swapped for the module's chunk URLs after the build.
6
+ */
7
+ export declare function clientModuleKey(modulePath: string): string;
8
+ /**
9
+ * Rewrites `clientModule(() => import("./x"))` calls imported from
10
+ * `@teyik0/furin/client`:
11
+ * - client: keeps the loader and appends the module key, which the production
12
+ * client build replaces with the module's chunk URLs;
13
+ * - server: drops the `import()` so the module is never bundled server-side and
14
+ * passes the key, resolved against the preload manifest at render time.
15
+ */
16
+ export declare function transformClientModules(source: string, filename: string, environment: IsomorphicEnvironment): string;
@@ -4,5 +4,7 @@ interface TransformResult {
4
4
  map: ReturnType<MagicString["generateMap"]> | null;
5
5
  removedServerCode: boolean;
6
6
  }
7
+ /** Server stages and their imports share one signature across both HMR graphs. */
8
+ export declare function getHmrDataSignature(code: string, filename: string): string;
7
9
  export declare function transformForClient(code: string, filename: string): TransformResult;
8
10
  export {};
@@ -5,5 +5,5 @@ export interface IsomorphicTransformResult {
5
5
  map: ReturnType<MagicString["generateMap"]> | null;
6
6
  transformed: boolean;
7
7
  }
8
- export declare function transformIsomorphicFunctions(source: string, filename: string, environment: IsomorphicEnvironment): IsomorphicTransformResult;
8
+ export declare function transformIsomorphicFunctions(input: string, filename: string, environment: IsomorphicEnvironment): IsomorphicTransformResult;
9
9
  export declare function isomorphicTransformPlugin(environment: IsomorphicEnvironment): Bun.BunPlugin;
package/dist/routes.d.ts CHANGED
@@ -4,3 +4,9 @@
4
4
  */
5
5
  export interface RouteMap {
6
6
  }
7
+ /** Literal route patterns for editor completion in APIs that accept path params. */
8
+ export interface RoutePatternMap {
9
+ }
10
+ /** Application contract for sync IDs and their resource scopes. */
11
+ export interface SyncQueryMap {
12
+ }