@teyik0/furin 0.1.0-alpha.9 → 0.2.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +33 -0
- package/dist/adapter/bun.d.ts +2 -2
- package/dist/adapter/static.d.ts +1 -1
- package/dist/build/client.d.ts +2 -2
- package/dist/build/compile-entry.d.ts +2 -16
- package/dist/build/compile-entry.ts +109 -0
- package/dist/build/entry-template.d.ts +24 -0
- package/dist/build/entry-template.ts +156 -0
- package/dist/build/hydrate.d.ts +3 -3
- package/dist/build/index.d.ts +1 -0
- package/dist/build/index.js +4027 -685
- package/dist/build/route-types.d.ts +1 -1
- package/dist/build/server-routes-entry.d.ts +2 -12
- package/dist/build/server-routes-entry.ts +36 -0
- package/dist/build/shared.d.ts +1 -1
- package/dist/build/ssg-cache.d.ts +4 -0
- package/dist/build/types.d.ts +5 -1
- package/dist/cli/index.js +4007 -687
- 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 +3450 -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 +7 -0
- package/dist/client/router/link-utils.d.ts +51 -0
- package/dist/client/router/provider.d.ts +4 -0
- package/dist/client/router/spa-response.d.ts +58 -0
- package/dist/{link.d.ts → client/router/types.d.ts} +114 -80
- package/dist/client/server-error.d.ts +12 -0
- package/dist/client.d.ts +51 -4
- package/dist/client.js +77 -1
- package/dist/config.d.ts +12 -2
- package/dist/config.js +1 -0
- package/dist/env.d.ts +50 -0
- package/dist/furin.d.ts +37 -2
- package/dist/furin.js +5291 -662
- package/dist/plugin/index.js +140 -48
- package/dist/plugin/transform-client.d.ts +2 -1
- 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/{context-logger.d.ts → server/context-logger.d.ts} +2 -0
- package/dist/server/dev-inspector.d.ts +89 -0
- package/dist/{internal.d.ts → server/internal.d.ts} +16 -0
- package/dist/server/internal.js +17 -0
- package/dist/server/lang-detect.d.ts +5 -0
- package/dist/server/render/assemble.d.ts +47 -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 +3 -0
- package/dist/server/render/loaders.d.ts +64 -0
- package/dist/server/render/not-found.d.ts +6 -0
- package/dist/{render → server/render}/shell.d.ts +17 -7
- package/{src → dist/server}/render/shell.ts +28 -13
- package/dist/server/render/ssg.d.ts +8 -0
- package/dist/server/render/ssr.d.ts +107 -0
- package/dist/server/router/discovery.d.ts +16 -0
- package/dist/server/router/hmr.d.ts +64 -0
- package/dist/server/router/index.d.ts +6 -0
- package/dist/server/router/index.js +28 -0
- package/dist/server/router/index.ts +29 -0
- package/dist/server/router/patterns.d.ts +40 -0
- package/dist/server/router/plugin.d.ts +20 -0
- package/dist/server/router/schemas.d.ts +51 -0
- package/dist/server/router/types.d.ts +60 -0
- package/dist/server/runtime-env.js +10 -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/utils/ast-walk.d.ts +18 -0
- package/dist/shared/utils/index.d.ts +13 -0
- package/package.json +56 -25
- package/src/adapter/bun.ts +90 -41
- package/src/adapter/static.ts +79 -36
- package/src/build/client.ts +8 -12
- package/src/build/compile-entry.ts +20 -14
- package/src/build/entry-template.ts +90 -8
- package/src/build/hydrate.ts +213 -36
- package/src/build/index.ts +10 -9
- package/src/build/route-types.ts +30 -4
- package/src/build/scan-server.ts +52 -67
- package/src/build/server-routes-entry.ts +7 -11
- package/src/build/shared.ts +1 -1
- package/src/build/ssg-cache.ts +31 -0
- package/src/build/types.ts +5 -1
- package/src/cli/index.ts +1 -0
- package/src/client/boundaries.tsx +259 -0
- package/src/client/default-screens.tsx +304 -0
- package/src/client/link.tsx +338 -0
- package/src/client/router/boundary-tree.tsx +116 -0
- package/src/client/router/context.ts +38 -0
- package/src/client/router/history.ts +41 -0
- package/src/client/router/index.ts +47 -0
- package/src/client/router/link-utils.ts +180 -0
- package/src/client/router/provider.tsx +723 -0
- package/src/client/router/spa-response.ts +143 -0
- package/src/client/router/types.ts +263 -0
- package/src/client/server-error.ts +47 -0
- package/src/client.ts +80 -3
- package/src/config.ts +11 -3
- package/src/env.d.ts +1 -0
- package/src/furin.ts +104 -26
- package/src/plugin/index.ts +7 -8
- package/src/plugin/transform-client.ts +146 -120
- package/src/server/auto-invalidate/index.ts +10 -0
- package/src/server/auto-invalidate/plugin.ts +25 -0
- package/src/server/auto-invalidate/registry.ts +60 -0
- package/src/server/auto-invalidate/runtime.ts +133 -0
- package/src/server/auto-invalidate/types.ts +16 -0
- package/src/server/cache/dev-loader.ts +211 -0
- package/src/server/cache/index.ts +34 -0
- package/src/server/cache/invalidation.ts +111 -0
- package/src/server/cache/isr-ssg.ts +41 -0
- package/src/server/cache/isr.ts +17 -0
- package/src/server/cache/registry.ts +35 -0
- package/src/server/cache/route-cache.ts +124 -0
- package/src/server/cache/ssg.ts +15 -0
- package/src/{context-logger.ts → server/context-logger.ts} +5 -0
- package/src/server/dev-inspector.ts +60 -0
- package/src/{dev-page-plugin.ts → server/dev-page-plugin.ts} +15 -0
- package/src/{internal.ts → server/internal.ts} +17 -0
- package/src/server/lang-detect.ts +46 -0
- package/src/server/render/assemble.ts +133 -0
- package/src/server/render/element.tsx +113 -0
- package/src/server/render/index.ts +22 -0
- package/src/server/render/isr.ts +295 -0
- package/src/server/render/loaders.ts +328 -0
- package/src/server/render/not-found.ts +96 -0
- package/src/server/render/shell.ts +202 -0
- package/src/server/render/ssg.ts +137 -0
- package/src/server/render/ssr.ts +545 -0
- package/src/server/router/discovery.ts +474 -0
- package/src/server/router/hmr.ts +372 -0
- package/src/server/router/index.ts +29 -0
- package/src/server/router/patterns.ts +214 -0
- package/src/server/router/plugin.ts +401 -0
- package/src/server/router/schemas.ts +163 -0
- package/src/server/router/types.ts +59 -0
- package/src/shared/await.tsx +192 -0
- package/src/shared/deferred-ndjson.ts +244 -0
- package/src/shared/digest.ts +71 -0
- package/src/shared/error.ts +49 -0
- package/src/shared/not-found.ts +40 -0
- package/src/shared/utils/ast-walk.ts +51 -0
- package/src/{utils.ts → shared/utils/index.ts} +32 -1
- package/dist/link.js +0 -1232
- package/dist/render/assemble.d.ts +0 -15
- package/dist/render/cache.d.ts +0 -95
- package/dist/render/element.d.ts +0 -4
- package/dist/render/index.d.ts +0 -27
- package/dist/render/loaders.d.ts +0 -12
- package/dist/router.d.ts +0 -45
- package/dist/router.js +0 -1671
- package/dist/utils.d.ts +0 -6
- package/src/link.tsx +0 -1120
- package/src/render/assemble.ts +0 -66
- package/src/render/cache.ts +0 -241
- package/src/render/element.tsx +0 -28
- package/src/render/index.ts +0 -483
- package/src/render/loaders.ts +0 -117
- package/src/router.ts +0 -439
- /package/dist/{dev-page-plugin.d.ts → server/dev-page-plugin.d.ts} +0 -0
- /package/dist/{render → server/render}/template.d.ts +0 -0
- /package/dist/{runtime-env.d.ts → server/runtime-env.d.ts} +0 -0
- /package/src/{render → server/render}/template.ts +0 -0
- /package/src/{runtime-env.ts → server/runtime-env.ts} +0 -0
|
@@ -1,24 +1,91 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import type { SsgCacheEntry } from "../server/cache/index.ts";
|
|
2
5
|
|
|
3
6
|
// import.meta.resolve() runs at runtime (not inlined at bundle time), resolves
|
|
4
|
-
// through package exports, and is the Web-standard API. The
|
|
5
|
-
//
|
|
6
|
-
|
|
7
|
-
const
|
|
8
|
-
const
|
|
7
|
+
// through package exports, and is the Web-standard API. The main entry is
|
|
8
|
+
// `src/furin.ts` (or `dist/furin.js`), so we strip two path segments to reach
|
|
9
|
+
// the package root.
|
|
10
|
+
const _pkgRoot = dirname(dirname(fileURLToPath(import.meta.resolve("@teyik0/furin"))));
|
|
11
|
+
const _pkgSrcDirRaw = existsSync(join(_pkgRoot, "src", "furin.ts"))
|
|
12
|
+
? join(_pkgRoot, "src")
|
|
13
|
+
: join(_pkgRoot, "dist");
|
|
14
|
+
// Normalize to forward slashes so endsWith checks and template paths work on Windows.
|
|
15
|
+
const _pkgSrcDir = _pkgSrcDirRaw.replace(/\\/g, "/");
|
|
16
|
+
const _ext = _pkgSrcDir.endsWith("/src") ? ".ts" : ".js";
|
|
17
|
+
const INTERNAL_MODULE_PATH = `${_pkgSrcDir}/server/internal${_ext}`;
|
|
18
|
+
const RUNTIME_ENV_MODULE_PATH = `${_pkgSrcDir}/server/runtime-env${_ext}`;
|
|
9
19
|
|
|
10
20
|
export interface EntryTemplateOptions {
|
|
11
21
|
buildId?: string;
|
|
12
22
|
extraContext?: string[];
|
|
13
23
|
extraImports?: string[];
|
|
14
24
|
headerComment: string;
|
|
25
|
+
rootConventions?: { errorPath?: string; notFoundPath?: string };
|
|
15
26
|
rootPath: string;
|
|
27
|
+
routeMetadata?: Record<
|
|
28
|
+
string,
|
|
29
|
+
{
|
|
30
|
+
segmentBoundaries: Array<{
|
|
31
|
+
depth: number;
|
|
32
|
+
path: string;
|
|
33
|
+
errorPath?: string;
|
|
34
|
+
notFoundPath?: string;
|
|
35
|
+
}>;
|
|
36
|
+
}
|
|
37
|
+
>;
|
|
16
38
|
routes: Array<{ mode: "ssr" | "ssg" | "isr"; path: string; pattern: string }>;
|
|
17
39
|
serverEntry: string;
|
|
40
|
+
ssgCache?: Record<string, SsgCacheEntry>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Unified options for generating a build entry (compile or disk-based). */
|
|
44
|
+
export interface BuildEntryOptions extends Omit<EntryTemplateOptions, "headerComment"> {
|
|
45
|
+
outDir: string;
|
|
46
|
+
headerComment?: string;
|
|
47
|
+
/** Embed mode: bundles client assets into the binary via `with { type: "file" }`. */
|
|
48
|
+
embed?: { clientDir: string };
|
|
49
|
+
publicDir?: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function collectConventionPaths(
|
|
53
|
+
rootConventions: EntryTemplateOptions["rootConventions"],
|
|
54
|
+
routeMetadata: EntryTemplateOptions["routeMetadata"]
|
|
55
|
+
): string[] {
|
|
56
|
+
const paths: string[] = [];
|
|
57
|
+
if (rootConventions?.errorPath) {
|
|
58
|
+
paths.push(rootConventions.errorPath);
|
|
59
|
+
}
|
|
60
|
+
if (rootConventions?.notFoundPath) {
|
|
61
|
+
paths.push(rootConventions.notFoundPath);
|
|
62
|
+
}
|
|
63
|
+
if (routeMetadata) {
|
|
64
|
+
for (const meta of Object.values(routeMetadata)) {
|
|
65
|
+
for (const seg of meta.segmentBoundaries) {
|
|
66
|
+
if (seg.errorPath) {
|
|
67
|
+
paths.push(seg.errorPath);
|
|
68
|
+
}
|
|
69
|
+
if (seg.notFoundPath) {
|
|
70
|
+
paths.push(seg.notFoundPath);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return [...new Set(paths)];
|
|
18
76
|
}
|
|
19
77
|
|
|
20
78
|
export function buildEntrySource(options: EntryTemplateOptions): string {
|
|
21
|
-
const {
|
|
79
|
+
const {
|
|
80
|
+
buildId,
|
|
81
|
+
headerComment,
|
|
82
|
+
rootPath,
|
|
83
|
+
routes,
|
|
84
|
+
serverEntry,
|
|
85
|
+
rootConventions,
|
|
86
|
+
routeMetadata,
|
|
87
|
+
ssgCache,
|
|
88
|
+
} = options;
|
|
22
89
|
let { extraImports, extraContext } = options;
|
|
23
90
|
if (extraImports === undefined) {
|
|
24
91
|
extraImports = [];
|
|
@@ -27,7 +94,11 @@ export function buildEntrySource(options: EntryTemplateOptions): string {
|
|
|
27
94
|
extraContext = [];
|
|
28
95
|
}
|
|
29
96
|
|
|
30
|
-
const allModulePaths = [
|
|
97
|
+
const allModulePaths = [
|
|
98
|
+
rootPath,
|
|
99
|
+
...routes.map((r) => r.path),
|
|
100
|
+
...collectConventionPaths(rootConventions, routeMetadata),
|
|
101
|
+
];
|
|
31
102
|
const moduleImports: string[] = [];
|
|
32
103
|
const moduleEntries: string[] = [];
|
|
33
104
|
|
|
@@ -43,6 +114,14 @@ export function buildEntrySource(options: EntryTemplateOptions): string {
|
|
|
43
114
|
` { pattern: ${JSON.stringify(r.pattern)}, path: ${JSON.stringify(r.path.replace(/\\/g, "/"))}, mode: ${JSON.stringify(r.mode)} },`
|
|
44
115
|
);
|
|
45
116
|
|
|
117
|
+
const rootConventionsLine = rootConventions
|
|
118
|
+
? ` rootConventions: ${JSON.stringify(rootConventions)},`
|
|
119
|
+
: "";
|
|
120
|
+
const routeMetadataLine = routeMetadata
|
|
121
|
+
? ` routeMetadata: ${JSON.stringify(routeMetadata)},`
|
|
122
|
+
: "";
|
|
123
|
+
const ssgCacheLine = ssgCache ? ` ssgCache: ${JSON.stringify(ssgCache)},` : "";
|
|
124
|
+
|
|
46
125
|
const lines = [
|
|
47
126
|
headerComment,
|
|
48
127
|
`import { __setCompileContext } from ${JSON.stringify(INTERNAL_MODULE_PATH)};`,
|
|
@@ -57,12 +136,15 @@ export function buildEntrySource(options: EntryTemplateOptions): string {
|
|
|
57
136
|
"__setCompileContext({",
|
|
58
137
|
` buildId: ${JSON.stringify(buildId ?? "")},`,
|
|
59
138
|
` rootPath: ${JSON.stringify(rootPath.replace(/\\/g, "/"))},`,
|
|
139
|
+
rootConventionsLine,
|
|
60
140
|
" modules: {",
|
|
61
141
|
...moduleEntries,
|
|
62
142
|
" },",
|
|
63
143
|
" routes: [",
|
|
64
144
|
...routeEntries,
|
|
65
145
|
" ],",
|
|
146
|
+
routeMetadataLine,
|
|
147
|
+
ssgCacheLine,
|
|
66
148
|
...extraContext,
|
|
67
149
|
"});",
|
|
68
150
|
"",
|
package/src/build/hydrate.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
-
import { generateIndexHtml } from "../render/shell";
|
|
4
|
-
import
|
|
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";
|
|
5
6
|
import { writeRouteTypes } from "./route-types";
|
|
6
7
|
import type { BuildClientOptions } from "./types";
|
|
7
8
|
|
|
@@ -22,16 +23,62 @@ import type { BuildClientOptions } from "./types";
|
|
|
22
23
|
export function generateHydrateEntry(
|
|
23
24
|
routes: ResolvedRoute[],
|
|
24
25
|
rootLayout: string,
|
|
25
|
-
basePath: string
|
|
26
|
+
basePath: string,
|
|
27
|
+
clientLogging: boolean
|
|
26
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
|
+
|
|
27
42
|
const routeEntries: string[] = [];
|
|
28
43
|
|
|
29
44
|
for (const route of routes) {
|
|
30
45
|
const resolvedPage = route.path.replace(/\\/g, "/");
|
|
31
|
-
const regexPattern = route.pattern
|
|
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}")`;
|
|
32
79
|
|
|
33
80
|
routeEntries.push(
|
|
34
|
-
` { pattern: "${route.pattern}", regex: new RegExp(
|
|
81
|
+
` { pattern: "${route.pattern}", regex: new RegExp(${JSON.stringify(regexPattern)}), load: () => ${loadBody} }`
|
|
35
82
|
);
|
|
36
83
|
}
|
|
37
84
|
|
|
@@ -41,26 +88,38 @@ export function generateHydrateEntry(
|
|
|
41
88
|
// Strip basePath only when it matches on a path boundary (prevents "/furin" from
|
|
42
89
|
// matching "/furinity/foo"). The boundary holds when the pathname ends exactly
|
|
43
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.
|
|
44
93
|
const pathnameExpr = basePath
|
|
45
|
-
? `(() => { const p = window.location.pathname; const b = ${basePathLiteral};
|
|
46
|
-
:
|
|
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(/\\/+$/, "") || "/"`;
|
|
47
96
|
|
|
48
97
|
// Log drain endpoint: prepend basePath so the request goes to the correct origin path.
|
|
49
98
|
const logEndpoint = basePath
|
|
50
99
|
? `${JSON.stringify(basePath)} + "/_furin/ingest"`
|
|
51
100
|
: `"/_furin/ingest"`;
|
|
52
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
|
+
|
|
53
112
|
// RouterProvider receives basePath so navigate() / Link push physical paths.
|
|
54
|
-
const
|
|
113
|
+
const routerProviderDefaults = `\n autoRefresh: true,\n basePath: ${basePathLiteral},\n defaultPreload: "intent",\n defaultPreloadDelay: 50,\n defaultPreloadStaleTime: 30000,\n prefetchCacheSize: 50,`;
|
|
55
114
|
|
|
56
115
|
return `import { hydrateRoot, createRoot } from "react-dom/client";
|
|
57
116
|
import { createElement } from "react";
|
|
58
|
-
import {
|
|
59
|
-
import {
|
|
60
|
-
import {
|
|
117
|
+
${loggingImports}import { RouterProvider } from "@teyik0/furin/link";
|
|
118
|
+
import { fromCrossJSON } from "@teyik0/furin/link";
|
|
119
|
+
import type { SerovalNode } from "seroval";
|
|
61
120
|
import { route as root } from "${rootLayout.replace(/\\/g, "/")}";
|
|
62
121
|
|
|
63
|
-
|
|
122
|
+
${loggerSetup}
|
|
64
123
|
|
|
65
124
|
const routes = [
|
|
66
125
|
${routeEntries.join(",\n")}
|
|
@@ -69,48 +128,166 @@ ${routeEntries.join(",\n")}
|
|
|
69
128
|
const pathname = ${pathnameExpr};
|
|
70
129
|
const _match = routes.find((r) => r.regex.test(pathname));
|
|
71
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
|
+
|
|
72
206
|
// Eagerly load only the current page module for initial hydration.
|
|
73
207
|
// All other pages are loaded on demand when the user navigates to them.
|
|
74
208
|
// Wrapped in an async IIFE to avoid top-level await, which causes Bun's HTML
|
|
75
209
|
// bundler to misidentify which chunk to reference as the entry in index.html.
|
|
76
210
|
(async () => {
|
|
211
|
+
let app;
|
|
77
212
|
if (_match) {
|
|
78
213
|
const _mod = await _match.load();
|
|
79
|
-
const match = {
|
|
214
|
+
const match = {
|
|
215
|
+
..._match,
|
|
216
|
+
component: _mod.default.component,
|
|
217
|
+
pageRoute: _mod.default._route,
|
|
218
|
+
segmentBoundaries: _mod.segmentBoundaries ?? _match.segmentBoundaries,
|
|
219
|
+
};
|
|
80
220
|
|
|
81
|
-
const
|
|
82
|
-
const loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
|
|
83
|
-
const rootEl = document.getElementById("root") as HTMLElement;
|
|
221
|
+
const isNotFound = loaderData.__furinStatus === 404;
|
|
84
222
|
|
|
85
|
-
|
|
223
|
+
app = createElement(RouterProvider, {
|
|
86
224
|
routes,
|
|
87
225
|
root,
|
|
88
226
|
initialMatch: match,
|
|
89
|
-
initialData: loaderData
|
|
227
|
+
initialData: { ...loaderData, ...deferredData },
|
|
228
|
+
initialDigest: loaderData.__furinError?.digest,
|
|
229
|
+
initialNotFound: isNotFound ? (loaderData.__furinNotFound ?? loaderData) : undefined,${routerProviderDefaults}
|
|
90
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
|
+
}
|
|
91
255
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
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());
|
|
104
271
|
}
|
|
105
272
|
} else if (rootEl.innerHTML.trim()) {
|
|
106
|
-
hydrateRoot
|
|
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;
|
|
107
277
|
} else {
|
|
108
|
-
createRoot
|
|
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;
|
|
109
283
|
}
|
|
110
|
-
|
|
284
|
+
} else if (rootEl.innerHTML.trim()) {
|
|
285
|
+
hydrateRoot(rootEl, app);
|
|
111
286
|
} else {
|
|
112
|
-
|
|
287
|
+
createRoot(rootEl).render(app);
|
|
113
288
|
}
|
|
289
|
+
|
|
290
|
+
log.info({ action: "hydrate_complete", pathname });
|
|
114
291
|
})().catch((err: unknown) => {
|
|
115
292
|
log.error({ action: "hydrate_failed", pathname, error: String(err) });
|
|
116
293
|
});
|
|
@@ -125,14 +302,14 @@ const _match = routes.find((r) => r.regex.test(pathname));
|
|
|
125
302
|
*/
|
|
126
303
|
export function writeDevFiles(
|
|
127
304
|
routes: ResolvedRoute[],
|
|
128
|
-
{ outDir, rootLayout, basePath }: BuildClientOptions,
|
|
305
|
+
{ outDir, rootLayout, basePath, clientLogging }: BuildClientOptions,
|
|
129
306
|
projectRoot: string
|
|
130
307
|
): void {
|
|
131
308
|
if (!existsSync(outDir)) {
|
|
132
309
|
mkdirSync(outDir, { recursive: true });
|
|
133
310
|
}
|
|
134
311
|
|
|
135
|
-
const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
|
|
312
|
+
const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
|
|
136
313
|
const hydratePath = join(outDir, "_hydrate.tsx");
|
|
137
314
|
const existingHydrate = existsSync(hydratePath) ? readFileSync(hydratePath, "utf8") : "";
|
|
138
315
|
if (hydrateCode !== existingHydrate) {
|
package/src/build/index.ts
CHANGED
|
@@ -2,8 +2,8 @@ import { existsSync, writeFileSync } from "node:fs";
|
|
|
2
2
|
import { join, relative, resolve } from "node:path";
|
|
3
3
|
import { buildBunTarget } from "../adapter/bun";
|
|
4
4
|
import { buildStaticTarget } from "../adapter/static";
|
|
5
|
-
import { BUILD_TARGETS, type BuildTarget } from "../config";
|
|
6
|
-
import { scanPages } from "../router";
|
|
5
|
+
import { BUILD_TARGETS, type BuildTarget, type FurinPlugin } from "../config";
|
|
6
|
+
import { scanPages } from "../server/router/index.ts";
|
|
7
7
|
import { scanFurinInstances } from "./scan-server";
|
|
8
8
|
import { ensureDir, toBuildRouteManifestEntry, toPosixPath } from "./shared";
|
|
9
9
|
import type { BuildAppOptions, BuildAppResult, BuildManifest } from "./types";
|
|
@@ -12,6 +12,7 @@ import type { BuildAppOptions, BuildAppResult, BuildManifest } from "./types";
|
|
|
12
12
|
export { buildClient } from "./client";
|
|
13
13
|
export { writeDevFiles } from "./hydrate";
|
|
14
14
|
export { patternToTypeString, schemaToTypeString, writeRouteTypes } from "./route-types";
|
|
15
|
+
export { buildSSGCacheSnapshot, type SSGCacheSnapshot } from "./ssg-cache";
|
|
15
16
|
export type {
|
|
16
17
|
BuildAppOptions,
|
|
17
18
|
BuildAppResult,
|
|
@@ -68,14 +69,14 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
|
|
|
68
69
|
// doesn't exist in the runtime context) are skipped silently — they only
|
|
69
70
|
// affect the Bun.build() client bundle, not server-side rendering.
|
|
70
71
|
for (const plugin of options.plugins ?? []) {
|
|
72
|
+
const { buildOnly, ...runtimePlugin } = plugin as FurinPlugin;
|
|
73
|
+
if (buildOnly) {
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
71
76
|
try {
|
|
72
|
-
Bun.plugin(
|
|
77
|
+
Bun.plugin(runtimePlugin);
|
|
73
78
|
} catch (err) {
|
|
74
|
-
|
|
75
|
-
// does not exist in the runtime context) are expected to throw here —
|
|
76
|
-
// they only affect the Bun.build() client bundle, not server-side rendering.
|
|
77
|
-
// Log at debug level so genuine plugin registration errors remain visible.
|
|
78
|
-
console.debug("[furin] Skipped build-only plugin at runtime:", err);
|
|
79
|
+
console.debug("[furin] Skipped plugin at runtime:", err);
|
|
79
80
|
}
|
|
80
81
|
}
|
|
81
82
|
|
|
@@ -117,7 +118,7 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
|
|
|
117
118
|
routes,
|
|
118
119
|
rootDir,
|
|
119
120
|
buildRoot,
|
|
120
|
-
root
|
|
121
|
+
root,
|
|
121
122
|
serverEntry,
|
|
122
123
|
options
|
|
123
124
|
);
|
package/src/build/route-types.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
-
import type { ResolvedRoute } from "../router";
|
|
3
|
+
import type { ResolvedRoute } from "../server/router/index.ts";
|
|
4
4
|
|
|
5
5
|
/** @internal Exported for unit testing only. */
|
|
6
6
|
export function patternToTypeString(pattern: string): string {
|
|
@@ -22,7 +22,11 @@ export function schemaToTypeString(schema: unknown): string {
|
|
|
22
22
|
}
|
|
23
23
|
const s = schema as Record<string, unknown>;
|
|
24
24
|
if (s.anyOf && Array.isArray(s.anyOf)) {
|
|
25
|
-
const parts =
|
|
25
|
+
const parts: string[] = [];
|
|
26
|
+
for (const item of s.anyOf as unknown[]) {
|
|
27
|
+
const t = schemaToTypeString(item);
|
|
28
|
+
if (t !== "null") parts.push(t);
|
|
29
|
+
}
|
|
26
30
|
return parts.join(" | ") || "unknown";
|
|
27
31
|
}
|
|
28
32
|
switch (s.type) {
|
|
@@ -50,6 +54,19 @@ export function schemaToTypeString(schema: unknown): string {
|
|
|
50
54
|
}
|
|
51
55
|
}
|
|
52
56
|
|
|
57
|
+
function tagKeyToPropertyName(tag: string): string {
|
|
58
|
+
return /^[$A-Z_a-z][$\w]*$/.test(tag) ? tag : JSON.stringify(tag);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function tagToStringLiteral(tag: string): string {
|
|
62
|
+
// Use JSON.stringify for robust escaping of control chars, unicode
|
|
63
|
+
// separators, backslashes and quotes, then convert double quotes to single.
|
|
64
|
+
const json = JSON.stringify(tag);
|
|
65
|
+
// json is double-quoted; convert to single-quoted literal by escaping
|
|
66
|
+
// any contained single quotes and swapping the outer quotes.
|
|
67
|
+
return `'${json.slice(1, -1).replaceAll("'", "\\'")}'`;
|
|
68
|
+
}
|
|
69
|
+
|
|
53
70
|
/**
|
|
54
71
|
* Generates furin-env.d.ts at the project root — augments RouteManifest
|
|
55
72
|
* in furin/link so that <Link to="..."> has type-safe autocompletion and
|
|
@@ -60,7 +77,8 @@ export function schemaToTypeString(schema: unknown): string {
|
|
|
60
77
|
*/
|
|
61
78
|
/** @internal Exported for unit testing only. */
|
|
62
79
|
export function writeRouteTypes(routes: ResolvedRoute[], projectRoot: string): void {
|
|
63
|
-
const
|
|
80
|
+
const sortedRoutes = [...routes].sort((a, b) => a.pattern.localeCompare(b.pattern));
|
|
81
|
+
const entries = sortedRoutes.map((r) => {
|
|
64
82
|
const typeKey = patternToTypeString(r.pattern);
|
|
65
83
|
const isDynamic = typeKey.startsWith("`");
|
|
66
84
|
const querySchema = r.routeChain?.find((rt) => rt.query)?.query;
|
|
@@ -70,6 +88,14 @@ export function writeRouteTypes(routes: ResolvedRoute[], projectRoot: string): v
|
|
|
70
88
|
: ` ${typeKey}: { search?: ${searchType} }`;
|
|
71
89
|
});
|
|
72
90
|
|
|
91
|
+
const sortedTags = [...new Set(routes.flatMap((route) => route.tags ?? []))].sort();
|
|
92
|
+
const tagBlock =
|
|
93
|
+
sortedTags.length > 0
|
|
94
|
+
? `\n\ndeclare module "@teyik0/furin" {\n interface FurinCacheTags {\n${sortedTags
|
|
95
|
+
.map((tag) => ` ${tagKeyToPropertyName(tag)}: ${tagToStringLiteral(tag)};`)
|
|
96
|
+
.join("\n")}\n }\n}`
|
|
97
|
+
: "";
|
|
98
|
+
|
|
73
99
|
const content = `// Auto-generated by Furin. Do not edit manually.
|
|
74
100
|
/// <reference types="@teyik0/furin/env" />
|
|
75
101
|
import "@teyik0/furin/link";
|
|
@@ -78,7 +104,7 @@ declare module "@teyik0/furin/link" {
|
|
|
78
104
|
interface RouteManifest {
|
|
79
105
|
${entries.join(";\n")};
|
|
80
106
|
}
|
|
81
|
-
}
|
|
107
|
+
}${tagBlock}
|
|
82
108
|
`;
|
|
83
109
|
|
|
84
110
|
const typesPath = join(projectRoot, "furin-env.d.ts");
|