fondu 0.9.5 → 0.10.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.
Files changed (51) hide show
  1. package/README.md +7 -12
  2. package/dist/client/app.d.ts +40 -0
  3. package/dist/client/app.js +162 -0
  4. package/dist/client/navigation.d.ts +35 -0
  5. package/dist/client/navigation.js +210 -0
  6. package/dist/client/progress.d.ts +16 -0
  7. package/dist/client/progress.js +51 -0
  8. package/dist/client.d.ts +4 -15
  9. package/dist/client.js +3 -47
  10. package/dist/index.d.ts +3 -4
  11. package/dist/index.js +3 -4
  12. package/dist/paths.d.ts +10 -7
  13. package/dist/paths.js +15 -15
  14. package/dist/server/app.d.ts +4 -5
  15. package/dist/server/app.js +81 -16
  16. package/dist/server/document.d.ts +3 -3
  17. package/dist/server/document.js +7 -6
  18. package/dist/server/errors.d.ts +4 -2
  19. package/dist/server/errors.js +21 -10
  20. package/dist/server/flash.d.ts +4 -7
  21. package/dist/server/flash.js +9 -14
  22. package/dist/server/handler.d.ts +1 -1
  23. package/dist/server/handler.js +1 -1
  24. package/dist/server/http.d.ts +7 -5
  25. package/dist/server/http.js +15 -6
  26. package/dist/server/prerender.d.ts +1 -1
  27. package/dist/server/prerender.js +6 -6
  28. package/dist/server/protocol.d.ts +22 -35
  29. package/dist/server/protocol.js +65 -195
  30. package/dist/server/routes.d.ts +1 -1
  31. package/dist/server/validate.d.ts +7 -9
  32. package/dist/server/validate.js +8 -21
  33. package/dist/types.d.ts +10 -6
  34. package/dist/virtual.d.ts +3 -5
  35. package/dist/vite/hmr.d.ts +3 -3
  36. package/dist/vite/hmr.js +5 -5
  37. package/dist/vite/index.d.ts +9 -5
  38. package/dist/vite/index.js +158 -79
  39. package/dist/vite/prerender.d.ts +7 -3
  40. package/dist/vite/prerender.js +49 -16
  41. package/dist/vite/strip.d.ts +21 -0
  42. package/dist/vite/strip.js +301 -0
  43. package/dist/vite/typegen.d.ts +3 -2
  44. package/dist/vite/typegen.js +6 -10
  45. package/package.json +2 -9
  46. package/dist/server/props.d.ts +0 -85
  47. package/dist/server/props.js +0 -44
  48. package/dist/vite/layouts.d.ts +0 -10
  49. package/dist/vite/layouts.js +0 -110
  50. package/dist/vite/vitest-cache.d.ts +0 -19
  51. package/dist/vite/vitest-cache.js +0 -30
@@ -1,5 +1,5 @@
1
1
  import { fillPattern, PAGE_DATA, pathOfPageData, staticFiles } from '../paths.js';
2
- import { isInertia } from './http.js';
2
+ import { isPageRequest } from './http.js';
3
3
  /** Node / Bun: reads a file of the client build (`docs/intro.html`), or null; set by the built server's entry */
4
4
  const STATIC_FILES = Symbol.for('fondu.staticFiles');
5
5
  /** a page's file: no hidden one (`.vite/manifest.json`), nothing above the client build (`..`), no empty segment */
@@ -38,7 +38,7 @@ export async function prerenderPaths(routes) {
38
38
  }
39
39
  /**
40
40
  * `fondu({ prerender: true })`: the page object of a page without a static file (`/_fondu/pages/x.json` → `/x`, as
41
- * a visit), and, while the build prerenders (`FONDU_PRERENDER` set), the paths to write.
41
+ * a navigation), and, while the build prerenders (`FONDU_PRERENDER` set), the paths to write.
42
42
  */
