@teyik0/furin 0.2.0-alpha.1 → 0.2.0-alpha.3

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 (84) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +33 -33
  3. package/dist/adapter/static.d.ts +1 -1
  4. package/dist/build/compile-entry.ts +109 -109
  5. package/dist/build/entry-template.ts +156 -156
  6. package/dist/build/index.js +1724 -687
  7. package/dist/build/route-types.d.ts +3 -1
  8. package/dist/build/server-routes-entry.ts +36 -36
  9. package/dist/build/shared.d.ts +1 -0
  10. package/dist/build/ssg-cache.d.ts +1 -1
  11. package/dist/cli/index.js +1673 -658
  12. package/dist/client/link.js +883 -89
  13. package/dist/client/router/index.d.ts +4 -0
  14. package/dist/client/router/link-utils.d.ts +3 -1
  15. package/dist/client/router/navigation.d.ts +10 -0
  16. package/dist/client/router/provider.d.ts +1 -1
  17. package/dist/client/router/search/index.d.ts +18 -0
  18. package/dist/client/router/search-store.d.ts +21 -0
  19. package/dist/client/router/types.d.ts +14 -1
  20. package/dist/client/sync.d.ts +25 -0
  21. package/dist/client.d.ts +1 -0
  22. package/dist/client.js +44 -0
  23. package/dist/furin.d.ts +9 -1
  24. package/dist/furin.js +1578 -258
  25. package/dist/server/auto-invalidate/runtime.d.ts +1 -1
  26. package/dist/server/dev-page-plugin.d.ts +3 -0
  27. package/dist/server/render/assemble.d.ts +2 -0
  28. package/dist/server/render/isr.d.ts +2 -1
  29. package/dist/server/render/ssg.d.ts +3 -2
  30. package/dist/server/render/ssr.d.ts +5 -4
  31. package/dist/server/router/hmr.d.ts +4 -3
  32. package/dist/server/router/index.d.ts +1 -1
  33. package/dist/server/router/index.js +1 -2
  34. package/dist/server/router/index.ts +1 -2
  35. package/dist/server/router/plugin.d.ts +2 -1
  36. package/dist/server/router/schemas.d.ts +25 -17
  37. package/dist/server/sync/config.d.ts +6 -0
  38. package/dist/server/sync/index.d.ts +4 -0
  39. package/dist/server/sync/plugin.d.ts +369 -0
  40. package/dist/server/sync/stream.d.ts +47 -0
  41. package/dist/shared/search-params.d.ts +17 -0
  42. package/package.json +10 -5
  43. package/src/adapter/README.md +13 -13
  44. package/src/adapter/static.ts +23 -6
  45. package/src/build/client.ts +152 -149
  46. package/src/build/compile-entry.ts +109 -109
  47. package/src/build/entry-template.ts +156 -156
  48. package/src/build/hydrate.ts +340 -331
  49. package/src/build/index.ts +152 -152
  50. package/src/build/route-types.ts +145 -115
  51. package/src/build/scan-server.ts +95 -95
  52. package/src/build/server-routes-entry.ts +36 -36
  53. package/src/build/shared.ts +80 -78
  54. package/src/build/ssg-cache.ts +32 -31
  55. package/src/build/types.ts +89 -89
  56. package/src/client/link.tsx +13 -4
  57. package/src/client/router/context.ts +2 -0
  58. package/src/client/router/index.ts +9 -0
  59. package/src/client/router/link-utils.ts +184 -180
  60. package/src/client/router/navigation.ts +61 -0
  61. package/src/client/router/provider.tsx +804 -723
  62. package/src/client/router/search/index.ts +99 -0
  63. package/src/client/router/search-store.ts +86 -0
  64. package/src/client/router/types.ts +276 -263
  65. package/src/client/sync.ts +98 -0
  66. package/src/client.ts +369 -355
  67. package/src/furin.ts +465 -437
  68. package/src/server/auto-invalidate/runtime.ts +134 -133
  69. package/src/server/dev-page-plugin.ts +454 -449
  70. package/src/server/render/assemble.ts +160 -133
  71. package/src/server/render/isr.ts +323 -295
  72. package/src/server/render/not-found.ts +2 -0
  73. package/src/server/render/ssg.ts +15 -4
  74. package/src/server/render/ssr.ts +585 -545
  75. package/src/server/router/hmr.ts +14 -10
  76. package/src/server/router/index.ts +1 -2
  77. package/src/server/router/patterns.ts +5 -0
  78. package/src/server/router/plugin.ts +384 -401
  79. package/src/server/router/schemas.ts +172 -57
  80. package/src/server/sync/config.ts +29 -0
  81. package/src/server/sync/index.ts +14 -0
  82. package/src/server/sync/plugin.ts +108 -0
  83. package/src/server/sync/stream.ts +144 -0
  84. package/src/shared/search-params.ts +182 -0
