fondu 0.4.0 → 0.5.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/dist/server/app.js +2 -1
- package/dist/server/document.d.ts +4 -1
- package/dist/server/document.js +8 -5
- package/dist/server/prerender.js +2 -1
- package/dist/server/protocol.js +2 -1
- package/dist/server/validate.d.ts +2 -1
- package/dist/server/validate.js +19 -7
- package/dist/vite/index.js +39 -2
- package/dist/vite/prerender.d.ts +10 -2
- package/dist/vite/prerender.js +15 -7
- package/package.json +5 -4
package/dist/server/app.js
CHANGED
|
@@ -76,7 +76,8 @@ export function createApp(options = {}) {
|
|
|
76
76
|
return error.getResponse();
|
|
77
77
|
return errorResponse(c, error instanceof HTTPException ? error.status : 500, error);
|
|
78
78
|
});
|
|
79
|
-
const modules = import.meta.glob(['/app/routes/**/*.ts', '!/app/routes/**/*.d.ts'
|
|
79
|
+
const modules = import.meta.glob(['/app/routes/**/*.ts', '!/app/routes/**/*.d.ts', '!/app/routes/**/*.{test,spec}.ts'], // test files aren't the app's
|
|
80
|
+
{ eager: true });
|
|
80
81
|
const files = Object.keys(modules).map((k) => k.slice(ROOT.length));
|
|
81
82
|
// a _middleware.ts may only set what applies to its directory (`prerender`), without a default export
|
|
82
83
|
const rootMiddleware = modules[ROOT + '_middleware.ts']?.default;
|
|
@@ -3,7 +3,8 @@ import type { Context, MiddlewareHandler } from 'hono';
|
|
|
3
3
|
import type { ReactElement } from 'react';
|
|
4
4
|
/**
|
|
5
5
|
* The HTML document around a page: `{head}` and `{body}` (in JSX, or `${head}` in a string) are where the page goes.
|
|
6
|
-
* An inline `<script>` of
|
|
6
|
+
* An inline `<script>` of a JSX document gets the request's nonce, so the Content Security Policy runs it; a string's
|
|
7
|
+
* writes it: `<script nonce="${nonce}">`.
|
|
7
8
|
*/
|
|
8
9
|
export interface DocumentParts {
|
|
9
10
|
/** the page's `<Head>` tags (server render), then the client's styles and scripts */
|
|
@@ -11,6 +12,8 @@ export interface DocumentParts {
|
|
|
11
12
|
/** the page data (`<script data-page>`) and the rendered page (`<div id="app">`) */
|
|
12
13
|
body: string;
|
|
13
14
|
c: Context;
|
|
15
|
+
/** the request's Content Security Policy nonce (`''` without one) */
|
|
16
|
+
nonce: string;
|
|
14
17
|
}
|
|
15
18
|
/** the document as JSX (`<html>…</html>`), or as an HTML string */
|
|
16
19
|
export type DocumentTemplate = (parts: DocumentParts) => ReactElement | string;
|
package/dist/server/document.js
CHANGED
|
@@ -19,12 +19,15 @@ const pageScript = (page) => `<script data-page="app" type="application/json">${
|
|
|
19
19
|
// never read as one
|
|
20
20
|
const HEAD = 'fondu:document-head';
|
|
21
21
|
const BODY = 'fondu:document-body';
|
|
22
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* The document's own markup. JSX: rendered (no whitespace between tags), its inline scripts given the nonce. A string
|
|
24
|
+
* is taken as it is: what it interpolates isn't escaped, so a nonce added there would run whatever got in.
|
|
25
|
+
*/
|
|
23
26
|
async function shell(template, c, nonce) {
|
|
24
|
-
const out = template({ head: HEAD, body: BODY, c });
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
27
|
+
const out = template({ head: HEAD, body: BODY, c, nonce: nonce ?? '' });
|
|
28
|
+
if (typeof out === 'string')
|
|
29
|
+
return out;
|
|
30
|
+
const html = `<!doctype html>${await renderMarkup(out)}`;
|
|
28
31
|
if (!nonce)
|
|
29
32
|
return html;
|
|
30
33
|
return html.replace(/<script\b(?![^>]*\s(?:src|nonce)=)/gi, `<script nonce="${nonce}"`);
|
package/dist/server/prerender.js
CHANGED
|
@@ -61,7 +61,8 @@ export function prerenderRoutes(app, routes, version) {
|
|
|
61
61
|
c.header('Cache-Control', 'private, no-cache');
|
|
62
62
|
if (data)
|
|
63
63
|
c.header('X-Inertia', 'true');
|
|
64
|
-
// the document's
|
|
64
|
+
// the document's own tags have the build's nonce (the build dropped any other): this response's instead, as the
|
|
65
|
+
// security headers give it a new one
|
|
65
66
|
const nonce = c.get('secureHeadersNonce');
|
|
66
67
|
if (!data && nonce) {
|
|
67
68
|
const html = new TextDecoder().decode(body).replace(/(<(?:script|link)\b[^>]*\snonce=")[^"]*"/gi, `$1${nonce}"`);
|
package/dist/server/protocol.js
CHANGED
|
@@ -52,7 +52,8 @@ export async function render(c, component, ...[props = {}, options = {}]) {
|
|
|
52
52
|
const except = partial ? headerSet(c, 'x-inertia-partial-except') : null;
|
|
53
53
|
const reset = headerSet(c, 'x-inertia-reset') ?? new Set();
|
|
54
54
|
const heldOnce = headerSet(c, 'x-inertia-except-once-props') ?? new Set();
|
|
55
|
-
|
|
55
|
+
// shown by the next page, a partial reload too (a form with `only`), as Laravel's session does; not a prefetch
|
|
56
|
+
const carried = takeCarried(c, !isPrefetch(c));
|
|
56
57
|
const sharedProps = shared.get(c) ?? {};
|
|
57
58
|
const all = { ...sharedProps, ...props };
|
|
58
59
|
const page = {
|
|
@@ -36,7 +36,8 @@ export declare function validationErrorResponse(c: Context, error: ValidationErr
|
|
|
36
36
|
/**
|
|
37
37
|
* A request body as one object: JSON, or form fields with PHP-style names, as Inertia's `useForm` sends files
|
|
38
38
|
* (`notify[0]`, `user[name]`) and as plain forms write them (`notify[]`); files are `File`s, empty file inputs
|
|
39
|
-
* are left out. Names that would change the object itself (`__proto__`…) are ignored.
|
|
39
|
+
* are left out. Names that would change the object itself (`__proto__`…) are ignored. A body that can't be one
|
|
40
|
+
* object (JSON that doesn't parse, `a=1&a[b]=2`, names nested deeper than 32) is a 400.
|
|
40
41
|
*/
|
|
41
42
|
export declare function readBody(c: Context): Promise<unknown>;
|
|
42
43
|
/** What `withValidator` checks: the request body (JSON or form), the query, the route params. */
|
package/dist/server/validate.js
CHANGED
|
@@ -21,37 +21,49 @@ export function validationErrorResponse(c, error) {
|
|
|
21
21
|
flashErrors(c, bag ? { [bag]: error.errors } : error.errors);
|
|
22
22
|
return back(c);
|
|
23
23
|
}
|
|
24
|
+
/** how deep form field names nest (`a[b][c]`: 3) */
|
|
25
|
+
const DEPTH = 32;
|
|
24
26
|
/**
|
|
25
27
|
* A request body as one object: JSON, or form fields with PHP-style names, as Inertia's `useForm` sends files
|
|
26
28
|
* (`notify[0]`, `user[name]`) and as plain forms write them (`notify[]`); files are `File`s, empty file inputs
|
|
27
|
-
* are left out. Names that would change the object itself (`__proto__`…) are ignored.
|
|
29
|
+
* are left out. Names that would change the object itself (`__proto__`…) are ignored. A body that can't be one
|
|
30
|
+
* object (JSON that doesn't parse, `a=1&a[b]=2`, names nested deeper than 32) is a 400.
|
|
28
31
|
*/
|
|
29
32
|
export async function readBody(c) {
|
|
33
|
+
const malformed = (why) => new HTTPException(400, { message: `Malformed request body: ${why}` });
|
|
30
34
|
const type = c.req.header('content-type') ?? '';
|
|
31
35
|
if (type.includes('application/json'))
|
|
32
|
-
return c.req.json();
|
|
36
|
+
return c.req.json().catch(() => Promise.reject(malformed('invalid JSON')));
|
|
33
37
|
if (!type.includes('multipart/form-data') && !type.includes('application/x-www-form-urlencoded'))
|
|
34
38
|
return {};
|
|
35
39
|
const form = await c.req.formData();
|
|
36
|
-
const body =
|
|
40
|
+
const body = Object.create(null);
|
|
37
41
|
for (const [key, value] of form.entries()) {
|
|
38
42
|
if (typeof value !== 'string' && value.size === 0 && value.name === '')
|
|
39
43
|
continue;
|
|
40
44
|
const path = key.replace(/\]/g, '').split('[');
|
|
45
|
+
if (path.length > DEPTH)
|
|
46
|
+
throw malformed(`a field name nests deeper than ${DEPTH}`);
|
|
41
47
|
if (path.some((p) => p === '__proto__' || p === 'constructor' || p === 'prototype'))
|
|
42
48
|
continue;
|
|
43
49
|
let target = body;
|
|
44
50
|
path.forEach((segment, i) => {
|
|
45
|
-
const last = i === path.length - 1;
|
|
46
51
|
const name = segment === '' ? String(Object.keys(target).length) : segment; // `a[]`: the next index
|
|
47
|
-
|
|
48
|
-
|
|
52
|
+
const has = Object.hasOwn(target, name);
|
|
53
|
+
if (i === path.length - 1) {
|
|
54
|
+
if (has && typeof target[name] === 'object' && !(target[name] instanceof File) && !Array.isArray(target[name]))
|
|
55
|
+
throw malformed(`\`${key}\` is both a value and an object`);
|
|
56
|
+
if (has && path.length === 1)
|
|
49
57
|
target[name] = [target[name], value].flat(); // `a=1&a=2`
|
|
50
58
|
else
|
|
51
59
|
target[name] = value;
|
|
52
60
|
}
|
|
53
61
|
else {
|
|
54
|
-
|
|
62
|
+
if (!has)
|
|
63
|
+
target[name] = Object.create(null);
|
|
64
|
+
else if (typeof target[name] !== 'object' || target[name] instanceof File || Array.isArray(target[name]))
|
|
65
|
+
throw malformed(`\`${key}\` is both a value and an object`);
|
|
66
|
+
target = target[name];
|
|
55
67
|
}
|
|
56
68
|
});
|
|
57
69
|
}
|
package/dist/vite/index.js
CHANGED
|
@@ -92,6 +92,7 @@ export default function fondu(options) {
|
|
|
92
92
|
core(options),
|
|
93
93
|
layouts(),
|
|
94
94
|
hmr(),
|
|
95
|
+
loadFailure(),
|
|
95
96
|
typegen(),
|
|
96
97
|
...(node ? runtimePlugins(options) : [serverReactDomClient()]),
|
|
97
98
|
];
|
|
@@ -175,6 +176,38 @@ function runtimePlugins(options) {
|
|
|
175
176
|
buildPlugin(options),
|
|
176
177
|
];
|
|
177
178
|
}
|
|
179
|
+
/**
|
|
180
|
+
* Dev: the app that fails to load (a route that throws as it is imported) is Vite's error page, which an Inertia
|
|
181
|
+
* visit can't show: its dialog's frame keeps the page's Content Security Policy, which stops the page's script. The
|
|
182
|
+
* visit loads the URL as a whole page instead (Inertia's 409), where Vite's overlay shows the error; the next change
|
|
183
|
+
* reloads it.
|
|
184
|
+
*/
|
|
185
|
+
function loadFailure() {
|
|
186
|
+
let failed = false;
|
|
187
|
+
return {
|
|
188
|
+
name: 'fondu:load-failure',
|
|
189
|
+
apply: 'serve',
|
|
190
|
+
configureServer(server) {
|
|
191
|
+
// after the dev server (the Cloudflare plugin's too), before Vite's error page
|
|
192
|
+
return () => server.middlewares.use((error, req, res, next) => {
|
|
193
|
+
const visit = Boolean(req.headers['x-inertia']);
|
|
194
|
+
// a page failed (not a module of the browser's): the next change reloads it
|
|
195
|
+
if (visit || req.headers.accept?.includes('text/html'))
|
|
196
|
+
failed = true;
|
|
197
|
+
if (!visit)
|
|
198
|
+
return next(error);
|
|
199
|
+
res.writeHead(409, { 'X-Inertia-Location': req.originalUrl ?? req.url });
|
|
200
|
+
res.end();
|
|
201
|
+
});
|
|
202
|
+
},
|
|
203
|
+
hotUpdate() {
|
|
204
|
+
if (this.environment.name !== 'client' || !failed)
|
|
205
|
+
return;
|
|
206
|
+
failed = false;
|
|
207
|
+
this.environment.hot.send({ type: 'full-reload' });
|
|
208
|
+
},
|
|
209
|
+
};
|
|
210
|
+
}
|
|
178
211
|
function core(options) {
|
|
179
212
|
let config;
|
|
180
213
|
let isBuild = false;
|
|
@@ -331,13 +364,17 @@ function core(options) {
|
|
|
331
364
|
return ((isBuild ? productionAssets(config, options) : devAssets(config.base)) +
|
|
332
365
|
`\nexport const prerender = ${Boolean(options.prerender)}`);
|
|
333
366
|
// the server-only guard: browser code must never import server code
|
|
334
|
-
if (this.environment.config.consumer === 'client' && isServerOnly(id)) {
|
|
367
|
+
if (this.environment.config.consumer === 'client' && isServerOnly(id, config.root)) {
|
|
335
368
|
this.error(`fondu: ${id.replace(config.root, '')} is server code (routes/, server.ts, *.server.ts) and cannot be imported by browser code`);
|
|
336
369
|
}
|
|
337
370
|
},
|
|
338
371
|
};
|
|
339
372
|
}
|
|
340
|
-
|
|
373
|
+
/** `*.server.ts`, or the app's `routes/` and `server.ts` (the root's: a path above it or in a package may have them) */
|
|
374
|
+
const isServerOnly = (id, root) => {
|
|
375
|
+
const file = id.split('?')[0];
|
|
376
|
+
return (/\.server\.[cm]?[jt]sx?$/.test(file) || file.startsWith(`${root}/app/routes/`) || file === `${root}/app/server.ts`);
|
|
377
|
+
};
|
|
341
378
|
const nonceAttr = `\${nonce ? \` nonce="\${nonce}"\` : ''}`;
|
|
342
379
|
function devAssets(base) {
|
|
343
380
|
const preamble = `import RefreshRuntime from "${base}@react-refresh";RefreshRuntime.injectIntoGlobalHook(window);window.$RefreshReg$=()=>{};window.$RefreshSig$=()=>(type)=>type;window.__vite_plugin_react_preamble_installed__=true;window.__getReactRefreshIgnoredExports=({id})=>window.${PAGE_EXPORTS}?.[id]??[]`;
|
package/dist/vite/prerender.d.ts
CHANGED
|
@@ -1,8 +1,16 @@
|
|
|
1
1
|
import type { Logger } from 'vite';
|
|
2
2
|
import { staticFiles } from '../paths.js';
|
|
3
3
|
export { staticFiles };
|
|
4
|
-
/**
|
|
5
|
-
|
|
4
|
+
/**
|
|
5
|
+
* A static document's own tags: those with the build's nonce (its Content Security Policy's). The nonce of a static
|
|
6
|
+
* document is replaced (Cloudflare: its inline scripts by their hashes; Node / Bun: by each response's nonce), which
|
|
7
|
+
* only these may get: a `nonce` the document has otherwise (in a page's markup) is dropped. Then the hashes of these
|
|
8
|
+
* inline scripts.
|
|
9
|
+
*/
|
|
10
|
+
export declare function ownScripts(html: string, policy: string | undefined): {
|
|
11
|
+
html: string;
|
|
12
|
+
hashes: string[];
|
|
13
|
+
};
|
|
6
14
|
/**
|
|
7
15
|
* A Content Security Policy for a static document: no nonce (one for every visitor is none); the scripts that had it
|
|
8
16
|
* allowed by their hashes instead, and `'self'` scripts
|
package/dist/vite/prerender.js
CHANGED
|
@@ -9,13 +9,22 @@ import { PAGE_DATA, staticFiles } from '../paths.js';
|
|
|
9
9
|
export { staticFiles };
|
|
10
10
|
/** the response headers a static document keeps: the security headers (hono/secure-headers' and the like) */
|
|
11
11
|
const SECURITY_HEADERS = /^(content-security-policy(-report-only)?|strict-transport-security|referrer-policy|permissions-policy|x-content-type-options|x-frame-options|x-xss-protection|x-dns-prefetch-control|x-download-options|x-permitted-cross-domain-policies|origin-agent-cluster|cross-origin-(opener|embedder|resource)-policy)$/i;
|
|
12
|
-
/**
|
|
13
|
-
|
|
12
|
+
/**
|
|
13
|
+
* A static document's own tags: those with the build's nonce (its Content Security Policy's). The nonce of a static
|
|
14
|
+
* document is replaced (Cloudflare: its inline scripts by their hashes; Node / Bun: by each response's nonce), which
|
|
15
|
+
* only these may get: a `nonce` the document has otherwise (in a page's markup) is dropped. Then the hashes of these
|
|
16
|
+
* inline scripts.
|
|
17
|
+
*/
|
|
18
|
+
export function ownScripts(html, policy) {
|
|
19
|
+
const nonce = policy?.match(/'nonce-([^']+)'/)?.[1];
|
|
20
|
+
if (!nonce)
|
|
21
|
+
return { html, hashes: [] };
|
|
22
|
+
const own = html.replace(/(<(?:script|link)\b[^>]*?)\snonce="([^"]*)"/gi, (tag, before, value) => value === nonce ? tag : before);
|
|
14
23
|
const hashes = new Set();
|
|
15
|
-
for (const [, attrs, code] of
|
|
16
|
-
if (
|
|
24
|
+
for (const [, attrs, code] of own.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi))
|
|
25
|
+
if (attrs.includes(` nonce="${nonce}"`) && !/\ssrc=/i.test(attrs))
|
|
17
26
|
hashes.add(`'sha256-${createHash('sha256').update(code).digest('base64')}'`);
|
|
18
|
-
return [...hashes];
|
|
27
|
+
return { html: own, hashes: [...hashes] };
|
|
19
28
|
}
|
|
20
29
|
/**
|
|
21
30
|
* A Content Security Policy for a static document: no nonce (one for every visitor is none); the scripts that had it
|
|
@@ -84,8 +93,7 @@ export async function prerender(start, clientDir, logger, headersFile) {
|
|
|
84
93
|
errors.push(`${path}: ${later.join(', ')} ask the server again; not for a prerendered page`);
|
|
85
94
|
continue;
|
|
86
95
|
}
|
|
87
|
-
const html = await doc.text();
|
|
88
|
-
const hashes = nonceScriptHashes(html);
|
|
96
|
+
const { html, hashes } = ownScripts(await doc.text(), doc.headers.get('content-security-policy') ?? undefined);
|
|
89
97
|
const headers = Object.fromEntries([...doc.headers]
|
|
90
98
|
.filter(([name]) => SECURITY_HEADERS.test(name))
|
|
91
99
|
.map(([name, value]) => [name, /^content-security-policy/i.test(name) ? staticPolicy(value, hashes) : value]));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fondu",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"description": "A small meta-framework for full-stack React apps, built on Hono, Vite and Inertia. It runs on Bun, Cloudflare Workers and Node.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"bun",
|
|
@@ -57,16 +57,17 @@
|
|
|
57
57
|
"devDependencies": {
|
|
58
58
|
"@inertiajs/core": "3.9.1",
|
|
59
59
|
"@inertiajs/react": "3.9.1",
|
|
60
|
-
"@types/node": "26.6.
|
|
60
|
+
"@types/node": "26.6.5",
|
|
61
61
|
"@types/react": "19.3.0",
|
|
62
62
|
"@types/react-dom": "19.3.0",
|
|
63
63
|
"hono": "4.13.13",
|
|
64
64
|
"typescript": "7.0.2",
|
|
65
65
|
"vite": "8.3.4",
|
|
66
|
-
"vitest": "5.0.
|
|
67
|
-
"zod": "4.6.
|
|
66
|
+
"vitest": "5.0.4",
|
|
67
|
+
"zod": "4.6.7"
|
|
68
68
|
},
|
|
69
69
|
"peerDependencies": {
|
|
70
|
+
"@inertiajs/core": "^3.9.0",
|
|
70
71
|
"@inertiajs/react": "^3.9.0",
|
|
71
72
|
"hono": "^4.13.0",
|
|
72
73
|
"react": "^19.0.0",
|