43
43
  export function prerenderRoutes(app, routes, version) {
44
44
  // Node / Bun: a prerendered page from its file, before the routes and behind the app's security headers (on
@@ -47,8 +47,8 @@ export function prerenderRoutes(app, routes, version) {
47
47
  const read = globalThis[STATIC_FILES];
48
48
  if (!read || (c.req.method !== 'GET' && c.req.method !== 'HEAD'))
49
49
  return next();
50
- const data = pathOfPageData(c.req.path) !== null; // a visit, rewritten to the page object by fondu/client
51
- if (!data && (isInertia(c) || !(c.req.header('accept') ?? '').includes('text/html')))
50
+ const data = pathOfPageData(c.req.path) !== null; // a navigation, rewritten to the page object by fondu/client
51
+ if (!data && (isPageRequest(c) || !(c.req.header('accept') ?? '').includes('text/html')))
52
52
  return next();
53
53
  let file;
54
54
  try {
@@ -64,7 +64,7 @@ export function prerenderRoutes(app, routes, version) {
64
64
  return next();
65
65
  c.header('Cache-Control', 'private, no-cache');
66
66
  if (data)
67
- c.header('X-Inertia', 'true');
67
+ c.header('X-Fondu', 'true');
68
68
  // the document's own tags have the build's nonce (the build dropped any other): this response's instead, as the
69
69
  // security headers give it a new one
70
70
  const nonce = c.get('secureHeadersNonce');
@@ -86,7 +86,7 @@ export function prerenderRoutes(app, routes, version) {
86
86
  const url = new URL(c.req.url);
87
87
  url.pathname = path;
88
88
  const headers = new Headers(c.req.raw.headers);
89
- headers.set('X-Inertia', 'true');
89
+ headers.set('X-Fondu', 'true');
90
90
  let ctx;
91
91
  try {
92
92
  ctx = c.executionCtx;
@@ -1,36 +1,30 @@
1
- import type { SharedPageProps } from '@inertiajs/core';
2
1
  import type { Context, MiddlewareHandler } from 'hono';
3
- import type { Pages } from '../types.js';
2
+ import type { Component, ReactNode } from 'react';
3
+ import type { Shared } from '../types.js';
4
4
  /**
5
- * The server side of Inertia's protocol (https://inertiajs.com/docs/v3/core-concepts/the-protocol).
6
- * The client is `@inertiajs/react`, unchanged.
5
+ * Fondu's protocol: a document gets the HTML page, a navigation of fondu/client (`X-Fondu`) the page as JSON.
7
6
  */
8
7
  type Shareable<T> = {
9
8
  [K in keyof T]?: T[K] | (() => T[K] | Promise<T[K]>);
10
9
  };
11
- /** Props every page of this request gets (a middleware calls it: the signed-in user…). */
12
- export declare function share(c: Context, props: Shareable<SharedPageProps>): void;
13
- type PageName = [keyof Pages] extends [never] ? string : Extract<keyof Pages, string>;
14
- type ComponentProps<N> = N extends keyof Pages ? Pages[N] extends {
15
- default: (...args: infer A) => unknown;
16
- } ? A extends [infer P, ...unknown[]] ? P : Record<string, never> : Record<string, unknown> : Record<string, unknown>;
10
+ /** Props every page of this request gets (a middleware calls it: the signed-in user…); a function when one renders */
11
+ export declare function share(c: Context, props: Shareable<Shared>): void;
12
+ /** a page: a component, its props what it receives (a function component, or a class one) */
13
+ type PageComponent<P> = ((props: P) => ReactNode | Promise<ReactNode>) | (new (props: P) => Component<P>);
17
14
  /** the props a page names: not an index signature (a page without props takes `Record<string, never>`) */
18
15
  type Named<P> = keyof {
19
16
  [K in keyof P as string extends K ? never : number extends K ? never : K]: 0;
20
17
  };
21
18
  /** shared props the page takes with the same type: `render` may leave them out (every page gets them) */
22
19
  type FromShared<P> = {
23
- [K in Named<P> & keyof SharedPageProps]: SharedPageProps[K] extends P[K] ? K : never;
24
- }[Named<P> & keyof SharedPageProps];
20
+ [K in Named<P> & keyof Shared]: Shared[K] extends P[K] ? K : never;
21
+ }[Named<P> & keyof Shared];
25
22
  /** a page prop named like a shared prop, of another type: it would hide the shared one from the layout */
26
- type Clashing<P> = string extends keyof SharedPageProps ? never : Exclude<Named<P> & keyof SharedPageProps, FromShared<P>>;
23
+ type Clashing<P> = string extends keyof Shared ? never : Exclude<Named<P> & keyof Shared, FromShared<P>>;
27
24
  type ClashError = 'fondu: this page prop has the name of a shared prop (share()); rename it';
28
25
  /** what `render` takes: the component's props, less `errors` and the shared props it gets anyway (may still be given) */
29
- type OwnProps<N> = Omit<ComponentProps<N>, FromShared<ComponentProps<N>> | Clashing<ComponentProps<N>> | 'errors'> & Partial<Pick<ComponentProps<N>, FromShared<ComponentProps<N>>>> & {
30
- [K in Clashing<ComponentProps<N>>]: ClashError;
31
- };
32
- type PropsInput<P> = {
33
- [K in keyof P]: P[K] | (() => P[K] | Promise<P[K]>);
26
+ type OwnProps<P> = Omit<P, FromShared<P> | Clashing<P> | 'errors'> & Partial<Pick<P, FromShared<P>>> & {
27
+ [K in Clashing<P>]: ClashError;
34
28
  };
35
29
  type Json = string | number | boolean | null;
36
30
  /** 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 */
@@ -57,27 +51,20 @@ export type Delivered<P> = {
57
51
  type RequiredKeys<T> = {
58
52
  [K in keyof T]-?: object extends Pick<T, K> ? never : K;
59
53
  }[keyof T];
60
- /**
61
- * The pages of these requests are encrypted in the browser's history (Laravel's `EncryptHistory` middleware), so Back
62
- * after signing out can't show them: in `routes/account/_middleware.ts`, `export default encryptHistory()`. A route
63
- * can still opt out: `render(c, page, props, { encryptHistory: false })`.
64
- */
65
- export declare const encryptHistory: () => MiddlewareHandler;
66
54
  export interface RenderOptions {
67
55
  status?: number;
68
- /** the page's state is encrypted in the browser's history; default: `encryptHistory()` above the route, or not */
69
- encryptHistory?: boolean;
70
- clearHistory?: boolean;
71
- preserveFragment?: boolean;
72
56
  }
73
- type RenderArgs<N> = [RequiredKeys<OwnProps<N>>] extends [never] ? OptionalArgs<N> : string extends keyof OwnProps<N> ? OptionalArgs<N> : RequiredArgs<N>;
74
- type OptionalArgs<N> = [props?: PropsInput<Delivered<OwnProps<N>>>, options?: RenderOptions];
75
- type RequiredArgs<N> = [props: PropsInput<Delivered<OwnProps<N>>>, options?: RenderOptions];
76
- export declare const hasPage: (name: string) => boolean;
57
+ type RenderArgs<P> = [keyof OwnProps<P>] extends [never] ? [props?: Record<string, never>, options?: RenderOptions] : [RequiredKeys<OwnProps<P>>] extends [never] ? OptionalArgs<P> : string extends keyof OwnProps<P> ? OptionalArgs<P> : RequiredArgs<P>;
58
+ type OptionalArgs<P> = [props?: Delivered<OwnProps<P>>, options?: RenderOptions];
59
+ type RequiredArgs<P> = [props: Delivered<OwnProps<P>>, options?: RenderOptions];
60
+ export declare const registerPage: (component: object, id: string) => void;
61
+ export declare const routePage: (id: string) => MiddlewareHandler;
77
62
  /**
78
- * The page `component` (a file in `pages/`, without extension) with these props: JSON for Inertia's requests,
79
- * the HTML document (server-rendered) otherwise. Props are checked against the component's own props.
63
+ * The route file's page (its default export) with these props: JSON for a navigation, the HTML document
64
+ * (server-rendered) otherwise. Props are checked against the component's own, as JSON delivers them.
80
65
  */
81
- export declare function render<N extends PageName>(c: Context, component: N, ...[props, options]: RenderArgs<N>): Promise<Response>;
66
+ export declare function render<P extends object>(c: Context, page: PageComponent<P>, ...[props, options]: RenderArgs<P>): Promise<Response>;
67
+ /** @internal the page `id` (a route file without its extension) with these props: `render()`, the error page */
68
+ export declare function renderPage(c: Context, id: string, props: Record<string, unknown>, options?: RenderOptions): Promise<Response>;
82
69
  export declare const protocol: MiddlewareHandler[];
83
70
  export {};
@@ -1,41 +1,24 @@
1
- import { pages, version } from 'virtual:fondu/assets';
2
- import { isPageFile } from '../paths.js';
1
+ import { version } from 'virtual:fondu/assets';
3
2
  import { renderDocument } from './document.js';
4
3
  import { flashCookie, takeCarried } from './flash.js';
5
- import { back, isInertia, sameOrigin } from './http.js';
6
- import { propSpec, resolve } from './props.js';
4
+ import { appendHeader, back, isPageRequest, sameOrigin } from './http.js';
7
5
  const shared = new WeakMap();
8
- /** Props every page of this request gets (a middleware calls it: the signed-in user…). */
6
+ /** Props every page of this request gets (a middleware calls it: the signed-in user…); a function when one renders */
9
7
  export function share(c, props) {
10
8
  shared.set(c, { ...shared.get(c), ...props });
11
9
  }
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();
10
+ // the pages of app/routes/ (createApp): a component → its ids; and, per request, the page of the route answering it
11
+ // (the ids: a page may be the default export of several, `export { default } from './index.tsx'`)
12
+ const pageIds = new WeakMap();
13
+ const ownPages = new WeakMap();
14
+ export const registerPage = (component, id) => {
15
+ const ids = pageIds.get(component) ?? new Set();
16
+ pageIds.set(component, ids.add(id));
21
17
  };
22
- // development: the files in app/pages/ (Vite keeps the list current); a build: the pages in the client manifest
23
- const devPages = import.meta.env.DEV ? import.meta.glob('/app/pages/**/*.{tsx,jsx,mdx}') : {};
24
- export const hasPage = (name) => pages
25
- ? pages.includes(name)
26
- : isPageFile(`${name}.tsx`) &&
27
- ['tsx', 'jsx', 'mdx'].some((ext) => `/app/pages/${name}.${ext}` in devPages);
28
- const headerSet = (c, name) => {
29
- const value = c.req.header(name);
30
- return value === undefined
31
- ? null
32
- : new Set(value
33
- .split(',')
34
- .map((s) => s.trim())
35
- .filter(Boolean));
18
+ export const routePage = (id) => async (c, next) => {
19
+ ownPages.set(c, id);
20
+ await next();
36
21
  };
37
- const isPrefetch = (c) => c.req.header('purpose') === 'prefetch' ||
38
- c.req.header('sec-purpose')?.includes('prefetch') === true;
39
22
  /** This URL as the page's: the request's for a GET, the page the request came from otherwise. */
40
23
  function pageUrl(c) {
41
24
  const here = new URL(c.req.url);
@@ -43,191 +26,78 @@ function pageUrl(c) {
43
26
  return from.pathname.replace(/^\/+/, '/') + from.search;
44
27
  }
45
28
  /**
46
- * The page `component` (a file in `pages/`, without extension) with these props: JSON for Inertia's requests,
47
- * the HTML document (server-rendered) otherwise. Props are checked against the component's own props.
29
+ * The route file's page (its default export) with these props: JSON for a navigation, the HTML document
30
+ * (server-rendered) otherwise. Props are checked against the component's own, as JSON delivers them.
48
31
  */
49
- export async function render(c, component, ...[props = {}, options = {}]) {
50
- if (!hasPage(component))
51
- throw new Error(`fondu: there is no page "${component}": create app/pages/${component}.tsx (or .mdx)`);
52
- const partial = c.req.header('x-inertia-partial-component') === component;
53
- const only = partial ? headerSet(c, 'x-inertia-partial-data') : null;
54
- const except = partial ? headerSet(c, 'x-inertia-partial-except') : null;
55
- const reset = headerSet(c, 'x-inertia-reset') ?? new Set();
56
- const heldOnce = headerSet(c, 'x-inertia-except-once-props') ?? new Set();
57
- // shown by the next page, a partial reload too (a form with `only`), as Laravel's session does; not a prefetch
58
- const carried = takeCarried(c, !isPrefetch(c));
59
- const sharedProps = shared.get(c) ?? {};
60
- const all = { ...sharedProps, ...props };
32
+ export function render(c, page, ...[props = {}, options = {}]) {
33
+ const own = ownPages.get(c);
34
+ if (!own || !pageIds.get(page)?.has(own))
35
+ throw new Error(own
36
+ ? `fondu: render() renders the page of its own route file, routes/${own}: its default export`
37
+ : 'fondu: render() renders the page of its route file (a .tsx or .mdx file, its default export); this route has none');
38
+ return renderPage(c, own, props, options);
39
+ }
40
+ /** @internal the page `id` (a route file without its extension) with these props: `render()`, the error page */
41
+ export async function renderPage(c, id, props, options = {}) {
42
+ const carried = takeCarried(c);
43
+ const fromShared = await Promise.all(Object.entries(shared.get(c) ?? {}).map(async ([key, value]) => [
44
+ key,
45
+ typeof value === 'function' ? await value() : value,
46
+ ]));
61
47
  const page = {
62
- component,
63
- props: { errors: {} },
48
+ component: id,
49
+ props: { ...Object.fromEntries(fromShared), ...props, errors: carried.errors },
64
50
  url: pageUrl(c),
65
51
  version: version ?? null,
66
52
  flash: carried.flash,
67
53
  };
68
- const lists = {
69
- mergeProps: [],
70
- prependProps: [],
71
- deepMergeProps: [],
72
- matchPropsOn: [],
73
- };
74
- const deferred = {};
75
- const onceProps = {};
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
- };
103
- for (const [key, value] of Object.entries(all)) {
104
- const spec = propSpec(value);
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)))
107
- continue;
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);
112
- continue;
113
- }
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);
123
- continue;
124
- }
125
- if (held) {
126
- listOnce(key, spec.once);
127
- continue;
128
- }
129
- if (spec?.once)
130
- listOnce(key, spec.once);
131
- if (spec?.merge || spec?.scroll)
132
- listMerge(key, spec);
133
- pending.push([key, value]);
134
- }
135
- const rescued = [];
136
- const resolved = await Promise.all(pending.map(async ([key, value]) => {
137
- const spec = propSpec(value);
138
- try {
139
- return [[key, await resolve(spec ? spec.value : value)]];
140
- }
141
- catch (error) {
142
- if (!spec?.defer?.rescue)
143
- throw error;
144
- console.error(`[fondu] deferred prop "${key}" failed (rescued):`, error);
145
- rescued.push(key);
146
- return [];
147
- }
148
- }));
149
- page.props = { ...Object.fromEntries(resolved.flat()), errors: carried.errors };
150
- if (rescued.length)
151
- page.rescuedProps = rescued;
152
- const scrollProps = {};
153
- for (const [key, value] of pending) {
154
- const spec = propSpec(value);
155
- if (spec?.scroll && key in page.props) {
156
- const { currentPage, previousPage, nextPage } = page.props[key];
157
- scrollProps[key] = {
158
- pageName: spec.scroll.pageName,
159
- currentPage,
160
- previousPage,
161
- nextPage,
162
- reset: reset.has(key),
163
- };
164
- }
165
- }
166
- if (Object.keys(scrollProps).length)
167
- page.scrollProps = scrollProps;
168
- for (const [name, list] of Object.entries(lists))
169
- if (list.length)
170
- page[name] = list;
171
- if (Object.keys(deferred).length)
172
- page.deferredProps = deferred;
173
- if (Object.keys(onceProps).length)
174
- page.onceProps = onceProps;
175
- const sharedKeys = Object.keys(sharedProps);
176
- if (sharedKeys.length)
177
- page.sharedProps = sharedKeys;
178
- if (options.encryptHistory ?? encrypted.has(c))
179
- page.encryptHistory = true;
180
- if (options.clearHistory || carried.clearHistory)
181
- page.clearHistory = true;
182
- if (options.preserveFragment)
183
- page.preserveFragment = true;
184
54
  // a page is this visitor's: not stored by shared caches, revalidated by the browser (unless the route said otherwise)
185
55
  if (!c.res.headers.has('Cache-Control'))
186
56
  c.header('Cache-Control', 'private, no-cache');
187
- if (isInertia(c)) {
188
- c.header('X-Inertia', 'true');
57
+ if (isPageRequest(c)) {
58
+ c.header('X-Fondu', 'true');
189
59
  return c.json(page, (options.status ?? 200));
190
60
  }
191
61
  return c.html(await renderDocument(c, page), (options.status ?? 200));
192
62
  }
63
+ /** an http(s) URL, as `to` resolves from the request's */
64
+ function webUrl(c, to) {
65
+ try {
66
+ return /^https?:$/.test(new URL(to, c.req.url).protocol);
67
+ }
68
+ catch {
69
+ return false;
70
+ }
71
+ }
193
72
  // ---- the protocol middleware (installed by createApp)
194
73
  const versionCheck = async (c, next) => {
195
- // an Inertia visit made by a client built from other assets: reload the page as a document
74
+ // a navigation of a client built from other assets: the page loads as a document
196
75
  if (version &&
197
76
  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
- });
77
+ isPageRequest(c) &&
78
+ c.req.header('x-fondu-version') !== version) {
79
+ return c.body(null, 409, { 'X-Fondu-Location': c.req.url, Vary: 'X-Fondu' });
205
80
  }
206
81
  await next();
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()) === '') {
82
+ // a URL answers a navigation and a document differently: caches keep them apart
83
+ appendHeader(c, 'Vary', 'X-Fondu');
84
+ // an empty answer to a form (an action that returns nothing to show): back to the page
85
+ if (isPageRequest(c) &&
86
+ c.res.status === 200 &&
87
+ !c.res.headers.has('x-fondu') &&
88
+ (await c.res.clone().text()) === '')
215
89
  c.res = back(c);
216
- return;
217
- }
218
- if (c.res.status < 300 || c.res.status > 399)
219
- return;
220
- const to = c.res.headers.get('location') ?? '';
221
- if (to.includes('#') && !isPrefetch(c)) {
222
- // the browser's fetch would follow the redirect and drop the #fragment: the client visits it itself
223
- const headers = new Headers(c.res.headers);
224
- headers.delete('location');
225
- headers.set('X-Inertia-Redirect', to);
226
- c.res = new Response(null, { status: 409, headers });
227
- }
228
- else if (c.res.status === 302 && ['PUT', 'PATCH', 'DELETE'].includes(c.req.method)) {
229
- // a 302 after PUT / PATCH / DELETE would be followed with the same method: make it 303 (Inertia's rule)
230
- c.res = new Response(c.res.body, { status: 303, headers: c.res.headers });
90
+ const to = c.res.headers.get('location');
91
+ if (isPageRequest(c) && c.res.status >= 300 && c.res.status < 400 && to) {
92
+ // to another site: fetch() can't follow it (CORS), the client loads it as a document; http(s) only (a browser
93
+ // follows no redirect to `javascript:`, and neither does the client)
94
+ if (!sameOrigin(c, to)) {
95
+ if (webUrl(c, to))
96
+ c.res = c.body(null, 409, { 'X-Fondu-Location': to });
97
+ }
98
+ // to a #fragment: fetch() follows it, the fragment lost (a Response's URL has none); the client follows
99
+ else if (to.includes('#'))
100
+ c.res = c.body(null, 200, { 'X-Fondu-Redirect': to });
231
101
  }
232
102
  };
