fondu 0.3.0 → 0.5.0

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 CHANGED
@@ -15,7 +15,7 @@ URLs, the document and error pages. Everything else is Hono's, Vite's and Inerti
15
15
  ## Quick start
16
16
 
17
17
  ```bash
18
- bun create fondu my-app # or: npm create fondu@latest my-app · pnpm create fondu my-app
18
+ bun create fondu@latest my-app # or: npm create fondu@latest my-app · pnpm create fondu@latest my-app
19
19
  cd my-app
20
20
  bun dev
21
21
  ```
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { defineHandler, defineMiddleware } from './server/handler.js';
2
- export { render, share, type RenderOptions } from './server/protocol.js';
2
+ export { render, share, encryptHistory, type RenderOptions } from './server/protocol.js';
3
3
  export { back, location, isInertia, wantsPage } from './server/http.js';
4
4
  export { optional, always, defer, once, merge, prepend, deepMerge, scroll, type Prop, type Paginated, } from './server/props.js';
5
5
  export { flash, clearHistory } from './server/flash.js';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { defineHandler, defineMiddleware } from './server/handler.js';
2
- export { render, share } from './server/protocol.js';
2
+ export { render, share, encryptHistory } from './server/protocol.js';
3
3
  export { back, location, isInertia, wantsPage } from './server/http.js';
4
4
  export { optional, always, defer, once, merge, prepend, deepMerge, scroll, } from './server/props.js';
5
5
  export { flash, clearHistory } from './server/flash.js';
@@ -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'], { eager: true });
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 the document gets the request's nonce, so the Content Security Policy runs it.
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;
@@ -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
- /** the document's own markup: JSX rendered (no whitespace between tags), its inline scripts given the nonce */
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
- let html = out;
26
- if (typeof out !== 'string')
27
- html = `<!doctype html>${await renderMarkup(out)}`;
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}"`);
@@ -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 scripts had the build's nonce: this response's, as the security headers give it a new one
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}"`);
@@ -28,18 +28,47 @@ type OwnProps<N> = Omit<ComponentProps<N>, FromShared<ComponentProps<N>> | Clash
28
28
  type PropsInput<P> = {
29
29
  [K in keyof P]: P[K] | (() => P[K] | Promise<P[K]>);
30
30
  };
31
+ type Json = string | number | boolean | null;
32
+ /** types JSON doesn't deliver as they are: a Date arrives as a string, a Map or a Set as {}, a function not at all */
33
+ type NotJson = Date | Map<unknown, unknown> | Set<unknown> | WeakMap<object, unknown> | WeakSet<object> | RegExp | bigint | symbol | ((...args: never[]) => unknown);
34
+ type IsAny<T> = 0 extends 1 & T ? true : false;
35
+ /** each member of T arrives as itself (depth-limited, for recursive types) */
36
+ type JsonMember<T, D extends unknown[]> = T extends Json | undefined ? true : T extends NotJson ? false : D['length'] extends 6 ? true : T extends readonly (infer E)[] ? Arrives<E, [...D, 0]> : T extends object ? Arrives<T[keyof T], [...D, 0]> : true;
37
+ type Arrives<T, D extends unknown[] = []> = IsAny<T> extends true ? true : unknown extends T ? true : [JsonMember<T, D>] extends [true] ? true : false;
38
+ /** what a route may pass for a page prop of type T: T, or anything JSON turns into it (a Date for a string: toJSON) */
39
+ type JsonInput<T> = IsAny<T> extends true ? T : T extends Json | undefined ? T | {
40
+ toJSON(): T;
41
+ } : T extends readonly (infer E)[] ? readonly JsonInput<E>[] | {
42
+ toJSON(): T;
43
+ } : T extends object ? {
44
+ [K in keyof T]: JsonInput<T[K]>;
45
+ } | {
46
+ toJSON(): T;
47
+ } : T;
48
+ type NotJsonError = 'fondu: the page receives this prop as JSON (a Date as a string, a Map as {}): type it as such';
49
+ /** a page's props as `render` takes them: what becomes each as JSON, or an error for a type JSON can't deliver */
50
+ export type Delivered<P> = {
51
+ [K in keyof P]: Arrives<P[K]> extends true ? JsonInput<P[K]> : NotJsonError;
52
+ };
31
53
  type RequiredKeys<T> = {
32
54
  [K in keyof T]-?: object extends Pick<T, K> ? never : K;
33
55
  }[keyof T];
