@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
@@ -6,6 +6,7 @@ import { parseSource } from "../shared/parser.ts";
6
6
  import type { AstNode } from "../shared/utils/ast-walk.ts";
7
7
  import { hasShadowingDeclaration } from "./binding-scope.ts";
8
8
  import { deadCodeElimination } from "./dead-code-elimination.ts";
9
+ import { hmrDependencySignature } from "./hmr-dependencies.ts";
9
10
  import { transformIsomorphicFunctions } from "./transform-isomorphic.ts";
10
11
 
11
12
  const FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
@@ -14,6 +15,7 @@ const REACT_COMPONENT_WRAPPERS = new Set(["forwardRef", "memo"]);
14
15
  const SERVER_ONLY_METHODS = new Set(["config", "head", "loader", "requestLoader", "staticParams"]);
15
16
  const REACT_HOOK_NAME_RE = /^use[A-Z0-9]/;
16
17
  const HMR_DATA_SIGNATURE = "furin.hmr.data-signature";
18
+ const HMR_SOURCE_SIGNATURE = "furin.hmr.source-signature";
17
19
  const TYPESCRIPT_RUNTIME_WRAPPERS = new Map([
18
20
  ["TSAsExpression", ["expression"]],
19
21
  ["TSInstantiationExpression", ["expression"]],
@@ -159,12 +161,79 @@ function chainRootIsDefineRoute(
159
161
  return false;
160
162
  }
161
163
 
164
+ function assertCompleteRouteChains(
165
+ program: Program,
166
+ bindings: Set<string>,
167
+ filename: string
168
+ ): void {
169
+ const namespaces = new Set<string>();
170
+ for (const statement of program.body) {
171
+ if (statement.type !== "ImportDeclaration") {
172
+ continue;
173
+ }
174
+ const declaration = statement as unknown as ImportDeclaration;
175
+ if (!isFurinRouteModule(declaration.source.value) || declaration.importKind === "type") {
176
+ continue;
177
+ }
178
+ for (const specifier of declaration.specifiers as unknown as AstNode[]) {
179
+ const name = localName(specifier);
180
+ if (name && specifier.type === "ImportNamespaceSpecifier") {
181
+ namespaces.add(name);
182
+ }
183
+ }
184
+ }
185
+ walk(program, {
186
+ MemberExpression(node, context) {
187
+ const object = asAstNode(node.object);
188
+ const property = asAstNode(node.property);
189
+ const method = property?.type === "Identifier" ? property.name : property?.value;
190
+ if (
191
+ object?.type === "Identifier" &&
192
+ typeof object.name === "string" &&
193
+ namespaces.has(object.name) &&
194
+ (method === "defineRoute" || method === "defineRootRoute") &&
195
+ !hasShadowingDeclaration(object.name, context.ancestors() as AstNode[])
196
+ ) {
197
+ throw new Error(`[furin] ${filename}: route builders require a named import.`);
198
+ }
199
+ if (
200
+ node.computed &&
201
+ context.parent?.type === "CallExpression" &&
202
+ chainRootIsDefineRoute(node.object, bindings, context.ancestors() as AstNode[])
203
+ ) {
204
+ throw new Error(`[furin] ${filename}: route builders require static builder methods.`);
205
+ }
206
+ },
207
+ VariableDeclarator(node, context) {
208
+ const initializer = asAstNode(node.init);
209
+ if (
210
+ !(
211
+ initializer &&
212
+ chainRootIsDefineRoute(initializer, bindings, context.ancestors() as AstNode[])
213
+ )
214
+ ) {
215
+ return;
216
+ }
217
+ const callee = initializer.type === "CallExpression" ? asAstNode(initializer.callee) : null;
218
+ const method = callee?.type === "MemberExpression" ? asAstNode(callee.property) : null;
219
+ if (method?.type !== "Identifier" || (method.name !== "page" && method.name !== "layout")) {
220
+ throw new Error(
221
+ `[furin] ${filename}: route builders must use one fluent chain ending in .page() or .layout().`
222
+ );
223
+ }
224
+ },
225
+ });
226
+ }
227
+
162
228
  function removeChainedServerCalls(
163
229
  source: MagicString,
164
230
  program: Program,
165
- bindings: Set<string>
231
+ bindings: Set<string>,
232
+ configBindings: Set<string>,
233
+ filename: string
166
234
  ): boolean {
167
235
  let transformed = rewriteClientImports(source, program, bindings);
236
+ const { declarations } = collectModuleBindings(program);
168
237
 
169
238
  walk(program, {
170
239
  CallExpression(call, context) {
@@ -190,6 +259,28 @@ function removeChainedServerCalls(
190
259
  if (!object) {
191
260
  return;
192
261
  }
262
+ if (property.name === "config" && Array.isArray(call.arguments)) {
263
+ const config = asAstNode(call.arguments[0]);
264
+ if (config?.type === "ObjectExpression" && Array.isArray(config.properties)) {
265
+ collectConfigBindings(config, declarations, configBindings);
266
+ const remount = resolveRemountProperty(
267
+ config,
268
+ declarations,
269
+ configBindings,
270
+ new Set(),
271
+ filename
272
+ );
273
+ if (remount) {
274
+ source.update(
275
+ object.end,
276
+ call.end,
277
+ `.config({ ${source.original.slice(remount.start, remount.end)} })`
278
+ );
279
+ transformed = true;
280
+ return;
281
+ }
282
+ }
283
+ }
193
284
  source.remove(object.end, call.end);
194
285
  transformed = true;
195
286
  },
@@ -197,6 +288,128 @@ function removeChainedServerCalls(
197
288
  return transformed;
198
289
  }
199
290
 
291
+ function collectConfigBindings(
292
+ config: AstNode | null,
293
+ declarations: Map<string, AstNode>,
294
+ names: Set<string>
295
+ ): void {
296
+ if (config?.type === "Identifier" && typeof config.name === "string" && !names.has(config.name)) {
297
+ names.add(config.name);
298
+ const declaration = declarations.get(config.name);
299
+ collectConfigBindings(asAstNode(declaration?.init), declarations, names);
300
+ } else if (config?.type === "ObjectExpression" && Array.isArray(config.properties)) {
301
+ for (const property of config.properties) {
302
+ const entry = asAstNode(property);
303
+ if (entry?.type === "SpreadElement") {
304
+ collectConfigBindings(asAstNode(entry.argument), declarations, names);
305
+ }
306
+ }
307
+ }
308
+ }
309
+
310
+ function resolveRemountProperty(
311
+ config: AstNode | null,
312
+ declarations: Map<string, AstNode>,
313
+ configBindings: Set<string>,
314
+ visiting: Set<string>,
315
+ filename: string
316
+ ): AstNode | null {
317
+ if (
318
+ config?.type === "Identifier" &&
319
+ typeof config.name === "string" &&
320
+ !visiting.has(config.name)
321
+ ) {
322
+ visiting.add(config.name);
323
+ configBindings.add(config.name);
324
+ const declaration = declarations.get(config.name);
325
+ const result = resolveRemountProperty(
326
+ asAstNode(declaration?.init),
327
+ declarations,
328
+ configBindings,
329
+ visiting,
330
+ filename
331
+ );
332
+ visiting.delete(config.name);
333
+ return result;
334
+ }
335
+ if (config?.type !== "ObjectExpression" || !Array.isArray(config.properties)) {
336
+ throw new Error(
337
+ `[furin] ${filename}: route config spreads must resolve to local object literals; declare remountDeps after dynamic spreads.`
338
+ );
339
+ }
340
+ for (let index = config.properties.length - 1; index >= 0; index -= 1) {
341
+ const entry = asAstNode(config.properties[index]);
342
+ if (entry?.type === "SpreadElement") {
343
+ const remount = resolveRemountProperty(
344
+ asAstNode(entry.argument),
345
+ declarations,
346
+ configBindings,
347
+ visiting,
348
+ filename
349
+ );
350
+ if (remount) {
351
+ return remount;
352
+ }
353
+ } else if (entry?.type === "Property") {
354
+ const key = asAstNode(entry.key);
355
+ if (
356
+ (key?.type === "Identifier" && entry.computed !== true && key.name === "remountDeps") ||
357
+ (key?.type === "Literal" && key.value === "remountDeps")
358
+ ) {
359
+ return entry;
360
+ }
361
+ }
362
+ }
363
+ return null;
364
+ }
365
+
366
+ function pruneUnusedConfigBindings(
367
+ source: MagicString,
368
+ filename: string,
369
+ names: Set<string>
370
+ ): MagicString {
371
+ let result = source;
372
+ let pruned = true;
373
+ while (pruned) {
374
+ pruned = false;
375
+ const code = result.toString();
376
+ const { program } = parseSource(code, detectLangFromPath(filename));
377
+ const references = new Set<string>();
378
+ walkWithAncestors(program, [], (node, ancestors) => {
379
+ if (
380
+ node.type === "Identifier" &&
381
+ typeof node.name === "string" &&
382
+ isReferenceIdentifier(node, ancestors)
383
+ ) {
384
+ references.add(node.name);
385
+ }
386
+ });
387
+ result = new MagicString(code);
388
+ for (const statement of program.body) {
389
+ if (statement.type !== "VariableDeclaration") {
390
+ continue;
391
+ }
392
+ const retained = statement.declarations.filter(
393
+ (declaration) =>
394
+ declaration.id.type !== "Identifier" ||
395
+ !names.has(declaration.id.name) ||
396
+ references.has(declaration.id.name)
397
+ );
398
+ if (retained.length !== statement.declarations.length) {
399
+ result.update(
400
+ statement.start,
401
+ statement.end,
402
+ retained.length
403
+ ? `${statement.kind} ${retained.map((node) => code.slice(node.start, node.end)).join(", ")};`
404
+ : ""
405
+ );
406
+ pruned = true;
407
+ }
408
+ }
409
+ }
410
+ return result;
411
+ }
412
+
200
413
  function collectBindingNames(pattern: unknown, names: string[]): void {
201
414
  const node = asAstNode(pattern);
202
415
  if (!node) {
@@ -256,16 +469,16 @@ function collectDeclarationBindings(
256
469
 
257
470
  function collectModuleBindings(program: Program): {
258
471
  declarations: Map<string, AstNode>;
259
- imports: Set<string>;
472
+ imports: Map<string, ImportDeclaration>;
260
473
  } {
261
474
  const declarations = new Map<string, AstNode>();
262
- const imports = new Set<string>();
475
+ const imports = new Map<string, ImportDeclaration>();
263
476
  for (const statement of program.body as unknown as AstNode[]) {
264
477
  if (statement.type === "ImportDeclaration" && Array.isArray(statement.specifiers)) {
265
478
  for (const specifier of statement.specifiers as AstNode[]) {
266
479
  const local = localName(specifier);
267
480
  if (local) {
268
- imports.add(local);
481
+ imports.set(local, statement as unknown as ImportDeclaration);
269
482
  }
270
483
  }
271
484
  continue;
@@ -399,7 +612,8 @@ function walkWithAncestors(
399
612
 
400
613
  interface HmrDependencyState {
401
614
  dependencies: Map<number, AstNode>;
402
- hasUnresolvedImport: boolean;
615
+ dynamicImports: Set<string>;
616
+ imports: Set<ImportDeclaration>;
403
617
  importTrackedDependencies: Set<number>;
404
618
  moduleBindings: ReturnType<typeof collectModuleBindings>;
405
619
  }
@@ -410,8 +624,16 @@ function collectDependencyIdentifier(
410
624
  trackImports: boolean,
411
625
  state: HmrDependencyState
412
626
  ): void {
627
+ const parent = ancestors.at(-1);
628
+ const jsxReference =
629
+ child.type === "JSXIdentifier" &&
630
+ ((parent?.type === "JSXOpeningElement" &&
631
+ parent.name === child &&
632
+ typeof child.name === "string" &&
633
+ child.name[0] === child.name[0]?.toUpperCase()) ||
634
+ (parent?.type === "JSXMemberExpression" && parent.object === child));
413
635
  if (
414
- child.type !== "Identifier" ||
636
+ !(child.type === "Identifier" || jsxReference) ||
415
637
  typeof child.name !== "string" ||
416
638
  !isReferenceIdentifier(child, ancestors) ||
417
639
  hasShadowingDeclaration(child.name, ancestors)
@@ -420,8 +642,9 @@ function collectDependencyIdentifier(
420
642
  }
421
643
  const declaration = state.moduleBindings.declarations.get(child.name);
422
644
  if (!declaration) {
423
- if (trackImports && state.moduleBindings.imports.has(child.name)) {
424
- state.hasUnresolvedImport = true;
645
+ const imported = state.moduleBindings.imports.get(child.name);
646
+ if (trackImports && imported) {
647
+ state.imports.add(imported);
425
648
  }
426
649
  return;
427
650
  }
@@ -447,14 +670,26 @@ function collectDependencies(
447
670
  ): void {
448
671
  walkWithAncestors(node, [], (child, ancestors) => {
449
672
  collectDependencyIdentifier(child, ancestors, trackImports, state);
673
+ if (trackImports && child.type === "ImportExpression") {
674
+ const specifier = asAstNode(child.source)?.value;
675
+ if (typeof specifier === "string") {
676
+ state.dynamicImports.add(specifier);
677
+ }
678
+ }
450
679
  });
451
680
  }
452
681
 
453
- function createHmrDataSignature(code: string, program: Program, bindings: Set<string>): string {
682
+ function createHmrDataSignature(
683
+ code: string,
684
+ program: Program,
685
+ bindings: Set<string>,
686
+ filename: string
687
+ ): string {
454
688
  const serverStages: Array<{ source: string; start: number }> = [];
455
689
  const dependencyState: HmrDependencyState = {
456
690
  dependencies: new Map(),
457
- hasUnresolvedImport: false,
691
+ dynamicImports: new Set(),
692
+ imports: new Set(),
458
693
  importTrackedDependencies: new Set(),
459
694
  moduleBindings: collectModuleBindings(program),
460
695
  };
@@ -500,6 +735,10 @@ function createHmrDataSignature(code: string, program: Program, bindings: Set<st
500
735
 
501
736
  const dataSource = [
502
737
  ...serverStages,
738
+ ...[...dependencyState.imports].map((imported) => ({
739
+ source: code.slice(imported.start, imported.end),
740
+ start: imported.start,
741
+ })),
503
742
  ...[...dependencyState.dependencies.values()].map((dependency) => ({
504
743
  source: code.slice(dependency.start, dependency.end),
505
744
  start: dependency.start,
@@ -509,7 +748,27 @@ function createHmrDataSignature(code: string, program: Program, bindings: Set<st
509
748
  .map((entry) => entry.source)
510
749
  .join("\n");
511
750
  const hash = new Bun.CryptoHasher("sha256").update(dataSource).digest("hex");
512
- return dependencyState.hasUnresolvedImport ? `external:${hash}` : hash;
751
+ if (dependencyState.imports.size === 0 && dependencyState.dynamicImports.size === 0) {
752
+ return hash;
753
+ }
754
+ const dependencies = hmrDependencySignature(
755
+ new Set([
756
+ ...[...dependencyState.imports].map((imported) => imported.source.value),
757
+ ...dependencyState.dynamicImports,
758
+ ]),
759
+ filename
760
+ );
761
+ return dependencies === undefined ? `external:${hash}` : `imports:${hash}:${dependencies}`;
762
+ }
763
+
764
+ /** Server stages and their imports share one signature across both HMR graphs. */
765
+ export function getHmrDataSignature(code: string, filename: string): string {
766
+ const { diagnostics, program } = parseSource(code, detectLangFromPath(filename));
767
+ const error = diagnostics.find((diagnostic) => diagnostic.severity === "error");
768
+ if (error) {
769
+ throw new Error(`Failed to parse ${filename}: ${error.message}`);
770
+ }
771
+ return createHmrDataSignature(code, program, collectDefineRouteBindings(program), filename);
513
772
  }
514
773
 
515
774
  function calledHookName(call: AstNode): string | null {
@@ -837,9 +1096,20 @@ export function transformForClient(code: string, filename: string): TransformRes
837
1096
 
838
1097
  let source = new MagicString(clientSource);
839
1098
  const routeBindings = collectDefineRouteBindings(program);
840
- const removedRouteCode = removeChainedServerCalls(source, program, routeBindings);
1099
+ assertCompleteRouteChains(program, routeBindings, filename);
1100
+ const configBindings = new Set<string>();
1101
+ const removedRouteCode = removeChainedServerCalls(
1102
+ source,
1103
+ program,
1104
+ routeBindings,
1105
+ configBindings,
1106
+ filename
1107
+ );
841
1108
  const removedServerCode = isomorphicResult.transformed || removedRouteCode;
842
1109
  if (removedServerCode) {
1110
+ if (configBindings.size > 0) {
1111
+ source = pruneUnusedConfigBindings(source, filename, configBindings);
1112
+ }
843
1113
  source = deadCodeElimination(source, code, lang);
844
1114
  }
845
1115
  const transformedCode = source.toString();
@@ -867,7 +1137,8 @@ export function transformForClient(code: string, filename: string): TransformRes
867
1137
  const hmrDataSignature = createHmrDataSignature(
868
1138
  code,
869
1139
  originalParse.program,
870
- collectDefineRouteBindings(originalParse.program)
1140
+ collectDefineRouteBindings(originalParse.program),
1141
+ filename
871
1142
  );
872
1143
  const signatureValue = Array.isArray(hookSignature)
873
1144
  ? JSON.stringify(hookSignature)
@@ -875,6 +1146,11 @@ export function transformForClient(code: string, filename: string): TransformRes
875
1146
  source.append(`
876
1147
  if (import.meta.hot && route?.component) {
877
1148
  const previousDataSignature = ${JSON.stringify(hmrDataSignature)};
1149
+ const previousSourceSignature = ${JSON.stringify(Bun.hash(code).toString(16))};
1150
+ Object.defineProperty(route, Symbol.for(${JSON.stringify(HMR_SOURCE_SIGNATURE)}), {
1151
+ configurable: true,
1152
+ value: previousSourceSignature,
1153
+ });
878
1154
  Object.defineProperty(route, Symbol.for(${JSON.stringify(HMR_DATA_SIGNATURE)}), {
879
1155
  configurable: true,
880
1156
  value: previousDataSignature,
@@ -890,10 +1166,14 @@ if (import.meta.hot && route?.component) {
890
1166
  updatedRoute,
891
1167
  Symbol.for(${JSON.stringify(HMR_DATA_SIGNATURE)})
892
1168
  );
1169
+ // An unchanged source can be re-evaluated by Bun after an import edit
1170
+ // without rerunning this transform. Its embedded dependency hash is stale.
893
1171
  const dataChanged =
894
1172
  previousDataSignature.startsWith("external:") ||
895
1173
  typeof updatedDataSignature !== "string" ||
896
1174
  updatedDataSignature.startsWith("external:") ||
1175
+ (updatedDataSignature.startsWith("imports:") &&
1176
+ Reflect.get(updatedRoute, Symbol.for(${JSON.stringify(HMR_SOURCE_SIGNATURE)})) === previousSourceSignature) ||
897
1177
  updatedDataSignature !== previousDataSignature;
898
1178
  window.__FURIN_HMR_UPDATE__?.(${JSON.stringify(filename)}, updatedRoute.component, dataChanged);
899
1179
  }
@@ -10,9 +10,12 @@ import { parseSource } from "../shared/parser.ts";
10
10
  import type { AstNode } from "../shared/utils/ast-walk.ts";
11
11
  import { hasShadowingDeclaration } from "./binding-scope.ts";
12
12
  import { deadCodeElimination } from "./dead-code-elimination.ts";
13
+ import { transformClientModules } from "./transform-client-module.ts";
13
14
 
14
15
  const FURIN_MODULES = new Set(["@teyik0/furin", "furin"]);
15
- const SCRIPT_FILE_FILTER = /^(?!.*(?:node_modules|[\\/]\.furin[\\/]build[\\/])).*\.(tsx?|jsx?)$/;
16
+ // Accepts a query suffix: dev-mode route discovery imports `page.tsx?furin-server&t=…`.
17
+ const SCRIPT_FILE_FILTER =
18
+ /^(?!.*(?:node_modules|[\\/]\.furin[\\/]build[\\/])).*\.(tsx?|jsx?)(?:\?.*)?$/;
16
19
 
17
20
  export type IsomorphicEnvironment = "client" | "server";
18
21
 
@@ -402,14 +405,16 @@ function assertStaticEnvironmentMethods(
402
405
  }
403
406
 
404
407
  export function transformIsomorphicFunctions(
405
- source: string,
408
+ input: string,
406
409
  filename: string,
407
410
  environment: IsomorphicEnvironment
408
411
  ): IsomorphicTransformResult {
409
412
  const lang = detectLangFromPath(filename);
410
413
  if (lang === "dts") {
411
- return { code: source, map: null, transformed: false };
414
+ return { code: input, map: null, transformed: false };
412
415
  }
416
+ const source = transformClientModules(input, filename, environment);
417
+ const clientModulesTransformed = source !== input;
413
418
 
414
419
  const { program, diagnostics } = parseSource(source, lang);
415
420
  const firstError = diagnostics.find((diagnostic) => diagnostic.severity === "error");
@@ -423,7 +428,7 @@ export function transformIsomorphicFunctions(
423
428
  assertNoSplitChains(source, filename, program, builders);
424
429
  const candidates = collectCandidates(source, filename, program, bindings);
425
430
  if (candidates.length === 0) {
426
- return { code: source, map: null, transformed: false };
431
+ return { code: source, map: null, transformed: clientModulesTransformed };
427
432
  }
428
433
 
429
434
  const transformed = new MagicString(source);
@@ -450,7 +455,8 @@ export function isomorphicTransformPlugin(environment: IsomorphicEnvironment): B
450
455
  return {
451
456
  name: `furin-isomorphic-${environment}`,
452
457
  setup(build) {
453
- build.onLoad({ filter: SCRIPT_FILE_FILTER }, async ({ path }) => {
458
+ build.onLoad({ filter: SCRIPT_FILE_FILTER }, async (args) => {
459
+ const path = args.path.split("?")[0] as string;
454
460
  const source = await Bun.file(path).text();
455
461
  const loader = detectLoaderFromPath(path);
456
462
  const result = transformIsomorphicFunctions(source, path, environment);
package/src/routes.ts CHANGED
@@ -4,3 +4,11 @@
4
4
  */
5
5
  // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmented by generated route types
6
6
  export interface RouteMap {}
7
+
8
+ /** Literal route patterns for editor completion in APIs that accept path params. */
9
+ // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmented by generated route types
10
+ export interface RoutePatternMap {}
11
+
12
+ /** Application contract for sync IDs and their resource scopes. */
13
+ // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmented by applications
14
+ export interface SyncQueryMap {}
@@ -82,27 +82,113 @@ export function restoreRscSource(kind: RscSourceKind, bytes: Uint8Array): unknow
82
82
  return kind === "renderable" ? createRenderableSource(state) : { [RSC_SOURCE]: state };
83
83
  }
84
84
 
85
- function resolveSlots(node: ReactNode, slots: object): ReactNode {
86
- return Children.map(node, (child) => {
87
- if (!isValidElement(child)) {
88
- return child;
85
+ function isLazyNode(value: object): boolean {
86
+ return "$$typeof" in value && value.$$typeof === Symbol.for("react.lazy");
87
+ }
88
+
89
+ function containsSlot(value: unknown, visited: WeakSet<object>): value is object {
90
+ if (value === null || typeof value !== "object" || visited.has(value)) {
91
+ return false;
92
+ }
93
+ visited.add(value);
94
+ if (isLazyNode(value)) {
95
+ return true;
96
+ }
97
+ if (isValidElement(value)) {
98
+ return value.type === SLOT_MARKER || containsSlot(value.props, visited);
99
+ }
100
+ if (Array.isArray(value)) {
101
+ return value.some((item) => containsSlot(item, visited));
102
+ }
103
+ return (
104
+ Object.getPrototypeOf(value) === Object.prototype &&
105
+ Object.values(value).some((item) => containsSlot(item, visited))
106
+ );
107
+ }
108
+
109
+ function resolveSlotArgument(
110
+ value: unknown,
111
+ slots: object,
112
+ visited: WeakMap<object, unknown>
113
+ ): unknown {
114
+ if (!containsSlot(value, new WeakSet())) {
115
+ return value;
116
+ }
117
+ if (visited.has(value)) {
118
+ return visited.get(value);
119
+ }
120
+ if (isLazyNode(value)) {
121
+ const result = createElement(LazySlots, { node: value as ReactNode, slots });
122
+ visited.set(value, result);
123
+ return result;
124
+ }
125
+ if (isValidElement(value)) {
126
+ const resolved = resolveSlotElement(value, slots);
127
+ const result = isValidElement(resolved) ? Children.map(value, () => resolved)?.[0] : resolved;
128
+ visited.set(value, result);
129
+ return result;
130
+ }
131
+ if (Array.isArray(value)) {
132
+ const result: unknown[] = [];
133
+ visited.set(value, result);
134
+ for (const item of value) {
135
+ result.push(resolveSlotArgument(item, slots, visited));
89
136
  }
90
- if (child.type === SLOT_MARKER) {
91
- const marker = child.props as { args?: unknown[]; name?: string };
92
- if (typeof marker.name !== "string") {
93
- return null;
137
+ const keys = new Set(result.filter(isValidElement).map((element) => element.key));
138
+ for (const [index, resolved] of result.entries()) {
139
+ if (isValidElement(resolved) && resolved.key === null) {
140
+ let key = String(index);
141
+ while (keys.has(key)) {
142
+ key = `.${key}`;
143
+ }
144
+ keys.add(key);
145
+ result[index] = cloneElement(resolved, { key });
94
146
  }
95
- const implementation = Reflect.get(slots, marker.name) as unknown;
96
- if (typeof implementation === "function") {
97
- return (implementation as (...args: unknown[]) => ReactNode)(...(marker.args ?? []));
98
- }
99
- return implementation as ReactNode;
100
147
  }
101
- const props = child.props as { children?: ReactNode };
102
- return props.children === undefined
103
- ? child
104
- : cloneElement(child, undefined, resolveSlots(props.children, slots));
105
- });
148
+ return result;
149
+ }
150
+ const result = {};
151
+ visited.set(value, result);
152
+ for (const [key, item] of Object.entries(value)) {
153
+ Object.defineProperty(result, key, {
154
+ configurable: true,
155
+ enumerable: true,
156
+ value: resolveSlotArgument(item, slots, visited),
157
+ writable: true,
158
+ });
159
+ }
160
+ return result;
161
+ }
162
+
163
+ function resolveSlotElement(child: ReactElement, slots: object): ReactNode {
164
+ if (child.type === SLOT_MARKER) {
165
+ const marker = child.props as { args?: unknown[]; name?: string };
166
+ if (typeof marker.name !== "string") {
167
+ return null;
168
+ }
169
+ const implementation = Reflect.get(slots, marker.name) as unknown;
170
+ if (typeof implementation === "function") {
171
+ const visited = new WeakMap<object, unknown>();
172
+ const args = (marker.args ?? []).map((argument) =>
173
+ resolveSlotArgument(argument, slots, visited)
174
+ );
175
+ return (implementation as (...args: unknown[]) => ReactNode)(...args);
176
+ }
177
+ return implementation as ReactNode;
178
+ }
179
+ const props = resolveSlotArgument(child.props, slots, new WeakMap());
180
+ return props === child.props ? child : cloneElement(child, props as object);
181
+ }
182
+
183
+ function resolveSlots(node: ReactNode, slots: object): ReactNode {
184
+ return Children.map(node, (child) =>
185
+ isValidElement(child) ? resolveSlotElement(child, slots) : child
186
+ );
187
+ }
188
+
189
+ function LazySlots({ node, slots }: { node: ReactNode; slots: object }): ReactNode {
190
+ // React unwraps Flight's lazy nodes here, inside their nearest Suspense boundary.
191
+ return resolveSlots(node, slots);
106
192
  }
107
193
 
108
194
  export function CompositeComponent<TProps extends object>(
@@ -66,6 +66,10 @@ export class AutoInvalidateRegistry {
66
66
  return [...paths];
67
67
  }
68
68
 
69
+ tagsForPath(path: string): string[] {
70
+ return [...(this.pathToTags.get(path) ?? [])];
71
+ }
72
+
69
73
  unregisterPath(urlPath: string, owner?: string): void {
70
74
  if (owner === undefined) {
71
75
  this.pathOwners.delete(urlPath);
@@ -132,6 +132,7 @@ async function invalidateTagsForInstance(
132
132
  let deleted = false;
133
133
  const purgedPaths = new Set<string>();
134
134
  const logicalPurgedPaths = new Set<string>();
135
+ const sharedInvalidations: Promise<{ invalidated: boolean; paths: readonly string[] }>[] = [];
135
136
  const pageCache = getPageCacheAdapter(instance);
136
137
  const sharedResult =
137
138
  pageCache === undefined
@@ -148,12 +149,26 @@ async function invalidateTagsForInstance(
148
149
  ...getAutoInvalidateRegistry(instance).pathsForTags(tagList),
149
150
  ...(sharedResult?.paths ?? []),
150
151
  ]);
152
+ const tags = new Set(tagList);
151
153
  // Registry paths are LOGICAL (unprefixed); the CDN caches the PHYSICAL
152
154
  // request URL, so prefix each with the instance's mount prefix before
153
155
  // queueing it for purge — otherwise a mounted app's `/admin/x` stays stale.
154
156
  for (const path of taggedPaths) {
155
157
  const logicalPath = pathWithoutSearch(path);
158
+ const registered = getAutoInvalidateRegistry(instance)
159
+ .tagsForPath(path)
160
+ .some((tag) => tags.has(tag));
156
161
  const result = revalidatePathForInstance(instance, logicalPath, "page", false);
162
+ if (pageCache !== undefined && registered) {
163
+ sharedInvalidations.push(
164
+ pageCache.invalidate({
165
+ kind: "path",
166
+ scope: instance.prefix,
167
+ path: logicalPath,
168
+ type: "page",
169
+ })
170
+ );
171
+ }
157
172
  deleted = result.deleted || deleted;
158
173
  purgedPaths.add(physicalPath(instance.prefix, logicalPath));
159
174
  logicalPurgedPaths.add(logicalPath);
@@ -162,6 +177,8 @@ async function invalidateTagsForInstance(
162
177
  logicalPurgedPaths.add(purged);
163
178
  }
164
179
  }
180
+ const pathResults = await Promise.all(sharedInvalidations);
181
+ deleted = pathResults.some((result) => result.invalidated) || deleted;
165
182
  if (IS_DEV) {
166
183
  withInstance(instance, () => {
167
184
  const request = currentInstrumentationRequest();