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

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 (233) hide show
  1. package/dist/adapter/bun.d.ts +2 -18
  2. package/dist/adapter/package.d.ts +2 -2
  3. package/dist/adapter/runtime-build.d.ts +33 -0
  4. package/dist/adapter/vercel.d.ts +3 -0
  5. package/dist/build/client.d.ts +1 -1
  6. package/dist/build/compile-entry.d.ts +6 -4
  7. package/dist/build/compile-entry.ts +36 -77
  8. package/dist/build/elysia-aot.d.ts +9 -0
  9. package/dist/build/entry-template.d.ts +9 -3
  10. package/dist/build/entry-template.ts +55 -13
  11. package/dist/build/index.d.ts +1 -1
  12. package/dist/build/index.js +8912 -6391
  13. package/dist/build/server-app-entry.d.ts +12 -0
  14. package/dist/build/ssg-cache.d.ts +13 -0
  15. package/dist/build/types.d.ts +25 -2
  16. package/dist/build/virtual-entry.d.ts +8 -0
  17. package/dist/cache.d.ts +6 -0
  18. package/dist/cache.js +282 -0
  19. package/dist/cli/index.js +8936 -6308
  20. package/dist/cli/preview.d.ts +7 -0
  21. package/dist/client/boundaries.d.ts +1 -0
  22. package/dist/client/browser-events-runtime.d.ts +2 -0
  23. package/dist/client/browser-events.d.ts +2 -0
  24. package/dist/client/define-route.d.ts +9 -8
  25. package/dist/client/dev-error-overlay.d.ts +1 -0
  26. package/dist/client/dev-error-overlay.ts +201 -0
  27. package/dist/client/document.d.ts +1 -0
  28. package/dist/client/hmr.d.ts +4 -2
  29. package/dist/client/internal/runtime-types.d.ts +8 -1
  30. package/dist/client/link.js +465 -86
  31. package/dist/client/router/provider.d.ts +1 -1
  32. package/dist/client/router/sync-catch-up.d.ts +1 -1
  33. package/dist/client/router/types.d.ts +8 -10
  34. package/dist/client/sync.d.ts +1 -0
  35. package/dist/client.js +37 -23
  36. package/dist/config.d.ts +35 -17
  37. package/dist/config.js +10 -2
  38. package/dist/define-route.d.ts +282 -1015
  39. package/dist/devtools/protocol.d.ts +2 -2
  40. package/dist/furin.d.ts +21 -6
  41. package/dist/furin.js +12823 -8484
  42. package/dist/plugin/index.js +476 -7
  43. package/dist/plugin/routes.d.ts +10 -3
  44. package/dist/rsc/build/index.d.ts +5 -1
  45. package/dist/server/assets/production.d.ts +3 -0
  46. package/dist/server/auto-invalidate/plugin.d.ts +8 -24
  47. package/dist/server/auto-invalidate/runtime.d.ts +2 -2
  48. package/dist/server/browser-events/plugin.d.ts +11 -0
  49. package/dist/server/browser-events/types.d.ts +9 -0
  50. package/dist/server/cache/invalidation.d.ts +2 -3
  51. package/dist/server/cache/isr.d.ts +1 -0
  52. package/dist/server/cache/page-cache-state.d.ts +5 -0
  53. package/dist/server/cache/page-cache.d.ts +53 -0
  54. package/dist/server/cache/purger.d.ts +7 -0
  55. package/dist/server/cache/redis/index.d.ts +39 -0
  56. package/dist/server/cache/redis/index.js +396 -0
  57. package/dist/server/cache/redis/scripts.d.ts +6 -0
  58. package/dist/server/cache/runtime-cache.d.ts +21 -0
  59. package/dist/server/context-logger.d.ts +2 -2
  60. package/dist/server/dev/browser-events.d.ts +4 -0
  61. package/dist/server/dev/diagnostics.d.ts +39 -0
  62. package/dist/server/dev/error.d.ts +17 -0
  63. package/dist/server/dev/graph.d.ts +86 -0
  64. package/dist/server/dev/plugin.d.ts +9 -0
  65. package/dist/server/dev/request-security.d.ts +1 -0
  66. package/dist/server/dev/rewrite-module-specifiers.d.ts +7 -0
  67. package/dist/server/dev/runtime.production.d.ts +6 -0
  68. package/dist/server/dev/symbolicate.d.ts +11 -0
  69. package/dist/server/dev/transform-failure.d.ts +4 -0
  70. package/dist/server/dev-page-plugin.d.ts +7 -0
  71. package/dist/server/dev-page-plugin.production.d.ts +1 -0
  72. package/dist/server/devtools/hub.d.ts +3 -2
  73. package/dist/server/devtools/instrumentation.d.ts +1 -1
  74. package/dist/server/devtools/instrumentation.production.d.ts +1 -1
  75. package/dist/server/devtools/plugin.d.ts +1 -1
  76. package/dist/server/evlog.d.ts +14 -0
  77. package/dist/server/external-prerender.d.ts +2 -0
  78. package/dist/server/instance.d.ts +2 -2
  79. package/dist/server/internal.d.ts +20 -2
  80. package/dist/server/internal.js +2973 -1
  81. package/dist/server/render/element.d.ts +1 -0
  82. package/dist/server/render/index.d.ts +1 -1
  83. package/dist/server/render/index.ts +1 -1
  84. package/dist/server/render/not-found.d.ts +1 -1
  85. package/dist/server/render/ppr-document.d.ts +21 -0
  86. package/dist/server/render/ppr-request.d.ts +26 -0
  87. package/dist/server/render/ppr-route.d.ts +3 -1
  88. package/dist/server/render/shell.ts +0 -12
  89. package/dist/server/render/ssg.d.ts +7 -0
  90. package/dist/server/render/ssr.d.ts +17 -6
  91. package/dist/server/render/static-params.d.ts +4 -0
  92. package/dist/server/router/defined-route.d.ts +1 -1
  93. package/dist/server/router/hmr.production.d.ts +2 -0
  94. package/dist/server/router/patterns.d.ts +1 -0
  95. package/dist/server/router/plugin.d.ts +3 -1
  96. package/dist/server/router/schemas.d.ts +1 -0
  97. package/dist/server/sync/adapter.d.ts +13 -0
  98. package/dist/server/sync/config.d.ts +5 -5
  99. package/dist/server/sync/index.d.ts +6 -6
  100. package/dist/server/sync/index.js +1252 -599
  101. package/dist/server/sync/notifier.d.ts +1 -0
  102. package/dist/server/sync/plugin.d.ts +31 -158
  103. package/dist/server/sync/postgres/index.d.ts +12 -1
  104. package/dist/server/sync/postgres/index.js +101 -6
  105. package/dist/server/sync/stream.d.ts +37 -61
  106. package/dist/shared/await.d.ts +3 -3
  107. package/dist/shared/browser-events.d.ts +22 -0
  108. package/dist/shared/compact-json.d.ts +8 -0
  109. package/dist/shared/deferred-ndjson.d.ts +6 -5
  110. package/dist/shared/dev-diagnostics.d.ts +36 -0
  111. package/dist/shared/elysia-contract.d.ts +8 -14
  112. package/dist/shared/prefix.d.ts +2 -0
  113. package/package.json +26 -11
  114. package/src/adapter/README.md +53 -1
  115. package/src/adapter/bun.ts +106 -283
  116. package/src/adapter/package.ts +21 -11
  117. package/src/adapter/runtime-build.ts +382 -0
  118. package/src/adapter/static.ts +87 -8
  119. package/src/adapter/vercel.ts +876 -0
  120. package/src/build/client.ts +55 -13
  121. package/src/build/compile-entry.ts +36 -77
  122. package/src/build/elysia-aot.ts +102 -0
  123. package/src/build/entry-template.ts +55 -13
  124. package/src/build/hydrate.ts +60 -20
  125. package/src/build/index.ts +17 -8
  126. package/src/build/production-instrumentation.ts +56 -4
  127. package/src/build/server-app-entry.ts +60 -0
  128. package/src/build/shared.ts +5 -2
  129. package/src/build/ssg-cache.ts +93 -12
  130. package/src/build/types.ts +31 -2
  131. package/src/build/virtual-entry.ts +28 -0
  132. package/src/cache.ts +26 -0
  133. package/src/cli/config.ts +3 -3
  134. package/src/cli/index.ts +58 -3
  135. package/src/cli/preview.ts +90 -0
  136. package/src/client/boundaries.tsx +10 -1
  137. package/src/client/browser-events-runtime.ts +204 -0
  138. package/src/client/browser-events.ts +22 -0
  139. package/src/client/define-route.ts +7 -17
  140. package/src/client/dev-error-overlay.ts +201 -0
  141. package/src/client/document.tsx +4 -7
  142. package/src/client/hmr.ts +26 -3
  143. package/src/client/internal/runtime-types.ts +10 -1
  144. package/src/client/router/boundary-tree.tsx +4 -4
  145. package/src/client/router/provider.tsx +165 -63
  146. package/src/client/router/sync-catch-up.ts +3 -4
  147. package/src/client/router/types.ts +6 -6
  148. package/src/client/sync.ts +1 -0
  149. package/src/config.ts +28 -2
  150. package/src/define-route.ts +285 -134
  151. package/src/devtools/devtools-element.js +56 -77
  152. package/src/devtools/protocol.ts +2 -2
  153. package/src/furin.ts +272 -203
  154. package/src/plugin/route-config-autofix.ts +11 -2
  155. package/src/plugin/routes.ts +291 -65
  156. package/src/plugin/transform-client.ts +685 -3
  157. package/src/react-dom-edge.d.ts +6 -0
  158. package/src/rsc/build/index.ts +15 -3
  159. package/src/server/assets/production.ts +99 -0
  160. package/src/server/auto-invalidate/plugin.ts +4 -4
  161. package/src/server/auto-invalidate/runtime.ts +76 -41
  162. package/src/server/browser-events/plugin.ts +173 -0
  163. package/src/server/browser-events/types.ts +11 -0
  164. package/src/server/cache/dev-loader.ts +30 -29
  165. package/src/server/cache/invalidation.ts +67 -35
  166. package/src/server/cache/isr.ts +9 -0
  167. package/src/server/cache/page-cache-state.ts +22 -0
  168. package/src/server/cache/page-cache.ts +300 -0
  169. package/src/server/cache/purger.ts +41 -0
  170. package/src/server/cache/redis/index.ts +350 -0
  171. package/src/server/cache/redis/scripts.ts +160 -0
  172. package/src/server/cache/runtime-cache.ts +137 -0
  173. package/src/server/context-logger.ts +5 -5
  174. package/src/server/dev/browser-events.ts +54 -0
  175. package/src/server/dev/diagnostics.ts +297 -0
  176. package/src/server/dev/error.ts +148 -0
  177. package/src/server/dev/graph.ts +438 -0
  178. package/src/server/dev/plugin.ts +130 -0
  179. package/src/server/dev/request-security.ts +38 -0
  180. package/src/server/dev/rewrite-module-specifiers.ts +81 -0
  181. package/src/server/dev/runtime.production.ts +28 -0
  182. package/src/server/dev/symbolicate.ts +135 -0
  183. package/src/server/dev/transform-failure.ts +8 -0
  184. package/src/server/dev-page-plugin.production.ts +3 -0
  185. package/src/server/dev-page-plugin.ts +136 -53
  186. package/src/server/devtools/hub.ts +6 -5
  187. package/src/server/devtools/instrumentation.production.ts +1 -1
  188. package/src/server/devtools/instrumentation.ts +12 -6
  189. package/src/server/devtools/plugin.ts +7 -150
  190. package/src/server/evlog.ts +99 -0
  191. package/src/server/external-prerender.ts +10 -0
  192. package/src/server/instance.ts +3 -3
  193. package/src/server/internal.ts +46 -2
  194. package/src/server/render/assemble.ts +4 -4
  195. package/src/server/render/document.tsx +13 -4
  196. package/src/server/render/element.tsx +18 -14
  197. package/src/server/render/index.ts +1 -1
  198. package/src/server/render/isr.ts +509 -136
  199. package/src/server/render/loaders.ts +31 -15
  200. package/src/server/render/not-found.ts +32 -8
  201. package/src/server/render/ppr-document.ts +239 -0
  202. package/src/server/render/ppr-request.ts +104 -0
  203. package/src/server/render/ppr-route.ts +335 -28
  204. package/src/server/render/shell.ts +0 -12
  205. package/src/server/render/ssg.ts +186 -24
  206. package/src/server/render/ssr.ts +215 -89
  207. package/src/server/render/static-params.ts +174 -0
  208. package/src/server/render/template.ts +47 -11
  209. package/src/server/router/defined-route.ts +9 -40
  210. package/src/server/router/hmr.production.ts +7 -0
  211. package/src/server/router/hmr.ts +108 -67
  212. package/src/server/router/patterns.ts +5 -1
  213. package/src/server/router/plugin.ts +164 -66
  214. package/src/server/router/schema-merge.ts +1 -1
  215. package/src/server/router/schemas.ts +174 -61
  216. package/src/server/router/source-version.ts +3 -10
  217. package/src/server/sync/adapter.ts +13 -0
  218. package/src/server/sync/config.ts +12 -12
  219. package/src/server/sync/index.ts +8 -8
  220. package/src/server/sync/notifier.ts +1 -0
  221. package/src/server/sync/plugin.ts +18 -11
  222. package/src/server/sync/postgres/index.ts +111 -5
  223. package/src/server/sync/response.ts +3 -3
  224. package/src/server/sync/runtime.ts +12 -0
  225. package/src/server/sync/stream.ts +78 -113
  226. package/src/shared/await.tsx +3 -3
  227. package/src/shared/browser-events.ts +28 -0
  228. package/src/shared/compact-json.ts +77 -0
  229. package/src/shared/deferred-ndjson.ts +20 -6
  230. package/src/shared/dev-diagnostics.ts +44 -0
  231. package/src/shared/elysia-contract.ts +23 -25
  232. package/src/shared/prefix.ts +8 -0
  233. package/src/shared/route-map.ts +10 -1