@@ -1,331 +1,340 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { generateIndexHtml } from "../server/render/shell.ts";
4
- import { buildRouteRegex } from "../server/router/patterns.ts";
5
- import type { ResolvedRoute } from "../server/router/index.ts";
6
- import { writeRouteTypes } from "./route-types";
7
- import type { BuildClientOptions } from "./types";
8
-
9
- /**
10
- * Generates the client hydration entry.
11
- *
12
- * Renders into <div id="root"> (the SSR outlet element) and retains the React
13
- * root across hot reloads via import.meta.hot.data.root so React Fast Refresh
14
- * applies in-place instead of remounting.
15
- *
16
- * @param routes - Resolved routes to include in the hydration manifest.
17
- * @param rootLayout - Absolute path to the root layout module.
18
- * @param basePath - Optional sub-path prefix for static deployments (e.g. "/furin").
19
- * When set, the generated code strips the prefix from `window.location.pathname`
20
- * before matching routes, and passes `basePath` to `RouterProvider` so SPA
21
- * navigation uses the correct physical URLs.
22
- */
23
- export function generateHydrateEntry(
24
- routes: ResolvedRoute[],
25
- rootLayout: string,
26
- basePath: string,
27
- clientLogging: boolean
28
- ): string {
29
- const getBoundaryIdent = (idents: Map<string, string>, filePath: string | undefined) => {
30
- if (!filePath) {
31
- return;
32
- }
33
- const existing = idents.get(filePath);
34
- if (existing) {
35
- return existing;
36
- }
37
- const ident = `__furin_bnd_${idents.size}`;
38
- idents.set(filePath, ident);
39
- return ident;
40
- };
41
-
42
- const routeEntries: string[] = [];
43
-
44
- for (const route of routes) {
45
- const resolvedPage = route.path.replace(/\\/g, "/");
46
- const regexPattern = buildRouteRegex(route.pattern).regex.source;
47
- const boundaryIdents = new Map<string, string>();
48
-
49
- // Emit one boundary literal per segment that actually carries a convention
50
- // file — segments that only declare one of the two are emitted with the
51
- // missing field omitted entirely (keeps the generated JS tidy).
52
- const boundaryLiterals: string[] = [];
53
- for (const seg of route.segmentBoundaries ?? []) {
54
- const errorIdent = getBoundaryIdent(boundaryIdents, seg.errorPath);
55
- const notFoundIdent = getBoundaryIdent(boundaryIdents, seg.notFoundPath);
56
- if (!(errorIdent || notFoundIdent)) {
57
- continue;
58
- }
59
- const parts = [`depth: ${seg.depth}`];
60
- if (errorIdent) {
61
- parts.push(`error: ${errorIdent}.default`);
62
- }
63
- if (notFoundIdent) {
64
- parts.push(`notFound: ${notFoundIdent}.default`);
65
- }
66
- boundaryLiterals.push(`{ ${parts.join(", ")} }`);
67
- }
68
-
69
- const lazyImports = [
70
- `import("${resolvedPage}")`,
71
- ...[...boundaryIdents.keys()].map((filePath) => `import("${filePath.replace(/\\/g, "/")}")`),
72
- ];
73
- const loadBody =
74
- boundaryLiterals.length > 0
75
- ? `Promise.all([${lazyImports.join(", ")}]).then(([__furin_page, ${[
76
- ...boundaryIdents.values(),
77
- ].join(", ")}]) => ({ default: __furin_page.default, segmentBoundaries: [${boundaryLiterals.join(", ")}] }))`
78
- : `import("${resolvedPage}")`;
79
-
80
- routeEntries.push(
81
- ` { pattern: "${route.pattern}", regex: new RegExp(${JSON.stringify(regexPattern)}), load: () => ${loadBody} }`
82
- );
83
- }
84
-
85
- // basePath stripping: when deployed to a sub-path (e.g. /furin), strip the
86
- // prefix before route matching so patterns like /docs/routing still work.
87
- const basePathLiteral = JSON.stringify(basePath);
88
- // Strip basePath only when it matches on a path boundary (prevents "/furin" from
89
- // matching "/furinity/foo"). The boundary holds when the pathname ends exactly
90
- // at the prefix length OR the next character is "/".
91
- // Trailing slashes are also stripped so "/docs/routing/" matches the route
92
- // pattern "/docs/routing" — GitHub Pages and many static hosts append them.
93
- const pathnameExpr = basePath
94
- ? `(() => { const p = window.location.pathname; const b = ${basePathLiteral}; const stripped = (p.startsWith(b) && (p.length === b.length || p[b.length] === "/")) ? p.slice(b.length) || "/" : p; return stripped === "/" ? "/" : stripped.replace(/\\/+$/, ""); })()`
95
- : `window.location.pathname.replace(/\\/+$/, "") || "/"`;
96
-
97
- // Log drain endpoint: prepend basePath so the request goes to the correct origin path.
98
- const logEndpoint = basePath
99
- ? `${JSON.stringify(basePath)} + "/_furin/ingest"`
100
- : `"/_furin/ingest"`;
101
-
102
- // Client-side HTTP draining is opt-in (config `clientLogging`). When disabled
103
- // we emit neither the hydrate-entry evlog imports nor initLogger, and define a
104
- // no-op `log` shim so the hydration body's log.* calls stay valid.
105
- const loggingImports = clientLogging
106
- ? 'import { initLogger, log } from "evlog";\nimport { createHttpLogDrain } from "evlog/http";\n'
107
- : "";
108
- const loggerSetup = clientLogging
109
- ? `initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });`
110
- : "const log = { error() {}, info() {} };";
111
-
112
- // RouterProvider receives basePath so navigate() / Link push physical paths.
113
- const routerProviderDefaults = `\n autoRefresh: true,\n basePath: ${basePathLiteral},\n defaultPreload: "intent",\n defaultPreloadDelay: 50,\n defaultPreloadStaleTime: 30000,\n prefetchCacheSize: 50,`;
114
-
115
- return `import { hydrateRoot, createRoot } from "react-dom/client";
116
- import { createElement } from "react";
117
- ${loggingImports}import { RouterProvider } from "@teyik0/furin/link";
118
- import { fromCrossJSON } from "@teyik0/furin/link";
119
- import type { SerovalNode } from "seroval";
120
- import { route as root } from "${rootLayout.replace(/\\/g, "/")}";
121
-
122
- ${loggerSetup}
123
-
124
- const routes = [
125
- ${routeEntries.join(",\n")}
126
- ];
127
-
128
- const pathname = ${pathnameExpr};
129
- const _match = routes.find((r) => r.regex.test(pathname));
130
-
131
- // Parse the server-embedded loader payload up front. It carries:
132
- // - normal loader props under arbitrary keys,
133
- // - __furinError.digest when SSR caught an error,
134
- // - __furinStatus: 404 when the server rendered the catch-all not-found
135
- // (direct load to an unknown URL, emitted by renderRootNotFound) OR when
136
- // a matched loader threw notFound(). The latter still has a _match; the
137
- // former does not — so the two cases fork on _match below.
138
- const dataEl = document.getElementById("__FURIN_DATA__");
139
- const loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
140
-
141
- // ── Deferred data hydration ─────────────────────────────────────────────────
142
- // window.__FURIN_DEFERRED__ is injected by the server when a loader returns
143
- // defer(). It carries:
144
- // - _chunks: raw CrossJSON chunks keyed by field name (from late <script> tags)
145
- // We deserialise each chunk with fromCrossJSON and create a Promise so <Await>
146
- // components receive a proper resolved Promise instead of the raw CrossJSON node.
147
- // Sync loader fields live exclusively in __FURIN_DATA__ (read above).
148
- interface FurinDeferredRegistry {
149
- _chunks: Record<string, { a: 0 | 1; v: SerovalNode }>;
150
- _deferredKeys: string[];
151
- _resolvers: Record<string, {
152
- promise: Promise<unknown>;
153
- reject: (reason: unknown) => void;
154
- resolve: (value: unknown) => void;
155
- }>;
156
- getPromise: (key: string) => Promise<unknown>;
157
- reject: (key: string, chunk: SerovalNode) => void;
158
- resolve: (key: string, chunk: SerovalNode) => void;
159
- }
160
- const __deferred = (window as unknown as { __FURIN_DEFERRED__?: FurinDeferredRegistry })
161
- .__FURIN_DEFERRED__;
162
- const deferredData: Record<string, Promise<unknown>> = {};
163
- if (__deferred && __deferred._chunks) {
164
- // Patch resolve/reject so any chunks that arrive AFTER this entry has run
165
- // settle immediately. The previous version stored late chunks in _chunks
166
- // when no resolver was registered yet, but the drain loop below only runs
167
- // ONCE at hydrate time — so any chunk landing after the drain would stay
168
- // orphaned and the corresponding Await would hang forever. Eagerly creating
169
- // the resolver via getPromise() fixes the race.
170
- __deferred.resolve = (key: string, chunk: SerovalNode) => {
171
- __deferred.getPromise(key);
172
- __deferred._resolvers[key].resolve(fromCrossJSON(chunk, {}));
173
- };
174
- __deferred.reject = (key: string, chunk: SerovalNode) => {
175
- __deferred.getPromise(key);
176
- __deferred._resolvers[key].reject(fromCrossJSON(chunk, {}));
177
- };
178
- for (const key of Object.keys(__deferred._chunks)) {
179
- const entry = __deferred._chunks[key] as { a: 0 | 1; v: SerovalNode };
180
- const p = __deferred.getPromise(key) as Promise<unknown>;
181
- const resolver = __deferred._resolvers[key];
182
- const value = fromCrossJSON(entry.v, {});
183
- if (entry.a === 0) {
184
- resolver.resolve(value);
185
- } else {
186
- resolver.reject(value);
187
- }
188
- deferredData[key] = p;
189
- }
190
- for (const key of __deferred._deferredKeys ?? []) {
191
- if (!(key in deferredData)) {
192
- deferredData[key] = __deferred.getPromise(key) as Promise<unknown>;
193
- }
194
- }
195
- // Keys that have a resolver (getPromise was called by <Await>) but no
196
- // chunk yet (the late <script> hasn't arrived) still need a Promise entry
197
- // so the hydration data record is complete.
198
- for (const key of Object.keys(__deferred._resolvers ?? {})) {
199
- if (!(key in deferredData)) {
200
- deferredData[key] = __deferred.getPromise(key) as Promise<unknown>;
201
- }
202
- }
203
- }
204
- const rootEl = document.getElementById("root") as HTMLElement;
205
-
206
- // Eagerly load only the current page module for initial hydration.
207
- // All other pages are loaded on demand when the user navigates to them.
208
- // Wrapped in an async IIFE to avoid top-level await, which causes Bun's HTML
209
- // bundler to misidentify which chunk to reference as the entry in index.html.
210
- (async () => {
211
- let app;
212
- if (_match) {
213
- const _mod = await _match.load();
214
- const match = {
215
- ..._match,
216
- component: _mod.default.component,
217
- pageRoute: _mod.default._route,
218
- segmentBoundaries: _mod.segmentBoundaries ?? _match.segmentBoundaries,
219
- };
220
-
221
- const isNotFound = loaderData.__furinStatus === 404;
222
-
223
- app = createElement(RouterProvider, {
224
- routes,
225
- root,
226
- initialMatch: match,
227
- initialData: { ...loaderData, ...deferredData },
228
- initialDigest: loaderData.__furinError?.digest,
229
- initialNotFound: isNotFound ? (loaderData.__furinNotFound ?? loaderData) : undefined,${routerProviderDefaults}
230
- } as any);
231
- } else if (loaderData.__furinStatus === 404) {
232
- // Direct load to an unknown URL. The server sent the root not-found UI
233
- // already rendered into the DOM. Mount RouterProvider with a null match
234
- // so the provider boots into its not-found branch, hydrating that exact
235
- // tree INSIDE a live RouterContext. Without this, Links in the 404 UI
236
- // (e.g. the default screen's "Go Home" button) hit the useRouter()
237
- // fallback that does a full window.location assignment — a jarring reload.
238
- // Strip the server-only signal keys before handing data to components.
239
- const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = loaderData;
240
- app = createElement(RouterProvider, {
241
- routes,
242
- root,
243
- initialMatch: null,
244
- initialData: cleanData,
245
- initialDigest: loaderData.__furinError?.digest,
246
- initialNotFound: loaderData.__furinNotFound ?? {},${routerProviderDefaults}
247
- } as any);
248
- } else {
249
- // No match and no 404 signal — either the client bundle is out of sync
250
- // with the server (stale deploy) or the server returned something we
251
- // don't know how to hydrate. Bail loudly; the page stays static.
252
- log.error({ action: "hydrate_no_match", pathname });
253
- return;
254
- }
255
-
256
- if (import.meta.hot) {
257
- // Dev mode — preserve root across HMR using a window global.
258
- // window is the only object that survives Bun's module re-evaluation.
259
- // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
260
- const existingRoot = (window as any).__FURIN_ROOT__;
261
- if (existingRoot) {
262
- // Already mounted — reconciliation, NOT hydration. React Fast Refresh
263
- // patched the component in-place, now re-render with the new module.
264
- existingRoot.render(app);
265
- // The initialData embedded in the DOM is stale (from the original SSR).
266
- // Trigger a loader-data refresh so the component renders with fresh
267
- // server state, avoiding hydration mismatches after a _route.tsx edit.
268
- const hmrRefresh = (window as any).__FURIN_HMR_REFRESH__;
269
- if (hmrRefresh) {
270
- requestAnimationFrame(() => hmrRefresh());
271
- }
272
- } else if (rootEl.innerHTML.trim()) {
273
- // First load with SSR content — hydrateRoot renders on construction
274
- const root = hydrateRoot(rootEl, app);
275
- // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
276
- (window as any).__FURIN_ROOT__ = root;
277
- } else {
278
- // First load without SSR content — createRoot requires explicit .render()
279
- const root = createRoot(rootEl);
280
- root.render(app);
281
- // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
282
- (window as any).__FURIN_ROOT__ = root;
283
- }
284
- } else if (rootEl.innerHTML.trim()) {
285
- hydrateRoot(rootEl, app);
286
- } else {
287
- createRoot(rootEl).render(app);
288
- }
289
-
290
- log.info({ action: "hydrate_complete", pathname });
291
- })().catch((err: unknown) => {
292
- log.error({ action: "hydrate_failed", pathname, error: String(err) });
293
- });
294
- `;
295
- }
296
-
297
- /**
298
- * Writes _hydrate.tsx + index.html to outDir for dev (Bun HMR) mode.
299
- *
300
- * Only rewrites a file when its content has actually changed so Bun's --hot
301
- * watcher does not trigger a spurious reload on every server restart.
302
- */
303
- export function writeDevFiles(
304
- routes: ResolvedRoute[],
305
- { outDir, rootLayout, basePath, clientLogging }: BuildClientOptions,
306
- projectRoot: string
307
- ): void {
308
- if (!existsSync(outDir)) {
309
- mkdirSync(outDir, { recursive: true });
310
- }
311
-
312
- const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
313
- const hydratePath = join(outDir, "_hydrate.tsx");
314
- const existingHydrate = existsSync(hydratePath) ? readFileSync(hydratePath, "utf8") : "";
315
- if (hydrateCode !== existingHydrate) {
316
- writeFileSync(hydratePath, hydrateCode);
317
- }
318
-
319
- const indexHtml = generateIndexHtml();
320
- const indexPath = join(outDir, "index.html");
321
- const existingIndex = existsSync(indexPath) ? readFileSync(indexPath, "utf8") : "";
322
- if (indexHtml !== existingIndex) {
323
- writeFileSync(indexPath, indexHtml);
324
- }
325
-
326
- writeRouteTypes(routes, projectRoot);
327
-
328
- console.log(
329
- "[furin] Dev files written (.furin/_hydrate.tsx + .furin/index.html + furin-env.d.ts)"
330
- );
331
- }
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { generateIndexHtml } from "../server/render/shell.ts";
4
+ import { mergeRouteSchemas } from "../server/router/index.ts";
5
+ import { buildRouteRegex } from "../server/router/patterns.ts";
6
+ import type { ResolvedRoute } from "../server/router/index.ts";
7
+ import { collectSearchDefaults } from "../shared/search-params.ts";
8
+ import { writeRouteTypes } from "./route-types";
9
+ import type { BuildClientOptions } from "./types";
10
+
11
+ /**
12
+ * Generates the client hydration entry.
13
+ *
14
+ * Renders into <div id="root"> (the SSR outlet element) and retains the React
15
+ * root across hot reloads via import.meta.hot.data.root so React Fast Refresh
16
+ * applies in-place instead of remounting.
17
+ *
18
+ * @param routes - Resolved routes to include in the hydration manifest.
19
+ * @param rootLayout - Absolute path to the root layout module.
20
+ * @param basePath - Optional sub-path prefix for static deployments (e.g. "/furin").
21
+ * When set, the generated code strips the prefix from `window.location.pathname`
22
+ * before matching routes, and passes `basePath` to `RouterProvider` so SPA
23
+ * navigation uses the correct physical URLs.
24
+ */
25
+ export function generateHydrateEntry(
26
+ routes: ResolvedRoute[],
27
+ rootLayout: string,
28
+ basePath: string,
29
+ clientLogging: boolean
30
+ ): string {
31
+ const getBoundaryIdent = (idents: Map<string, string>, filePath: string | undefined) => {
32
+ if (!filePath) {
33
+ return;
34
+ }
35
+ const existing = idents.get(filePath);
36
+ if (existing) {
37
+ return existing;
38
+ }
39
+ const ident = `__furin_bnd_${idents.size}`;
40
+ idents.set(filePath, ident);
41
+ return ident;
42
+ };
43
+
44
+ const routeEntries: string[] = [];
45
+
46
+ for (const route of routes) {
47
+ const resolvedPage = route.path.replace(/\\/g, "/");
48
+ const regexPattern = buildRouteRegex(route.pattern).regex.source;
49
+ const searchDefaults = collectSearchDefaults(mergeRouteSchemas(route.routeChain ?? [], "query"));
50
+ const boundaryIdents = new Map<string, string>();
51
+
52
+ // Emit one boundary literal per segment that actually carries a convention
53
+ // file — segments that only declare one of the two are emitted with the
54
+ // missing field omitted entirely (keeps the generated JS tidy).
55
+ const boundaryLiterals: string[] = [];
56
+ for (const seg of route.segmentBoundaries ?? []) {
57
+ const errorIdent = getBoundaryIdent(boundaryIdents, seg.errorPath);
58
+ const notFoundIdent = getBoundaryIdent(boundaryIdents, seg.notFoundPath);
59
+ if (!(errorIdent || notFoundIdent)) {
60
+ continue;
61
+ }
62
+ const parts = [`depth: ${seg.depth}`];
63
+ if (errorIdent) {
64
+ parts.push(`error: ${errorIdent}.default`);
65
+ }
66
+ if (notFoundIdent) {
67
+ parts.push(`notFound: ${notFoundIdent}.default`);
68
+ }
69
+ boundaryLiterals.push(`{ ${parts.join(", ")} }`);
70
+ }
71
+
72
+ const lazyImports = [
73
+ `import("${resolvedPage}")`,
74
+ ...[...boundaryIdents.keys()].map((filePath) => `import("${filePath.replace(/\\/g, "/")}")`),
75
+ ];
76
+ const loadBody =
77
+ boundaryLiterals.length > 0
78
+ ? `Promise.all([${lazyImports.join(", ")}]).then(([__furin_page, ${[
79
+ ...boundaryIdents.values(),
80
+ ].join(", ")}]) => ({ default: __furin_page.default, segmentBoundaries: [${boundaryLiterals.join(", ")}] }))`
81
+ : `import("${resolvedPage}")`;
82
+
83
+ const searchDefaultsEntry = searchDefaults
84
+ ? `, searchDefaults: ${JSON.stringify(searchDefaults)}`
85
+ : "";
86
+ routeEntries.push(
87
+ ` { pattern: "${route.pattern}", regex: new RegExp(${JSON.stringify(regexPattern)}), load: () => ${loadBody}${searchDefaultsEntry} }`
88
+ );
89
+ }
90
+
91
+ // basePath stripping: when deployed to a sub-path (e.g. /furin), strip the
92
+ // prefix before route matching so patterns like /docs/routing still work.
93
+ const basePathLiteral = JSON.stringify(basePath);
94
+ // Strip basePath only when it matches on a path boundary (prevents "/furin" from
95
+ // matching "/furinity/foo"). The boundary holds when the pathname ends exactly
96
+ // at the prefix length OR the next character is "/".
97
+ // Trailing slashes are also stripped so "/docs/routing/" matches the route
98
+ // pattern "/docs/routing" — GitHub Pages and many static hosts append them.
99
+ const pathnameExpr = basePath
100
+ ? `(() => { const p = window.location.pathname; const b = ${basePathLiteral}; const stripped = (p.startsWith(b) && (p.length === b.length || p[b.length] === "/")) ? p.slice(b.length) || "/" : p; return stripped === "/" ? "/" : stripped.replace(/\\/+$/, ""); })()`
101
+ : `window.location.pathname.replace(/\\/+$/, "") || "/"`;
102
+
103
+ // Log drain endpoint: prepend basePath so the request goes to the correct origin path.
104
+ const logEndpoint = basePath
105
+ ? `${JSON.stringify(basePath)} + "/_furin/ingest"`
106
+ : `"/_furin/ingest"`;
107
+
108
+ // Client-side HTTP draining is opt-in (config `clientLogging`). When disabled
109
+ // we emit neither the hydrate-entry evlog imports nor initLogger, and define a
110
+ // no-op `log` shim so the hydration body's log.* calls stay valid.
111
+ const loggingImports = clientLogging
112
+ ? 'import { initLogger, log } from "evlog";\nimport { createHttpLogDrain } from "evlog/http";\n'
113
+ : "";
114
+ const loggerSetup = clientLogging
115
+ ? `initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });`
116
+ : "const log = { error() {}, info() {} };";
117
+
118
+ // RouterProvider receives basePath so navigate() / Link push physical paths.
119
+ const routerProviderDefaults = `\n autoRefresh: true,\n basePath: ${basePathLiteral},\n defaultPreload: "intent",\n defaultPreloadDelay: 50,\n defaultPreloadStaleTime: 30000,\n prefetchCacheSize: 50,\n syncStream,`;
120
+
121
+ return `import { hydrateRoot, createRoot } from "react-dom/client";
122
+ import { createElement } from "react";
123
+ ${loggingImports}import { RouterProvider } from "@teyik0/furin/link";
124
+ import { fromCrossJSON } from "@teyik0/furin/link";
125
+ import type { SerovalNode } from "seroval";
126
+ import { route as root } from "${rootLayout.replace(/\\/g, "/")}";
127
+
128
+ ${loggerSetup}
129
+
130
+ const routes = [
131
+ ${routeEntries.join(",\n")}
132
+ ];
133
+
134
+ const pathname = ${pathnameExpr};
135
+ const _match = routes.find((r) => r.regex.test(pathname));
136
+
137
+ // Parse the server-embedded loader payload up front. It carries:
138
+ // - normal loader props under arbitrary keys,
139
+ // - __furinError.digest when SSR caught an error,
140
+ // - __furinStatus: 404 when the server rendered the catch-all not-found
141
+ // (direct load to an unknown URL, emitted by renderRootNotFound) OR when
142
+ // a matched loader threw notFound(). The latter still has a _match; the
143
+ // former does not — so the two cases fork on _match below.
144
+ const dataEl = document.getElementById("__FURIN_DATA__");
145
+ const loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
146
+ const syncEl = document.getElementById("__FURIN_SYNC__");
147
+ const syncConfig = syncEl ? JSON.parse(syncEl.textContent || "{}") : {};
148
+ const syncStream = typeof syncConfig.stream === "string" ? syncConfig.stream : undefined;
149
+
150
+ // ── Deferred data hydration ─────────────────────────────────────────────────
151
+ // window.__FURIN_DEFERRED__ is injected by the server when a loader returns
152
+ // defer(). It carries:
153
+ // - _chunks: raw CrossJSON chunks keyed by field name (from late <script> tags)
154
+ // We deserialise each chunk with fromCrossJSON and create a Promise so <Await>
155
+ // components receive a proper resolved Promise instead of the raw CrossJSON node.
156
+ // Sync loader fields live exclusively in __FURIN_DATA__ (read above).
157
+ interface FurinDeferredRegistry {
158
+ _chunks: Record<string, { a: 0 | 1; v: SerovalNode }>;
159
+ _deferredKeys: string[];
160
+ _resolvers: Record<string, {
161
+ promise: Promise<unknown>;
162
+ reject: (reason: unknown) => void;
163
+ resolve: (value: unknown) => void;
164
+ }>;
165
+ getPromise: (key: string) => Promise<unknown>;
166
+ reject: (key: string, chunk: SerovalNode) => void;
167
+ resolve: (key: string, chunk: SerovalNode) => void;
168
+ }
169
+ const __deferred = (window as unknown as { __FURIN_DEFERRED__?: FurinDeferredRegistry })
170
+ .__FURIN_DEFERRED__;
171
+ const deferredData: Record<string, Promise<unknown>> = {};
172
+ if (__deferred && __deferred._chunks) {
173
+ // Patch resolve/reject so any chunks that arrive AFTER this entry has run
174
+ // settle immediately. The previous version stored late chunks in _chunks
175
+ // when no resolver was registered yet, but the drain loop below only runs
176
+ // ONCE at hydrate time — so any chunk landing after the drain would stay
177
+ // orphaned and the corresponding Await would hang forever. Eagerly creating
178
+ // the resolver via getPromise() fixes the race.
179
+ __deferred.resolve = (key: string, chunk: SerovalNode) => {
180
+ __deferred.getPromise(key);
181
+ __deferred._resolvers[key].resolve(fromCrossJSON(chunk, {}));
182
+ };
183
+ __deferred.reject = (key: string, chunk: SerovalNode) => {
184
+ __deferred.getPromise(key);
185
+ __deferred._resolvers[key].reject(fromCrossJSON(chunk, {}));
186
+ };
187
+ for (const key of Object.keys(__deferred._chunks)) {
188
+ const entry = __deferred._chunks[key] as { a: 0 | 1; v: SerovalNode };
189
+ const p = __deferred.getPromise(key) as Promise<unknown>;
190
+ const resolver = __deferred._resolvers[key];
191
+ const value = fromCrossJSON(entry.v, {});
192
+ if (entry.a === 0) {
193
+ resolver.resolve(value);
194
+ } else {
195
+ resolver.reject(value);
196
+ }
197
+ deferredData[key] = p;
198
+ }
199
+ for (const key of __deferred._deferredKeys ?? []) {
200
+ if (!(key in deferredData)) {
201
+ deferredData[key] = __deferred.getPromise(key) as Promise<unknown>;
202
+ }
203
+ }
204
+ // Keys that have a resolver (getPromise was called by <Await>) but no
205
+ // chunk yet (the late <script> hasn't arrived) still need a Promise entry
206
+ // so the hydration data record is complete.
207
+ for (const key of Object.keys(__deferred._resolvers ?? {})) {
208
+ if (!(key in deferredData)) {
209
+ deferredData[key] = __deferred.getPromise(key) as Promise<unknown>;
210
+ }
211
+ }
212
+ }
213
+ const rootEl = document.getElementById("root") as HTMLElement;
214
+
215
+ // Eagerly load only the current page module for initial hydration.
216
+ // All other pages are loaded on demand when the user navigates to them.
217
+ // Wrapped in an async IIFE to avoid top-level await, which causes Bun's HTML
218
+ // bundler to misidentify which chunk to reference as the entry in index.html.
219
+ (async () => {
220
+ let app;
221
+ if (_match) {
222
+ const _mod = await _match.load();
223
+ const match = {
224
+ ..._match,
225
+ component: _mod.default.component,
226
+ pageRoute: _mod.default._route,
227
+ segmentBoundaries: _mod.segmentBoundaries ?? _match.segmentBoundaries,
228
+ };
229
+
230
+ const isNotFound = loaderData.__furinStatus === 404;
231
+
232
+ app = createElement(RouterProvider, {
233
+ routes,
234
+ root,
235
+ initialMatch: match,
236
+ initialData: { ...loaderData, ...deferredData },
237
+ initialDigest: loaderData.__furinError?.digest,
238
+ initialNotFound: isNotFound ? (loaderData.__furinNotFound ?? loaderData) : undefined,${routerProviderDefaults}
239
+ } as any);
240
+ } else if (loaderData.__furinStatus === 404) {
241
+ // Direct load to an unknown URL. The server sent the root not-found UI
242
+ // already rendered into the DOM. Mount RouterProvider with a null match
243
+ // so the provider boots into its not-found branch, hydrating that exact
244
+ // tree INSIDE a live RouterContext. Without this, Links in the 404 UI
245
+ // (e.g. the default screen's "Go Home" button) hit the useRouter()
246
+ // fallback that does a full window.location assignment — a jarring reload.
247
+ // Strip the server-only signal keys before handing data to components.
248
+ const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = loaderData;
249
+ app = createElement(RouterProvider, {
250
+ routes,
251
+ root,
252
+ initialMatch: null,
253
+ initialData: cleanData,
254
+ initialDigest: loaderData.__furinError?.digest,
255
+ initialNotFound: loaderData.__furinNotFound ?? {},${routerProviderDefaults}
256
+ } as any);
257
+ } else {
258
+ // No match and no 404 signal — either the client bundle is out of sync
259
+ // with the server (stale deploy) or the server returned something we
260
+ // don't know how to hydrate. Bail loudly; the page stays static.
261
+ log.error({ action: "hydrate_no_match", pathname });
262
+ return;
263
+ }
264
+
265
+ if (import.meta.hot) {
266
+ // Dev mode — preserve root across HMR using a window global.
267
+ // window is the only object that survives Bun's module re-evaluation.
268
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
269
+ const existingRoot = (window as any).__FURIN_ROOT__;
270
+ if (existingRoot) {
271
+ // Already mounted — reconciliation, NOT hydration. React Fast Refresh
272
+ // patched the component in-place, now re-render with the new module.
273
+ existingRoot.render(app);
274
+ // The initialData embedded in the DOM is stale (from the original SSR).
275
+ // Trigger a loader-data refresh so the component renders with fresh
276
+ // server state, avoiding hydration mismatches after a _route.tsx edit.
277
+ const hmrRefresh = (window as any).__FURIN_HMR_REFRESH__;
278
+ if (hmrRefresh) {
279
+ requestAnimationFrame(() => hmrRefresh());
280
+ }
281
+ } else if (rootEl.innerHTML.trim()) {
282
+ // First load with SSR content — hydrateRoot renders on construction
283
+ const root = hydrateRoot(rootEl, app);
284
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
285
+ (window as any).__FURIN_ROOT__ = root;
286
+ } else {
287
+ // First load without SSR content — createRoot requires explicit .render()
288
+ const root = createRoot(rootEl);
289
+ root.render(app);
290
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
291
+ (window as any).__FURIN_ROOT__ = root;
292
+ }
293
+ } else if (rootEl.innerHTML.trim()) {
294
+ hydrateRoot(rootEl, app);
295
+ } else {
296
+ createRoot(rootEl).render(app);
297
+ }
298
+
299
+ log.info({ action: "hydrate_complete", pathname });
300
+ })().catch((err: unknown) => {
301
+ log.error({ action: "hydrate_failed", pathname, error: String(err) });
302
+ });
303
+ `;
304
+ }
305
+
306
+ /**
307
+ * Writes _hydrate.tsx + index.html to outDir for dev (Bun HMR) mode.
308
+ *
309
+ * Only rewrites a file when its content has actually changed so Bun's --hot
310
+ * watcher does not trigger a spurious reload on every server restart.
311
+ */
312
+ export function writeDevFiles(
313
+ routes: ResolvedRoute[],
314
+ { outDir, rootLayout, basePath, clientLogging }: BuildClientOptions,
315
+ projectRoot: string
316
+ ): void {
317
+ if (!existsSync(outDir)) {
318
+ mkdirSync(outDir, { recursive: true });
319
+ }
320
+
321
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
322
+ const hydratePath = join(outDir, "_hydrate.tsx");
323
+ const existingHydrate = existsSync(hydratePath) ? readFileSync(hydratePath, "utf8") : "";
324
+ if (hydrateCode !== existingHydrate) {
325
+ writeFileSync(hydratePath, hydrateCode);
326
+ }
327
+
328
+ const indexHtml = generateIndexHtml();
329
+ const indexPath = join(outDir, "index.html");
330
+ const existingIndex = existsSync(indexPath) ? readFileSync(indexPath, "utf8") : "";
331
+ if (indexHtml !== existingIndex) {
332
+ writeFileSync(indexPath, indexHtml);
333
+ }
334
+
335
+ writeRouteTypes(routes, projectRoot);
336
+
337
+ console.log(
338
+ "[furin] Dev files written (.furin/_hydrate.tsx + .furin/index.html + furin-env.d.ts)"
339
+ );
340
+ }