@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
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
import { type AnyElysia, type Context, Elysia, t } from "elysia";
|
|
2
|
+
import type { AnySchema } from "elysia/types";
|
|
3
|
+
import { toCrossJSON, toCrossJSONAsync } from "seroval";
|
|
4
|
+
import { computeErrorDigest } from "../../shared/digest.ts";
|
|
5
|
+
import { autoInvalidateRegistry } from "../auto-invalidate/registry.ts";
|
|
6
|
+
import { useLogger } from "../context-logger.ts";
|
|
7
|
+
import { resolvePath } from "../render/assemble.ts";
|
|
8
|
+
import {
|
|
9
|
+
handleISR,
|
|
10
|
+
prerenderSSG,
|
|
11
|
+
renderSSR,
|
|
12
|
+
runLoaders,
|
|
13
|
+
serializeDeferredRejection,
|
|
14
|
+
} from "../render/index.ts";
|
|
15
|
+
import { extractTitle } from "../render/shell.ts";
|
|
16
|
+
import { IS_DEV } from "../runtime-env.ts";
|
|
17
|
+
import { handleDevRequest } from "./hmr.ts";
|
|
18
|
+
import { buildRouteMatcher } from "./patterns.ts";
|
|
19
|
+
import {
|
|
20
|
+
applySchemaDefaults,
|
|
21
|
+
detectQueryDefaultRedirect,
|
|
22
|
+
mergeRouteSchemas,
|
|
23
|
+
parseDataEndpointPath,
|
|
24
|
+
queryDefaultRedirectHook,
|
|
25
|
+
} from "./schemas.ts";
|
|
26
|
+
import type { ResolvedRoute, RootLayout } from "./types.ts";
|
|
27
|
+
|
|
28
|
+
/** @internal Handles a production SSG route — sets ETags, Cache-Control, and Cache-Tag. */
|
|
29
|
+
async function handleSSGRequest(
|
|
30
|
+
route: ResolvedRoute,
|
|
31
|
+
ctx: Context,
|
|
32
|
+
root: RootLayout,
|
|
33
|
+
buildId: string
|
|
34
|
+
): Promise<unknown> {
|
|
35
|
+
const origin = new URL(ctx.request.url).origin;
|
|
36
|
+
const entry = await prerenderSSG(route, ctx.params, root, origin, undefined);
|
|
37
|
+
|
|
38
|
+
// Loader issued a redirect — forward it directly to the client.
|
|
39
|
+
if (entry instanceof Response) {
|
|
40
|
+
return entry;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const resolvedPath = resolvePath(route.pattern, ctx.params ?? {});
|
|
44
|
+
|
|
45
|
+
// ETag: "buildId:cachedAt" — unique per render cycle, changes after revalidatePath
|
|
46
|
+
const etag = buildId ? `"${buildId}:${entry.cachedAt}"` : null;
|
|
47
|
+
if (etag && ctx.request.headers.get("if-none-match") === etag) {
|
|
48
|
+
ctx.set.status = 304;
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
ctx.set.headers["content-type"] = "text/html; charset=utf-8";
|
|
53
|
+
// Browser: max-age=0 + must-revalidate → always validates via ETag (304 = free)
|
|
54
|
+
// CDN: s-maxage=31536000 → cache for 1 year, purge via revalidatePath + purger
|
|
55
|
+
ctx.set.headers["cache-control"] = "public, max-age=0, must-revalidate, s-maxage=31536000";
|
|
56
|
+
if (etag) {
|
|
57
|
+
ctx.set.headers.etag = etag;
|
|
58
|
+
}
|
|
59
|
+
ctx.set.headers["cache-tag"] = resolvedPath;
|
|
60
|
+
return entry.html;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function createRoutePlugin(
|
|
64
|
+
route: ResolvedRoute,
|
|
65
|
+
root: RootLayout,
|
|
66
|
+
buildId?: string
|
|
67
|
+
): AnyElysia {
|
|
68
|
+
const resolvedBuildId = buildId ?? "";
|
|
69
|
+
const { pattern, routeChain } = route;
|
|
70
|
+
|
|
71
|
+
const allParams = mergeRouteSchemas(routeChain, "params");
|
|
72
|
+
const allQuery = mergeRouteSchemas(routeChain, "query");
|
|
73
|
+
const hasQuerySchema = !!allQuery;
|
|
74
|
+
|
|
75
|
+
// Guard and handler MUST live in the same Elysia scope so that validation
|
|
76
|
+
// (including default-filling) applies to the route handler's ctx.query.
|
|
77
|
+
const plugin = new Elysia();
|
|
78
|
+
|
|
79
|
+
if (allParams || allQuery) {
|
|
80
|
+
plugin.guard({
|
|
81
|
+
params: allParams as AnySchema,
|
|
82
|
+
query: allQuery as AnySchema,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
plugin.get(pattern, (ctx) => {
|
|
87
|
+
// Redirect when Elysia applied query defaults (validator-agnostic)
|
|
88
|
+
if (hasQuerySchema) {
|
|
89
|
+
const redirect = queryDefaultRedirectHook(ctx);
|
|
90
|
+
if (redirect) {
|
|
91
|
+
return redirect;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Dev mode: re-imports page + layouts on every request via the
|
|
96
|
+
// ?furin-server cache-buster, then dispatches into one of:
|
|
97
|
+
// - renderDevISRWithLoaderCache (mode === "isr")
|
|
98
|
+
// - renderDevSSGWithLoaderCache (mode === "ssg")
|
|
99
|
+
// - renderSSR (otherwise)
|
|
100
|
+
//
|
|
101
|
+
// Only the LOADER OUTPUT is cached in dev — HTML is always re-assembled
|
|
102
|
+
// fresh so the response always embeds the latest Bun client chunk URL.
|
|
103
|
+
// This avoids the "infinite reload loop" footgun where a cached ISR/SSG
|
|
104
|
+
// HTML response held an OLD chunk URL after Bun rebundled. The dev
|
|
105
|
+
// cache is invalidated source-aware via `isDevLoaderCacheValid`
|
|
106
|
+
// (mtime-checked dependency walk on every read).
|
|
107
|
+
if (IS_DEV) {
|
|
108
|
+
return handleDevRequest(route, ctx, root);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (route.mode === "ssg") {
|
|
112
|
+
return handleSSGRequest(route, ctx, root, resolvedBuildId);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (route.mode === "isr") {
|
|
116
|
+
ctx.set.headers["cache-tag"] = resolvePath(route.pattern, ctx.params ?? {});
|
|
117
|
+
return handleISR(route, ctx, root, resolvedBuildId);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return renderSSR(route, ctx, root, undefined);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
return plugin;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Elysia plugin that handles `GET /_furin/data?path=<logicalHref>`.
|
|
128
|
+
*
|
|
129
|
+
* Returns an NDJSON stream (one-line, v1) produced by `toCrossJSONAsync`:
|
|
130
|
+
* Line 0 — CrossJSON serialisation of `{ ...syncData, ...deferredPromises }`
|
|
131
|
+
*
|
|
132
|
+
* The `deferredPromises` values are awaited by `toCrossJSONAsync` before
|
|
133
|
+
* serialising, so the client receives all data resolved in one round-trip.
|
|
134
|
+
* SPA navigation calls this endpoint via `parseDeferredNdjson` in
|
|
135
|
+
* `router-provider.tsx`.
|
|
136
|
+
*
|
|
137
|
+
* Special fields emitted alongside data:
|
|
138
|
+
* - `__furinStatus: 404` — when the loader called `notFound()`
|
|
139
|
+
* - `__furinNotFound` — not-found payload
|
|
140
|
+
* - `__furinRedirect` — logical path after a server-side redirect
|
|
141
|
+
*/
|
|
142
|
+
export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
|
|
143
|
+
const plugin = new Elysia();
|
|
144
|
+
const matchRoute = buildRouteMatcher(routes);
|
|
145
|
+
|
|
146
|
+
plugin.get(
|
|
147
|
+
"/_furin/data",
|
|
148
|
+
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: data endpoint handler validates path, resolves loaders, handles deferred/SPA/ISR modes — each branch is a distinct protocol case; splitting would spread context across many functions
|
|
149
|
+
async (ctx) => {
|
|
150
|
+
const rawPath = ctx.query.path;
|
|
151
|
+
if (!rawPath || typeof rawPath !== "string") {
|
|
152
|
+
return new Response("Missing required query param: path", { status: 400 });
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const parsed = parseDataEndpointPath(rawPath);
|
|
156
|
+
if (!parsed) {
|
|
157
|
+
return new Response("Invalid path", { status: 400 });
|
|
158
|
+
}
|
|
159
|
+
const { url, pathname } = parsed;
|
|
160
|
+
|
|
161
|
+
// Rewrite the request-scoped wide event so logs / drains report the
|
|
162
|
+
// *logical* path the user navigated to (e.g. "/board/123/card/456")
|
|
163
|
+
// instead of the technical "/_furin/data" transport URL. We set this
|
|
164
|
+
// before the route-match check so 404s also surface the attempted path
|
|
165
|
+
// — otherwise monitoring just sees "GET /_furin/data 404" with no clue.
|
|
166
|
+
const wideEventLog = useLogger();
|
|
167
|
+
wideEventLog.set({ path: rawPath });
|
|
168
|
+
|
|
169
|
+
// Precompiled at plugin creation: route regexes are built once, sorted
|
|
170
|
+
// most-specific first, then the hot path only executes regex matches.
|
|
171
|
+
const matched = matchRoute(pathname);
|
|
172
|
+
|
|
173
|
+
if (!matched) {
|
|
174
|
+
return new Response("Route not found", { status: 404 });
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Now that we know the matched pattern, add it as a stable aggregation
|
|
178
|
+
// key for drains (e.g. "p99 latency by route").
|
|
179
|
+
wideEventLog.set({ routePattern: matched.route.pattern });
|
|
180
|
+
|
|
181
|
+
// Build a synthetic Elysia-compatible context for the matched route.
|
|
182
|
+
// Loaders receive request, params, query, set, headers, and cookie.
|
|
183
|
+
// Build the synthetic URL from the parsed `pathname + search` only —
|
|
184
|
+
// never from `rawPath` directly — so an attacker cannot smuggle a
|
|
185
|
+
// foreign origin into `syntheticRequest.url`.
|
|
186
|
+
const syntheticRequest = new Request(new URL(pathname + url.search, ctx.request.url));
|
|
187
|
+
const syntheticSet = { headers: {} as Record<string, string>, status: 200 as number };
|
|
188
|
+
const syntheticCtx = {
|
|
189
|
+
request: syntheticRequest,
|
|
190
|
+
params: matched.params,
|
|
191
|
+
query: Object.fromEntries(url.searchParams),
|
|
192
|
+
set: syntheticSet,
|
|
193
|
+
headers: ctx.headers,
|
|
194
|
+
cookie: ctx.cookie,
|
|
195
|
+
path: pathname,
|
|
196
|
+
// Loader-emitted redirects flow through `runLoaders` → `result.type
|
|
197
|
+
// === "redirect"` and are converted to NDJSON below. The Response we
|
|
198
|
+
// return here only has to be detectable by that pipeline.
|
|
199
|
+
redirect: (location: string, status?: number) =>
|
|
200
|
+
new Response(null, { status: status ?? 302, headers: { location } }),
|
|
201
|
+
// Synthetic `status` helper: numeric codes only. Callers that reach
|
|
202
|
+
// this endpoint never dispatch a string-keyed status; rejecting them
|
|
203
|
+
// is safer than coercing via `Number(code)` and silently producing
|
|
204
|
+
// `NaN`. Query-default redirects no longer flow through this helper —
|
|
205
|
+
// they are detected via `detectQueryDefaultRedirect` below.
|
|
206
|
+
status: (code: number) => new Response(null, { status: code }),
|
|
207
|
+
} as unknown as Context;
|
|
208
|
+
|
|
209
|
+
// Normalize params and query through the same merged schemas used by
|
|
210
|
+
// createRoutePlugin so loaders see identical typed/defaulted inputs.
|
|
211
|
+
const mergedParams = mergeRouteSchemas(matched.route.routeChain, "params");
|
|
212
|
+
const mergedQuery = mergeRouteSchemas(matched.route.routeChain, "query");
|
|
213
|
+
syntheticCtx.params = applySchemaDefaults(
|
|
214
|
+
mergedParams as Record<string, unknown> | undefined,
|
|
215
|
+
syntheticCtx.params as Record<string, unknown>
|
|
216
|
+
) as Record<string, string>;
|
|
217
|
+
syntheticCtx.query = applySchemaDefaults(
|
|
218
|
+
mergedQuery as Record<string, unknown> | undefined,
|
|
219
|
+
syntheticCtx.query as Record<string, unknown>
|
|
220
|
+
) as Record<string, string>;
|
|
221
|
+
|
|
222
|
+
// Query-default redirect: detect via the pure helper so we can emit the
|
|
223
|
+
// NDJSON `__furinRedirect` sentinel (the SPA client cannot parse a real
|
|
224
|
+
// HTTP 302 — it never sees one because `parseDeferredNdjson` reads the
|
|
225
|
+
// body, not the redirect chain).
|
|
226
|
+
if (mergedQuery) {
|
|
227
|
+
const redirectLocation = detectQueryDefaultRedirect(
|
|
228
|
+
syntheticRequest,
|
|
229
|
+
syntheticCtx.query as Record<string, unknown>
|
|
230
|
+
);
|
|
231
|
+
if (redirectLocation) {
|
|
232
|
+
const serialized = await toCrossJSONAsync({ __furinRedirect: redirectLocation });
|
|
233
|
+
return new Response(`${JSON.stringify(serialized)}\n`, {
|
|
234
|
+
headers: { "content-type": "application/x-ndjson" },
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const result = await runLoaders(matched.route, syntheticCtx);
|
|
240
|
+
|
|
241
|
+
// Keep the auto-invalidate registry in sync with whatever path was just
|
|
242
|
+
// served, so subsequent `revalidateTag(...)` calls (e.g. from a mutation
|
|
243
|
+
// afterHandle) can still find this URL by tag. Without this, a SPA-only
|
|
244
|
+
// navigation path (which never goes through the full-HTML render that
|
|
245
|
+
// also registers tags) would silently fall off the registry — the first
|
|
246
|
+
// mutation invalidates and unregisters via the cache `onDelete` hook,
|
|
247
|
+
// the next SPA fetch re-loads but does not re-register, and from then
|
|
248
|
+
// on `revalidateTag` finds no path to invalidate.
|
|
249
|
+
if (result.type === "data") {
|
|
250
|
+
autoInvalidateRegistry.registerLoaderTags(pathname, matched.route.tags);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
if (result.type === "redirect") {
|
|
254
|
+
// Encode the redirect target as a special field for the client to follow
|
|
255
|
+
const redirectUrl = new URL(
|
|
256
|
+
result.response.headers.get("location") ?? "/",
|
|
257
|
+
ctx.request.url
|
|
258
|
+
);
|
|
259
|
+
const serialized = await toCrossJSONAsync({
|
|
260
|
+
__furinRedirect: redirectUrl.pathname + redirectUrl.search,
|
|
261
|
+
});
|
|
262
|
+
return new Response(`${JSON.stringify(serialized)}\n`, {
|
|
263
|
+
headers: { "content-type": "application/x-ndjson" },
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
if (result.type === "not-found") {
|
|
268
|
+
const serialized = await toCrossJSONAsync({
|
|
269
|
+
__furinStatus: 404,
|
|
270
|
+
__furinNotFound: { message: result.error.message, data: result.error.data },
|
|
271
|
+
});
|
|
272
|
+
return new Response(`${JSON.stringify(serialized)}\n`, {
|
|
273
|
+
status: 200,
|
|
274
|
+
headers: { "content-type": "application/x-ndjson" },
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
if (result.type === "error") {
|
|
279
|
+
// Compute the digest server-side ONCE so:
|
|
280
|
+
// 1. The HTTP response body carries it (client error UI displays the
|
|
281
|
+
// same id the server logs).
|
|
282
|
+
// 2. The server-log line below uses the SAME digest a user would see
|
|
283
|
+
// on screen, enabling support correlation.
|
|
284
|
+
// Recomputing client-side from a synthetic message + stack would yield
|
|
285
|
+
// a different hash — see boundaries.tsx for the digest precedence.
|
|
286
|
+
const digest = computeErrorDigest(result.error);
|
|
287
|
+
const serialized = await toCrossJSONAsync({
|
|
288
|
+
__furinError: {
|
|
289
|
+
digest,
|
|
290
|
+
message: result.message,
|
|
291
|
+
status: result.status,
|
|
292
|
+
},
|
|
293
|
+
});
|
|
294
|
+
return new Response(`${JSON.stringify(serialized)}\n`, {
|
|
295
|
+
status: result.status,
|
|
296
|
+
headers: { "content-type": "application/x-ndjson" },
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// Resolve the page title server-side: head() never runs in the browser,
|
|
301
|
+
// so SPA navigation depends on the endpoint shipping it as __furinTitle.
|
|
302
|
+
const syncDataWithTitle = withResolvedTitle(matched.route, result.syncData);
|
|
303
|
+
|
|
304
|
+
if (result.deferredPromises) {
|
|
305
|
+
return new Response(
|
|
306
|
+
createDeferredNdjsonStream(syncDataWithTitle, result.deferredPromises),
|
|
307
|
+
{
|
|
308
|
+
// Loader headers first so custom headers survive; the NDJSON
|
|
309
|
+
// content-type is framework-owned and must win — a loader cannot be
|
|
310
|
+
// allowed to mislabel the data-endpoint payload.
|
|
311
|
+
headers: {
|
|
312
|
+
...result.headers,
|
|
313
|
+
"content-type": "application/x-ndjson",
|
|
314
|
+
},
|
|
315
|
+
}
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// No deferred fields: emit the single-line payload used by the legacy path.
|
|
320
|
+
const serialized = await toCrossJSONAsync(syncDataWithTitle);
|
|
321
|
+
return new Response(`${JSON.stringify(serialized)}\n`, {
|
|
322
|
+
headers: {
|
|
323
|
+
...result.headers,
|
|
324
|
+
"content-type": "application/x-ndjson",
|
|
325
|
+
},
|
|
326
|
+
});
|
|
327
|
+
},
|
|
328
|
+
{
|
|
329
|
+
query: t.Object({ path: t.Optional(t.String()) }),
|
|
330
|
+
}
|
|
331
|
+
);
|
|
332
|
+
|
|
333
|
+
return plugin;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Runs the matched page's `head()` against the resolved sync data and, when it
|
|
338
|
+
* yields a title, returns a copy of `syncData` carrying the reserved
|
|
339
|
+
* `__furinTitle` field. `head()` never executes in the browser, so this is the
|
|
340
|
+
* only channel through which SPA navigation can learn the new document title.
|
|
341
|
+
*
|
|
342
|
+
* Deferred fields are absent from `syncData` (they are still Promises), so a
|
|
343
|
+
* `head()` that reads one sees `undefined` — titles should be derived from
|
|
344
|
+
* synchronous loader data. A throwing `head()` is swallowed: a missing title
|
|
345
|
+
* must never break the data response.
|
|
346
|
+
*/
|
|
347
|
+
function withResolvedTitle(
|
|
348
|
+
route: ResolvedRoute,
|
|
349
|
+
syncData: Record<string, unknown>
|
|
350
|
+
): Record<string, unknown> {
|
|
351
|
+
const head = route.page.head;
|
|
352
|
+
if (!head) {
|
|
353
|
+
return syncData;
|
|
354
|
+
}
|
|
355
|
+
let title: string | undefined;
|
|
356
|
+
try {
|
|
357
|
+
title = extractTitle(head(syncData).meta);
|
|
358
|
+
} catch {
|
|
359
|
+
return syncData;
|
|
360
|
+
}
|
|
361
|
+
if (title === undefined) {
|
|
362
|
+
return syncData;
|
|
363
|
+
}
|
|
364
|
+
return { ...syncData, __furinTitle: title };
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function createDeferredNdjsonStream(
|
|
368
|
+
syncData: Record<string, unknown>,
|
|
369
|
+
deferredPromises: Record<string, Promise<unknown>>
|
|
370
|
+
): ReadableStream<Uint8Array> {
|
|
371
|
+
const enc = new TextEncoder();
|
|
372
|
+
const entries = Object.entries(deferredPromises);
|
|
373
|
+
|
|
374
|
+
return new ReadableStream<Uint8Array>({
|
|
375
|
+
async start(controller) {
|
|
376
|
+
const initial = toCrossJSON({
|
|
377
|
+
...syncData,
|
|
378
|
+
__furinDeferredKeys: entries.map(([key]) => key),
|
|
379
|
+
});
|
|
380
|
+
controller.enqueue(enc.encode(`${JSON.stringify(initial)}\n`));
|
|
381
|
+
|
|
382
|
+
await Promise.all(
|
|
383
|
+
entries.map(async ([key, promise]) => {
|
|
384
|
+
try {
|
|
385
|
+
const value = await promise;
|
|
386
|
+
controller.enqueue(
|
|
387
|
+
enc.encode(
|
|
388
|
+
`${JSON.stringify({ key, action: "resolve", value: toCrossJSON(value) })}\n`
|
|
389
|
+
)
|
|
390
|
+
);
|
|
391
|
+
} catch (err) {
|
|
392
|
+
const normalized = await serializeDeferredRejection(err);
|
|
393
|
+
const value = toCrossJSON(normalized);
|
|
394
|
+
controller.enqueue(enc.encode(`${JSON.stringify({ key, action: "reject", value })}\n`));
|
|
395
|
+
}
|
|
396
|
+
})
|
|
397
|
+
);
|
|
398
|
+
controller.close();
|
|
399
|
+
},
|
|
400
|
+
});
|
|
401
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import type { Context } from "elysia";
|
|
2
|
+
import { t } from "elysia";
|
|
3
|
+
import type { AnySchema } from "elysia/types";
|
|
4
|
+
import type { RuntimeRoute } from "../../client.ts";
|
|
5
|
+
|
|
6
|
+
// ── Query-default redirect ──────────────────────────────────────────────────
|
|
7
|
+
// Validator-agnostic: after Elysia applies defaults (TypeBox, Zod, Valibot…),
|
|
8
|
+
// compare the raw URL query keys with the resolved ctx.query keys. If ctx.query
|
|
9
|
+
// contains keys absent from the URL, defaults were applied → 302 redirect to
|
|
10
|
+
// the canonical URL so the address bar always reflects the actual app state.
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Detects whether a validator filled in default query values that the original
|
|
14
|
+
* URL did not carry, and returns the canonical `pathname + search` to redirect
|
|
15
|
+
* to — or `undefined` when the URL already reflects the resolved query.
|
|
16
|
+
*
|
|
17
|
+
* Pure helper extracted from `queryDefaultRedirectHook` so the `/_furin/data`
|
|
18
|
+
* NDJSON endpoint can detect the same condition without going through
|
|
19
|
+
* Elysia's `status()` shim (which only emits HTTP 302s, unparseable by the
|
|
20
|
+
* SPA client).
|
|
21
|
+
*
|
|
22
|
+
* @internal Exported for unit testing.
|
|
23
|
+
*/
|
|
24
|
+
export function detectQueryDefaultRedirect(
|
|
25
|
+
request: Request,
|
|
26
|
+
resolvedQuery: Record<string, unknown>
|
|
27
|
+
): string | undefined {
|
|
28
|
+
const queryKeys = Object.keys(resolvedQuery);
|
|
29
|
+
if (queryKeys.length === 0) {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const rawParams = new URL(request.url).searchParams;
|
|
34
|
+
let needsRedirect = false;
|
|
35
|
+
for (const key of queryKeys) {
|
|
36
|
+
if (!rawParams.has(key) && resolvedQuery[key] != null) {
|
|
37
|
+
needsRedirect = true;
|
|
38
|
+
break;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
if (!needsRedirect) {
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const url = new URL(request.url);
|
|
46
|
+
for (const [k, v] of Object.entries(resolvedQuery)) {
|
|
47
|
+
if (v != null) {
|
|
48
|
+
url.searchParams.set(k, String(v));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return url.pathname + url.search;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Parses the `?path=` argument of `/_furin/data`, rejecting absolute /
|
|
56
|
+
* protocol-relative inputs that would let a caller smuggle a foreign origin
|
|
57
|
+
* into the synthetic loader request.
|
|
58
|
+
*
|
|
59
|
+
* Returns `{ url, pathname }` on success, or `undefined` when the input is
|
|
60
|
+
* unsafe (the caller should reply 400). `new URL(rawPath, base)` ignores the
|
|
61
|
+
* base when `rawPath` is itself absolute, so without these prefix and origin
|
|
62
|
+
* checks a value like `https://evil.com/foo` would propagate to
|
|
63
|
+
* `syntheticRequest.url`.
|
|
64
|
+
*
|
|
65
|
+
* @internal Exported for unit testing.
|
|
66
|
+
*/
|
|
67
|
+
export function parseDataEndpointPath(rawPath: string): { url: URL; pathname: string } | undefined {
|
|
68
|
+
if (rawPath.includes("://") || rawPath.startsWith("//")) {
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
let url: URL;
|
|
72
|
+
try {
|
|
73
|
+
url = new URL(rawPath, "http://localhost");
|
|
74
|
+
} catch {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (url.origin !== "http://localhost") {
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
return { url, pathname: url.pathname };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** @internal Exported for unit testing. */
|
|
84
|
+
export function queryDefaultRedirectHook({ request, query, status, set }: Context) {
|
|
85
|
+
const location = detectQueryDefaultRedirect(request, query as Record<string, unknown>);
|
|
86
|
+
if (!location) {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
set.headers.location = location;
|
|
90
|
+
return status("Found");
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Standard structural keys on a TObject — everything else is a user-supplied option
|
|
94
|
+
// (e.g. additionalProperties, $id, description, title) and must be preserved.
|
|
95
|
+
const TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Merges TObject schemas from all routeChain entries for a given key.
|
|
99
|
+
* Properties are spread left-to-right (leaf wins on key conflict).
|
|
100
|
+
* Object-level options (additionalProperties, $id, description, …) are also
|
|
101
|
+
* merged with the same leaf-wins semantics so they are not silently dropped.
|
|
102
|
+
* Returns undefined when no entry in the chain defines the key.
|
|
103
|
+
*
|
|
104
|
+
* @internal Exported for unit testing.
|
|
105
|
+
*/
|
|
106
|
+
export function mergeRouteSchemas(
|
|
107
|
+
routeChain: RuntimeRoute[],
|
|
108
|
+
key: "params" | "query"
|
|
109
|
+
): AnySchema | undefined {
|
|
110
|
+
const schemas = routeChain.flatMap((r) => (r[key] ? [r[key]] : [])) as Record<string, unknown>[];
|
|
111
|
+
|
|
112
|
+
if (schemas.length === 0) {
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (schemas.length === 1) {
|
|
116
|
+
return schemas[0] as AnySchema;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const mergedProperties = Object.assign(
|
|
120
|
+
{},
|
|
121
|
+
...schemas.map((s) => (s.properties as Record<string, unknown>) ?? {})
|
|
122
|
+
);
|
|
123
|
+
|
|
124
|
+
const mergedOptions = Object.assign(
|
|
125
|
+
{},
|
|
126
|
+
...schemas.map((s) =>
|
|
127
|
+
Object.fromEntries(Object.entries(s).filter(([k]) => !TOBJECT_STRUCTURAL_KEYS.has(k)))
|
|
128
|
+
)
|
|
129
|
+
);
|
|
130
|
+
|
|
131
|
+
return t.Object(mergedProperties, mergedOptions) as AnySchema;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Applies top-level `default` values from a TypeBox TObject schema to a
|
|
136
|
+
* values record. Used in the `/_furin/data` endpoint so loaders see the same
|
|
137
|
+
* defaulted query objects that the SSR path produces via Elysia's guard.
|
|
138
|
+
*/
|
|
139
|
+
export function applySchemaDefaults(
|
|
140
|
+
schema: Record<string, unknown> | undefined,
|
|
141
|
+
values: Record<string, unknown>
|
|
142
|
+
): Record<string, unknown> {
|
|
143
|
+
if (!schema || typeof schema !== "object") {
|
|
144
|
+
return values;
|
|
145
|
+
}
|
|
146
|
+
const s = schema as Record<string, unknown>;
|
|
147
|
+
if (s.type !== "object" || !s.properties || typeof s.properties !== "object") {
|
|
148
|
+
return values;
|
|
149
|
+
}
|
|
150
|
+
const result = { ...values };
|
|
151
|
+
const properties = s.properties as Record<string, Record<string, unknown>>;
|
|
152
|
+
for (const [key, propSchema] of Object.entries(properties)) {
|
|
153
|
+
if (
|
|
154
|
+
!(key in result) &&
|
|
155
|
+
propSchema &&
|
|
156
|
+
typeof propSchema === "object" &&
|
|
157
|
+
"default" in propSchema
|
|
158
|
+
) {
|
|
159
|
+
result[key] = propSchema.default;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return result;
|
|
163
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { RuntimePage, RuntimeRoute } from "../../client.ts";
|
|
2
|
+
import type { ErrorComponent } from "../../shared/error.ts";
|
|
3
|
+
import type { NotFoundComponent } from "../../shared/not-found.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A single directory-scoped boundary declaration.
|
|
7
|
+
*
|
|
8
|
+
* Each entry represents ONE directory on the path from `pagesDir` to the page
|
|
9
|
+
* file. `error` / `notFound` hold the components defined IN THAT DIRECTORY
|
|
10
|
+
* only — never inherited from a parent. This 1:1 tie between directory and
|
|
11
|
+
* entry is what lets the render layer insert React error boundaries at the
|
|
12
|
+
* exact nesting level where the user authored them (Next.js app-router model).
|
|
13
|
+
*/
|
|
14
|
+
export interface SegmentBoundary {
|
|
15
|
+
/** 0 = `pagesDir`; increments with each nested subdirectory. */
|
|
16
|
+
depth: number;
|
|
17
|
+
error?: ErrorComponent;
|
|
18
|
+
/**
|
|
19
|
+
* Absolute path to the `error.tsx` module, when present. Carried alongside
|
|
20
|
+
* the component so the client hydrate entry can emit a static `import`
|
|
21
|
+
* statement for each unique convention file — a component reference alone
|
|
22
|
+
* can't survive the server→client boundary.
|
|
23
|
+
*/
|
|
24
|
+
errorPath?: string;
|
|
25
|
+
notFound?: NotFoundComponent;
|
|
26
|
+
/** Absolute path to the `not-found.tsx` module, when present. */
|
|
27
|
+
notFoundPath?: string;
|
|
28
|
+
/** Absolute directory path. */
|
|
29
|
+
path: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ResolvedRoute {
|
|
33
|
+
error?: ErrorComponent;
|
|
34
|
+
isrCache?: { html: string; generatedAt: number; revalidate: number };
|
|
35
|
+
mode: "ssr" | "ssg" | "isr";
|
|
36
|
+
notFound?: NotFoundComponent;
|
|
37
|
+
page: RuntimePage;
|
|
38
|
+
path: string;
|
|
39
|
+
pattern: string;
|
|
40
|
+
routeChain: RuntimeRoute[];
|
|
41
|
+
/**
|
|
42
|
+
* Per-directory boundary chain, ordered shallow → deep. Only directories
|
|
43
|
+
* that DECLARE at least one of `error.tsx` / `not-found.tsx` are included;
|
|
44
|
+
* directories without conventions are skipped. Empty when no conventions
|
|
45
|
+
* exist anywhere in the path.
|
|
46
|
+
*/
|
|
47
|
+
segmentBoundaries: SegmentBoundary[];
|
|
48
|
+
ssgHtml?: string;
|
|
49
|
+
tags?: string[];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface RootLayout {
|
|
53
|
+
error?: ErrorComponent;
|
|
54
|
+
errorPath?: string;
|
|
55
|
+
notFound?: NotFoundComponent;
|
|
56
|
+
notFoundPath?: string;
|
|
57
|
+
path: string;
|
|
58
|
+
route: RuntimeRoute;
|
|
59
|
+
}
|