fondu 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026-present, Fondu contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,169 @@
1
- # Temporary Holding Version
1
+ # Fondu
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Inertia v3 on Hono.** The browser runs `@inertiajs/react` as it is; the server is Hono with Fondu's Inertia v3
4
+ protocol; `app/routes/` holds the server side (loader, action, actions), `app/pages/` the React pages. The same app
5
+ runs on **Node, Bun and Cloudflare Workers**.
6
+
7
+ Fondu is glue, not a new framework: it joins Hono, Inertia and Vite, and writes as little of its own as it can.
8
+
9
+ ```
10
+ packages/fondu the package (≈1,100 lines)
11
+ apps/node a small example: Link, loader, action, HTTP routes — Node and Bun
12
+ apps/cloudflare every Inertia v3 feature, one page each — Workers, D1, Better Auth
13
+ ```
14
+
15
+ ## Who does what
16
+
17
+ | Part | Done by |
18
+ | ----------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
19
+ | Browser: visits, history, prefetch, forms, progress, `<Head>`, deferred, merging, infinite scroll, optimistic updates, Precognition | `@inertiajs/react` |
20
+ | HTTP, middleware, CSRF, security headers, trailing slashes | Hono and its middleware |
21
+ | Dev server, production build | Node / Bun: `@hono/vite-dev-server`, `@hono/vite-build`; Cloudflare: `@cloudflare/vite-plugin` |
22
+ | Page resolution, the server render's entry | `@inertiajs/vite` (rendered in the same process) |
23
+ | The Inertia v3 server protocol, `routes/`, generated types, the document, error pages, server-only guard | Fondu |
24
+
25
+ ## This repository
26
+
27
+ ```bash
28
+ bun install # also builds packages/fondu (the examples use the built package, like a real app)
29
+ bun run test # the protocol, on a small app with app.request()
30
+ bun run typecheck # the package and both examples (with apps/cloudflare/e2e/types.ts)
31
+ bun run check # format (oxfmt), lint (oxlint), typecheck
32
+ bun run dev # rebuild packages/fondu on change
33
+ ```
34
+
35
+ Commits follow [Conventional Commits](https://www.conventionalcommits.org) (lefthook runs commitlint, and formats and
36
+ lints what is staged). A release: `bun run release` picks the version, tags it and pushes; CI publishes the tag to npm
37
+ (trusted publishing, with provenance) and writes the GitHub Release from the commits.
38
+
39
+ `apps/node`: `bun run dev`; `bun run build && bun run start` (Node); `bun run build:bun && bun run start:bun` (Bun).
40
+ `apps/cloudflare`: `cp .dev.vars.example .dev.vars`, then `bun run dev` (in workerd), `bun run preview`, `bun run deploy`.
41
+
42
+ ## An app
43
+
44
+ ```
45
+ package.json fondu hono @inertiajs/react react react-dom (Node: also @hono/node-server)
46
+ "imports": { "#/*": "./app/*" }: import '#/lib/db.server.ts' from anywhere in app/
47
+ vite.config.ts plugins: [fondu({ target: 'node' })] 'bun'; Cloudflare: [cloudflare(), fondu({ target: 'cloudflare' })]
48
+ app/
49
+ server.ts export default createApp()
50
+ app.tsx createInertiaApp({ pages: './pages', … }): browser and server render
51
+ routes/ server code only; the file path is the URL
52
+ _middleware.ts for its directory and below (routes/_middleware.ts: every request, 404s too)
53
+ index.ts /
54
+ users/[id].ts /users/:id
55
+ api/health.ts /api/health
56
+ pages/ React pages, rendered by name: 'users/show' is pages/users/show.tsx
57
+ error.tsx the error page (404, 403, 500…)
58
+ fondu.gen.d.ts generated types (commit it)
59
+ ```
60
+
61
+ `createApp()` comes with CSRF protection, security headers (`Referrer-Policy: same-origin`, which `back()` needs), a
62
+ Content Security Policy, one URL per page (`/users/` → `/users`) and error handling. Options: `document` (the HTML
63
+ around pages: `<html>` attributes, the viewport, fonts…), `errorPage`, `trailingSlash: 'append'`, `csrf` and
64
+ `secureHeaders` (Hono's options, or `false`).
65
+
66
+ The policy: `default-src 'self'`, scripts of this site or with the request's nonce (the document's scripts have it),
67
+ inline styles (style attributes), `data:` images and fonts, no plugins (`object-src 'none'`), `base-uri 'self'`. A
68
+ directive of yours replaces that one: `secureHeaders: { contentSecurityPolicy: { fontSrc: ["'self'",
69
+ 'https://fonts.gstatic.com'] } }` (apps/node does so for Google Fonts); `contentSecurityPolicy: false`: none.
70
+
71
+ ### routes/: loader, action, actions
72
+
73
+ ```ts
74
+ // app/routes/users/[id].ts
75
+ import { back, defineHandler, flash, render } from 'fondu'
76
+ import * as z from 'zod/mini'
77
+
78
+ const params = z.object({ id: z.coerce.number() })
79
+
80
+ export const loader = defineHandler.withValidator({ params })(async (c, { params }) =>
81
+ // GET /users/7
82
+ render(c, 'users/show', { user: await getUser(params.id) }),
83
+ )
84
+
85
+ export const actions = {
86
+ rename: defineHandler.withValidator({ params, body: renameSchema })(requireUser, async (c, { params, body }) => {
87
+ await renameUser(params.id, body.name) // POST /users/7?rename
88
+ return back(c)
89
+ }),
90
+ }
91
+ ```
92
+
93
+ - `loader` is GET, `action` POST, `actions.x` `POST ?x` (a plain form can pick one). HTTP routes export `GET` / `POST` / `PUT` / `PATCH` / `DELETE`.
94
+ - `defineHandler(...middleware, handler)` is Hono's `createHandlers`. `.withValidator({ body, query, params })(...middleware, (c, input) => …)`: the middleware first (up to three; more: `every()` from `hono/combine`), then the schemas (any Standard Schema).
95
+ - Every `.ts` file in `routes/` is a route, except `_middleware.ts` and tests. `(group)` directories take no URL segment.
96
+
97
+ ### Validation (Inertia's way)
98
+
99
+ Invalid `body` or `query`: Inertia visits and plain forms get a 303 back with the errors in the next page's `errors`
100
+ prop (in the `X-Inertia-Error-Bag` bag when there is one); API clients get 422 `{ errors }`. Params that don't fit are
101
+ a 404. A Precognition request (`<Form>`'s `validate()`, `useForm().withPrecognition()`) is only validated: 204 or 422.
102
+ The same schema can be imported by the page to check before sending.
103
+
104
+ ### Pages and props
105
+
106
+ ```tsx
107
+ // app/pages/users/show.tsx — the component's parameter is the page's props
108
+ export default function Show({ user }: { user: User }) { … }
109
+ ```
110
+
111
+ `render(c, 'users/show', props, options?)` takes only pages that exist, with the component's props; a page prop named
112
+ like a shared prop is a type error. A function prop is called only when it is sent.
113
+
114
+ | prop | |
115
+ | -------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
116
+ | `optional(fn)` | only when a partial reload names it |
117
+ | `always(v)` | partial reloads too |
118
+ | `defer(fn, { group?, rescue? })` | after the page renders, one request per group; `rescue`: a failure is listed in `rescuedProps` |
119
+ | `merge` / `prepend` / `deepMerge(v, { matchOn? })` | merged with what the client holds |
120
+ | `once(fn, { key?, ttl?, fresh? })` | skipped when the client holds it |
121
+ | `scroll(fn, { pageName? })` | a page of a list for `<InfiniteScroll>`: `{ data, currentPage, previousPage, nextPage }` |
122
+
123
+ Options: `status`, `encryptHistory`, `clearHistory`, `preserveFragment`. Also `flash(c, data)`, `clearHistory(c)`,
124
+ `back(c)`, `location(c, url)` (409 + `X-Inertia-Location`); a redirect with a `#fragment` becomes a 409
125
+ `X-Inertia-Redirect` by itself.
126
+
127
+ ### Types
128
+
129
+ ```ts
130
+ // where the values are set (e.g. routes/_middleware.ts)
131
+ declare module 'hono' {
132
+ interface ContextVariableMap {
133
+ user: User | null
134
+ } // c.get('user')
135
+ }
136
+ declare module '@inertiajs/core' {
137
+ interface InertiaConfig {
138
+ sharedPageProps: { auth: { user: { name: string } | null } } // share(), usePage().props
139
+ flashDataType: { message?: string } // flash(), usePage().flash
140
+ }
141
+ }
142
+ ```
143
+
144
+ `href(path, params?)` from `fondu/client`: a URL of `routes/` (or one of a file's actions: `'/users/:id?rename'`),
145
+ params required, a typo is a type error. The method is Inertia's: `<Link href={href('/logout')} method="post" as="button">`.
146
+
147
+ ### Server-side rendering
148
+
149
+ Document loads are rendered on the server in the same process, then hydrated. Off for the whole app:
150
+ `fondu({ ssr: false })`. Off for some routes: `withoutSsr()` (in a `_middleware.ts` for a directory, or in one
151
+ handler). A browser-only part of a page: Inertia's `<WhenMounted>`.
152
+
153
+ ### Errors
154
+
155
+ Unknown URLs and thrown errors: API clients get plain text; pages get `pages/error.tsx` with `{ status }`, inside the
156
+ layout with the shared props. In development a 500 is a report of the error instead (Inertia shows it in its dialog
157
+ during a visit). `render()` of a page that doesn't exist says which file to create. Your own handling: Hono's
158
+ `app.notFound()` / `app.onError()` on the app `createApp()` returns.
159
+
160
+ ### Editor snippets
161
+
162
+ `.vscode/fondu.code-snippets`: `/route`, `/api`, `/loader`, `/action`, `/actions`, `/validated`, `/get` … `/delete`,
163
+ `/middleware` in routes; `/page`, `/layout`, `/form` in pages. Copy it into your app's `.vscode/` and edit it freely.
164
+
165
+ ## Deploying
166
+
167
+ - **Node**: `vite build --mode client && vite build`, then `node dist/index.js` (dependencies stay in `node_modules`). `PORT` sets the port; SIGTERM / SIGINT wait for running requests (10 s).
168
+ - **Bun**: `fondu({ target: 'bun' })`, `bun dist/index.js`.
169
+ - **Cloudflare Workers**: `wrangler.jsonc` `main` is `./app/server.ts`; one `vite build`; `wrangler deploy`. `/assets/*` get long-lived caching from a generated `_headers` (unless `public/_headers` exists).
@@ -0,0 +1,19 @@
1
+ import type { Routes } from './types.js';
2
+ /**
3
+ * Typed URLs from `app/routes/` (as React Router's `href`): `href('/users/:id', { id })` → `'/users/7'`;
4
+ * one of a file's `actions`: `href('/users/:id?delete', { id })`. Only patterns that exist; params are required.
5
+ * The method is Inertia's: `<Link href={href('/logout')} method="post" as="button">`, `<Form action=… method="post">`.
6
+ */
7
+ type Keys = keyof Routes & string;
8
+ type Actions = {
9
+ [P in Keys]: Routes[P] extends {
10
+ actions: infer A;
11
+ } ? `${P}?${keyof A & string}` : never;
12
+ }[Keys];
13
+ export type Href = [Keys] extends [never] ? string : Keys | Actions;
14
+ type ParamNames<P extends string> = P extends `${string}:${infer Name}{${string}}${infer Rest}` ? Name | ParamNames<Rest> : P extends `${string}:${infer Name}/${infer Rest}` ? Name | ParamNames<`/${Rest}`> : P extends `${string}:${infer Name}?${string}` ? Name : P extends `${string}:${infer Name}` ? Name : never;
15
+ type Args<P extends string> = [ParamNames<P>] extends [never] ? [] : [params: {
16
+ [K in ParamNames<P>]: string | number;
17
+ }];
18
+ export declare function href<P extends Href>(path: P, ...[params]: Args<P>): string;
19
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,4 @@
1
+ import { fillPattern } from './paths.js';
2
+ export function href(path, ...[params]) {
3
+ return fillPattern(path, params);
4
+ }
@@ -0,0 +1,9 @@
1
+ export { defineHandler, defineMiddleware } from './server/handler.js';
2
+ export { render, share, type RenderOptions } from './server/protocol.js';
3
+ export { back, location, isInertia, wantsPage } from './server/http.js';
4
+ export { optional, always, defer, once, merge, prepend, deepMerge, scroll, type Prop, type Paginated, } from './server/props.js';
5
+ export { flash, clearHistory } from './server/flash.js';
6
+ export { ValidationError, type StandardSchemaV1 } from './server/validate.js';
7
+ export { withoutSsr, type DocumentParts, type DocumentTemplate } from './server/document.js';
8
+ export type { Register } from './types.js';
9
+ export { createApp, type CreateAppOptions } from './server/app.js';
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ export { defineHandler, defineMiddleware } from './server/handler.js';
2
+ export { render, share } from './server/protocol.js';
3
+ export { back, location, isInertia, wantsPage } from './server/http.js';
4
+ export { optional, always, defer, once, merge, prepend, deepMerge, scroll, } from './server/props.js';
5
+ export { flash, clearHistory } from './server/flash.js';
6
+ export { ValidationError } from './server/validate.js';
7
+ export { withoutSsr } from './server/document.js';
8
+ // last: createApp imports the app's routes, which import this module (the exports above are ready by then)
9
+ export { createApp } from './server/app.js';
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `routes/` file → URL pattern (Hono syntax). Shared by the runtime (`createApp`) and the type generator.
3
+ *
4
+ * - `index.ts` is its directory: `routes/users/index.ts` → `/users`
5
+ * - `[id]` → `:id`, `[...path]` → `:path{.+}` (one or more segments)
6
+ * - `(group)` directories group files without a URL segment
7
+ * - `_middleware.ts` applies to its directory
8
+ */
9
+ export declare function routePattern(file: string): string;
10
+ /** a path inside `routes/` that is a route file: every `.ts` file but `_middleware.ts`, tests and declarations */
11
+ export declare function isRouteFile(file: string): boolean;
12
+ /** the `_middleware.ts` files that apply to a route file, outermost first */
13
+ export declare function middlewareFor(file: string, middleware: readonly string[]): string[];
14
+ /** `/users/:id` + `{ id: 7 }` → `/users/7`; catch-alls keep their slashes */
15
+ export declare function fillPattern(pattern: string, params?: Record<string, string | number>): string;
package/dist/paths.js ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * `routes/` file → URL pattern (Hono syntax). Shared by the runtime (`createApp`) and the type generator.
3
+ *
4
+ * - `index.ts` is its directory: `routes/users/index.ts` → `/users`
5
+ * - `[id]` → `:id`, `[...path]` → `:path{.+}` (one or more segments)
6
+ * - `(group)` directories group files without a URL segment
7
+ * - `_middleware.ts` applies to its directory
8
+ */
9
+ export function routePattern(file) {
10
+ const segments = file
11
+ .replace(/\.ts$/, '')
12
+ .split('/')
13
+ .filter((s) => s !== '' && s !== 'index' && !/^\(.+\)$/.test(s))
14
+ .map((s) => s.replace(/^\[\.\.\.(\w+)\]$/, ':$1{.+}').replace(/^\[(\w+)\]$/, ':$1'));
15
+ return '/' + segments.join('/');
16
+ }
17
+ /** a path inside `routes/` that is a route file: every `.ts` file but `_middleware.ts`, tests and declarations */
18
+ export function isRouteFile(file) {
19
+ return (file.endsWith('.ts') &&
20
+ !file.endsWith('.d.ts') &&
21
+ !/\.(test|spec)\.ts$/.test(file) &&
22
+ file.split('/').at(-1) !== '_middleware.ts');
23
+ }
24
+ /** the `_middleware.ts` files that apply to a route file, outermost first */
25
+ export function middlewareFor(file, middleware) {
26
+ const dirs = file.split('/').slice(0, -1);
27
+ const out = [];
28
+ for (let i = 0; i <= dirs.length; i++) {
29
+ const candidate = [...dirs.slice(0, i), '_middleware.ts'].join('/');
30
+ if (middleware.includes(candidate))
31
+ out.push(candidate);
32
+ }
33
+ return out;
34
+ }
35
+ /** `/users/:id` + `{ id: 7 }` → `/users/7`; catch-alls keep their slashes */
36
+ export function fillPattern(pattern, params = {}) {
37
+ return pattern.replace(/:(\w+)(\{[^}]*\})?/g, (_, name, catchAll) => {
38
+ const value = params[name];
39
+ if (value === undefined)
40
+ throw new Error(`fondu: missing param "${name}" for ${pattern}`);
41
+ const parts = catchAll ? String(value).split('/') : [String(value)];
42
+ if (parts.some((p) => p === '' || p === '.' || p === '..'))
43
+ throw new Error(`fondu: param "${name}" is not a path segment: ${JSON.stringify(value)}`);
44
+ return parts.map(encodeURIComponent).join('/');
45
+ });
46
+ }
@@ -0,0 +1,32 @@
1
+ import { Hono } from 'hono';
2
+ import { csrf } from 'hono/csrf';
3
+ import { secureHeaders } from 'hono/secure-headers';
4
+ import { type DocumentTemplate } from './document.js';
5
+ export interface CreateAppOptions {
6
+ /** the HTML document around pages (default: a minimal one) */
7
+ document?: DocumentTemplate;
8
+ /** the page for 404 / 500… (it gets `{ status }`), default `'error'` (`app/pages/error.tsx`); `false`: plain text */
9
+ errorPage?: string | false;
10
+ /** `/users/` → `/users` (`'trim'`, default) or the other way (`'append'`): Hono's trailing-slash middleware */
11
+ trailingSlash?: 'trim' | 'append';
12
+ /** `hono/csrf`'s options; `false`: off */
13
+ csrf?: Parameters<typeof csrf>[0] | false;
14
+ /**
15
+ * `hono/secure-headers`' options; `false`: off. Defaults: `referrerPolicy: 'same-origin'` (which `back()` needs) and
16
+ * a Content Security Policy whose directives yours replace one by one; `contentSecurityPolicy: false`: none
17
+ */
18
+ secureHeaders?: (Omit<SecureHeadersOptions, 'contentSecurityPolicy'> & {
19
+ contentSecurityPolicy?: SecureHeadersOptions['contentSecurityPolicy'] | false;
20
+ }) | false;
21
+ }
22
+ type SecureHeadersOptions = NonNullable<Parameters<typeof secureHeaders>[0]>;
23
+ /**
24
+ * The Hono app from `app/routes/` (found by Vite, no generated code). Each file is a URL; it exports:
25
+ * - `loader` (GET), `action` (POST), `actions` (POST `?name`) — usually rendering a page from `app/pages/`
26
+ * - or plain HTTP handlers: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`
27
+ * `_middleware.ts` applies to its directory and below (`routes/_middleware.ts`: every request, 404s included).
28
+ * Built in: CSRF protection, security headers, one URL per page (trailing slash), the error page. Your own 404 /
29
+ * error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
30
+ */
31
+ export declare function createApp(options?: CreateAppOptions): Hono;
32
+ export {};
@@ -0,0 +1,130 @@
1
+ import { Hono } from 'hono';
2
+ import { every } from 'hono/combine';
3
+ import { csrf } from 'hono/csrf';
4
+ import { HTTPException } from 'hono/http-exception';
5
+ import { NONCE, secureHeaders } from 'hono/secure-headers';
6
+ import { appendTrailingSlash, trimTrailingSlash } from 'hono/trailing-slash';
7
+ import { isRouteFile, middlewareFor, routePattern } from '../paths.js';
8
+ import { settings } from './document.js';
9
+ import { errorResponse } from './errors.js';
10
+ import { protocol } from './protocol.js';
11
+ import { ValidationError, validationErrorResponse } from './validate.js';
12
+ /** the default Content Security Policy: scripts of this site or with the request's nonce (the document's) */
13
+ const CSP = {
14
+ defaultSrc: ["'self'"],
15
+ scriptSrc: ["'self'", NONCE],
16
+ styleSrc: ["'self'", "'unsafe-inline'"], // style attributes (React, Base UI), Inertia's progress bar
17
+ imgSrc: ["'self'", 'data:'],
18
+ fontSrc: ["'self'", 'data:'],
19
+ objectSrc: ["'none'"],
20
+ baseUri: ["'self'"],
21
+ };
22
+ const ROOT = '/app/routes/';
23
+ const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
24
+ /** a thrown `ValidationError` becomes the page it came from with its errors (or 422 for an API client) */
25
+ const handle = (h) => async (c, next) => {
26
+ try {
27
+ return await h(c, next);
28
+ }
29
+ catch (error) {
30
+ if (error instanceof ValidationError)
31
+ return validationErrorResponse(c, error);
32
+ throw error;
33
+ }
34
+ };
35
+ const chain = (handlers) => [handlers].flat().map(handle);
36
+ /** the action a POST asks for: `?update` (the first query key, without a value) */
37
+ function actionName(url) {
38
+ const first = new URL(url).searchParams.entries().next().value;
39
+ return first && first[1] === '' ? first[0] : null;
40
+ }
41
+ /**
42
+ * The Hono app from `app/routes/` (found by Vite, no generated code). Each file is a URL; it exports:
43
+ * - `loader` (GET), `action` (POST), `actions` (POST `?name`) — usually rendering a page from `app/pages/`
44
+ * - or plain HTTP handlers: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`
45
+ * `_middleware.ts` applies to its directory and below (`routes/_middleware.ts`: every request, 404s included).
46
+ * Built in: CSRF protection, security headers, one URL per page (trailing slash), the error page. Your own 404 /
47
+ * error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
48
+ */
49
+ export function createApp(options = {}) {
50
+ const app = new Hono();
51
+ const own = { document: options.document, errorPage: options.errorPage ?? 'error' };
52
+ const append = options.trailingSlash === 'append';
53
+ app.use(async (c, next) => {
54
+ settings.set(c, own);
55
+ await next();
56
+ });
57
+ if (options.secureHeaders !== false) {
58
+ const { contentSecurityPolicy: csp, ...headers } = options.secureHeaders ?? {};
59
+ app.use(secureHeaders({
60
+ referrerPolicy: 'same-origin',
61
+ ...headers,
62
+ contentSecurityPolicy: csp === false ? undefined : { ...CSP, ...csp },
63
+ }));
64
+ }
65
+ if (options.csrf !== false)
66
+ app.use(csrf(options.csrf));
67
+ app.use(append ? appendTrailingSlash() : trimTrailingSlash(), ...protocol);
68
+ app.notFound((c) => errorResponse(c, 404));
69
+ app.onError((error, c) => {
70
+ if (error instanceof HTTPException && error.res)
71
+ return error.getResponse();
72
+ return errorResponse(c, error instanceof HTTPException ? error.status : 500, error);
73
+ });
74
+ const modules = import.meta.glob(['/app/routes/**/*.ts', '!/app/routes/**/*.d.ts'], { eager: true });
75
+ const files = Object.keys(modules).map((k) => k.slice(ROOT.length));
76
+ if (modules[ROOT + '_middleware.ts'])
77
+ app.use(...chain(modules[ROOT + '_middleware.ts'].default ?? []));
78
+ const middlewareFiles = files.filter((f) => f.endsWith('/_middleware.ts'));
79
+ const routes = files
80
+ .filter(isRouteFile)
81
+ // static before dynamic before catch-all, segment by segment
82
+ .map((file) => ({ file, pattern: withSlash(routePattern(file), append), mod: modules[ROOT + file] }))
83
+ .sort((a, b) => rank(a.pattern).localeCompare(rank(b.pattern)));
84
+ for (const { file, pattern, mod } of routes) {
85
+ const mws = middlewareFor(file, middlewareFiles).flatMap((f) => chain(modules[ROOT + f].default ?? []));
86
+ const conflict = (a, b) => {
87
+ if (mod[a] && mod[b])
88
+ throw new Error(`fondu: routes/${file} exports both \`${a}\` and \`${b}\`, which handle the same requests`);
89
+ };
90
+ conflict('loader', 'GET');
91
+ conflict('action', 'POST');
92
+ conflict('actions', 'POST');
93
+ const add = (method, handlers) => app.on(method, pattern, ...handlers);
94
+ const get = mod.loader ?? mod.GET;
95
+ if (get)
96
+ add('GET', [...mws, ...chain(get)]);
97
+ if (mod.action || mod.actions || mod.POST) {
98
+ const defaultPost = mod.action ?? mod.POST;
99
+ const actions = mod.actions ?? {};
100
+ add('POST', [
101
+ ...mws,
102
+ async (c, next) => {
103
+ const name = actionName(c.req.url);
104
+ const picked = name !== null && Object.hasOwn(actions, name)
105
+ ? actions[name]
106
+ : name === null || !mod.actions
107
+ ? defaultPost
108
+ : undefined;
109
+ if (!picked)
110
+ return c.notFound();
111
+ return every(...chain(picked))(c, next);
112
+ },
113
+ ]);
114
+ }
115
+ for (const method of METHODS) {
116
+ if (method === 'GET' || method === 'POST')
117
+ continue;
118
+ const h = mod[method];
119
+ if (h)
120
+ add(method, [...mws, ...chain(h)]);
121
+ }
122
+ }
123
+ return app;
124
+ }
125
+ const withSlash = (pattern, append) => append && pattern !== '/' && !pattern.endsWith('}') ? pattern + '/' : pattern;
126
+ /** sort key: static segments first, then `:param`, then catch-alls */
127
+ const rank = (pattern) => pattern
128
+ .split('/')
129
+ .map((s) => (s.includes('{') ? '2' : s.startsWith(':') ? '1' : '0') + s)
130
+ .join('/');
@@ -0,0 +1,23 @@
1
+ import type { Page } from '@inertiajs/core';
2
+ import type { Context, MiddlewareHandler } from 'hono';
3
+ /** The HTML document around a page. */
4
+ export interface DocumentParts {
5
+ /** the page's `<Head>` tags (server render), then the client's styles and scripts */
6
+ head: string;
7
+ /** the page data (`<script data-page>`) and the rendered page (`<div id="app">`) */
8
+ body: string;
9
+ c: Context;
10
+ }
11
+ export type DocumentTemplate = (parts: DocumentParts) => string;
12
+ /** the options of the app (`createApp`) a request belongs to */
13
+ export declare const settings: WeakMap<Context<any, any, {}>, {
14
+ document?: DocumentTemplate;
15
+ errorPage: string | false;
16
+ }>;
17
+ /**
18
+ * Pages of these requests are rendered in the browser only (Laravel's `withoutSsr`): in `routes/admin/_middleware.ts`,
19
+ * `export default withoutSsr()`; for one route, `defineHandler(withoutSsr(), …)`. No server rendering at all:
20
+ * `fondu({ ssr: false })`.
21
+ */
22
+ export declare const withoutSsr: () => MiddlewareHandler;
23
+ export declare function renderDocument(c: Context, page: Page): Promise<string>;
@@ -0,0 +1,34 @@
1
+ import { assetTags } from 'virtual:fondu/assets';
2
+ import { renderPage } from 'virtual:fondu/ssr';
3
+ const defaultTemplate = ({ head, body }) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">${head}</head><body>${body}</body></html>`;
4
+ /** the options of the app (`createApp`) a request belongs to */
5
+ export const settings = new WeakMap();
6
+ const browserOnly = new WeakSet();
7
+ /**
8
+ * Pages of these requests are rendered in the browser only (Laravel's `withoutSsr`): in `routes/admin/_middleware.ts`,
9
+ * `export default withoutSsr()`; for one route, `defineHandler(withoutSsr(), …)`. No server rendering at all:
10
+ * `fondu({ ssr: false })`.
11
+ */
12
+ export const withoutSsr = () => async (c, next) => {
13
+ browserOnly.add(c);
14
+ await next();
15
+ };
16
+ /** Inertia's own encoding of the page data (`buildSSRBody`): `/` and `<` escaped, no HTML entities. */
17
+ const pageScript = (page) => `<script data-page="app" type="application/json">${JSON.stringify(page).replace(/\//g, '\\/').replace(/</g, '\\u003c')}</script>`;
18
+ export async function renderDocument(c, page) {
19
+ const nonce = c.get('secureHeadersNonce');
20
+ let ssr = null;
21
+ try {
22
+ if (renderPage && !browserOnly.has(c))
23
+ ssr = await renderPage(page);
24
+ }
25
+ catch (error) {
26
+ // like Laravel: a page that fails to render on the server is still sent, and rendered in the browser
27
+ console.error(`[fondu] server render of "${page.component}" failed, sending it to render in the browser:`, error);
28
+ }
29
+ // the page data first, as Inertia writes it: its client reads the first `script[data-page]` in the document, so
30
+ // nothing in the page's content can come before it
31
+ const body = ssr?.body ?? `${pageScript(page)}<div id="app"></div>`;
32
+ const template = settings.get(c)?.document ?? defaultTemplate;
33
+ return template({ head: (ssr?.head.join('') ?? '') + assetTags(page.component, nonce), body, c });
34
+ }
@@ -0,0 +1,8 @@
1
+ import type { Context } from 'hono';
2
+ /**
3
+ * The answer to an unmatched URL or a thrown error (installed by `createApp`):
4
+ * - API clients: the `HTTPException`'s response, or plain text
5
+ * - pages, in development: a report of the error (Inertia shows it in its dialog during a visit)
6
+ * - pages: the error page (`app/pages/error.tsx`, `{ status }`) with the shared props, as Inertia's docs describe
7
+ */
8
+ export declare function errorResponse(c: Context, status: number, error?: unknown): Promise<Response>;
@@ -0,0 +1,73 @@
1
+ import { HTTPException } from 'hono/http-exception';
2
+ import { settings } from './document.js';
3
+ import { wantsPage } from './http.js';
4
+ import { hasPage, render } from './protocol.js';
5
+ const TEXT = {
6
+ 401: 'Unauthorized',
7
+ 403: 'Forbidden',
8
+ 404: 'Not Found',
9
+ 419: 'Page Expired',
10
+ 429: 'Too Many Requests',
11
+ 503: 'Service Unavailable',
12
+ };
13
+ /**
14
+ * The answer to an unmatched URL or a thrown error (installed by `createApp`):
15
+ * - API clients: the `HTTPException`'s response, or plain text
16
+ * - pages, in development: a report of the error (Inertia shows it in its dialog during a visit)
17
+ * - pages: the error page (`app/pages/error.tsx`, `{ status }`) with the shared props, as Inertia's docs describe
18
+ */
19
+ export async function errorResponse(c, status, error) {
20
+ if (status >= 500)
21
+ console.error(error);
22
+ const code = status;
23
+ const text = TEXT[status] ?? (status >= 500 ? 'Internal Server Error' : 'Error');
24
+ if (!wantsPage(c))
25
+ return error instanceof HTTPException ? error.getResponse() : c.text(text, code);
26
+ if (import.meta.env.DEV && status >= 500)
27
+ return c.html(report(c, error), 500);
28
+ const page = settings.get(c)?.errorPage;
29
+ if (page && hasPage(page)) {
30
+ try {
31
+ return await render(c, page, { status }, { status });
32
+ }
33
+ catch (failure) {
34
+ console.error('[fondu] the error page failed to render:', failure);
35
+ }
36
+ }
37
+ return c.text(text, code);
38
+ }
39
+ const escape = (s) => s.replace(/[&<>"']/g, (ch) => `&#${ch.charCodeAt(0)};`);
40
+ /** the development error report: what failed, where (your files first), for which request */
41
+ function report(c, error) {
42
+ const err = error instanceof Error ? error : new Error(String(error));
43
+ const frames = (err.stack ?? '')
44
+ .split('\n')
45
+ .slice(1)
46
+ .map((line) => line.trim())
47
+ .filter(Boolean);
48
+ const nonce = c.get('secureHeadersNonce');
49
+ const url = new URL(c.req.url);
50
+ const frame = (line) => {
51
+ const own = /\/app\//.test(line) && !line.includes('node_modules');
52
+ return `<li class="${own ? 'own' : ''}">${escape(line.replace(/^at /, ''))}</li>`;
53
+ };
54
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escape(err.name)}: ${escape(err.message)}</title>
55
+ <style${nonce ? ` nonce="${nonce}"` : ''}>
56
+ *{box-sizing:border-box}body{margin:0;padding:clamp(16px,6vw,80px);font:14px/1.55 ui-sans-serif,system-ui,sans-serif;color:#1f2328;background:#f9f9f9;--x:clamp(16px,4vw,32px)}
57
+ article{background:#fff;border:1px solid #eaecef;border-radius:6px;overflow:hidden}
58
+ header{padding:28px var(--x) 22px;border-bottom:1px solid #eaecef;border-top:4px solid #d1242f}
59
+ .kind{font:600 12px ui-monospace,SFMono-Regular,Menlo,monospace;color:#d1242f;margin:0 0 8px}
60
+ h1{margin:0;font-size:20px;font-weight:600;line-height:1.35;white-space:pre-wrap;word-break:break-word}
61
+ .req{margin:12px 0 0;font:13px ui-monospace,SFMono-Regular,Menlo,monospace;color:#57606a}
62
+ .req b{color:#1f2328;font-weight:600}
63
+ main{padding:20px var(--x) 28px}h2{margin:0 0 10px;font-size:12px;font-weight:600;color:#57606a}
64
+ ol{display:grid;grid-template-columns:minmax(100%,max-content);margin:0;padding:0;list-style:none;font:12.5px/1.7 ui-monospace,SFMono-Regular,Menlo,monospace;color:#8c959f;overflow-x:auto}
65
+ li{white-space:pre;padding:1px 8px;border-radius:4px}li.own{color:#1f2328;background:#fff8c5}
66
+ footer{padding:0 var(--x) 24px;color:#afb8c1;font-size:12px;font-weight:400}
67
+ </style></head><body><article>
68
+ <header><p class="kind">${escape(err.name)} · 500</p><h1>${escape(err.message)}</h1>
69
+ <p class="req"><b>${escape(c.req.method)}</b> ${escape(url.pathname + url.search)}${c.req.header('x-inertia') ? ' · Inertia visit' : ''}</p></header>
70
+ <main><h2>Stack — your files are highlighted</h2><ol>${frames.map(frame).join('')}</ol></main>
71
+ <footer>Shown in development only. In production this request gets your error page with status 500.</footer>
72
+ </article></body></html>`;
73
+ }
@@ -0,0 +1,18 @@
1
+ import type { FlashData } from '@inertiajs/core';
2
+ import type { Context, MiddlewareHandler } from 'hono';
3
+ /** https, directly or behind a proxy that says so */
4
+ export declare const isSecure: (c: Context) => boolean;
5
+ /** Flash data for the next page (`page.flash` / `usePage().flash`, Inertia's `flash` event). */
6
+ export declare function flash(c: Context, data: Partial<FlashData> & Record<string, unknown>): void;
7
+ /** Validation errors for the next page (its `errors` prop). */
8
+ export declare function flashErrors(c: Context, errors: Record<string, unknown>): void;
9
+ /** The next page clears the browser history Inertia kept (and encrypted): after signing out, for example. */
10
+ export declare function clearHistory(c: Context): void;
11
+ /** What this page shows: carried over from the previous request (read once), plus what this request set. */
12
+ export declare function takeCarried(c: Context, consume: boolean): {
13
+ flash: Record<string, unknown>;
14
+ errors: Record<string, unknown>;
15
+ clearHistory: boolean;
16
+ };
17
+ /** Writes what is left for the next request; clears what was shown. Installed by `createApp()`. */
18
+ export declare const flashCookie: MiddlewareHandler;