fondu 0.5.1 → 0.6.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/README.md CHANGED
@@ -9,8 +9,10 @@ Routes are Hono handlers in `app/routes/`; pages are React components in `app/pa
9
9
  props, and Inertia does the rest in the browser: visits without full reloads, forms with validation, deferred and
10
10
  merged props, all without an API to write or a client-side router to keep in sync.
11
11
 
12
- Fondu writes as little of its own as it can: the server side of Inertia's protocol, file routes, typed pages and
13
- URLs, the document and error pages. Everything else is Hono's, Vite's and Inertia's.
12
+ Fondu writes only what none of them does: Inertia's server side for Hono (the protocol, forms' errors and flash
13
+ data), file routes, typed pages and URLs, the document and error pages. Everything else is Hono's, Vite's and
14
+ Inertia's. [Fondu and @hono/inertia](https://fondu.dev/docs#fondu-and-honoinertia) says how it compares with Hono's
15
+ own middleware.
14
16
 
15
17
  ## Quick start
16
18
 
@@ -20,8 +22,9 @@ cd my-app
20
22
  bun dev
21
23
  ```
22
24
 
23
- It asks where the app runs (Bun, Cloudflare Workers or Node; or `--target bun|cloudflare|node`) and writes a small
24
- app: a route, its page, the error page, Tailwind CSS, editor snippets and an `AGENTS.md` for coding agents.
25
+ It asks where the app runs (Bun, Cloudflare Workers or Node; or `--target bun|cloudflare|node`) and whether to add
26
+ code checks (oxfmt, oxlint, lefthook, commitlint; or `--checks`), and writes a small app: a route, its page, the
27
+ error page, Tailwind CSS, editor snippets and an `AGENTS.md` for coding agents. `--yes` asks nothing more.
25
28
 
26
29
  [demo.fondu.dev](https://demo.fondu.dev) ([apps/demo](https://github.com/fondujs/fondu/tree/main/apps/demo)) shows every Inertia feature, one page each, on
27
30
  Cloudflare Workers with D1 and Better Auth.
package/dist/client.js CHANGED
@@ -23,6 +23,10 @@ export function prerendered() {
23
23
  const page = JSON.parse(response.data);
24
24
  if (!page.version || page.version === version)
25
25
  return response;
26
- return { status: 409, data: '', headers: { 'x-inertia-location': page.url, 'x-inertia-version': page.version } };
26
+ return {
27
+ status: 409,
28
+ data: '',
29
+ headers: { 'x-inertia-location': page.url, 'x-inertia-version': page.version },
30
+ };
27
31
  });
28
32
  }