@@ -10,7 +10,18 @@ import { transformIsomorphicFunctions } from "./transform-isomorphic.ts";
10
10
 
11
11
  const FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
12
12
  const FURIN_SERVER_MODULES = new Set(["@teyik0/furin", "furin"]);
13
+ const REACT_COMPONENT_WRAPPERS = new Set(["forwardRef", "memo"]);
13
14
  const SERVER_ONLY_METHODS = new Set(["config", "head", "loader", "requestLoader", "staticParams"]);
15
+ const REACT_HOOK_NAME_RE = /^use[A-Z0-9]/;
16
+ const HMR_DATA_SIGNATURE = "furin.hmr.data-signature";
17
+ const TYPESCRIPT_RUNTIME_WRAPPERS = new Map([
18
+ ["TSAsExpression", ["expression"]],
19
+ ["TSInstantiationExpression", ["expression"]],
20
+ ["TSNonNullExpression", ["expression"]],
21
+ ["TSParameterProperty", ["decorators", "parameter"]],
22
+ ["TSSatisfiesExpression", ["expression"]],
23
+ ["TSTypeAssertion", ["expression"]],
24
+ ]);
14
25
 
15
26
  interface TransformResult {
16
27
  code: string;
@@ -186,6 +197,630 @@ function removeChainedServerCalls(
186
197
  return transformed;
187
198
  }
188
199
 
200
+ function collectBindingNames(pattern: unknown, names: string[]): void {
201
+ const node = asAstNode(pattern);
202
+ if (!node) {
203
+ return;
204
+ }
205
+ if (node.type === "Identifier" && typeof node.name === "string") {
206
+ names.push(node.name);
207
+ return;
208
+ }
209
+ if (node.type === "AssignmentPattern") {
210
+ collectBindingNames(node.left, names);
211
+ return;
212
+ }
213
+ if (node.type === "RestElement") {
214
+ collectBindingNames(node.argument, names);
215
+ return;
216
+ }
217
+ if (node.type === "ArrayPattern" && Array.isArray(node.elements)) {
218
+ for (const element of node.elements) {
219
+ collectBindingNames(element, names);
220
+ }
221
+ return;
222
+ }
223
+ if (node.type === "ObjectPattern" && Array.isArray(node.properties)) {
224
+ for (const property of node.properties) {
225
+ const propertyNode = asAstNode(property);
226
+ collectBindingNames(
227
+ propertyNode?.type === "Property" ? propertyNode.value : propertyNode?.argument,
228
+ names
229
+ );
230
+ }
231
+ }
232
+ }
233
+
234
+ function collectDeclarationBindings(
235
+ declaration: AstNode | null,
236
+ declarations: Map<string, AstNode>
237
+ ): void {
238
+ if (declaration?.type === "FunctionDeclaration" || declaration?.type === "ClassDeclaration") {
239
+ const identifier = asAstNode(declaration.id);
240
+ if (identifier?.type === "Identifier" && typeof identifier.name === "string") {
241
+ declarations.set(identifier.name, declaration);
242
+ }
243
+ return;
244
+ }
245
+ if (declaration?.type !== "VariableDeclaration" || !Array.isArray(declaration.declarations)) {
246
+ return;
247
+ }
248
+ for (const item of declaration.declarations as AstNode[]) {
249
+ const names: string[] = [];
250
+ collectBindingNames(item.id, names);
251
+ for (const name of names) {
252
+ declarations.set(name, item);
253
+ }
254
+ }
255
+ }
256
+
257
+ function collectModuleBindings(program: Program): {
258
+ declarations: Map<string, AstNode>;
259
+ imports: Set<string>;
260
+ } {
261
+ const declarations = new Map<string, AstNode>();
262
+ const imports = new Set<string>();
263
+ for (const statement of program.body as unknown as AstNode[]) {
264
+ if (statement.type === "ImportDeclaration" && Array.isArray(statement.specifiers)) {
265
+ for (const specifier of statement.specifiers as AstNode[]) {
266
+ const local = localName(specifier);
267
+ if (local) {
268
+ imports.add(local);
269
+ }
270
+ }
271
+ continue;
272
+ }
273
+ const declaration =
274
+ statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration"
275
+ ? asAstNode(statement.declaration)
276
+ : statement;
277
+ collectDeclarationBindings(declaration, declarations);
278
+ }
279
+ return { declarations, imports };
280
+ }
281
+
282
+ function isBindingIdentifier(identifier: AstNode, pattern: unknown): boolean {
283
+ const node = asAstNode(pattern);
284
+ if (!node) {
285
+ return false;
286
+ }
287
+ if (node.type === "Identifier") {
288
+ return node.start === identifier.start && node.end === identifier.end;
289
+ }
290
+ if (node.type === "AssignmentPattern") {
291
+ return isBindingIdentifier(identifier, node.left);
292
+ }
293
+ if (node.type === "RestElement") {
294
+ return isBindingIdentifier(identifier, node.argument);
295
+ }
296
+ if (node.type === "ArrayPattern" && Array.isArray(node.elements)) {
297
+ return node.elements.some((element) => isBindingIdentifier(identifier, element));
298
+ }
299
+ if (node.type === "ObjectPattern" && Array.isArray(node.properties)) {
300
+ return node.properties.some((property) => {
301
+ const propertyNode = asAstNode(property);
302
+ return isBindingIdentifier(
303
+ identifier,
304
+ propertyNode?.type === "Property" ? propertyNode.value : propertyNode?.argument
305
+ );
306
+ });
307
+ }
308
+ return false;
309
+ }
310
+
311
+ function nodeContains(container: unknown, node: AstNode): boolean {
312
+ if (Array.isArray(container)) {
313
+ return container.some((entry) => nodeContains(entry, node));
314
+ }
315
+ const containerNode = asAstNode(container);
316
+ return Boolean(
317
+ containerNode && containerNode.start <= node.start && node.end <= containerNode.end
318
+ );
319
+ }
320
+
321
+ function isTypePosition(node: AstNode, ancestors: AstNode[]): boolean {
322
+ return ancestors.some((ancestor) => {
323
+ if (!ancestor.type.startsWith("TS")) {
324
+ return false;
325
+ }
326
+ const runtimeChildren = TYPESCRIPT_RUNTIME_WRAPPERS.get(ancestor.type);
327
+ if (runtimeChildren) {
328
+ return !runtimeChildren.some((key) => nodeContains(ancestor[key], node));
329
+ }
330
+ return true;
331
+ });
332
+ }
333
+
334
+ function isNonReferenceKey(node: AstNode, parent: AstNode | undefined): boolean {
335
+ return Boolean(
336
+ parent &&
337
+ ((parent.type === "MemberExpression" &&
338
+ parent.computed !== true &&
339
+ parent.property === node) ||
340
+ (parent.type === "Property" &&
341
+ parent.computed !== true &&
342
+ parent.shorthand !== true &&
343
+ parent.key === node) ||
344
+ ((parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") &&
345
+ parent.computed !== true &&
346
+ parent.key === node) ||
347
+ ((parent.type === "LabeledStatement" ||
348
+ parent.type === "BreakStatement" ||
349
+ parent.type === "ContinueStatement") &&
350
+ parent.label === node))
351
+ );
352
+ }
353
+
354
+ function isReferenceIdentifier(node: AstNode, ancestors: AstNode[]): boolean {
355
+ if (isTypePosition(node, ancestors) || isNonReferenceKey(node, ancestors.at(-1))) {
356
+ return false;
357
+ }
358
+ for (const ancestor of ancestors) {
359
+ if (
360
+ (ancestor.type === "VariableDeclarator" && isBindingIdentifier(node, ancestor.id)) ||
361
+ ((ancestor.type === "FunctionDeclaration" ||
362
+ ancestor.type === "FunctionExpression" ||
363
+ ancestor.type === "ArrowFunctionExpression") &&
364
+ (isBindingIdentifier(node, ancestor.id) ||
365
+ (Array.isArray(ancestor.params) &&
366
+ ancestor.params.some((parameter) => isBindingIdentifier(node, parameter))))) ||
367
+ (ancestor.type === "ClassDeclaration" && isBindingIdentifier(node, ancestor.id)) ||
368
+ (ancestor.type === "CatchClause" && isBindingIdentifier(node, ancestor.param))
369
+ ) {
370
+ return false;
371
+ }
372
+ }
373
+ return true;
374
+ }
375
+
376
+ function walkWithAncestors(
377
+ value: unknown,
378
+ ancestors: AstNode[],
379
+ visitor: (node: AstNode, ancestors: AstNode[]) => void
380
+ ): void {
381
+ if (Array.isArray(value)) {
382
+ for (const entry of value) {
383
+ walkWithAncestors(entry, ancestors, visitor);
384
+ }
385
+ return;
386
+ }
387
+ const node = asAstNode(value);
388
+ if (!node) {
389
+ return;
390
+ }
391
+ visitor(node, ancestors);
392
+ const nextAncestors = [...ancestors, node];
393
+ for (const [key, child] of Object.entries(node)) {
394
+ if (key !== "type" && key !== "start" && key !== "end" && key !== "comments") {
395
+ walkWithAncestors(child, nextAncestors, visitor);
396
+ }
397
+ }
398
+ }
399
+
400
+ interface HmrDependencyState {
401
+ dependencies: Map<number, AstNode>;
402
+ hasUnresolvedImport: boolean;
403
+ importTrackedDependencies: Set<number>;
404
+ moduleBindings: ReturnType<typeof collectModuleBindings>;
405
+ }
406
+
407
+ function collectDependencyIdentifier(
408
+ child: AstNode,
409
+ ancestors: AstNode[],
410
+ trackImports: boolean,
411
+ state: HmrDependencyState
412
+ ): void {
413
+ if (
414
+ child.type !== "Identifier" ||
415
+ typeof child.name !== "string" ||
416
+ !isReferenceIdentifier(child, ancestors) ||
417
+ hasShadowingDeclaration(child.name, ancestors)
418
+ ) {
419
+ return;
420
+ }
421
+ const declaration = state.moduleBindings.declarations.get(child.name);
422
+ if (!declaration) {
423
+ if (trackImports && state.moduleBindings.imports.has(child.name)) {
424
+ state.hasUnresolvedImport = true;
425
+ }
426
+ return;
427
+ }
428
+ const alreadyTracked = state.dependencies.has(declaration.start);
429
+ if (!alreadyTracked) {
430
+ state.dependencies.set(declaration.start, declaration);
431
+ }
432
+ if (trackImports) {
433
+ if (state.importTrackedDependencies.has(declaration.start)) {
434
+ return;
435
+ }
436
+ state.importTrackedDependencies.add(declaration.start);
437
+ } else if (alreadyTracked) {
438
+ return;
439
+ }
440
+ collectDependencies(declaration, trackImports, state);
441
+ }
442
+
443
+ function collectDependencies(
444
+ node: AstNode,
445
+ trackImports: boolean,
446
+ state: HmrDependencyState
447
+ ): void {
448
+ walkWithAncestors(node, [], (child, ancestors) => {
449
+ collectDependencyIdentifier(child, ancestors, trackImports, state);
450
+ });
451
+ }
452
+
453
+ function createHmrDataSignature(code: string, program: Program, bindings: Set<string>): string {
454
+ const serverStages: Array<{ source: string; start: number }> = [];
455
+ const dependencyState: HmrDependencyState = {
456
+ dependencies: new Map(),
457
+ hasUnresolvedImport: false,
458
+ importTrackedDependencies: new Set(),
459
+ moduleBindings: collectModuleBindings(program),
460
+ };
461
+
462
+ walk(program, {
463
+ CallExpression(call, context) {
464
+ const callee = asAstNode(call.callee);
465
+ if (
466
+ callee?.type !== "MemberExpression" ||
467
+ callee.computed === true ||
468
+ !callee.property ||
469
+ typeof callee.property !== "object"
470
+ ) {
471
+ return;
472
+ }
473
+ const property = callee.property as AstNode;
474
+ if (
475
+ property.type !== "Identifier" ||
476
+ typeof property.name !== "string" ||
477
+ !SERVER_ONLY_METHODS.has(property.name) ||
478
+ !chainRootIsDefineRoute(callee.object, bindings, context.ancestors() as AstNode[])
479
+ ) {
480
+ return;
481
+ }
482
+ const object = asAstNode(callee.object);
483
+ if (!object) {
484
+ return;
485
+ }
486
+ serverStages.push({
487
+ source: code.slice(object.end, call.end),
488
+ start: call.start,
489
+ });
490
+ if (Array.isArray(call.arguments)) {
491
+ for (const argument of call.arguments) {
492
+ const argumentNode = asAstNode(argument);
493
+ if (argumentNode) {
494
+ collectDependencies(argumentNode, property.name !== "config", dependencyState);
495
+ }
496
+ }
497
+ }
498
+ },
499
+ });
500
+
501
+ const dataSource = [
502
+ ...serverStages,
503
+ ...[...dependencyState.dependencies.values()].map((dependency) => ({
504
+ source: code.slice(dependency.start, dependency.end),
505
+ start: dependency.start,
506
+ })),
507
+ ]
508
+ .sort((left, right) => left.start - right.start)
509
+ .map((entry) => entry.source)
510
+ .join("\n");
511
+ const hash = new Bun.CryptoHasher("sha256").update(dataSource).digest("hex");
512
+ return dependencyState.hasUnresolvedImport ? `external:${hash}` : hash;
513
+ }
514
+
515
+ function calledHookName(call: AstNode): string | null {
516
+ const callee = asAstNode(call.callee);
517
+ if (callee?.type === "Identifier" && typeof callee.name === "string") {
518
+ return REACT_HOOK_NAME_RE.test(callee.name) ? callee.name : null;
519
+ }
520
+ if (
521
+ callee?.type === "MemberExpression" &&
522
+ callee.computed !== true &&
523
+ callee.property &&
524
+ typeof callee.property === "object"
525
+ ) {
526
+ const property = callee.property as AstNode;
527
+ if (
528
+ property.type === "Identifier" &&
529
+ typeof property.name === "string" &&
530
+ REACT_HOOK_NAME_RE.test(property.name)
531
+ ) {
532
+ return property.name;
533
+ }
534
+ }
535
+ return null;
536
+ }
537
+
538
+ function routeComponentExpression(program: Program, bindings: Set<string>): AstNode | null {
539
+ let component: AstNode | null = null;
540
+ walk(program, {
541
+ CallExpression(call, context) {
542
+ const callee = asAstNode(call.callee);
543
+ if (
544
+ callee?.type !== "MemberExpression" ||
545
+ callee.computed === true ||
546
+ !callee.property ||
547
+ typeof callee.property !== "object"
548
+ ) {
549
+ return;
550
+ }
551
+ const property = callee.property as AstNode;
552
+ const ancestors = context.ancestors() as AstNode[];
553
+ const routeDeclarator = ancestors.find((ancestor) => {
554
+ if (ancestor.type !== "VariableDeclarator") {
555
+ return false;
556
+ }
557
+ const identifier = asAstNode(ancestor.id);
558
+ return identifier?.type === "Identifier" && identifier.name === "route";
559
+ });
560
+ if (
561
+ !(
562
+ routeDeclarator &&
563
+ ancestors.some((ancestor) => ancestor.type === "ExportNamedDeclaration")
564
+ ) ||
565
+ property.type !== "Identifier" ||
566
+ (property.name !== "page" && property.name !== "layout") ||
567
+ !chainRootIsDefineRoute(callee.object, bindings, ancestors)
568
+ ) {
569
+ return;
570
+ }
571
+ const args = call.arguments;
572
+ component = Array.isArray(args) ? asAstNode(args[0]) : null;
573
+ context.stop();
574
+ },
575
+ });
576
+ return component;
577
+ }
578
+
579
+ function namedFunction(declaration: AstNode, name: string): AstNode | null {
580
+ if (declaration.type === "FunctionDeclaration") {
581
+ const identifier = asAstNode(declaration.id);
582
+ return identifier?.type === "Identifier" && identifier.name === name ? declaration : null;
583
+ }
584
+ if (declaration.type === "VariableDeclaration" && Array.isArray(declaration.declarations)) {
585
+ for (const item of declaration.declarations as AstNode[]) {
586
+ const identifier = asAstNode(item.id);
587
+ const initializer = asAstNode(item.init);
588
+ if (
589
+ identifier?.type === "Identifier" &&
590
+ identifier.name === name &&
591
+ (initializer?.type === "ArrowFunctionExpression" ||
592
+ initializer?.type === "FunctionExpression")
593
+ ) {
594
+ return initializer;
595
+ }
596
+ }
597
+ }
598
+ return null;
599
+ }
600
+
601
+ function localFunction(program: Program, name: string): AstNode | null {
602
+ for (const statement of program.body as unknown as AstNode[]) {
603
+ const declaration =
604
+ statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration"
605
+ ? asAstNode(statement.declaration)
606
+ : statement;
607
+ const component = declaration ? namedFunction(declaration, name) : null;
608
+ if (component) {
609
+ return component;
610
+ }
611
+ }
612
+ return null;
613
+ }
614
+
615
+ interface ImportedRouteComponent {
616
+ end: number;
617
+ expression: string;
618
+ start: number;
619
+ }
620
+
621
+ function isImportedBinding(program: Program, name: string): boolean {
622
+ return program.body.some(
623
+ (statement) =>
624
+ statement.type === "ImportDeclaration" &&
625
+ statement.importKind !== "type" &&
626
+ (statement.specifiers as unknown as AstNode[]).some(
627
+ (specifier) => specifier.importKind !== "type" && localName(specifier) === name
628
+ )
629
+ );
630
+ }
631
+
632
+ interface ReactWrapperBindings {
633
+ members: Set<string>;
634
+ namespaces: Set<string>;
635
+ }
636
+
637
+ function collectReactWrapperBindings(program: Program): ReactWrapperBindings {
638
+ const bindings: ReactWrapperBindings = {
639
+ members: new Set<string>(),
640
+ namespaces: new Set<string>(),
641
+ };
642
+ for (const statement of program.body) {
643
+ if (statement.type !== "ImportDeclaration" || statement.source.value !== "react") {
644
+ continue;
645
+ }
646
+ for (const specifier of statement.specifiers as unknown as AstNode[]) {
647
+ const local = localName(specifier);
648
+ if (!local || specifier.importKind === "type") {
649
+ continue;
650
+ }
651
+ const imported = importedName(specifier);
652
+ if (
653
+ specifier.type === "ImportSpecifier" &&
654
+ imported &&
655
+ REACT_COMPONENT_WRAPPERS.has(imported)
656
+ ) {
657
+ bindings.members.add(local);
658
+ } else if (
659
+ specifier.type === "ImportDefaultSpecifier" ||
660
+ specifier.type === "ImportNamespaceSpecifier" ||
661
+ (specifier.type === "ImportSpecifier" && imported === "default")
662
+ ) {
663
+ bindings.namespaces.add(local);
664
+ }
665
+ }
666
+ }
667
+ return bindings;
668
+ }
669
+
670
+ function wrappedComponentFunction(
671
+ program: Program,
672
+ expression: AstNode,
673
+ bindings: ReactWrapperBindings
674
+ ): AstNode | null {
675
+ if (expression.type === "ArrowFunctionExpression" || expression.type === "FunctionExpression") {
676
+ return expression;
677
+ }
678
+ if (expression.type === "Identifier" && typeof expression.name === "string") {
679
+ return localFunction(program, expression.name);
680
+ }
681
+ if (expression.type !== "CallExpression") {
682
+ return null;
683
+ }
684
+ const callee = asAstNode(expression.callee);
685
+ const isNamedWrapper =
686
+ callee?.type === "Identifier" &&
687
+ typeof callee.name === "string" &&
688
+ bindings.members.has(callee.name);
689
+ const object = callee?.type === "MemberExpression" ? asAstNode(callee.object) : null;
690
+ const property = callee?.type === "MemberExpression" ? asAstNode(callee.property) : null;
691
+ const isNamespaceWrapper =
692
+ callee?.type === "MemberExpression" &&
693
+ callee.computed !== true &&
694
+ object?.type === "Identifier" &&
695
+ typeof object.name === "string" &&
696
+ bindings.namespaces.has(object.name) &&
697
+ property?.type === "Identifier" &&
698
+ typeof property.name === "string" &&
699
+ REACT_COMPONENT_WRAPPERS.has(property.name);
700
+ if (!(isNamedWrapper || isNamespaceWrapper)) {
701
+ return null;
702
+ }
703
+ const args = expression.arguments;
704
+ const wrapped = Array.isArray(args) ? asAstNode(args[0]) : null;
705
+ return wrapped ? wrappedComponentFunction(program, wrapped, bindings) : null;
706
+ }
707
+
708
+ function importedMemberBinding(program: Program, expression: AstNode): string | null {
709
+ let object = expression.type === "MemberExpression" ? asAstNode(expression.object) : null;
710
+ while (object?.type === "MemberExpression") {
711
+ object = asAstNode(object.object);
712
+ }
713
+ return object?.type === "Identifier" &&
714
+ typeof object.name === "string" &&
715
+ isImportedBinding(program, object.name)
716
+ ? object.name
717
+ : null;
718
+ }
719
+
720
+ function sourceText(code: string, node: AstNode | null): string {
721
+ return node ? code.slice(node.start, node.end) : "";
722
+ }
723
+
724
+ function unusedIdentifier(program: Program, preferred: string): string {
725
+ const identifiers = new Set<string>();
726
+ walk(program, {
727
+ Identifier(node) {
728
+ identifiers.add(node.name);
729
+ },
730
+ });
731
+ if (!identifiers.has(preferred)) {
732
+ return preferred;
733
+ }
734
+ let suffix = 1;
735
+ while (identifiers.has(`${preferred}_${suffix}`)) {
736
+ suffix += 1;
737
+ }
738
+ return `${preferred}_${suffix}`;
739
+ }
740
+
741
+ function hookCallsiteSignature(
742
+ code: string,
743
+ call: AstNode,
744
+ hookName: string,
745
+ parent: AstNode | null
746
+ ): string {
747
+ let key = parent?.type === "VariableDeclarator" ? sourceText(code, asAstNode(parent.id)) : "";
748
+ const args = call.arguments;
749
+ const stateArgument = Array.isArray(args) ? asAstNode(args[0]) : null;
750
+ const reducerArgument = Array.isArray(args) ? asAstNode(args[1]) : null;
751
+ if (hookName === "useState" && stateArgument) {
752
+ key += `(${sourceText(code, stateArgument)})`;
753
+ } else if (hookName === "useReducer" && reducerArgument) {
754
+ key += `(${sourceText(code, reducerArgument)})`;
755
+ }
756
+ return `${hookName}{${key}}`;
757
+ }
758
+
759
+ function collectFunctionHookSignature(code: string, component: AstNode): string[] {
760
+ const hooks: string[] = [];
761
+ walk(component as never, {
762
+ CallExpression(call, context) {
763
+ const callNode = call as unknown as AstNode;
764
+ const name = calledHookName(callNode);
765
+ if (name) {
766
+ hooks.push(
767
+ hookCallsiteSignature(code, callNode, name, asAstNode(context.parent as unknown))
768
+ );
769
+ }
770
+ },
771
+ Function(node, context) {
772
+ if ((node as unknown as AstNode) !== component) {
773
+ context.skip();
774
+ }
775
+ },
776
+ });
777
+ return hooks;
778
+ }
779
+
780
+ function collectClientHookSignature(
781
+ code: string,
782
+ filename: string
783
+ ): string[] | ImportedRouteComponent | "external" | null {
784
+ const lang = detectLangFromPath(filename);
785
+ const { program } = parseSource(code, lang);
786
+ const componentExpression = routeComponentExpression(
787
+ program,
788
+ collectDefineRouteBindings(program)
789
+ );
790
+ if (!componentExpression) {
791
+ return null;
792
+ }
793
+ const wrappedComponent = wrappedComponentFunction(
794
+ program,
795
+ componentExpression,
796
+ collectReactWrapperBindings(program)
797
+ );
798
+ if (wrappedComponent) {
799
+ return collectFunctionHookSignature(code, wrappedComponent);
800
+ }
801
+ if (componentExpression.type !== "Identifier" || typeof componentExpression.name !== "string") {
802
+ if (importedMemberBinding(program, componentExpression)) {
803
+ return {
804
+ end: componentExpression.end,
805
+ expression: sourceText(code, componentExpression),
806
+ start: componentExpression.start,
807
+ };
808
+ }
809
+ return collectFunctionHookSignature(code, componentExpression);
810
+ }
811
+ const component = localFunction(program, componentExpression.name);
812
+ if (component) {
813
+ return collectFunctionHookSignature(code, component);
814
+ }
815
+ return isImportedBinding(program, componentExpression.name)
816
+ ? {
817
+ end: componentExpression.end,
818
+ expression: componentExpression.name,
819
+ start: componentExpression.start,
820
+ }
821
+ : "external";
822
+ }
823
+
189
824
  export function transformForClient(code: string, filename: string): TransformResult {
190
825
  const lang = detectLangFromPath(filename);
191
826
  if (lang === "dts") {
@@ -207,13 +842,60 @@ export function transformForClient(code: string, filename: string): TransformRes
207
842
  if (removedServerCode) {
208
843
  source = deadCodeElimination(source, code, lang);
209
844
  }
210
- if (routeBindings.size > 0) {
845
+ const transformedCode = source.toString();
846
+ let hookSignature =
847
+ routeBindings.size > 0 ? collectClientHookSignature(transformedCode, filename) : null;
848
+ if (hookSignature && typeof hookSignature === "object" && !Array.isArray(hookSignature)) {
849
+ const createElementBinding = unusedIdentifier(program, "__furinCreateElement");
850
+ source = new MagicString(transformedCode);
851
+ source.prepend(`import { createElement as ${createElementBinding} } from "react";\n`);
852
+ source.update(
853
+ hookSignature.start,
854
+ hookSignature.end,
855
+ `(import.meta.hot ? (props) => ${createElementBinding}(${hookSignature.expression}, props) : ${hookSignature.expression})`
856
+ );
857
+ hookSignature = [];
858
+ }
859
+ if (routeBindings.size > 0 && hookSignature !== null) {
860
+ const originalParse = parseSource(code, lang);
861
+ const originalError = originalParse.diagnostics.find(
862
+ (diagnostic) => diagnostic.severity === "error"
863
+ );
864
+ if (originalError) {
865
+ throw new Error(`Failed to parse ${filename}: ${originalError.message}`);
866
+ }
867
+ const hmrDataSignature = createHmrDataSignature(
868
+ code,
869
+ originalParse.program,
870
+ collectDefineRouteBindings(originalParse.program)
871
+ );
872
+ const signatureValue = Array.isArray(hookSignature)
873
+ ? JSON.stringify(hookSignature)
874
+ : 'route.component[Symbol.for("furin.hmr.hook-signature")] ?? [String(route.component)]';
211
875
  source.append(`
212
- if (import.meta.hot) {
876
+ if (import.meta.hot && route?.component) {
877
+ const previousDataSignature = ${JSON.stringify(hmrDataSignature)};
878
+ Object.defineProperty(route, Symbol.for(${JSON.stringify(HMR_DATA_SIGNATURE)}), {
879
+ configurable: true,
880
+ value: previousDataSignature,
881
+ });
882
+ Object.defineProperty(route.component, Symbol.for("furin.hmr.hook-signature"), {
883
+ configurable: true,
884
+ value: ${signatureValue},
885
+ });
213
886
  import.meta.hot.accept((updatedModule) => {
214
887
  const updatedRoute = updatedModule?.route;
215
888
  if (updatedRoute?.component) {
216
- window.__FURIN_HMR_UPDATE__?.(${JSON.stringify(filename)}, updatedRoute.component);
889
+ const updatedDataSignature = Reflect.get(
890
+ updatedRoute,
891
+ Symbol.for(${JSON.stringify(HMR_DATA_SIGNATURE)})
892
+ );
893
+ const dataChanged =
894
+ previousDataSignature.startsWith("external:") ||
895
+ typeof updatedDataSignature !== "string" ||
896
+ updatedDataSignature.startsWith("external:") ||
897
+ updatedDataSignature !== previousDataSignature;
898
+ window.__FURIN_HMR_UPDATE__?.(${JSON.stringify(filename)}, updatedRoute.component, dataChanged);
217
899
  }
218
900
  });
219
901
  }