56
+ /**
57
+ * The pages of these requests are encrypted in the browser's history (Laravel's `EncryptHistory` middleware), so Back
58
+ * after signing out can't show them: in `routes/account/_middleware.ts`, `export default encryptHistory()`. A route
59
+ * can still opt out: `render(c, page, props, { encryptHistory: false })`.
60
+ */
61
+ export declare const encryptHistory: () => MiddlewareHandler;
34
62
  export interface RenderOptions {
35
63
  status?: number;
64
+ /** the page's state is encrypted in the browser's history; default: `encryptHistory()` above the route, or not */
36
65
  encryptHistory?: boolean;
37
66
  clearHistory?: boolean;
38
67
  preserveFragment?: boolean;
39
68
  }
40
69
  type RenderArgs<N> = [RequiredKeys<OwnProps<N>>] extends [never] ? OptionalArgs<N> : string extends keyof OwnProps<N> ? OptionalArgs<N> : RequiredArgs<N>;
41
- type OptionalArgs<N> = [props?: PropsInput<OwnProps<N>>, options?: RenderOptions];
42
- type RequiredArgs<N> = [props: PropsInput<OwnProps<N>>, options?: RenderOptions];
70
+ type OptionalArgs<N> = [props?: PropsInput<Delivered<OwnProps<N>>>, options?: RenderOptions];
71
+ type RequiredArgs<N> = [props: PropsInput<Delivered<OwnProps<N>>>, options?: RenderOptions];
43
72
  export declare const hasPage: (name: string) => boolean;
44
73
  /**
45
74
  * The page `component` (a file in `pages/`, without extension) with these props: JSON for Inertia's requests,
@@ -9,6 +9,16 @@ const shared = new WeakMap();
9
9
  export function share(c, props) {
10
10
  shared.set(c, { ...shared.get(c), ...props });
11
11
  }
12
+ const encrypted = new WeakSet();
13
+ /**
14
+ * The pages of these requests are encrypted in the browser's history (Laravel's `EncryptHistory` middleware), so Back
15
+ * after signing out can't show them: in `routes/account/_middleware.ts`, `export default encryptHistory()`. A route
16
+ * can still opt out: `render(c, page, props, { encryptHistory: false })`.
17
+ */
18
+ export const encryptHistory = () => async (c, next) => {
19
+ encrypted.add(c);
20
+ await next();
21
+ };
12
22
  // development: the files in app/pages/ (Vite keeps the list current); a build: the pages in the client manifest
13
23
  const devPages = import.meta.env.DEV ? import.meta.glob('/app/pages/**/*.{tsx,jsx,mdx}') : {};
14
24
  export const hasPage = (name) => pages
@@ -136,7 +146,7 @@ export async function render(c, component, ...[props = {}, options = {}]) {
136
146
  const sharedKeys = Object.keys(sharedProps);
137
147
  if (sharedKeys.length)
138
148
  page.sharedProps = sharedKeys;
139
- if (options.encryptHistory)
149
+ if (options.encryptHistory ?? encrypted.has(c))
140
150
  page.encryptHistory = true;
141
151
  if (options.clearHistory || carried.clearHistory)
142
152
  page.clearHistory = true;
@@ -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. */
@@ -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
- if (last) {
48
- if (name in target && path.length === 1)
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
- target = (target[name] ??= {});
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
  }
@@ -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
- const isServerOnly = (id) => /\.server\.[cm]?[jt]sx?(\?.*)?$/.test(id) || /\/app\/(routes\/|server\.ts)/.test(id);
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]??[]`;
@@ -1,8 +1,16 @@
1
1
  import type { Logger } from 'vite';
2
2
  import { staticFiles } from '../paths.js';
3
3
  export { staticFiles };
4
- /** the hashes of a document's inline scripts that have the nonce (the document's own, as Fondu gave it) */
5
- export declare function nonceScriptHashes(html: string): string[];
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
@@ -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
- /** the hashes of a document's inline scripts that have the nonce (the document's own, as Fondu gave it) */
13
- export function nonceScriptHashes(html) {
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 html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi))
16
- if (/\snonce=/i.test(attrs) && !/\ssrc=/i.test(attrs))
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.0",
3
+ "version": "0.5.0",
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.4",
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.3",
67
- "zod": "4.6.5"
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",