@@ -87,14 +87,21 @@ export function createApp(options = {}) {
87
87
  const routes = files
88
88
  .filter(isRouteFile)
89
89
  // static before dynamic before catch-all, segment by segment
90
- .map((file) => ({ file, pattern: withSlash(routePattern(file), append), mod: modules[ROOT + file] }))
90
+ .map((file) => ({
91
+ file,
92
+ pattern: withSlash(routePattern(file), append),
93
+ mod: modules[ROOT + file],
94
+ }))
91
95
  .sort((a, b) => rank(a.pattern).localeCompare(rank(b.pattern)));
92
96
  for (const { file, pattern, mod } of routes) {
93
97
  const mws = middlewareFor(file, middlewareFiles).flatMap((f) => chain(modules[ROOT + f].default ?? []));
94
98
  prerendered.push({
95
99
  file,
96
100
  pattern,
97
- settings: [file, ...middlewareFor(file, [...middlewareFiles, '_middleware.ts']).reverse()].map((f) => modules[ROOT + f]?.prerender),
101
+ settings: [
102
+ file,
103
+ ...middlewareFor(file, [...middlewareFiles, '_middleware.ts']).reverse(),
104
+ ].map((f) => modules[ROOT + f]?.prerender),
98
105
  get: Boolean(mod.loader ?? mod.GET),
99
106
  others: [
100
107
  ...(mod.action || mod.actions || mod.POST ? ['POST'] : []),
@@ -51,5 +51,5 @@ export async function renderDocument(c, page) {
51
51
  const [before, between, after, ...more] = html.split(new RegExp(`${HEAD}|${BODY}`));
52
52
  if (after === undefined || more.length || html.indexOf(HEAD) > html.indexOf(BODY))
53
53
  throw new Error('fondu: the document must have `head` once, in <head>, and `body` once, in <body>');
54
- return before + (ssr?.head.join('') ?? '') + assetTags(page.component, nonce) + between + body + after;
54
+ return (before + (ssr?.head.join('') ?? '') + assetTags(page.component, nonce) + between + body + after);
55
55
  }
@@ -7,7 +7,8 @@ const state = (c) => {
7
7
  return s;
8
8
  };
9
9
  /** https, directly or behind a proxy that says so */
10
- export const isSecure = (c) => new URL(c.req.url).protocol === 'https:' || c.req.header('x-forwarded-proto')?.split(',')[0]?.trim() === 'https';
10
+ export const isSecure = (c) => new URL(c.req.url).protocol === 'https:' ||
11
+ c.req.header('x-forwarded-proto')?.split(',')[0]?.trim() === 'https';
11
12
  const cookieName = (c) => (isSecure(c) ? '__Host-fondu-flash' : 'fondu-flash');
12
13
  /** Flash data for the next page (`page.flash` / `usePage().flash`, Inertia's `flash` event). */
13
14
  export function flash(c, data) {
@@ -65,7 +65,9 @@ export function prerenderRoutes(app, routes, version) {
65
65
  // security headers give it a new one
66
66
  const nonce = c.get('secureHeadersNonce');
67
67
  if (!data && nonce) {
68
- const html = new TextDecoder().decode(body).replace(/(<(?:script|link)\b[^>]*\snonce=")[^"]*"/gi, `$1${nonce}"`);
68
+ const html = new TextDecoder()
69
+ .decode(body)
70
+ .replace(/(<(?:script|link)\b[^>]*\snonce=")[^"]*"/gi, `$1${nonce}"`);
69
71
  return c.html(html, 200);
70
72
  }
71
73
  return c.body(body, 200, {
@@ -89,7 +91,8 @@ export function prerenderRoutes(app, routes, version) {
89
91
  });
90
92
  app.get('/__fondu/prerender', async (c) => {
91
93
  // set for the build only: a Worker binding, or the environment of `node` / `bun dist/index.js`
92
- const env = c.env?.FONDU_PRERENDER ?? globalThis.process?.env?.FONDU_PRERENDER;
94
+ const env = c.env?.FONDU_PRERENDER ??
95
+ globalThis.process?.env?.FONDU_PRERENDER;
93
96
  if (!env)
94
97
  return c.notFound();
95
98
  return c.json({ version, ...(await prerenderPaths(routes())) });
@@ -2,17 +2,24 @@
2
2
  * Inertia's prop types (the names are Inertia's: what the client docs call them). A plain value is always sent;
3
3
  * a function is called only when its prop is sent.
4
4
  *
5
- * - `optional(fn)`: never on a full visit, only when a partial reload asks for it
5
+ * - `optional(fn)`: never on a full visit, only when a partial reload names it (`only`)
6
6
  * - `always(value)`: sent on partial reloads too, even when not asked for
7
7
  * - `defer(fn, { group?, rescue? })`: left out of the page, fetched by the client right after it renders (one
8
8
  * request per group); `rescue`: if it throws, the page still loads and `<Deferred>` shows its `rescue` slot
9
- * - `merge(value)` / `prepend(value)` / `deepMerge(value)`: partial reloads merge into what the client holds
9
+ * - `merge(value, { path?, matchOn? })` / `prepend(…)` / `deepMerge(value, { matchOn? })`: partial reloads merge into
10
+ * what the client holds; `path`: the list to merge, inside the prop (`'data'`); `matchOn`: the field, from the
11
+ * prop, that finds an item to replace (`'id'`, `'data.id'`)
10
12
  * - `once(fn, { key?, ttl?, fresh? })`: computed once; later requests say the client holds it and it is skipped
11
13
  * (`fresh`: send it anyway)
12
14
  * - `scroll(fn, { pageName? })`: a page of a list for `<InfiniteScroll>`; `fn` returns `{ data, currentPage,
13
15
  * previousPage, nextPage }` for the page in the query (`?page=`)
16
+ *
17
+ * They combine as Inertia's do (Laravel's `->once()`, `->merge()`, `->defer()`), by wrapping one in another:
18
+ * `once(defer(fn))`, `once(optional(fn))`, `once(merge(fn))`, `merge(defer(fn))` (and `deepMerge`, `prepend`),
19
+ * `defer(scroll(fn))`.
14
20
  */
15
21
  declare const PROP: unique symbol;
22
+ declare const BRAND: unique symbol;
16
23
  type Resolver<T> = () => T | Promise<T>;
17
24
  export type Lazy<T> = T | Resolver<T>;
18
25
  export interface Paginated<T> {
@@ -21,44 +28,41 @@ export interface Paginated<T> {
21
28
  previousPage: number | string | null;
22
29
  nextPage: number | string | null;
23
30
  }
24
- export type PropSpec = {
25
- [PROP]: 'optional';
26
- value: Lazy<unknown>;
27
- } | {
28
- [PROP]: 'always';
29
- value: Lazy<unknown>;
30
- } | {
31
- [PROP]: 'defer';
32
- value: Lazy<unknown>;
33
- group: string;
34
- rescue: boolean;
35
- } | {
36
- [PROP]: 'merge';
31
+ export interface PropSpec {
32
+ [PROP]: true;
37
33
  value: Lazy<unknown>;
38
- strategy: 'append' | 'prepend' | 'deep';
39
- matchOn: string[];
40
- } | {
41
- [PROP]: 'once';
42
- value: Lazy<unknown>;
43
- key?: string;
44
- ttl?: number;
45
- fresh?: boolean;
46
- } | {
47
- [PROP]: 'scroll';
48
- value: Lazy<unknown>;
49
- pageName: string;
50
- };
34
+ optional?: true;
35
+ always?: true;
36
+ defer?: {
37
+ group: string;
38
+ rescue: boolean;
39
+ };
40
+ once?: {
41
+ key?: string;
42
+ ttl?: number;
43
+ fresh?: boolean;
44
+ };
45
+ merge?: {
46
+ strategy: 'append' | 'prepend' | 'deep';
47
+ paths: string[];
48
+ matchOn: string[];
49
+ };
50
+ scroll?: {
51
+ pageName: string;
52
+ };
53
+ }
51
54
  /** A prop with an Inertia behaviour; at the type level it stands for the value it resolves to. */
52
55
  export type Prop<T> = T & {
53
- readonly [PROP]?: never;
56
+ readonly [BRAND]: true;
54
57
  };
58
+ export declare const propSpec: (value: unknown) => PropSpec | null;
55
59
  export declare const optional: <T>(value: Resolver<T>) => Prop<T>;
56
60
  export declare const always: <T>(value: Lazy<T>) => Prop<T>;
57
- export declare const defer: <T>(value: Resolver<T>, { group, rescue }?: {
61
+ export declare const defer: <T>(value: Resolver<T> | Prop<T>, { group, rescue }?: {
58
62
  group?: string;
59
63
  rescue?: boolean;
60
64
  }) => Prop<T>;
61
- export declare const once: <T>(value: Resolver<T>, options?: {
65
+ export declare const once: <T>(value: Resolver<T> | Prop<T>, options?: {
62
66
  key?: string;
63
67
  ttl?: number;
64
68
  fresh?: boolean;
@@ -66,16 +70,16 @@ export declare const once: <T>(value: Resolver<T>, options?: {
66
70
  export declare const scroll: <T>(value: Resolver<Paginated<T>>, { pageName }?: {
67
71
  pageName?: string;
68
72
  }) => Prop<Paginated<T>>;
69
- export declare const merge: <T>(value: Lazy<T>, options?: {
73
+ export declare const merge: <T>(value: Lazy<T> | Prop<T>, options?: {
74
+ path?: string | string[];
70
75
  matchOn?: string | string[];
71
76
  }) => Prop<T>;
72
- export declare const prepend: <T>(value: Lazy<T>, options?: {
77
+ export declare const prepend: <T>(value: Lazy<T> | Prop<T>, options?: {
78
+ path?: string | string[];
73
79
  matchOn?: string | string[];
74
80
  }) => Prop<T>;
75
- export declare const deepMerge: <T>(value: Lazy<T>, options?: {
81
+ export declare const deepMerge: <T>(value: Lazy<T> | Prop<T>, options?: {
76
82
  matchOn?: string | string[];
77
83
  }) => Prop<T>;
78
- export declare const propSpec: (value: unknown) => PropSpec | null;
79
- export declare const kindOf: (spec: PropSpec) => "always" | "defer" | "merge" | "once" | "optional" | "scroll";
80
84
  export declare const resolve: (value: Lazy<unknown>) => Promise<unknown>;
81
85
  export {};
@@ -2,27 +2,43 @@
2
2
  * Inertia's prop types (the names are Inertia's: what the client docs call them). A plain value is always sent;
3
3
  * a function is called only when its prop is sent.
4
4
  *
5
- * - `optional(fn)`: never on a full visit, only when a partial reload asks for it
5
+ * - `optional(fn)`: never on a full visit, only when a partial reload names it (`only`)
6
6
  * - `always(value)`: sent on partial reloads too, even when not asked for
7
7
  * - `defer(fn, { group?, rescue? })`: left out of the page, fetched by the client right after it renders (one
8
8
  * request per group); `rescue`: if it throws, the page still loads and `<Deferred>` shows its `rescue` slot
9
- * - `merge(value)` / `prepend(value)` / `deepMerge(value)`: partial reloads merge into what the client holds
9
+ * - `merge(value, { path?, matchOn? })` / `prepend(…)` / `deepMerge(value, { matchOn? })`: partial reloads merge into
10
+ * what the client holds; `path`: the list to merge, inside the prop (`'data'`); `matchOn`: the field, from the
11
+ * prop, that finds an item to replace (`'id'`, `'data.id'`)
10
12
  * - `once(fn, { key?, ttl?, fresh? })`: computed once; later requests say the client holds it and it is skipped
11
13
  * (`fresh`: send it anyway)
12
14
  * - `scroll(fn, { pageName? })`: a page of a list for `<InfiniteScroll>`; `fn` returns `{ data, currentPage,
13
15
  * previousPage, nextPage }` for the page in the query (`?page=`)
16
+ *
17
+ * They combine as Inertia's do (Laravel's `->once()`, `->merge()`, `->defer()`), by wrapping one in another:
18
+ * `once(defer(fn))`, `once(optional(fn))`, `once(merge(fn))`, `merge(defer(fn))` (and `deepMerge`, `prepend`),
19
+ * `defer(scroll(fn))`.
14
20
  */
15
21
  const PROP = Symbol.for('fondu.prop');
16
- const make = (spec) => spec;
17
- export const optional = (value) => make({ [PROP]: 'optional', value });
18
- export const always = (value) => make({ [PROP]: 'always', value });
19
- export const defer = (value, { group = 'default', rescue = false } = {}) => make({ [PROP]: 'defer', value, group, rescue });
20
- export const once = (value, options = {}) => make({ [PROP]: 'once', value, ...options });
21
- export const scroll = (value, { pageName = 'page' } = {}) => make({ [PROP]: 'scroll', value, pageName });
22
- const merger = (strategy) => (value, options = {}) => make({ [PROP]: 'merge', value, strategy, matchOn: [options.matchOn ?? []].flat() });
22
+ export const propSpec = (value) => typeof value === 'object' && value !== null && PROP in value ? value : null;
23
+ /** a new prop, or `kind` added to the one it wraps when Inertia combines them (`can`: the kinds it may wrap) */
24
+ function make(name, value, add, can) {
25
+ const inner = propSpec(value);
26
+ if (!inner)
27
+ return { [PROP]: true, value, ...add };
28
+ const kinds = Object.keys(inner).filter((k) => k !== 'value');
29
+ const other = kinds.find((k) => !can.includes(k));
30
+ if (other)
31
+ throw new Error(`fondu: ${name}() can't wrap ${other}()`);
32
+ return { ...inner, ...add };
33
+ }
34
+ export const optional = (value) => make('optional', value, { optional: true }, []);
35
+ export const always = (value) => make('always', value, { always: true }, []);
36
+ export const defer = (value, { group = 'default', rescue = false } = {}) => make('defer', value, { defer: { group, rescue } }, ['scroll']);
37
+ export const once = (value, options = {}) => make('once', value, { once: options }, ['defer', 'optional', 'merge']);
38
+ export const scroll = (value, { pageName = 'page' } = {}) => make('scroll', value, { scroll: { pageName } }, []);
39
+ const list = (value) => [value ?? []].flat();
40
+ const merger = (strategy) => (value, options = {}) => make(strategy === 'append' ? 'merge' : 'prepend', value, { merge: { strategy, paths: list(options.path), matchOn: list(options.matchOn) } }, ['defer', 'once']);
23
41
  export const merge = merger('append');
24
42
  export const prepend = merger('prepend');
25
- export const deepMerge = merger('deep');
26
- export const propSpec = (value) => typeof value === 'object' && value !== null && PROP in value ? value : null;
27
- export const kindOf = (spec) => spec[PROP];
43
+ export const deepMerge = (value, options = {}) => make('deepMerge', value, { merge: { strategy: 'deep', paths: [], matchOn: list(options.matchOn) } }, ['defer', 'once']);
28
44
  export const resolve = async (value) => typeof value === 'function' ? value() : value;
@@ -2,8 +2,8 @@ import { pages, version } from 'virtual:fondu/assets';
2
2
  import { isPageFile } from '../paths.js';
3
3
  import { renderDocument } from './document.js';
4
4
  import { flashCookie, takeCarried } from './flash.js';
5
- import { isInertia, sameOrigin } from './http.js';
6
- import { kindOf, propSpec, resolve } from './props.js';
5
+ import { back, isInertia, sameOrigin } from './http.js';
6
+ import { propSpec, resolve } from './props.js';
7
7
  const shared = new WeakMap();
8
8
  /** Props every page of this request gets (a middleware calls it: the signed-in user…). */
9
9
  export function share(c, props) {
@@ -23,7 +23,8 @@ export const encryptHistory = () => async (c, next) => {
23
23
  const devPages = import.meta.env.DEV ? import.meta.glob('/app/pages/**/*.{tsx,jsx,mdx}') : {};
24
24
  export const hasPage = (name) => pages
25
25
  ? pages.includes(name)
26
- : isPageFile(`${name}.tsx`) && ['tsx', 'jsx', 'mdx'].some((ext) => `/app/pages/${name}.${ext}` in devPages);
26
+ : isPageFile(`${name}.tsx`) &&
27
+ ['tsx', 'jsx', 'mdx'].some((ext) => `/app/pages/${name}.${ext}` in devPages);
27
28
  const headerSet = (c, name) => {
28
29
  const value = c.req.header(name);
29
30
  return value === undefined
@@ -33,7 +34,8 @@ const headerSet = (c, name) => {
33
34
  .map((s) => s.trim())
34
35
  .filter(Boolean));
35
36
  };
36
- const isPrefetch = (c) => c.req.header('purpose') === 'prefetch' || c.req.header('sec-purpose')?.includes('prefetch') === true;
37
+ const isPrefetch = (c) => c.req.header('purpose') === 'prefetch' ||
38
+ c.req.header('sec-purpose')?.includes('prefetch') === true;
37
39
  /** This URL as the page's: the request's for a GET, the page the request came from otherwise. */
38
40
  function pageUrl(c) {
39
41
  const here = new URL(c.req.url);
@@ -72,36 +74,62 @@ export async function render(c, component, ...[props = {}, options = {}]) {
72
74
  const deferred = {};
73
75
  const onceProps = {};
74
76
  const pending = [];
77
+ const listOnce = (key, once) => {
78
+ onceProps[once.key ?? key] = {
79
+ prop: key,
80
+ expiresAt: once.ttl ? Date.now() + once.ttl * 1000 : null,
81
+ };
82
+ };
83
+ const listMerge = (key, spec) => {
84
+ if (reset.has(key))
85
+ return;
86
+ if (spec.scroll) {
87
+ // <InfiniteScroll> says which side it loads: the previous page goes before what the client holds
88
+ const intent = c.req.header('x-inertia-infinite-scroll-merge-intent') === 'prepend'
89
+ ? 'prependProps'
90
+ : 'mergeProps';
91
+ lists[intent].push(`${key}.data`);
92
+ return;
93
+ }
94
+ const { strategy, paths, matchOn } = spec.merge;
95
+ const into = strategy === 'append'
96
+ ? 'mergeProps'
97
+ : strategy === 'prepend'
98
+ ? 'prependProps'
99
+ : 'deepMergeProps';
100
+ lists[into].push(...(paths.length ? paths.map((path) => `${key}.${path}`) : [key]));
101
+ lists.matchPropsOn.push(...matchOn.map((field) => `${key}.${field}`));
102
+ };
75
103
  for (const [key, value] of Object.entries(all)) {
76
104
  const spec = propSpec(value);
77
- const kind = spec && kindOf(spec);
78
- const asked = only ? only.has(key) : true;
79
- const sent = kind === 'always' || (asked && !except?.has(key));
80
- if (kind === 'defer' && !partial) {
81
- ;
82
- (deferred[spec.group] ??= []).push(key);
105
+ // a partial reload: the props it names (`only`) or keeps (`except`), and the `always` ones
106
+ if (!spec?.always && ((only && !only.has(key)) || except?.has(key)))
83
107
  continue;
84
- }
85
- if (kind === 'optional' && !only?.has(key))
108
+ // only when named (Inertia's docs: `only`), not with `except`, though inertia-laravel's code sends it then
109
+ if (spec?.optional && !only?.has(key)) {
110
+ if (!partial && spec.once)
111
+ listOnce(key, spec.once);
86
112
  continue;
87
- if (kind === 'once') {
88
- const once = spec;
89
- const name = once.key ?? key;
90
- onceProps[name] = { prop: key, expiresAt: once.ttl ? Date.now() + once.ttl * 1000 : null };
91
- if (heldOnce.has(name) && !only?.has(key) && !once.fresh)
92
- continue;
93
113
  }
94
- if (!sent)
114
+ // held by the client: not sent again on a visit (a partial reload sends what it asks for), still listed
115
+ const held = !partial && spec?.once && heldOnce.has(spec.once.key ?? key) && !spec.once.fresh;
116
+ if (spec?.defer && !partial) {
117
+ if (!held)
118
+ (deferred[spec.defer.group] ??= []).push(key);
119
+ if (spec.once)
120
+ listOnce(key, spec.once);
121
+ if (spec.merge || spec.scroll)
122
+ listMerge(key, spec);
95
123
  continue;
96
- if (kind === 'merge' && !reset.has(key)) {
97
- const m = spec;
98
- lists[m.strategy === 'append' ? 'mergeProps' : m.strategy === 'prepend' ? 'prependProps' : 'deepMergeProps'].push(key);
99
- lists.matchPropsOn.push(...m.matchOn.map((field) => `${key}.${field}`));
100
124
  }
101
- if (kind === 'scroll' && !reset.has(key)) {
102
- // <InfiniteScroll> says which side it loads: the previous page goes before what the client holds
103
- lists[c.req.header('x-inertia-infinite-scroll-merge-intent') === 'prepend' ? 'prependProps' : 'mergeProps'].push(`${key}.data`);
125
+ if (held) {
126
+ listOnce(key, spec.once);
127
+ continue;
104
128
  }
129
+ if (spec?.once)
130
+ listOnce(key, spec.once);
131
+ if (spec?.merge || spec?.scroll)
132
+ listMerge(key, spec);
105
133
  pending.push([key, value]);
106
134
  }
107
135
  const rescued = [];
@@ -111,7 +139,7 @@ export async function render(c, component, ...[props = {}, options = {}]) {
111
139
  return [[key, await resolve(spec ? spec.value : value)]];
112
140
  }
113
141
  catch (error) {
114
- if (!(spec && kindOf(spec) === 'defer' && spec.rescue))
142
+ if (!spec?.defer?.rescue)
115
143
  throw error;
116
144
  console.error(`[fondu] deferred prop "${key}" failed (rescued):`, error);
117
145
  rescued.push(key);
@@ -124,10 +152,10 @@ export async function render(c, component, ...[props = {}, options = {}]) {
124
152
  const scrollProps = {};
125
153
  for (const [key, value] of pending) {
126
154
  const spec = propSpec(value);
127
- if (spec && kindOf(spec) === 'scroll' && key in page.props) {
155
+ if (spec?.scroll && key in page.props) {
128
156
  const { currentPage, previousPage, nextPage } = page.props[key];
129
157
  scrollProps[key] = {
130
- pageName: spec.pageName,
158
+ pageName: spec.scroll.pageName,
131
159
  currentPage,
132
160
  previousPage,
133
161
  nextPage,
@@ -153,7 +181,6 @@ export async function render(c, component, ...[props = {}, options = {}]) {
153
181
  page.clearHistory = true;
154
182
  if (options.preserveFragment)
155
183
  page.preserveFragment = true;
156
- c.header('Vary', 'X-Inertia', { append: true });
157
184
  // a page is this visitor's: not stored by shared caches, revalidated by the browser (unless the route said otherwise)
158
185
  if (!c.res.headers.has('Cache-Control'))
159
186
  c.header('Cache-Control', 'private, no-cache');
@@ -166,14 +193,32 @@ export async function render(c, component, ...[props = {}, options = {}]) {
166
193
  // ---- the protocol middleware (installed by createApp)
167
194
  const versionCheck = async (c, next) => {
168
195
  // an Inertia visit made by a client built from other assets: reload the page as a document
169
- if (version && c.req.method === 'GET' && isInertia(c) && c.req.header('x-inertia-version') !== version) {
170
- return c.body(null, 409, { 'X-Inertia-Location': c.req.url, 'X-Inertia-Version': version });
196
+ if (version &&
197
+ c.req.method === 'GET' &&
198
+ isInertia(c) &&
199
+ c.req.header('x-inertia-version') !== version) {
200
+ return c.body(null, 409, {
201
+ 'X-Inertia-Location': c.req.url,
202
+ 'X-Inertia-Version': version,
203
+ Vary: 'X-Inertia',
204
+ });
171
205
  }
172
206
  await next();
173
- if (!isInertia(c) || c.res.status < 300 || c.res.status > 399)
207
+ // a URL answers a visit and a document differently: caches keep them apart
208
+ c.header('Vary', 'X-Inertia', { append: true });
209
+ if (!isInertia(c))
210
+ return;
211
+ // an empty answer to a visit (an action that returns nothing to show): back to the page, as inertia-laravel does
212
+ if (c.res.status === 200 &&
213
+ !c.res.headers.has('x-inertia') &&
214
+ (await c.res.clone().text()) === '') {
215
+ c.res = back(c);
216
+ return;
217
+ }
218
+ if (c.res.status < 300 || c.res.status > 399)
174
219
  return;
175
220
  const to = c.res.headers.get('location') ?? '';
176
- if (to.includes('#')) {
221
+ if (to.includes('#') && !isPrefetch(c)) {
177
222
  // the browser's fetch would follow the redirect and drop the #fragment: the client visits it itself
178
223
  const headers = new Headers(c.res.headers);
179
224
  headers.delete('location');
@@ -51,7 +51,10 @@ export async function readBody(c) {
51
51
  const name = segment === '' ? String(Object.keys(target).length) : segment; // `a[]`: the next index
52
52
  const has = Object.hasOwn(target, name);
53
53
  if (i === path.length - 1) {
54
- if (has && typeof target[name] === 'object' && !(target[name] instanceof File) && !Array.isArray(target[name]))
54
+ if (has &&
55
+ typeof target[name] === 'object' &&
56
+ !(target[name] instanceof File) &&
57
+ !Array.isArray(target[name]))
55
58
  throw malformed(`\`${key}\` is both a value and an object`);
56
59
  if (has && path.length === 1)
57
60
  target[name] = [target[name], value].flat(); // `a=1&a=2`
@@ -61,7 +64,9 @@ export async function readBody(c) {
61
64
  else {
62
65
  if (!has)
63
66
  target[name] = Object.create(null);
64
- else if (typeof target[name] !== 'object' || target[name] instanceof File || Array.isArray(target[name]))
67
+ else if (typeof target[name] !== 'object' ||
68
+ target[name] instanceof File ||
69
+ Array.isArray(target[name]))
65
70
  throw malformed(`\`${key}\` is both a value and an object`);
66
71
  target = target[name];
67
72
  }
@@ -107,7 +112,9 @@ export function validator(schemas) {
107
112
  }
108
113
  if (c.req.header('precognition') === 'true') {
109
114
  const only = c.req.header('precognition-validate-only')?.split(',').filter(Boolean);
110
- const shown = only ? Object.fromEntries(Object.entries(errors).filter(([field]) => only.includes(field))) : errors;
115
+ const shown = only
116
+ ? Object.fromEntries(Object.entries(errors).filter(([field]) => only.includes(field)))
117
+ : errors;
111
118
  const headers = { Precognition: 'true', Vary: 'Precognition' };
112
119
  return Object.keys(shown).length
113
120
  ? c.json({ errors: shown }, 422, headers)
package/dist/virtual.d.ts CHANGED
@@ -11,7 +11,9 @@ declare module 'virtual:fondu/assets' {
11
11
  }
12
12
  declare module 'virtual:fondu/ssr' {
13
13
  /** the app's `createInertiaApp(...)` rendering a page on the server (null: `fondu({ ssr: false })`) */
14
- export const renderPage: ((page: import('@inertiajs/core').Page) => Promise<{ head: string[]; body: string }>) | null
14
+ export const renderPage:
15
+ | ((page: import('@inertiajs/core').Page) => Promise<{ head: string[]; body: string }>)
16
+ | null
15
17
  /** React's static markup of a JSX document (`react-dom/server`'s `renderToStaticMarkup`) */
16
18
  export function renderMarkup(element: import('react').ReactElement): string | Promise<string>
17
19
  }
package/dist/vite/hmr.js CHANGED
@@ -99,7 +99,8 @@ function namedExports(program) {
99
99
  for (const d of declaration?.declarations ?? [])
100
100
  if (d.id.type === 'Identifier')
101
101
  names.push(d.id.name);
102
- for (const s of node.specifiers ?? [])
102
+ for (const s of node.specifiers ??
103
+ [])
103
104
  names.push(s.exported.name ?? s.exported.value);
104
105
  }
105
106
  return names.filter((n) => n !== 'default');
@@ -98,7 +98,9 @@ export default function fondu(options) {
98
98
  ];
99
99
  }
100
100
  async function buildPlugin(options) {
101
- const { default: build } = options.target === 'bun' ? await import('@hono/vite-build/bun') : await import('@hono/vite-build/node');
101
+ const { default: build } = options.target === 'bun'
102
+ ? await import('@hono/vite-build/bun')
103
+ : await import('@hono/vite-build/node');
102
104
  // the app's dependencies stay in node_modules (as with any Node server: native modules cannot be bundled)
103
105
  const pkg = JSON.parse(readFileSync(resolve('package.json'), 'utf8'));
104
106
  const external = Object.keys(pkg.dependencies ?? {}).filter((d) => d !== 'fondu');
@@ -196,7 +198,9 @@ function loadFailure() {
196
198
  failed = true;
197
199
  if (!visit)
198
200
  return next(error);
199
- res.writeHead(409, { 'X-Inertia-Location': req.originalUrl ?? req.url });
201
+ res.writeHead(409, {
202
+ 'X-Inertia-Location': req.originalUrl ?? req.url,
203
+ });
200
204
  res.end();
201
205
  });
202
206
  },
@@ -251,7 +255,10 @@ function core(options) {
251
255
  ? { build: { ...client, outDir: 'dist/client', emptyOutDir: true } }
252
256
  : {
253
257
  ssr: { noExternal: ['fondu'] },
254
- build: { copyPublicDir: false, rollupOptions: { output: { chunkFileNames: 'server/[name]-[hash].js' } } },
258
+ build: {
259
+ copyPublicDir: false,
260
+ rollupOptions: { output: { chunkFileNames: 'server/[name]-[hash].js' } },
261
+ },
255
262
  };
256
263
  },
257
264
  // dev: the dependencies are found before the first request (Vite scans index.html by default; an app has none),
@@ -310,7 +317,8 @@ function core(options) {
310
317
  walk(m);
311
318
  };
312
319
  walk(env.moduleGraph.getModuleById(resolve(config.root, ENTRY)));
313
- const parts = await Promise.all(css.map(async (url) => (await env.transformRequest(url + (url.includes('?') ? '&' : '?') + 'direct'))?.code ?? ''));
320
+ const parts = await Promise.all(css.map(async (url) => (await env.transformRequest(url + (url.includes('?') ? '&' : '?') + 'direct'))
321
+ ?.code ?? ''));
314
322
  res.setHeader('Content-Type', 'text/css');
315
323
  res.end(parts.join('\n'));
316
324
  }
@@ -373,7 +381,9 @@ function core(options) {
373
381
  /** `*.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
382
  const isServerOnly = (id, root) => {
375
383
  const file = id.split('?')[0];
376
- return (/\.server\.[cm]?[jt]sx?$/.test(file) || file.startsWith(`${root}/app/routes/`) || file === `${root}/app/server.ts`);
384
+ return (/\.server\.[cm]?[jt]sx?$/.test(file) ||
385
+ file.startsWith(`${root}/app/routes/`) ||
386
+ file === `${root}/app/server.ts`);
377
387
  };
378
388
  const nonceAttr = `\${nonce ? \` nonce="\${nonce}"\` : ''}`;
379
389
  function devAssets(base) {
@@ -33,7 +33,9 @@ export function layouts() {
33
33
  if (!found)
34
34
  return;
35
35
  // added at the end (imports are hoisted) and within a line: the lines stay where they were (`map: null`)
36
- const imports = chain.map((f, i) => `import __fondu_layout_${i} from ${JSON.stringify(f)};`).join('\n');
36
+ const imports = chain
37
+ .map((f, i) => `import __fondu_layout_${i} from ${JSON.stringify(f)};`)
38
+ .join('\n');
37
39
  const set = `${found.name}.layout ??= [${chain.map((_, i) => `__fondu_layout_${i}`).join(', ')}];`;
38
40
  return { code: `${found.code}\n${imports}\n${set}\n`, map: null };
39
41
  },
@@ -19,7 +19,7 @@ export function ownScripts(html, policy) {
19
19
  const nonce = policy?.match(/'nonce-([^']+)'/)?.[1];
20
20
  if (!nonce)
21
21
  return { html, hashes: [] };
22
- const own = html.replace(/(<(?:script|link)\b[^>]*?)\snonce="([^"]*)"/gi, (tag, before, value) => value === nonce ? tag : before);
22
+ const own = html.replace(/(<(?:script|link)\b[^>]*?)\snonce="([^"]*)"/gi, (tag, before, value) => (value === nonce ? tag : before));
23
23
  const hashes = new Set();
24
24
  for (const [, attrs, code] of own.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi))
25
25
  if (attrs.includes(` nonce="${nonce}"`) && !/\ssrc=/i.test(attrs))
@@ -81,7 +81,10 @@ export async function prerender(start, clientDir, logger, headersFile) {
81
81
  const errors = [];
82
82
  for (const path of paths) {
83
83
  const doc = await get(path, { Accept: 'text/html' });
84
- const visit = await get(path, { 'X-Inertia': 'true', ...(version && { 'X-Inertia-Version': version }) });
84
+ const visit = await get(path, {
85
+ 'X-Inertia': 'true',
86
+ ...(version && { 'X-Inertia-Version': version }),
87
+ });
85
88
  if (doc.status !== 200 || visit.status !== 200) {
86
89
  const to = doc.headers.get('location');
87
90
  errors.push(`${path}: ${doc.status}${to ? ` → ${to}` : ''} (a prerendered page must answer 200 to anyone)`);
@@ -96,7 +99,10 @@ export async function prerender(start, clientDir, logger, headersFile) {
96
99
  const { html, hashes } = ownScripts(await doc.text(), doc.headers.get('content-security-policy') ?? undefined);
97
100
  const headers = Object.fromEntries([...doc.headers]
98
101
  .filter(([name]) => SECURITY_HEADERS.test(name))
99
- .map(([name, value]) => [name, /^content-security-policy/i.test(name) ? staticPolicy(value, hashes) : value]));
102
+ .map(([name, value]) => [
103
+ name,
104
+ /^content-security-policy/i.test(name) ? staticPolicy(value, hashes) : value,
105
+ ]));
100
106
  if (headersFile && security && JSON.stringify(headers) !== JSON.stringify(security)) {
101
107
  errors.push(`${path}: its security headers differ from ${paths[0]}'s; one set is written for all`);
102
108
  continue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fondu",
3
- "version": "0.5.1",
3
+ "version": "0.6.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",