fondu 0.9.6 → 0.11.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 +11 -15
  2. package/dist/client/app.d.ts +40 -0
  3. package/dist/client/app.js +185 -0
  4. package/dist/client/navigation.d.ts +36 -0
  5. package/dist/client/navigation.js +432 -0
  6. package/dist/client/progress.d.ts +16 -0
  7. package/dist/client/progress.js +64 -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 +23 -8
  13. package/dist/paths.js +52 -21
  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 +27 -6
  18. package/dist/server/errors.d.ts +4 -2
  19. package/dist/server/errors.js +23 -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 +18 -10
  28. package/dist/server/protocol.d.ts +22 -35
  29. package/dist/server/protocol.js +67 -195
  30. package/dist/server/routes.d.ts +1 -1
  31. package/dist/server/validate.d.ts +8 -9
  32. package/dist/server/validate.js +23 -37
  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 +174 -80
  39. package/dist/vite/prerender.d.ts +3 -3
  40. package/dist/vite/prerender.js +17 -12
  41. package/dist/vite/strip.d.ts +21 -0
  42. package/dist/vite/strip.js +306 -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
@@ -12,7 +12,7 @@ interface WithInput<S extends Schemas> {
12
12
  /**
13
13
  * Validated input for the handler, after the middleware (a guard runs before the request body is read):
14
14
  * `defineHandler.withValidator({ body, query, params })(...middleware, (c, { body, query, params }) => …)`.
15
- * Any Standard Schema. Invalid input: back to the page with the errors (Inertia), or 422 `{ errors }`.
15
+ * Any Standard Schema. Invalid input: back to the page with the errors, or 422 `{ errors }`.
16
16
  * More than three middleware: combine them with `every()` from `hono/combine`.
17
17
  */
18
18
  declare function withValidator<S extends Schemas>(schemas: S): WithInput<S>;
@@ -4,7 +4,7 @@ const factory = createFactory();
4
4
  /**
5
5
  * Validated input for the handler, after the middleware (a guard runs before the request body is read):
6
6
  * `defineHandler.withValidator({ body, query, params })(...middleware, (c, { body, query, params }) => …)`.
7
- * Any Standard Schema. Invalid input: back to the page with the errors (Inertia), or 422 `{ errors }`.
7
+ * Any Standard Schema. Invalid input: back to the page with the errors, or 422 `{ errors }`.
8
8
  * More than three middleware: combine them with `every()` from `hono/combine`.
9
9
  */
10
10
  function withValidator(schemas) {
@@ -1,13 +1,15 @@
1
1
  import type { Context } from 'hono';
2
- export declare const isInertia: (c: Context) => boolean;
3
- /** a visit or a document load (gets a page), not an API client (gets data) */
2
+ /** a navigation of fondu/client: it wants the page as JSON */
3
+ export declare const isPageRequest: (c: Context) => boolean;
4
+ /** a navigation or a document load (gets a page), not an API client (gets data) */
4
5
  export declare const wantsPage: (c: Context) => boolean;
5
6
  /** `url` as a URL of this site, or null (another site, unparsable) */
6
7
  export declare function sameOrigin(c: Context, url: string | undefined): URL | null;
7
8
  /** Back to the page the request came from (303), or `fallback` when there is none on this site. */
8
9
  export declare const back: (c: Context, fallback?: string) => Response & import("hono").TypedResponse<undefined, 303, "redirect">;
9
10
  /**
10
- * A full page load of `url` (another site, a non-Inertia page): Inertia's requests get 409 + `X-Inertia-Location`
11
- * (the client then sets `window.location`), others a plain redirect.
11
+ * A header added to the response a handler returned. Hono's `c.header()` would copy that response first, and on Bun
12
+ * the copy of `new Response('text')` (`c.text()`) has no Content-Type: browsers download it. Its own headers, then,
13
+ * unless they can't change (a `fetch()`'s): the copy.
12
14
  */
13
- export declare const location: (c: Context, url: string) => (Response & import("hono").TypedResponse<undefined, 302, "redirect">) | (Response & import("hono").TypedResponse<null, 409, "body">);
15
+ export declare function appendHeader(c: Context, name: string, value: string): void;
@@ -1,6 +1,7 @@
1
- export const isInertia = (c) => c.req.header('x-inertia') === 'true';
2
- /** a visit or a document load (gets a page), not an API client (gets data) */
3
- export const wantsPage = (c) => isInertia(c) || (c.req.header('accept') ?? '').includes('text/html');
1
+ /** a navigation of fondu/client: it wants the page as JSON */
2
+ export const isPageRequest = (c) => c.req.header('x-fondu') === 'true';
3
+ /** a navigation or a document load (gets a page), not an API client (gets data) */
4
+ export const wantsPage = (c) => isPageRequest(c) || (c.req.header('accept') ?? '').includes('text/html');
4
5
  /** `url` as a URL of this site, or null (another site, unparsable) */
5
6
  export function sameOrigin(c, url) {
6
7
  if (!url)
@@ -19,7 +20,15 @@ export const back = (c, fallback = '/') => {
19
20
  return c.redirect(from ? from.pathname.replace(/^\/+/, '/') + from.search : fallback, 303);
20
21
  };
21
22
  /**
22
- * A full page load of `url` (another site, a non-Inertia page): Inertia's requests get 409 + `X-Inertia-Location`
23
- * (the client then sets `window.location`), others a plain redirect.
23
+ * A header added to the response a handler returned. Hono's `c.header()` would copy that response first, and on Bun
24
+ * the copy of `new Response('text')` (`c.text()`) has no Content-Type: browsers download it. Its own headers, then,
25
+ * unless they can't change (a `fetch()`'s): the copy.
24
26
  */
25
- export const location = (c, url) => isInertia(c) ? c.body(null, 409, { 'X-Inertia-Location': url }) : c.redirect(url, 302);
27
+ export function appendHeader(c, name, value) {
28
+ try {
29
+ c.res.headers.append(name, value);
30
+ }
31
+ catch {
32
+ c.header(name, value, { append: true });
33
+ }
34
+ }
@@ -18,6 +18,6 @@ export declare function prerenderPaths(routes: PrerenderRoute[]): Promise<{
18
18
  }>;
19
19
  /**
20
20
  * `fondu({ prerender: true })`: the page object of a page without a static file (`/_fondu/pages/x.json` → `/x`, as
21
- * a visit), and, while the build prerenders (`FONDU_PRERENDER` set), the paths to write.
21
+ * a navigation), and, while the build prerenders (`FONDU_PRERENDER` set), the paths to write.
22
22
  */
23
23
  export declare function prerenderRoutes(app: Hono, routes: () => PrerenderRoute[], version: string | null): void;
@@ -1,5 +1,5 @@
1
- import { fillPattern, PAGE_DATA, pathOfPageData, staticFiles } from '../paths.js';
2
- import { isInertia } from './http.js';
1
+ import { endsInIndex, fillPattern, PAGE_DATA, pathOfPageData, staticFiles } from '../paths.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 */
@@ -19,16 +19,21 @@ export async function prerenderPaths(routes) {
19
19
  continue;
20
20
  }
21
21
  const dynamic = route.pattern.includes(':');
22
+ // a page whose URL ends in index: its file would be its directory's page's (index.html), another page
23
+ const add = (path) => endsInIndex(path)
24
+ ? problems.push(`${where}: ${path} ends in index, so its static file would be the page of its directory: ` +
25
+ `leave it out of \`prerender\``)
26
+ : paths.add(path);
22
27
  if (setting === true) {
23
28
  if (dynamic)
24
29
  problems.push(`${where} is dynamic: \`export const prerender = () => [{ …params }]\` lists its pages, or \`= false\``);
25
30
  else
26
- paths.add(route.pattern);
31
+ add(route.pattern);
27
32
  continue;
28
33
  }
29
34
  try {
30
35
  for (const params of await setting())
31
- paths.add(fillPattern(route.pattern, params));
36
+ add(fillPattern(route.pattern, params));
32
37
  }
33
38
  catch (error) {
34
39
  problems.push(`${where}: ${error instanceof Error ? error.message : String(error)}`);
@@ -38,7 +43,7 @@ export async function prerenderPaths(routes) {
38
43
  }
39
44
  /**
40
45
  * `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.
46
+ * a navigation), and, while the build prerenders (`FONDU_PRERENDER` set), the paths to write.
42
47
  */
43
48
  export function prerenderRoutes(app, routes, version) {
44
49
  // Node / Bun: a prerendered page from its file, before the routes and behind the app's security headers (on
@@ -47,8 +52,11 @@ export function prerenderRoutes(app, routes, version) {
47
52
  const read = globalThis[STATIC_FILES];
48
53
  if (!read || (c.req.method !== 'GET' && c.req.method !== 'HEAD'))
49
54
  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')))
55
+ const data = pathOfPageData(c.req.path) !== null; // a navigation, rewritten to the page object by fondu/client
56
+ if (!data && (isPageRequest(c) || !(c.req.header('accept') ?? '').includes('text/html')))
57
+ return next();
58
+ // a URL ending in index is never a static document: that file is its directory's page (the routes answer it)
59
+ if (!data && endsInIndex(c.req.path))
52
60
  return next();
53
61
  let file;
54
62
  try {
@@ -64,7 +72,7 @@ export function prerenderRoutes(app, routes, version) {
64
72
  return next();
65
73
  c.header('Cache-Control', 'private, no-cache');
66
74
  if (data)
67
- c.header('X-Inertia', 'true');
75
+ c.header('X-Fondu', 'true');
68
76
  // the document's own tags have the build's nonce (the build dropped any other): this response's instead, as the
69
77
  // security headers give it a new one
70
78
  const nonce = c.get('secureHeadersNonce');
@@ -81,12 +89,12 @@ export function prerenderRoutes(app, routes, version) {
81
89
  app.get(`${PAGE_DATA}/*`, (c) => {
82
90
  const path = pathOfPageData(c.req.path);
83
91
  // a page object's own URL is not a page: no page object of a page object (and so on)
84
- if (!path || path.startsWith(`${PAGE_DATA}/`))
92
+ if (!path || path.startsWith('/_fondu/'))
85
93
  return c.notFound();
86
94
  const url = new URL(c.req.url);
87
95
  url.pathname = path;
88
96
  const headers = new Headers(c.req.raw.headers);
89
- headers.set('X-Inertia', 'true');
97
+ headers.set('X-Fondu', 'true');
90
98
  let ctx;
91
99
  try {
92
100
  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,80 @@ 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, `c.body(null)`): back to the page. Its body
85
+ // isn't read to tell (a stream's would be, to its end)
86
+ if (isPageRequest(c) && c.res.status === 200 && !c.res.headers.has('x-fondu') && !c.res.body)
215
87
  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 });
88
+ const to = c.res.headers.get('location');
89
+ if (isPageRequest(c) && c.res.status >= 300 && c.res.status < 400 && to) {
90
+ // to another site: fetch() can't follow it (CORS), the client loads it as a document; http(s) only (a browser
91
+ // follows no redirect to `javascript:`, and neither does the client)
92
+ const here = sameOrigin(c, to);
93
+ if (!here) {
94
+ if (webUrl(c, to))
95
+ c.res = c.body(null, 409, { 'X-Fondu-Location': to });
96
+ }
97
+ // to a #fragment: fetch() follows it, the fragment lost (a Response's URL has none); the client follows, from
98
+ // this site's root (a relative Location is the request's, not the page's on the screen)
99
+ else if (to.includes('#'))
100
+ c.res = c.body(null, 200, {
101
+ 'X-Fondu-Redirect': here.pathname.replace(/^\/+/, '/') + here.search + here.hash,
102
+ });
231
103
  }
232
104
  };
233
105
  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,11 @@ 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. A name given again is a list (`a=1&a=2`,
39
+ * `a[b]=1&a[b]=2`); `[]` is the index after the highest one so far. Names that would change the object itself
40
+ * (`__proto__`…) are ignored. A body that can't be one object (JSON or form data that doesn't parse,
41
+ * `a=1&a[b]=2`, names nested deeper than 32) is a 400.
41
42
  */
42
43
  export declare function readBody(c: Context): Promise<unknown>;
43
44
  /** What `withValidator` checks: the request body (JSON or form), the query, the route params. */
@@ -51,9 +52,7 @@ export type Input<S extends Schemas> = {
51
52
  };
52
53
  /**
53
54
  * 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.
55
+ * fit the schema are a 404 (`/users/abc` names no user); invalid body or query fields are a `ValidationError`.
57
56
  */
58
57
  export declare function validator<S extends Schemas>(schemas: S): [MiddlewareHandler, (c: Context) => Input<S>];
59
58
  export {};