@teyik0/furin 0.2.0-alpha.2 → 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.
- package/LICENSE +21 -21
- package/README.md +33 -33
- package/dist/adapter/bun.d.ts +3 -0
- package/dist/adapter/static.d.ts +3 -0
- package/dist/build/client.d.ts +25 -0
- package/dist/build/compile-entry.d.ts +9 -0
- package/dist/build/compile-entry.ts +109 -0
- package/dist/build/entry-template.d.ts +38 -0
- package/dist/build/entry-template.ts +156 -0
- package/dist/build/hydrate.d.ts +24 -0
- package/dist/build/index.d.ts +8 -0
- package/dist/build/index.js +8106 -0
- package/dist/build/route-types.d.ts +23 -0
- package/dist/build/scan-server.d.ts +8 -0
- package/dist/build/server-routes-entry.d.ts +13 -0
- package/dist/build/server-routes-entry.ts +36 -0
- package/dist/build/shared.d.ts +12 -0
- package/dist/build/ssg-cache.d.ts +4 -0
- package/dist/build/types.d.ts +80 -0
- package/dist/cli/config.d.ts +9 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +8097 -0
- package/dist/client/boundaries.d.ts +117 -0
- package/dist/client/default-screens.d.ts +17 -0
- package/dist/client/link.d.ts +22 -0
- package/dist/client/link.js +4244 -0
- package/dist/client/router/boundary-tree.d.ts +26 -0
- package/dist/client/router/context.d.ts +8 -0
- package/dist/client/router/history.d.ts +9 -0
- package/dist/client/router/index.d.ts +11 -0
- package/dist/client/router/link-utils.d.ts +53 -0
- package/dist/client/router/navigation.d.ts +10 -0
- package/dist/client/router/provider.d.ts +4 -0
- package/dist/client/router/search/index.d.ts +18 -0
- package/dist/client/router/search-store.d.ts +21 -0
- package/dist/client/router/spa-response.d.ts +58 -0
- package/dist/client/router/types.d.ts +292 -0
- package/dist/client/server-error.d.ts +12 -0
- package/dist/client/sync.d.ts +25 -0
- package/dist/client.d.ts +243 -0
- package/dist/client.js +140 -0
- package/dist/config.d.ts +57 -0
- package/dist/config.js +29 -0
- package/dist/env.d.ts +50 -0
- package/dist/furin.d.ts +77 -0
- package/dist/furin.js +8693 -0
- package/dist/plugin/index.d.ts +20 -0
- package/dist/plugin/index.js +1500 -0
- package/dist/plugin/transform-client.d.ts +10 -0
- package/dist/server/auto-invalidate/index.d.ts +4 -0
- package/dist/server/auto-invalidate/plugin.d.ts +38 -0
- package/dist/server/auto-invalidate/registry.d.ts +9 -0
- package/dist/server/auto-invalidate/runtime.d.ts +9 -0
- package/dist/server/auto-invalidate/types.d.ts +12 -0
- package/dist/server/cache/dev-loader.d.ts +28 -0
- package/dist/server/cache/index.d.ts +10 -0
- package/dist/server/cache/invalidation.d.ts +12 -0
- package/dist/server/cache/isr-ssg.d.ts +26 -0
- package/dist/server/cache/isr.d.ts +6 -0
- package/dist/server/cache/registry.d.ts +5 -0
- package/dist/server/cache/route-cache.d.ts +26 -0
- package/dist/server/cache/ssg.d.ts +5 -0
- package/dist/server/context-logger.d.ts +28 -0
- package/dist/server/dev-inspector.d.ts +89 -0
- package/dist/server/dev-page-plugin.d.ts +112 -0
- package/dist/server/internal.d.ts +35 -0
- package/dist/server/internal.js +17 -0
- package/dist/server/lang-detect.d.ts +5 -0
- package/dist/server/render/assemble.d.ts +49 -0
- package/dist/server/render/element.d.ts +24 -0
- package/dist/server/render/index.d.ts +7 -0
- package/dist/server/render/index.ts +22 -0
- package/dist/server/render/isr.d.ts +4 -0
- package/dist/server/render/loaders.d.ts +64 -0
- package/dist/server/render/not-found.d.ts +6 -0
- package/dist/server/render/shell.d.ts +39 -0
- package/dist/server/render/shell.ts +202 -0
- package/dist/server/render/ssg.d.ts +9 -0
- package/dist/server/render/ssr.d.ts +108 -0
- package/dist/server/render/template.d.ts +6 -0
- package/dist/server/router/discovery.d.ts +16 -0
- package/dist/server/router/hmr.d.ts +65 -0
- package/dist/server/router/index.d.ts +6 -0
- package/dist/server/router/index.js +27 -0
- package/dist/server/router/index.ts +28 -0
- package/dist/server/router/patterns.d.ts +40 -0
- package/dist/server/router/plugin.d.ts +21 -0
- package/dist/server/router/schemas.d.ts +59 -0
- package/dist/server/router/types.d.ts +60 -0
- package/dist/server/runtime-env.d.ts +3 -0
- package/dist/server/runtime-env.js +10 -0
- package/dist/server/sync/config.d.ts +6 -0
- package/dist/server/sync/index.d.ts +4 -0
- package/dist/server/sync/plugin.d.ts +369 -0
- package/dist/server/sync/stream.d.ts +47 -0
- package/dist/shared/await.d.ts +67 -0
- package/dist/shared/deferred-ndjson.d.ts +32 -0
- package/dist/shared/digest.d.ts +16 -0
- package/dist/shared/error.d.ts +37 -0
- package/dist/shared/not-found.d.ts +19 -0
- package/dist/shared/search-params.d.ts +17 -0
- package/dist/shared/utils/ast-walk.d.ts +18 -0
- package/dist/shared/utils/index.d.ts +13 -0
- package/package.json +5 -5
- package/src/adapter/README.md +13 -13
- package/src/build/client.ts +152 -152
- package/src/build/compile-entry.ts +109 -109
- package/src/build/entry-template.ts +156 -156
- package/src/build/hydrate.ts +340 -337
- package/src/build/index.ts +152 -152
- package/src/build/route-types.ts +145 -145
- package/src/build/scan-server.ts +95 -95
- package/src/build/server-routes-entry.ts +36 -36
- package/src/build/shared.ts +80 -79
- package/src/build/ssg-cache.ts +32 -32
- package/src/build/types.ts +89 -89
- package/src/client/router/link-utils.ts +184 -177
- package/src/client/router/provider.tsx +804 -759
- package/src/client/router/types.ts +276 -271
- package/src/client/sync.ts +98 -0
- package/src/client.ts +369 -355
- package/src/furin.ts +465 -444
- package/src/server/auto-invalidate/runtime.ts +134 -133
- package/src/server/dev-page-plugin.ts +454 -449
- package/src/server/render/assemble.ts +160 -133
- package/src/server/render/isr.ts +323 -317
- package/src/server/render/ssr.ts +585 -583
- package/src/server/router/plugin.ts +384 -384
- package/src/server/sync/config.ts +29 -0
- package/src/server/sync/index.ts +14 -0
- package/src/server/sync/plugin.ts +108 -0
- package/src/server/sync/stream.ts +144 -0
package/src/build/hydrate.ts
CHANGED
|
@@ -1,337 +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 { 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,`;
|
|
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
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
//
|
|
151
|
-
//
|
|
152
|
-
//
|
|
153
|
-
//
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
//
|
|
174
|
-
//
|
|
175
|
-
//
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
__deferred.
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
const
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
//
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
//
|
|
242
|
-
//
|
|
243
|
-
//
|
|
244
|
-
//
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
//
|
|
272
|
-
//
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
//
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
//
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
});
|
|
300
|
-
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
*
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
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
|
+
}
|