233
103
  export const protocol = [flashCookie, versionCheck];
@@ -8,7 +8,7 @@ export interface RouteModule {
8
8
  prerender?: Prerender;
9
9
  /** the values its params take, `{ lang: ['de', 'fr'] }`, any other not its URL (also in a `_middleware.ts`) */
10
10
  params?: Params;
11
- /** a `_middleware.ts`: the middleware */
11
+ /** a `_middleware.ts`: the middleware; a page: its component */
12
12
  default?: Handlers;
13
13
  loader?: Handlers;
14
14
  action?: Handlers;
@@ -24,8 +24,8 @@ type StandardResult<Output> = {
24
24
  };
25
25
  type InferOutput<S> = S extends StandardSchemaV1<unknown, infer O> ? O : never;
26
26
  /**
27
- * Field errors (`{ email: 'Enter a valid email' }`). Thrown from an action, or by `withValidator`: Inertia's requests
28
- * and plain forms go back to the page they came from with the errors (its `errors` prop, as Laravel does); other
27
+ * Field errors (`{ email: 'Enter a valid email' }`). Thrown from an action, or by `withValidator`: navigations
28
+ * and forms go back to the page they came from with the errors (its `errors` prop, as Laravel does); other
29
29
  * requests (an API client) get 422 `{ errors }`.
30
30
  */
31
31
  export declare class ValidationError extends Error {
@@ -34,10 +34,10 @@ export declare class ValidationError extends Error {
34
34
  }
35
35
  export declare function validationErrorResponse(c: Context, error: ValidationError): Response;
36
36
  /**
37
- * A request body as one object: JSON, or form fields with PHP-style names, as Inertia's `useForm` sends files
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. 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.
37
+ * A request body as one object: JSON, or form fields with PHP-style names, as forms write them (`notify[]`,
38
+ * `user[name]`); files are `File`s, empty file inputs are left out. Names that would change the object itself
39
+ * (`__proto__`…) are ignored. A body that can't be one object (JSON that doesn't parse, `a=1&a[b]=2`, names nested
40
+ * deeper than 32) is a 400.
41
41
  */
42
42
  export declare function readBody(c: Context): Promise<unknown>;
43
43
  /** What `withValidator` checks: the request body (JSON or form), the query, the route params. */
@@ -51,9 +51,7 @@ export type Input<S extends Schemas> = {
51
51
  };
52
52
  /**
53
53
  * The validation step of `withValidator`: a middleware, and the validated input of its request. Params that don't
54
- * fit the schema are a 404 (`/users/abc` names no user); invalid body or query fields are a `ValidationError`. A Precognition
55
- * request (Inertia's live validation: `<Form validate>`, `useForm().withPrecognition()`) stops here: 204 when
56
- * valid, 422 `{ errors }` otherwise, the handler never runs.
54
+ * fit the schema are a 404 (`/users/abc` names no user); invalid body or query fields are a `ValidationError`.
57
55
  */
58
56
  export declare function validator<S extends Schemas>(schemas: S): [MiddlewareHandler, (c: Context) => Input<S>];
59
57
  export {};
@@ -2,8 +2,8 @@ import { HTTPException } from 'hono/http-exception';
2
2
  import { flashErrors } from './flash.js';
3
3
  import { back, wantsPage } from './http.js';
4
4
  /**
5
- * Field errors (`{ email: 'Enter a valid email' }`). Thrown from an action, or by `withValidator`: Inertia's requests
6
- * and plain forms go back to the page they came from with the errors (its `errors` prop, as Laravel does); other
5
+ * Field errors (`{ email: 'Enter a valid email' }`). Thrown from an action, or by `withValidator`: navigations
6
+ * and forms go back to the page they came from with the errors (its `errors` prop, as Laravel does); other
7
7
  * requests (an API client) get 422 `{ errors }`.
8
8
  */
9
9
  export class ValidationError extends Error {
@@ -17,17 +17,16 @@ export class ValidationError extends Error {
17
17
  export function validationErrorResponse(c, error) {
18
18
  if (!wantsPage(c))
19
19
  return c.json({ errors: error.errors }, 422);
20
- const bag = c.req.header('x-inertia-error-bag');
21
- flashErrors(c, bag ? { [bag]: error.errors } : error.errors);
20
+ flashErrors(c, error.errors);
22
21
  return back(c);
23
22
  }
24
23
  /** how deep form field names nest (`a[b][c]`: 3) */
25
24
  const DEPTH = 32;
26
25
  /**
27
- * A request body as one object: JSON, or form fields with PHP-style names, as Inertia's `useForm` sends files
28
- * (`notify[0]`, `user[name]`) and as plain forms write them (`notify[]`); files are `File`s, empty file inputs
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.
26
+ * A request body as one object: JSON, or form fields with PHP-style names, as forms write them (`notify[]`,
27
+ * `user[name]`); files are `File`s, empty file inputs are left out. Names that would change the object itself
28
+ * (`__proto__`…) are ignored. A body that can't be one object (JSON that doesn't parse, `a=1&a[b]=2`, names nested
29
+ * deeper than 32) is a 400.
31
30
  */
32
31
  export async function readBody(c) {
33
32
  const malformed = (why) => new HTTPException(400, { message: `Malformed request body: ${why}` });
@@ -85,9 +84,7 @@ const arrays = (value) => {
85
84
  const pathOf = (path) => (path ?? []).map((p) => String(typeof p === 'object' ? p.key : p)).join('.');
86
85
  /**
87
86
  * The validation step of `withValidator`: a middleware, and the validated input of its request. Params that don't
88
- * fit the schema are a 404 (`/users/abc` names no user); invalid body or query fields are a `ValidationError`. A Precognition
89
- * request (Inertia's live validation: `<Form validate>`, `useForm().withPrecognition()`) stops here: 204 when
90
- * valid, 422 `{ errors }` otherwise, the handler never runs.
87
+ * fit the schema are a 404 (`/users/abc` names no user); invalid body or query fields are a `ValidationError`.
91
88
  */
92
89
  export function validator(schemas) {
93
90
  const inputs = new WeakMap();
@@ -110,16 +107,6 @@ export function validator(schemas) {
110
107
  else
111
108
  input[key] = result.value;
112
109
  }
113
- if (c.req.header('precognition') === 'true') {
114
- const only = c.req.header('precognition-validate-only')?.split(',').filter(Boolean);
115
- const shown = only
116
- ? Object.fromEntries(Object.entries(errors).filter(([field]) => only.includes(field)))
117
- : errors;
118
- const headers = { Precognition: 'true', Vary: 'Precognition' };
119
- return Object.keys(shown).length
120
- ? c.json({ errors: shown }, 422, headers)
121
- : c.body(null, 204, { ...headers, 'Precognition-Success': 'true' });
122
- }
123
110
  if (Object.keys(errors).length)
124
111
  throw new ValidationError(errors);
125
112
  inputs.set(c, input);
package/dist/types.d.ts CHANGED
@@ -1,15 +1,19 @@
1
1
  /**
2
2
  * Filled in by the generated `app/fondu.gen.d.ts` (written by the Vite plugin, committed with the app):
3
- * `pages`: page name → its module, `routes`: URL pattern → its route module.
3
+ * `routes`: URL pattern → its route module.
4
4
  *
5
- * `c.get()` / `c.set()` are typed by Hono's own `ContextVariableMap`; shared props and flash by Inertia's
6
- * `InertiaConfig`.
5
+ * And by the app, where it likes (`declare module 'fondu' { interface Register { … } }`): `shared`, the props
6
+ * `share()` gives every page; `flash`, what `flash()` takes. `c.get()` / `c.set()` are typed by Hono's own
7
+ * `ContextVariableMap`.
7
8
  */
8
9
  export interface Register {
9
10
  }
10
- export type Pages = Register extends {
11
- pages: infer P;
12
- } ? P : Record<string, unknown>;
13
11
  export type Routes = Register extends {
14
12
  routes: infer R;
15
13
  } ? R : Record<string, unknown>;
14
+ export type Shared = Register extends {
15
+ shared: infer S;
16
+ } ? S : Record<string, unknown>;
17
+ export type Flash = Register extends {
18
+ flash: infer F;
19
+ } ? F : Record<string, unknown>;
package/dist/virtual.d.ts CHANGED
@@ -1,18 +1,16 @@
1
1
  // Modules generated by the fondu Vite plugin.
2
2
  declare module 'virtual:fondu/assets' {
3
- /** client asset version (production builds); a page visit from other assets is reloaded as a document */
3
+ /** client asset version (production builds); a navigation from other assets loads as a document */
4
4
  export const version: string | null
5
- /** the page names of a build (from the client manifest); null in development */
6
- export const pages: string[] | null
7
5
  /** `fondu({ prerender: true })`: page objects of pages without a static file are answered (`/_fondu/pages/…`) */
8
6
  export const prerender: boolean
9
7
  /** the `<head>` tags a page needs: the client entry and its styles, the page component's chunk */
10
8
  export function assetTags(component: string, nonce?: string): string
11
9
  }
12
10
  declare module 'virtual:fondu/ssr' {
13
- /** the app's `createInertiaApp(...)` rendering a page on the server (null: `fondu({ ssr: false })`) */
11
+ /** the server render of a page (null: `fondu({ ssr: false })`) */
14
12
  export const renderPage:
15
- | ((page: import('@inertiajs/core').Page) => Promise<{ head: string[]; body: string }>)
13
+ | ((page: import('./client/navigation.js').Page) => Promise<{ head: string; body: string }>)
16
14
  | null
17
15
  /** React's static markup of a JSX document (`react-dom/server`'s `renderToStaticMarkup`) */
18
16
  export function renderMarkup(element: import('react').ReactElement): string | Promise<string>
@@ -1,5 +1,5 @@
1
1
  import type { Plugin } from 'vite';
2
- /** the browser's event for "the current page's props may have changed" (the client entry: Inertia's reload) */
2
+ /** the browser's event for "the current page's props may have changed" (the client entry: `reload()`) */
3
3
  export declare const PROPS_EVENT = "fondu:props";
4
4
  /** the global the dev preamble reads: the named exports of each page module (`__getReactRefreshIgnoredExports`) */
5
5
  export declare const PAGE_EXPORTS = "__fondu_pageExports";
@@ -10,7 +10,7 @@ type Node = {
10
10
  /**
11
11
  * What a change to a module reaches on the server, through the app's own modules only (app/, not node_modules nor
12
12
  * fondu): a route (`app/routes/…`: what it renders may have changed), and the document (`app/server.ts`, reached
13
- * other than through a route or the pages' entry). `app/app.tsx` is the pages' entry: the browser's own HMR.
13
+ * other than through a route).
14
14
  */
15
15
  export declare function reach(start: Iterable<Node>, root: string): {
16
16
  routes: boolean;
@@ -20,7 +20,7 @@ export declare function reach(start: Iterable<Node>, root: string): {
20
20
  * Dev: a change updates what it changes, without reloading the page where it can.
21
21
  * - The browser's code: React Fast Refresh (`@vitejs/plugin-react`), MDX pages too. A page module's other exports
22
22
  * (an MDX page's `toc`) are left out of Fast Refresh's check: the server reads them, and the next rule applies.
23
- * - What a route depends on: the browser asks for the page's props again (Inertia's `router.reload()`), its state
23
+ * - What a route depends on: the browser asks for the page's props again (fondu/client's `reload()`), its state
24
24
  * and scroll kept, as React Router's "Hot Data Revalidation".
25
25
  * - The document (`server.ts` and what only it imports): the page reloads.
26
26
  */