@teyik0/furin 0.1.0-alpha.13 → 0.1.0-alpha.14
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/README.md +14 -232
- package/dist/await.d.ts +67 -0
- package/dist/build/index.js +2013 -191
- package/dist/cli/index.js +2007 -190
- package/dist/client.d.ts +33 -2
- package/dist/client.js +65 -1
- package/dist/deferred-ndjson.d.ts +32 -0
- package/dist/error.d.ts +14 -0
- package/dist/furin.d.ts +3 -0
- package/dist/furin.js +2684 -318
- package/dist/lang-detect.d.ts +5 -0
- package/dist/link.d.ts +1 -0
- package/dist/link.js +1453 -95
- package/dist/plugin/index.js +96 -25
- package/dist/plugin/transform-client.d.ts +2 -1
- package/dist/render/assemble.d.ts +32 -0
- package/dist/render/cache.d.ts +7 -0
- package/dist/render/element.d.ts +17 -1
- package/dist/render/index.d.ts +10 -1
- package/dist/render/index.ts +247 -44
- package/dist/render/loaders.d.ts +46 -3
- package/dist/render/shell.d.ts +16 -6
- package/dist/render/shell.ts +27 -12
- package/dist/router-provider.d.ts +86 -18
- package/dist/router.d.ts +63 -0
- package/dist/router.js +2768 -317
- package/dist/router.ts +543 -54
- package/dist/server-error.d.ts +12 -0
- package/dist/utils.d.ts +7 -0
- package/package.json +8 -7
- package/src/adapter/bun.ts +3 -3
- package/src/adapter/static.ts +73 -31
- package/src/await.tsx +175 -0
- package/src/build/client.ts +4 -8
- package/src/build/hydrate.ts +67 -1
- package/src/build/route-types.ts +5 -1
- package/src/build/scan-server.ts +6 -23
- package/src/client.ts +58 -1
- package/src/deferred-ndjson.ts +212 -0
- package/src/dev-page-plugin.ts +2 -0
- package/src/error.ts +18 -1
- package/src/furin.ts +12 -2
- package/src/lang-detect.ts +46 -0
- package/src/link.tsx +16 -3
- package/src/plugin/index.ts +7 -8
- package/src/plugin/transform-client.ts +108 -39
- package/src/render/assemble.ts +67 -0
- package/src/render/boundaries.tsx +23 -5
- package/src/render/cache.ts +7 -0
- package/src/render/default-screens.tsx +4 -11
- package/src/render/element.tsx +26 -3
- package/src/render/index.ts +247 -44
- package/src/render/loaders.ts +221 -18
- package/src/render/shell.ts +27 -12
- package/src/router-provider.tsx +414 -122
- package/src/router.ts +543 -54
- package/src/server-error.ts +47 -0
- package/src/utils.ts +31 -0
package/src/render/loaders.ts
CHANGED
|
@@ -1,14 +1,82 @@
|
|
|
1
1
|
import type { Context } from "elysia";
|
|
2
|
-
import type
|
|
2
|
+
import { isDeferred, type RuntimeRoute } from "../client";
|
|
3
3
|
import { useLogger } from "../context-logger.ts";
|
|
4
4
|
import { type FurinNotFoundError, isNotFoundError } from "../not-found.ts";
|
|
5
5
|
import type { ResolvedRoute } from "../router";
|
|
6
6
|
|
|
7
7
|
export type LoaderResult =
|
|
8
|
-
| {
|
|
8
|
+
| {
|
|
9
|
+
type: "data";
|
|
10
|
+
/**
|
|
11
|
+
* Synchronous (JSON-serialisable) loader fields. Injected into the initial
|
|
12
|
+
* HTML shell as `__FURIN_DATA__` / the deferred registry's `_data` object.
|
|
13
|
+
*/
|
|
14
|
+
syncData: Record<string, unknown>;
|
|
15
|
+
/**
|
|
16
|
+
* Promise-valued fields from a `defer()` return. `undefined` when the page
|
|
17
|
+
* loader did not call `defer()`. Streamed as late `<script>` resolution
|
|
18
|
+
* chunks (SSR) or as NDJSON chunks via `/_furin/data` (SPA nav).
|
|
19
|
+
*/
|
|
20
|
+
deferredPromises: Record<string, Promise<unknown>> | undefined;
|
|
21
|
+
headers: Record<string, string>;
|
|
22
|
+
}
|
|
9
23
|
| { type: "redirect"; response: Response }
|
|
10
24
|
| { type: "not-found"; error: FurinNotFoundError; headers: Record<string, string> }
|
|
11
|
-
| {
|
|
25
|
+
| {
|
|
26
|
+
type: "error";
|
|
27
|
+
/**
|
|
28
|
+
* Original thrown value, kept for digest computation and server logging.
|
|
29
|
+
* For thrown `Response` objects this is the Response instance whose body
|
|
30
|
+
* has already been consumed by `runLoaders` (do NOT read it again).
|
|
31
|
+
*/
|
|
32
|
+
error: unknown;
|
|
33
|
+
/** HTTP status to return. Default 500; sourced from `Response.status` for thrown Response objects. */
|
|
34
|
+
status: number;
|
|
35
|
+
/**
|
|
36
|
+
* Safe public message extracted at the loader boundary. For thrown
|
|
37
|
+
* `Response` objects: response body or `statusText`. For thrown `Error`
|
|
38
|
+
* / non-Error values: a generic "Something went wrong" string (the raw
|
|
39
|
+
* error/message is never leaked here — `errorMessageOf` decides what to
|
|
40
|
+
* surface from the original `error` value when an `error.tsx` fallback
|
|
41
|
+
* exists).
|
|
42
|
+
*/
|
|
43
|
+
message: string;
|
|
44
|
+
headers: Record<string, string>;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Navigation redirect status codes — the exact set `ctx.redirect()` can emit.
|
|
49
|
+
* Other 3xx codes (304 Not Modified, 305/306) are NOT navigation redirects and
|
|
50
|
+
* must not be treated as one even when they carry a `Location` header.
|
|
51
|
+
*/
|
|
52
|
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* `true` only for HTTP responses that are syntactically valid redirects:
|
|
56
|
+
* a navigation redirect status code AND a `Location` header. A redirect status
|
|
57
|
+
* without `Location` is invalid HTTP and almost always a developer mistake —
|
|
58
|
+
* surfaced as an error so it's debuggable rather than silently redirecting to `/`.
|
|
59
|
+
*/
|
|
60
|
+
function isHttpRedirect(res: Response): boolean {
|
|
61
|
+
return REDIRECT_STATUSES.has(res.status) && res.headers.has("location");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Reads the body of a thrown `Response` exactly once. Returns the body text
|
|
66
|
+
* if present, otherwise the response's `statusText`. The body is consumed
|
|
67
|
+
* destructively — callers must NOT read `res.body` / `res.text()` again.
|
|
68
|
+
*/
|
|
69
|
+
async function readResponseMessage(res: Response): Promise<string> {
|
|
70
|
+
if (res.body === null) {
|
|
71
|
+
return res.statusText;
|
|
72
|
+
}
|
|
73
|
+
try {
|
|
74
|
+
const body = await res.text();
|
|
75
|
+
return body || res.statusText;
|
|
76
|
+
} catch {
|
|
77
|
+
return res.statusText;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
12
80
|
|
|
13
81
|
/**
|
|
14
82
|
* Wraps the Elysia context so that any property NOT present on `ctx` is
|
|
@@ -53,12 +121,102 @@ function createLoaderCtx(
|
|
|
53
121
|
});
|
|
54
122
|
}
|
|
55
123
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
124
|
+
/**
|
|
125
|
+
* Splits a `defer()` page result into sync scalars and deferred Promises,
|
|
126
|
+
* then merges in the already-resolved route-chain loader data.
|
|
127
|
+
*/
|
|
128
|
+
function splitDeferredResult(
|
|
129
|
+
pageResult: Record<string, unknown>,
|
|
130
|
+
routeChainData: Record<string, unknown>
|
|
131
|
+
): {
|
|
132
|
+
syncData: Record<string, unknown>;
|
|
133
|
+
deferredPromises: Record<string, Promise<unknown>> | undefined;
|
|
134
|
+
} {
|
|
135
|
+
const syncData: Record<string, unknown> = {};
|
|
136
|
+
const deferredPromises: Record<string, Promise<unknown>> = {};
|
|
137
|
+
|
|
138
|
+
// Route-chain data first so page sync fields can overwrite it — matching the
|
|
139
|
+
// non-deferred Object.assign order where page result is spread last and wins.
|
|
140
|
+
for (const [key, value] of Object.entries(routeChainData)) {
|
|
141
|
+
syncData[key] = value;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
for (const [key, value] of Object.entries(pageResult)) {
|
|
145
|
+
if (key === "__isDeferred") {
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
if (isPromiseLike(value)) {
|
|
149
|
+
deferredPromises[key] = Promise.resolve(value);
|
|
150
|
+
} else {
|
|
151
|
+
syncData[key] = value;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
return {
|
|
156
|
+
syncData,
|
|
157
|
+
deferredPromises: Object.keys(deferredPromises).length > 0 ? deferredPromises : undefined,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
|
|
162
|
+
return (
|
|
163
|
+
(typeof value === "object" || typeof value === "function") &&
|
|
164
|
+
value !== null &&
|
|
165
|
+
typeof (value as { then?: unknown }).then === "function"
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Normalises an error thrown inside a deferred Promise into a value that is
|
|
171
|
+
* safe to send through `toCrossJSON` and that preserves the original semantics
|
|
172
|
+
* after `fromCrossJSON` on the client.
|
|
173
|
+
*
|
|
174
|
+
* Symmetric to the rejection handling in `runLoaders` (lines 247-272) but for
|
|
175
|
+
* the *deferred* path, where the rejection is delivered to a client-side
|
|
176
|
+
* `<Await>` instead of becoming a top-level response.
|
|
177
|
+
*
|
|
178
|
+
* - `notFound()` → `Error` carrying `__furinBrand` + `data` so the
|
|
179
|
+
* client-side `isNotFoundError()` (duck-typed)
|
|
180
|
+
* recognises the rejection.
|
|
181
|
+
* - `Response(status, body)` → `Error` carrying `__furinStatus` and the
|
|
182
|
+
* body/statusText as `message`.
|
|
183
|
+
* - `Error` → returned unchanged.
|
|
184
|
+
* - anything else → wrapped in `new Error(String(value))`.
|
|
185
|
+
*/
|
|
186
|
+
export async function serializeDeferredRejection(err: unknown): Promise<unknown> {
|
|
187
|
+
if (isNotFoundError(err)) {
|
|
188
|
+
const wrapped = new Error(err.message);
|
|
189
|
+
Object.assign(wrapped, { __furinBrand: "FURIN_NOT_FOUND", data: err.data });
|
|
190
|
+
return wrapped;
|
|
191
|
+
}
|
|
192
|
+
if (err instanceof Response) {
|
|
193
|
+
const body = await readResponseMessage(err);
|
|
194
|
+
const wrapped = new Error(body || err.statusText || "Something went wrong");
|
|
195
|
+
Object.assign(wrapped, { __furinStatus: err.status });
|
|
196
|
+
return wrapped;
|
|
197
|
+
}
|
|
198
|
+
if (err instanceof Error) {
|
|
199
|
+
return err;
|
|
200
|
+
}
|
|
201
|
+
return new Error(String(err));
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* v1 restriction: defer() is only valid in a page loader. Route/layout loaders
|
|
206
|
+
* returning a deferred object would silently leak the brand into syncData and
|
|
207
|
+
* pass raw Promises to descendants — fail fast at the loader boundary instead.
|
|
208
|
+
*/
|
|
209
|
+
function assertNoDeferredInRouteLoaders(routeResults: unknown[]): void {
|
|
210
|
+
for (const result of routeResults) {
|
|
211
|
+
if (isDeferred(result as Record<string, unknown>)) {
|
|
212
|
+
throw new Error(
|
|
213
|
+
"[furin] defer() is only supported in a page loader (route.page({ loader })). A route/layout loader returned a deferred object; move the deferred fields to the page loader, or `await` them in the route loader and return resolved values."
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export async function runLoaders(route: ResolvedRoute, ctx: Context): Promise<LoaderResult> {
|
|
62
220
|
try {
|
|
63
221
|
// Inject `log` so loaders can destructure it directly as `({ log })`.
|
|
64
222
|
// useLogger() resolves the correct logger for every rendering context:
|
|
@@ -104,24 +262,69 @@ export async function runLoaders(
|
|
|
104
262
|
? Promise.resolve(route.page.loader(pageCtx)).then((r) => r ?? {})
|
|
105
263
|
: Promise.resolve({});
|
|
106
264
|
|
|
107
|
-
// Await everything in parallel, then flat-merge
|
|
265
|
+
// Await everything in parallel, then flat-merge.
|
|
108
266
|
const results = await Promise.all([...loaderMap.values(), pagePromise]);
|
|
109
|
-
const
|
|
267
|
+
const merged = Object.assign({}, ...results);
|
|
110
268
|
const headers: Record<string, string> = {};
|
|
111
269
|
Object.assign(headers, ctx.set.headers);
|
|
112
270
|
|
|
113
|
-
|
|
271
|
+
// When the page loader returned a `defer()` object, split its fields:
|
|
272
|
+
// - Promise-valued fields → deferredPromises (streamed lazily)
|
|
273
|
+
// - Scalar fields + all route-chain loader data → syncData (injected into the HTML shell)
|
|
274
|
+
//
|
|
275
|
+
// Route-chain loaders (layouts) are never deferred in v1; their data always
|
|
276
|
+
// lands in syncData. Only the page loader's own `defer()` fields are split.
|
|
277
|
+
const routeOnlyResults = results.slice(0, loaderMap.size);
|
|
278
|
+
const pageResult = results[loaderMap.size] as Record<string, unknown>;
|
|
279
|
+
|
|
280
|
+
assertNoDeferredInRouteLoaders(routeOnlyResults);
|
|
281
|
+
// Route context is always injected into syncData so components receive
|
|
282
|
+
// params, query and path regardless of the serialisation path (SSR, SPA
|
|
283
|
+
// nav, dev cache).
|
|
284
|
+
const routeCtx = { params: ctx.params, query: ctx.query, path: ctx.path };
|
|
285
|
+
if (isDeferred(pageResult)) {
|
|
286
|
+
const routeMerged = Object.assign({}, ...routeOnlyResults) as Record<string, unknown>;
|
|
287
|
+
const { syncData, deferredPromises } = splitDeferredResult(pageResult, routeMerged);
|
|
288
|
+
return { type: "data", syncData: { ...syncData, ...routeCtx }, deferredPromises, headers };
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// No defer() — all data is synchronous
|
|
292
|
+
return {
|
|
293
|
+
type: "data",
|
|
294
|
+
syncData: { ...merged, ...routeCtx },
|
|
295
|
+
deferredPromises: undefined,
|
|
296
|
+
headers,
|
|
297
|
+
};
|
|
114
298
|
} catch (err) {
|
|
299
|
+
const headers: Record<string, string> = {};
|
|
300
|
+
Object.assign(headers, ctx.set.headers);
|
|
115
301
|
if (isNotFoundError(err)) {
|
|
116
|
-
const headers: Record<string, string> = {};
|
|
117
|
-
Object.assign(headers, ctx.set.headers);
|
|
118
302
|
return { type: "not-found", error: err, headers };
|
|
119
303
|
}
|
|
120
304
|
if (err instanceof Response) {
|
|
121
|
-
|
|
305
|
+
if (isHttpRedirect(err)) {
|
|
306
|
+
return { type: "redirect", response: err };
|
|
307
|
+
}
|
|
308
|
+
// Non-redirect Response → error. Read the body ONCE here so downstream
|
|
309
|
+
// consumers (digest, logging, error UI) all share the same extracted
|
|
310
|
+
// message without consuming the stream a second time.
|
|
311
|
+
//
|
|
312
|
+
// A *malformed redirect* is a redirect-status code WITHOUT a `Location`
|
|
313
|
+
// header (we only reach here when `isHttpRedirect` was false) — invalid
|
|
314
|
+
// HTTP, coerced to 500. Other 3xx codes (304/305/306) are not redirects
|
|
315
|
+
// at all, so they keep their own status rather than being rewritten.
|
|
316
|
+
const isMalformedRedirect = REDIRECT_STATUSES.has(err.status);
|
|
317
|
+
const status = isMalformedRedirect ? 500 : err.status;
|
|
318
|
+
const body = await readResponseMessage(err);
|
|
319
|
+
const message = body || "Something went wrong";
|
|
320
|
+
return { type: "error", error: err, status, message, headers };
|
|
122
321
|
}
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
322
|
+
return {
|
|
323
|
+
type: "error",
|
|
324
|
+
error: err,
|
|
325
|
+
status: 500,
|
|
326
|
+
message: "Something went wrong",
|
|
327
|
+
headers,
|
|
328
|
+
};
|
|
126
329
|
}
|
|
127
330
|
}
|
package/src/render/shell.ts
CHANGED
|
@@ -39,10 +39,13 @@ export function safeJson(value: unknown): string {
|
|
|
39
39
|
}
|
|
40
40
|
|
|
41
41
|
export function renderAttrs(obj: Record<string, string | undefined>): string {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
42
|
+
const parts: string[] = [];
|
|
43
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
44
|
+
if (v !== undefined) {
|
|
45
|
+
parts.push(`${k}="${escapeHtml(String(v))}"`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return parts.join(" ");
|
|
46
49
|
}
|
|
47
50
|
|
|
48
51
|
// ---------------------------------------------------------------------------
|
|
@@ -147,17 +150,28 @@ export function generateIndexHtml(): string {
|
|
|
147
150
|
* Called after Bun.build() completes so we can inject the correct entry chunk
|
|
148
151
|
* and CSS paths derived from result.outputs.
|
|
149
152
|
*
|
|
150
|
-
* @param
|
|
151
|
-
*
|
|
152
|
-
* @param
|
|
153
|
-
*
|
|
154
|
-
*
|
|
153
|
+
* @param entryChunk - Hashed URL of the client entry script.
|
|
154
|
+
* @param cssChunks - Hashed URLs of the CSS chunks to inject as `<link>`s.
|
|
155
|
+
* @param buildId - Short hash identifying this specific build (or `undefined`
|
|
156
|
+
* for static exports where stale-deploy detection is not applicable).
|
|
157
|
+
* Injected as a `<meta name="furin-build-id">` tag so the client can
|
|
158
|
+
* detect stale deploys.
|
|
159
|
+
* @param faviconHref - Absolute href for the favicon (e.g. "/furin/favicon.ico"),
|
|
160
|
+
* or `undefined` when no favicon is provided. When set, a `<link rel="icon">`
|
|
161
|
+
* tag is injected so browsers can locate the favicon even when the site is
|
|
162
|
+
* served from a sub-path.
|
|
163
|
+
* @param staticMode - `true` for static exports, `false` for SSR/ISR. When
|
|
164
|
+
* `true`, a `<meta name="furin-mode" content="static">` tag is injected so
|
|
165
|
+
* the SPA client knows to fetch loader data from the per-route
|
|
166
|
+
* `__furin_data.ndjson` file instead of the runtime `/_furin/data` endpoint
|
|
167
|
+
* (which doesn't exist on a static host).
|
|
155
168
|
*/
|
|
156
169
|
export function generateProdIndexHtml(
|
|
157
170
|
entryChunk: string,
|
|
158
171
|
cssChunks: string[],
|
|
159
|
-
buildId
|
|
160
|
-
faviconHref
|
|
172
|
+
buildId: string | undefined,
|
|
173
|
+
faviconHref: string | undefined,
|
|
174
|
+
staticMode: boolean
|
|
161
175
|
): string {
|
|
162
176
|
const cssLinks = cssChunks
|
|
163
177
|
.map((c) => ` <link rel="stylesheet" crossorigin href="${c}">`)
|
|
@@ -169,6 +183,7 @@ export function generateProdIndexHtml(
|
|
|
169
183
|
const faviconLink = faviconHref
|
|
170
184
|
? ` <link rel="icon" href="${escapeHtml(faviconHref)}">\n`
|
|
171
185
|
: "";
|
|
186
|
+
const modeMeta = staticMode ? ` <meta name="furin-mode" content="static">\n` : "";
|
|
172
187
|
|
|
173
188
|
return `<!DOCTYPE html>
|
|
174
189
|
<html lang="en">
|
|
@@ -176,7 +191,7 @@ export function generateProdIndexHtml(
|
|
|
176
191
|
<meta charset="UTF-8">
|
|
177
192
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
178
193
|
${THEME_INIT_SCRIPT}
|
|
179
|
-
${buildIdMeta}${faviconLink}${cssLinks ? `${cssLinks}\n` : ""} <!--ssr-head-->
|
|
194
|
+
${buildIdMeta}${modeMeta}${faviconLink}${cssLinks ? `${cssLinks}\n` : ""} <!--ssr-head-->
|
|
180
195
|
</head>
|
|
181
196
|
<body>
|
|
182
197
|
<div id="root"><!--ssr-outlet--></div>
|