fondu 0.12.1 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/client/app.d.ts +36 -8
- package/dist/client/app.js +65 -41
- package/dist/client/form.d.ts +3 -1
- package/dist/client/form.js +11 -7
- package/dist/client/navigation.d.ts +4 -1
- package/dist/client/navigation.js +173 -29
- package/dist/client.d.ts +12 -8
- package/dist/client.js +7 -1
- package/dist/form.d.ts +2 -2
- package/dist/form.js +3 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/paths.d.ts +13 -2
- package/dist/paths.js +18 -7
- package/dist/server/app.d.ts +7 -3
- package/dist/server/app.js +38 -27
- package/dist/server/document.d.ts +10 -2
- package/dist/server/document.js +71 -19
- package/dist/server/errors.d.ts +0 -2
- package/dist/server/errors.js +4 -3
- package/dist/server/flash.d.ts +0 -2
- package/dist/server/flash.js +1 -1
- package/dist/server/http.d.ts +4 -0
- package/dist/server/http.js +5 -0
- package/dist/server/prerender.js +7 -49
- package/dist/server/protocol.d.ts +16 -2
- package/dist/server/protocol.js +95 -15
- package/dist/server/routes.d.ts +4 -1
- package/dist/server/routes.js +9 -1
- package/dist/server/static.d.ts +14 -0
- package/dist/server/static.js +37 -0
- package/dist/server/validate.d.ts +2 -6
- package/dist/virtual.d.ts +5 -1
- package/dist/vite/index.d.ts +4 -1
- package/dist/vite/index.js +33 -25
- package/dist/vite/prerender.d.ts +12 -9
- package/dist/vite/prerender.js +17 -13
- package/dist/vite/strip.d.ts +1 -3
- package/dist/vite/strip.js +3 -15
- package/dist/vite/typegen.d.ts +0 -6
- package/dist/vite/typegen.js +3 -3
- package/package.json +1 -1
package/dist/client.d.ts
CHANGED
|
@@ -1,11 +1,5 @@
|
|
|
1
1
|
import type { schemasOf } from './server/handler.js';
|
|
2
2
|
import type { Routes } from './types.js';
|
|
3
|
-
/**
|
|
4
|
-
* Typed URLs from `app/routes/` (as React Router's `href`): `href('/users/:id', { id })` → `'/users/7'`;
|
|
5
|
-
* one of a file's `actions`: `href('/users/:id?delete', { id })`. Only patterns that exist; params are required.
|
|
6
|
-
* A form's action too: `<form method="post" action={href('/logout')}>`. With `query` (typed by the route's
|
|
7
|
-
* `withValidator({ query })`, if it has one) and `hash`: `href('/search', { query: { q }, hash: 'results' })`.
|
|
8
|
-
*/
|
|
9
3
|
type Keys = keyof Routes & string;
|
|
10
4
|
type Actions = {
|
|
11
5
|
[P in Keys]: Routes[P] extends {
|
|
@@ -13,7 +7,11 @@ type Actions = {
|
|
|
13
7
|
} ? `${P}?${keyof A & string}` : never;
|
|
14
8
|
}[Keys];
|
|
15
9
|
export type Href = [Keys] extends [never] ? string : Keys | Actions;
|
|
16
|
-
|
|
10
|
+
/** the params of a URL pattern, without its action (`?name`): `/users/:id/files/:path{.+}` → id, path */
|
|
11
|
+
type ParamNames<P extends string> = P extends `${infer Path}?${string}` ? PathParams<Path> : PathParams<P>;
|
|
12
|
+
type PathParams<P extends string> = P extends `${string}:${infer Rest}` ? Rest extends `${infer Segment}/${infer More}` ? ParamName<Segment> | PathParams<More> : ParamName<Rest> : never;
|
|
13
|
+
/** a param's name, without its pattern (a catch-all's `{.+}`) */
|
|
14
|
+
type ParamName<S extends string> = S extends `${infer Name}{${string}` ? Name : S;
|
|
17
15
|
/** the handlers answering a GET of the URL (its page's `loader`, a `.ts` file's `GET`), or the action's */
|
|
18
16
|
type HandlersOf<P extends string> = P extends `${infer K}?${infer A}` ? K extends Keys ? Routes[K] extends {
|
|
19
17
|
actions: infer As;
|
|
@@ -48,8 +46,14 @@ type Extra<P extends string> = {
|
|
|
48
46
|
type Args<P extends string> = [ParamNames<P>] extends [never] ? {} extends QueryOf<P> ? [options?: Extra<P>] : [options: Extra<P>] : [params: {
|
|
49
47
|
[K in ParamNames<P>]: string | number;
|
|
50
48
|
} & Extra<P>];
|
|
49
|
+
/**
|
|
50
|
+
* Typed URLs from `app/routes/` (as React Router's `href`): `href('/users/:id', { id })` → `'/users/7'`;
|
|
51
|
+
* one of a file's `actions`: `href('/users/:id?delete', { id })`. Only patterns that exist; params are required.
|
|
52
|
+
* A form's action too: `<form method="post" action={href('/logout')}>`. With `query` (typed by the route's
|
|
53
|
+
* `withValidator({ query })`, if it has one) and `hash`: `href('/search', { query: { q }, hash: 'results' })`.
|
|
54
|
+
*/
|
|
51
55
|
export declare function href<P extends Href>(path: P, ...[options]: Args<P>): string;
|
|
52
|
-
export { usePage, useNavigation, reload, __entry, renderPage, type Errors, type Navigation, } from './client/app.js';
|
|
56
|
+
export { usePage, useNavigation, reload, Deferred, __entry, renderPage, type Errors, type Navigation, } from './client/app.js';
|
|
53
57
|
export { useForm } from './client/form.js';
|
|
54
58
|
export { loadDocument, navigate, type Page } from './client/navigation.js';
|
|
55
59
|
export type { ProgressOptions } from './client/progress.js';
|
package/dist/client.js
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
import { fillPattern } from './paths.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
|
+
* A form's action too: `<form method="post" action={href('/logout')}>`. With `query` (typed by the route's
|
|
6
|
+
* `withValidator({ query })`, if it has one) and `hash`: `href('/search', { query: { q }, hash: 'results' })`.
|
|
7
|
+
*/
|
|
2
8
|
export function href(path, ...[options]) {
|
|
3
9
|
const { query, hash, ...params } = (options ?? {});
|
|
4
10
|
let url = fillPattern(path, params);
|
|
@@ -14,6 +20,6 @@ export function href(path, ...[options]) {
|
|
|
14
20
|
url += `#${encodeURI(hash)}`;
|
|
15
21
|
return url;
|
|
16
22
|
}
|
|
17
|
-
export { usePage, useNavigation, reload, __entry, renderPage, } from './client/app.js';
|
|
23
|
+
export { usePage, useNavigation, reload, Deferred, __entry, renderPage, } from './client/app.js';
|
|
18
24
|
export { useForm } from './client/form.js';
|
|
19
25
|
export { loadDocument, navigate } from './client/navigation.js';
|
package/dist/form.d.ts
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
export declare class MalformedForm extends Error {
|
|
7
7
|
}
|
|
8
8
|
type Entry = [string, FormDataEntryValue];
|
|
9
|
+
/** a field's text as the browser sends it: line breaks as CRLF (a <textarea>'s) */
|
|
10
|
+
export declare const crlf: (text: string) => string;
|
|
9
11
|
/**
|
|
10
12
|
* Form fields with PHP-style names, as forms write them (`notify[]`, `user[name]`); files are `File`s, empty file
|
|
11
13
|
* inputs are left out. A name given again is a list (`a=1&a=2`, `a[b]=1&a[b]=2`); `[]` is the index after the
|
|
@@ -20,8 +22,6 @@ export interface Issue {
|
|
|
20
22
|
readonly key: PropertyKey;
|
|
21
23
|
}> | undefined;
|
|
22
24
|
}
|
|
23
|
-
/** an issue's field: its path joined with dots (`user.name`, `tags.0`); the form's own issues are `''` */
|
|
24
|
-
export declare const issueKey: (path: Issue['path']) => string;
|
|
25
25
|
/** a field name's key in the errors: `user[name]` → `user.name`, `tags[]` → `tags` */
|
|
26
26
|
export declare const fieldKey: (name: string) => string;
|
|
27
27
|
/** each field's first message (no prototype: a field named `toString` is a field like any other) */
|
package/dist/form.js
CHANGED
|
@@ -7,6 +7,8 @@ const DEPTH = 32;
|
|
|
7
7
|
/** a body that can't be one object: a 400 on the server */
|
|
8
8
|
export class MalformedForm extends Error {
|
|
9
9
|
}
|
|
10
|
+
/** a field's text as the browser sends it: line breaks as CRLF (a <textarea>'s) */
|
|
11
|
+
export const crlf = (text) => text.replace(/\r\n|\r|\n/g, '\r\n');
|
|
10
12
|
/**
|
|
11
13
|
* Form fields with PHP-style names, as forms write them (`notify[]`, `user[name]`); files are `File`s, empty file
|
|
12
14
|
* inputs are left out. A name given again is a list (`a=1&a=2`, `a[b]=1&a[b]=2`); `[]` is the index after the
|
|
@@ -63,7 +65,7 @@ const arrays = (value) => {
|
|
|
63
65
|
return isList ? entries.map(([, v]) => v) : Object.fromEntries(entries);
|
|
64
66
|
};
|
|
65
67
|
/** an issue's field: its path joined with dots (`user.name`, `tags.0`); the form's own issues are `''` */
|
|
66
|
-
|
|
68
|
+
const issueKey = (path) => (path ?? []).map((p) => String(typeof p === 'object' ? p.key : p)).join('.');
|
|
67
69
|
/** a field name's key in the errors: `user[name]` → `user.name`, `tags[]` → `tags` */
|
|
68
70
|
export const fieldKey = (name) => name.replace(/\]/g, '').split('[').filter(Boolean).join('.');
|
|
69
71
|
/** each field's first message (no prototype: a field named `toString` is a field like any other) */
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { defineHandler, defineMiddleware } from './server/handler.js';
|
|
2
|
-
export { render, share, type RenderOptions } from './server/protocol.js';
|
|
2
|
+
export { defer, render, share, type RenderOptions } from './server/protocol.js';
|
|
3
3
|
export { back } from './server/http.js';
|
|
4
4
|
export { flash } from './server/flash.js';
|
|
5
5
|
export { ValidationError, type StandardSchemaV1 } from './server/validate.js';
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { defineHandler, defineMiddleware } from './server/handler.js';
|
|
2
|
-
export { render, share } from './server/protocol.js';
|
|
2
|
+
export { defer, render, share } from './server/protocol.js';
|
|
3
3
|
export { back } from './server/http.js';
|
|
4
4
|
export { flash } from './server/flash.js';
|
|
5
5
|
export { ValidationError } from './server/validate.js';
|
package/dist/paths.d.ts
CHANGED
|
@@ -10,12 +10,16 @@
|
|
|
10
10
|
*/
|
|
11
11
|
export declare function routePatterns(file: string): string[];
|
|
12
12
|
/**
|
|
13
|
-
* a path inside `routes/` that is a route file: `.ts` (server code: handlers) or `.tsx`, `.
|
|
13
|
+
* a path inside `routes/` that is a route file: `.ts` (server code: handlers) or `.tsx`, `.mdx` (a page), but
|
|
14
14
|
* tests and declarations, and neither its name nor a directory on its path starting with `_` (`_middleware.ts`,
|
|
15
15
|
* `_layout.tsx`, `_parts/badge.tsx`)
|
|
16
16
|
*/
|
|
17
17
|
export declare function isRouteFile(file: string): boolean;
|
|
18
|
-
/** a route file
|
|
18
|
+
/** what a route file exports for the server, besides its page: HTTP methods, a page's handlers, its settings */
|
|
19
|
+
export declare const METHODS: readonly ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
|
|
20
|
+
export declare const HANDLERS: readonly ['loader', 'action', 'actions'];
|
|
21
|
+
export declare const CONFIG: readonly ['prerender', 'params'];
|
|
22
|
+
/** a route file that is a page (React: `.tsx`, `.mdx`), not server code only (`.ts`) */
|
|
19
23
|
export declare const isPageFile: (file: string) => boolean;
|
|
20
24
|
/** a page's id, its route file without the extension: `users/[id].tsx` → `users/[id]` (the client's name for it) */
|
|
21
25
|
export declare const pageId: (file: string) => string;
|
|
@@ -36,6 +40,8 @@ export declare const PAGE_DATA = "/_fondu/pages";
|
|
|
36
40
|
* `…/index.json`), and a last segment named index (or ~index…) gets one more `~` (`/items/index` → `…/items/~index.json`)
|
|
37
41
|
*/
|
|
38
42
|
export declare function pageDataPath(path: string): string;
|
|
43
|
+
/** a URL segment decoded, or as it is if it doesn't decode */
|
|
44
|
+
export declare function decoded(segment: string): string;
|
|
39
45
|
/**
|
|
40
46
|
* a path whose last segment is index (`/index`, `/docs/%69ndex`): its static file would be its directory's
|
|
41
47
|
* (`index.html`, `docs/index.html`), which is another page
|
|
@@ -43,6 +49,11 @@ export declare function pageDataPath(path: string): string;
|
|
|
43
49
|
export declare const endsInIndex: (path: string) => boolean;
|
|
44
50
|
/** the other way: `/_fondu/pages/docs/intro.json` → `/docs/intro`; null for any other path */
|
|
45
51
|
export declare function pathOfPageData(pathname: string): string | null;
|
|
52
|
+
/**
|
|
53
|
+
* a prerendered page's document file from its path as a server reads it (decoded): `/docs/intro` → `docs/intro.html`,
|
|
54
|
+
* `/docs/` → `docs/index.html`
|
|
55
|
+
*/
|
|
56
|
+
export declare const htmlFile: (decodedPath: string) => string;
|
|
46
57
|
/** the files of a prerendered page: `/docs/intro` → `docs/intro.html` and `_fondu/pages/docs/intro.json` (decoded) */
|
|
47
58
|
export declare function staticFiles(path: string): {
|
|
48
59
|
html: string;
|
package/dist/paths.js
CHANGED
|
@@ -33,19 +33,23 @@ export function routePatterns(file) {
|
|
|
33
33
|
.join('/');
|
|
34
34
|
return optional.length ? [pattern(false), pattern(true)] : [pattern(true)];
|
|
35
35
|
}
|
|
36
|
-
const ROUTE_EXTENSION = /\.(?:
|
|
36
|
+
const ROUTE_EXTENSION = /\.(?:tsx?|mdx)$/;
|
|
37
37
|
/**
|
|
38
|
-
* a path inside `routes/` that is a route file: `.ts` (server code: handlers) or `.tsx`, `.
|
|
38
|
+
* a path inside `routes/` that is a route file: `.ts` (server code: handlers) or `.tsx`, `.mdx` (a page), but
|
|
39
39
|
* tests and declarations, and neither its name nor a directory on its path starting with `_` (`_middleware.ts`,
|
|
40
40
|
* `_layout.tsx`, `_parts/badge.tsx`)
|
|
41
41
|
*/
|
|
42
42
|
export function isRouteFile(file) {
|
|
43
43
|
return (ROUTE_EXTENSION.test(file) &&
|
|
44
44
|
!file.endsWith('.d.ts') &&
|
|
45
|
-
!/\.(?:test|spec)\.
|
|
45
|
+
!/\.(?:test|spec)\.tsx?$/.test(file) &&
|
|
46
46
|
!file.split('/').some((s) => s.startsWith('_')));
|
|
47
47
|
}
|
|
48
|
-
/** a route file
|
|
48
|
+
/** what a route file exports for the server, besides its page: HTTP methods, a page's handlers, its settings */
|
|
49
|
+
export const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
|
|
50
|
+
export const HANDLERS = ['loader', 'action', 'actions'];
|
|
51
|
+
export const CONFIG = ['prerender', 'params'];
|
|
52
|
+
/** a route file that is a page (React: `.tsx`, `.mdx`), not server code only (`.ts`) */
|
|
49
53
|
export const isPageFile = (file) => isRouteFile(file) && !file.endsWith('.ts');
|
|
50
54
|
/** a page's id, its route file without the extension: `users/[id].tsx` → `users/[id]` (the client's name for it) */
|
|
51
55
|
export const pageId = (file) => file.replace(ROUTE_EXTENSION, '');
|
|
@@ -98,7 +102,7 @@ export function pageDataPath(path) {
|
|
|
98
102
|
return `${PAGE_DATA}${named}.json`;
|
|
99
103
|
}
|
|
100
104
|
/** a URL segment decoded, or as it is if it doesn't decode */
|
|
101
|
-
function decoded(segment) {
|
|
105
|
+
export function decoded(segment) {
|
|
102
106
|
try {
|
|
103
107
|
return decodeURIComponent(segment);
|
|
104
108
|
}
|
|
@@ -118,8 +122,15 @@ export function pathOfPageData(pathname) {
|
|
|
118
122
|
return null;
|
|
119
123
|
return m[1].replace(/(?<=\/)index$/, '').replace(/(?<=\/)~(~*index)$/, '$1');
|
|
120
124
|
}
|
|
125
|
+
/**
|
|
126
|
+
* a prerendered page's document file from its path as a server reads it (decoded): `/docs/intro` → `docs/intro.html`,
|
|
127
|
+
* `/docs/` → `docs/index.html`
|
|
128
|
+
*/
|
|
129
|
+
export const htmlFile = (decodedPath) => (decodedPath.endsWith('/') ? `${decodedPath}index.html` : `${decodedPath}.html`).slice(1);
|
|
121
130
|
/** the files of a prerendered page: `/docs/intro` → `docs/intro.html` and `_fondu/pages/docs/intro.json` (decoded) */
|
|
122
131
|
export function staticFiles(path) {
|
|
123
|
-
|
|
124
|
-
|
|
132
|
+
return {
|
|
133
|
+
html: htmlFile(decodeURIComponent(path)),
|
|
134
|
+
json: decodeURIComponent(pageDataPath(path)).slice(1),
|
|
135
|
+
};
|
|
125
136
|
}
|
package/dist/server/app.d.ts
CHANGED
|
@@ -9,6 +9,8 @@ export interface CreateAppOptions {
|
|
|
9
9
|
trailingSlash?: 'trim' | 'append';
|
|
10
10
|
/** `hono/csrf`'s options; `false`: off */
|
|
11
11
|
csrf?: Parameters<typeof csrf>[0] | false;
|
|
12
|
+
/** the largest request body, in bytes (default: 10 MB), then 413: `hono/body-limit`; `false`: no limit */
|
|
13
|
+
bodyLimit?: number | false;
|
|
12
14
|
/**
|
|
13
15
|
* `hono/secure-headers`' options; `false`: off. Defaults: `referrerPolicy: 'same-origin'` (which `back()` needs) and
|
|
14
16
|
* a Content Security Policy whose directives yours replace one by one; `contentSecurityPolicy: false`: none
|
|
@@ -18,13 +20,15 @@ export interface CreateAppOptions {
|
|
|
18
20
|
}) | false;
|
|
19
21
|
}
|
|
20
22
|
type SecureHeadersOptions = NonNullable<Parameters<typeof secureHeaders>[0]>;
|
|
23
|
+
export declare function checkExports(file: string, mod: Record<string, unknown>): void;
|
|
21
24
|
/**
|
|
22
25
|
* The Hono app from `app/routes/` (found by Vite, no generated code). Each file is a URL:
|
|
23
26
|
* - a page, `.tsx` or `.mdx`: its component (default), `loader` (GET; without one, the page with no props of its
|
|
24
|
-
* own), `action` (POST) or `actions` (POST `?name`)
|
|
25
|
-
* - server code, `.ts`:
|
|
27
|
+
* own), `action` (POST) or `actions` (POST `?name`); `.mdx` has no handlers
|
|
28
|
+
* - server code, `.ts`: HTTP handlers only, `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS` (not `loader`,
|
|
29
|
+
* `action`, `actions`: those are a page's)
|
|
26
30
|
* `_middleware.ts` applies to its directory and below (`routes/_middleware.ts`: every request, 404s included).
|
|
27
|
-
* Built in: CSRF protection, security headers, one URL per page (trailing slash), the error page. Your own 404 /
|
|
31
|
+
* Built in: CSRF protection, security headers, a request body limit, one URL per page (trailing slash), the error page. Your own 404 /
|
|
28
32
|
* error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
|
|
29
33
|
*/
|
|
30
34
|
export declare function createApp(options?: CreateAppOptions): Hono;
|
package/dist/server/app.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { Hono } from 'hono';
|
|
2
|
+
import { bodyLimit } from 'hono/body-limit';
|
|
2
3
|
import { every } from 'hono/combine';
|
|
3
4
|
import { csrf } from 'hono/csrf';
|
|
4
5
|
import { HTTPException } from 'hono/http-exception';
|
|
5
6
|
import { NONCE, secureHeaders } from 'hono/secure-headers';
|
|
6
7
|
import { appendTrailingSlash, trimTrailingSlash } from 'hono/trailing-slash';
|
|
7
8
|
import { prerender, version } from 'virtual:fondu/assets';
|
|
8
|
-
import { isPageFile, isRouteFile, pageId } from '../paths.js';
|
|
9
|
+
import { CONFIG, HANDLERS, isPageFile, isRouteFile, METHODS, pageId } from '../paths.js';
|
|
9
10
|
import { settings } from './document.js';
|
|
10
11
|
import { errorResponse } from './errors.js';
|
|
11
12
|
import { prerenderRoutes } from './prerender.js';
|
|
@@ -23,18 +24,16 @@ const CSP = {
|
|
|
23
24
|
baseUri: ["'self'"],
|
|
24
25
|
};
|
|
25
26
|
const ROOT = '/app/routes/';
|
|
26
|
-
const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
|
|
27
|
-
const HANDLERS = ['loader', 'action', 'actions'];
|
|
28
|
-
const CONFIG = ['prerender', 'params'];
|
|
29
27
|
/**
|
|
30
|
-
* What a file of `app/routes/` may export, and what to do with anything else:
|
|
31
|
-
*
|
|
28
|
+
* What a file of `app/routes/` may export, and what to do with anything else: one spelling per kind of file. A
|
|
29
|
+
* page's route file (`.tsx`) is its page and `loader`, `action` or `actions`; a `.ts` file is server code, with the
|
|
30
|
+
* HTTP methods. The rest of a page's code goes to modules of its own (the browser gets the page alone)
|
|
32
31
|
*/
|
|
33
32
|
function exportsOf(file) {
|
|
34
33
|
const name = file.split('/').at(-1);
|
|
35
34
|
if (name === '_middleware.ts')
|
|
36
35
|
return { allowed: ['default', ...CONFIG], hint: 'its middleware (default), prerender, params' };
|
|
37
|
-
if (/^_(?:layout|error)\.
|
|
36
|
+
if (/^_(?:layout|error)\.tsx$/.test(name))
|
|
38
37
|
return { allowed: ['default'], hint: 'its component only (default)' };
|
|
39
38
|
if (file.endsWith('.mdx'))
|
|
40
39
|
return {
|
|
@@ -43,21 +42,32 @@ function exportsOf(file) {
|
|
|
43
42
|
};
|
|
44
43
|
if (file.endsWith('.ts'))
|
|
45
44
|
return {
|
|
46
|
-
allowed: [...
|
|
47
|
-
hint: '
|
|
45
|
+
allowed: [...METHODS, ...CONFIG],
|
|
46
|
+
hint: 'GET, POST, PUT, PATCH, DELETE, OPTIONS, prerender, params',
|
|
48
47
|
};
|
|
49
48
|
return {
|
|
50
49
|
allowed: ['default', ...HANDLERS, ...CONFIG],
|
|
51
50
|
hint: 'its page (default), loader, action or actions, prerender, params; the rest goes to a module of its own',
|
|
52
51
|
};
|
|
53
52
|
}
|
|
54
|
-
|
|
53
|
+
/** what a page's handler is called in a `.ts` file */
|
|
54
|
+
const INSTEAD = {
|
|
55
|
+
loader: 'in a .ts file it is `GET`',
|
|
56
|
+
action: 'in a .ts file it is `POST`',
|
|
57
|
+
actions: "a .ts file has one `POST`: a file per action, or a page's route file (.tsx)",
|
|
58
|
+
};
|
|
59
|
+
export function checkExports(file, mod) {
|
|
55
60
|
const { allowed, hint } = exportsOf(file);
|
|
56
61
|
const mdx = file.endsWith('.mdx');
|
|
57
62
|
const extra = Object.keys(mod).filter((k) => mdx ? [...HANDLERS, ...METHODS, ...CONFIG].includes(k) : !allowed.includes(k));
|
|
58
|
-
if (extra.length)
|
|
59
|
-
|
|
60
|
-
|
|
63
|
+
if (extra.length) {
|
|
64
|
+
const renamed = file.endsWith('.ts')
|
|
65
|
+
? extra.filter((k) => k in INSTEAD)
|
|
66
|
+
: [];
|
|
67
|
+
throw new Error(`fondu: routes/${file} exports ${extra.map((k) => `\`${k}\``).join(', ')}. It exports ${hint}` +
|
|
68
|
+
(renamed.length ? ` (${renamed.map((k) => `\`${k}\`: ${INSTEAD[k]}`).join('; ')})` : ''));
|
|
69
|
+
}
|
|
70
|
+
if (/\.(?:tsx|mdx)$/.test(file) && typeof mod.default !== 'function')
|
|
61
71
|
throw new Error(`fondu: routes/${file} is a page: its default export is the component (code for the server only: a .ts file)`);
|
|
62
72
|
}
|
|
63
73
|
/** a thrown `ValidationError` becomes the page it came from with its errors (or 422 for an API client) */
|
|
@@ -80,10 +90,11 @@ function actionName(url) {
|
|
|
80
90
|
/**
|
|
81
91
|
* The Hono app from `app/routes/` (found by Vite, no generated code). Each file is a URL:
|
|
82
92
|
* - a page, `.tsx` or `.mdx`: its component (default), `loader` (GET; without one, the page with no props of its
|
|
83
|
-
* own), `action` (POST) or `actions` (POST `?name`)
|
|
84
|
-
* - server code, `.ts`:
|
|
93
|
+
* own), `action` (POST) or `actions` (POST `?name`); `.mdx` has no handlers
|
|
94
|
+
* - server code, `.ts`: HTTP handlers only, `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS` (not `loader`,
|
|
95
|
+
* `action`, `actions`: those are a page's)
|
|
85
96
|
* `_middleware.ts` applies to its directory and below (`routes/_middleware.ts`: every request, 404s included).
|
|
86
|
-
* Built in: CSRF protection, security headers, one URL per page (trailing slash), the error page. Your own 404 /
|
|
97
|
+
* Built in: CSRF protection, security headers, a request body limit, one URL per page (trailing slash), the error page. Your own 404 /
|
|
87
98
|
* error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
|
|
88
99
|
*/
|
|
89
100
|
export function createApp(options = {}) {
|
|
@@ -91,14 +102,13 @@ export function createApp(options = {}) {
|
|
|
91
102
|
const modules = Object.fromEntries(Object.entries(
|
|
92
103
|
// without a type argument: Vitest's module cache leaves out a module with `import.meta.glob(` only
|
|
93
104
|
import.meta.glob([
|
|
94
|
-
'/app/routes/**/*.{ts,tsx,jsx,mdx}',
|
|
105
|
+
'/app/routes/**/*.{ts,tsx,jsx,mdx}', // a .jsx file is found to be refused (routeTable)
|
|
95
106
|
'!/app/routes/**/*.d.ts',
|
|
96
107
|
'!/app/routes/**/*.{test,spec}.{ts,tsx,jsx}', // test files aren't the app's
|
|
97
108
|
'!/app/routes/**/_*/**', // nor what a directory keeps beside its routes
|
|
98
109
|
], { eager: true })).map(([path, mod]) => [path.slice(ROOT.length), mod]));
|
|
99
110
|
for (const [file, mod] of Object.entries(modules)) {
|
|
100
|
-
if (!isRouteFile(file) &&
|
|
101
|
-
!/(?:^|\/)_(?:middleware\.ts|layout\.[jt]sx|error\.[jt]sx)$/.test(file))
|
|
111
|
+
if (!isRouteFile(file) && !/(?:^|\/)_(?:middleware\.ts|layout\.tsx|error\.tsx)$/.test(file))
|
|
102
112
|
continue; // a file of a directory's own (`_badge.tsx`)
|
|
103
113
|
checkExports(file, mod);
|
|
104
114
|
if (isPageFile(file))
|
|
@@ -106,7 +116,7 @@ export function createApp(options = {}) {
|
|
|
106
116
|
}
|
|
107
117
|
const own = {
|
|
108
118
|
document: options.document,
|
|
109
|
-
errorPage: Boolean(modules['_error.tsx']
|
|
119
|
+
errorPage: Boolean(modules['_error.tsx']),
|
|
110
120
|
};
|
|
111
121
|
const append = options.trailingSlash === 'append';
|
|
112
122
|
app.use(async (c, next) => {
|
|
@@ -123,6 +133,14 @@ export function createApp(options = {}) {
|
|
|
123
133
|
}
|
|
124
134
|
if (options.csrf !== false)
|
|
125
135
|
app.use(csrf(options.csrf));
|
|
136
|
+
if (options.bodyLimit !== false)
|
|
137
|
+
app.use(bodyLimit({
|
|
138
|
+
maxSize: options.bodyLimit ?? 10 * 1024 * 1024,
|
|
139
|
+
// Fondu's own answer: the error page for a visitor, the status alone for an API client
|
|
140
|
+
onError: () => {
|
|
141
|
+
throw new HTTPException(413);
|
|
142
|
+
},
|
|
143
|
+
}));
|
|
126
144
|
const prerendered = [];
|
|
127
145
|
if (prerender)
|
|
128
146
|
prerenderRoutes(app, () => prerendered, version);
|
|
@@ -155,13 +173,6 @@ export function createApp(options = {}) {
|
|
|
155
173
|
...METHODS.filter((m) => m !== 'GET' && m !== 'POST' && mod[m]),
|
|
156
174
|
],
|
|
157
175
|
});
|
|
158
|
-
const conflict = (a, b) => {
|
|
159
|
-
if (mod[a] && mod[b])
|
|
160
|
-
throw new Error(`fondu: routes/${file} exports both \`${a}\` and \`${b}\`, which handle the same requests`);
|
|
161
|
-
};
|
|
162
|
-
conflict('loader', 'GET');
|
|
163
|
-
conflict('action', 'POST');
|
|
164
|
-
conflict('actions', 'POST');
|
|
165
176
|
if (mod.action && mod.actions)
|
|
166
177
|
throw new Error(`fondu: routes/${file} exports both \`action\` and \`actions\`: one form posts to \`action\`, several each to one of \`actions\` (?name)`);
|
|
167
178
|
const add = (method, handlers) => app.on(method, pattern, ...handlers);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Context, MiddlewareHandler } from 'hono';
|
|
2
|
-
import type
|
|
2
|
+
import { type ReactElement } from 'react';
|
|
3
3
|
import type { Page } from '../client/navigation.js';
|
|
4
4
|
/**
|
|
5
5
|
* The HTML document around a page: `{head}` and `{body}` (in JSX, or `${head}` in a string) are where the page goes.
|
|
@@ -28,4 +28,12 @@ export declare const settings: WeakMap<Context<any, any, {}>, {
|
|
|
28
28
|
* `fondu({ ssr: false })`.
|
|
29
29
|
*/
|
|
30
30
|
export declare const withoutSsr: () => MiddlewareHandler;
|
|
31
|
-
|
|
31
|
+
/**
|
|
32
|
+
* The document, streamed. First: the template's start, the stylesheets and the client's tags, the tags the page hoists
|
|
33
|
+
* (React writes them before the page), the page data and the page's shell. Then what React adds as the Suspense
|
|
34
|
+
* boundaries of the page resolve. Last: the template's end. The status and the headers are the loader's: sent with the
|
|
35
|
+
* first byte. A string for a page that is not rendered here (`withoutSsr`, a shell that failed to render, a HEAD).
|
|
36
|
+
* `whole`: wait for every boundary first (a prerendered page: no scripts of React's in the file, what
|
|
37
|
+
* `renderToString` gave).
|
|
38
|
+
*/
|
|
39
|
+
export declare function renderDocument(c: Context, page: Page, whole?: boolean): Promise<string | ReadableStream<Uint8Array>>;
|
package/dist/server/document.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { createElement } from 'react';
|
|
1
2
|
import { assetTags } from 'virtual:fondu/assets';
|
|
2
3
|
import { renderMarkup, renderPage } from 'virtual:fondu/ssr';
|
|
3
4
|
import { SCROLL_KEY, SCROLL_STORAGE } from '../paths.js';
|
|
5
|
+
import { nonceOf } from './http.js';
|
|
4
6
|
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>`;
|
|
5
7
|
/** the options of the app (`createApp`) a request belongs to */
|
|
6
8
|
export const settings = new WeakMap();
|
|
@@ -22,7 +24,7 @@ const pageScript = (page) => `<script data-page="app" type="application/json">${
|
|
|
22
24
|
* their own until then (to the #fragment, WebKit and Firefox), fondu/client keeping their restoration off. Not once
|
|
23
25
|
* the visitor has scrolled, typed or clicked: their own scrolling wins.
|
|
24
26
|
*/
|
|
25
|
-
const restoreScroll =
|
|
27
|
+
const restoreScroll = `try{var k=history.state&&history.state[${JSON.stringify(SCROLL_KEY)}],p=k&&JSON.parse(sessionStorage.getItem(${JSON.stringify(SCROLL_STORAGE)}+k));if(p){var go=function(){scrollTo(+p.x||0,+p.y||0)},off=function(){go=0};go();["wheel","touchstart","keydown","mousedown"].forEach(function(t){addEventListener(t,off,{once:!0,passive:!0})});addEventListener("load",function(){setTimeout(function(){go&&go()})})}}catch(e){}`;
|
|
26
28
|
// where the page goes, in the document a template returns: replaced before the page is in, so a page's content is
|
|
27
29
|
// never read as one
|
|
28
30
|
const HEAD = 'fondu:document-head';
|
|
@@ -40,13 +42,43 @@ async function shell(template, c, nonce) {
|
|
|
40
42
|
return html;
|
|
41
43
|
return html.replace(/<script\b(?![^>]*\s(?:src|nonce)=)/gi, `<script nonce="${nonce}"`);
|
|
42
44
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
+
/**
|
|
46
|
+
* The document, streamed. First: the template's start, the stylesheets and the client's tags, the tags the page hoists
|
|
47
|
+
* (React writes them before the page), the page data and the page's shell. Then what React adds as the Suspense
|
|
48
|
+
* boundaries of the page resolve. Last: the template's end. The status and the headers are the loader's: sent with the
|
|
49
|
+
* first byte. A string for a page that is not rendered here (`withoutSsr`, a shell that failed to render, a HEAD).
|
|
50
|
+
* `whole`: wait for every boundary first (a prerendered page: no scripts of React's in the file, what
|
|
51
|
+
* `renderToString` gave).
|
|
52
|
+
*/
|
|
53
|
+
export async function renderDocument(c, page, whole = false) {
|
|
54
|
+
const nonce = nonceOf(c);
|
|
55
|
+
// the template first: one that is wrong fails before anything renders (no stream left running)
|
|
56
|
+
const template = settings.get(c)?.document ?? defaultTemplate;
|
|
57
|
+
const html = await shell(template, c, nonce);
|
|
58
|
+
const [before, between, after, ...more] = html.split(new RegExp(`${HEAD}|${BODY}`));
|
|
59
|
+
if (after === undefined || more.length || html.indexOf(HEAD) > html.indexOf(BODY))
|
|
60
|
+
throw new Error('fondu: the document must have `head` once, in <head>, and `body` once, in <body>');
|
|
45
61
|
let ssr = null;
|
|
62
|
+
// what fails in a boundary is for the browser to render, and is logged. The shell's failure is logged below, once:
|
|
63
|
+
// React reports it to `onError` too, so what it reports is held until the shell is known to be there
|
|
64
|
+
const pending = [];
|
|
65
|
+
let live = false;
|
|
66
|
+
const late = (error) => console.error(`[fondu] a Suspense boundary of "${page.component}" failed on the server, the browser renders it:`, error);
|
|
46
67
|
try {
|
|
47
|
-
//
|
|
48
|
-
if (renderPage && !browserOnly.has(c))
|
|
49
|
-
|
|
68
|
+
// a HEAD: Hono drops its body without cancelling it, so React would keep rendering for nothing
|
|
69
|
+
if (renderPage && !browserOnly.has(c) && c.req.method !== 'HEAD') {
|
|
70
|
+
// the page as the browser gets it, through JSON (a Date a string): the markup is the same on both sides
|
|
71
|
+
const stream = await renderPage(JSON.parse(JSON.stringify(page)), { nonce, onError: (error) => (live ? late(error) : void pending.push(error)) },
|
|
72
|
+
// the position back for a page rendered here (one rendered in the browser has nothing to scroll yet): in the
|
|
73
|
+
// shell, right after the page, before what the boundaries add
|
|
74
|
+
createElement('script', { nonce, dangerouslySetInnerHTML: { __html: restoreScroll } }));
|
|
75
|
+
if (whole)
|
|
76
|
+
await stream.allReady;
|
|
77
|
+
ssr = stream.pipeThrough(new TextDecoderStream());
|
|
78
|
+
for (const error of pending)
|
|
79
|
+
late(error);
|
|
80
|
+
live = true;
|
|
81
|
+
}
|
|
50
82
|
}
|
|
51
83
|
catch (error) {
|
|
52
84
|
// like Laravel: a page that fails to render on the server is still sent, and rendered in the browser
|
|
@@ -54,13 +86,7 @@ export async function renderDocument(c, page) {
|
|
|
54
86
|
}
|
|
55
87
|
// the page data first: the client reads the first `script[data-page]` in the document, so nothing in the page's
|
|
56
88
|
// content can come before it
|
|
57
|
-
|
|
58
|
-
const body = pageScript(page) + (ssr ? ssr.body + restoreScroll(nonce) : '<div id="app"></div>');
|
|
59
|
-
const template = settings.get(c)?.document ?? defaultTemplate;
|
|
60
|
-
const html = await shell(template, c, nonce);
|
|
61
|
-
const [before, between, after, ...more] = html.split(new RegExp(`${HEAD}|${BODY}`));
|
|
62
|
-
if (after === undefined || more.length || html.indexOf(HEAD) > html.indexOf(BODY))
|
|
63
|
-
throw new Error('fondu: the document must have `head` once, in <head>, and `body` once, in <body>');
|
|
89
|
+
const data = pageScript(page);
|
|
64
90
|
// the stylesheets first, right after <meta charset>: found, and asked for, before anything else of the head, the
|
|
65
91
|
// document's own tags included (React puts a JSX document's links and metas before `head`). A browser that lays
|
|
66
92
|
// the page out early (Firefox's, with its tools open) has them sooner
|
|
@@ -68,10 +94,36 @@ export async function renderDocument(c, page) {
|
|
|
68
94
|
const css = tags.match(/<link rel="stylesheet"[^>]*>/g)?.join('') ?? '';
|
|
69
95
|
const charset = /<meta charset=[^>]*>/i;
|
|
70
96
|
const top = css && charset.test(before) ? before.replace(charset, (meta) => meta + css) : before + css;
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
97
|
+
const start = top + tags.replace(/<link rel="stylesheet"[^>]*>/g, '');
|
|
98
|
+
if (!ssr)
|
|
99
|
+
return start + between + data + '<div id="app"></div>' + after;
|
|
100
|
+
// React's own: the tags the page hoists, then the page (`<div id="app"`), found across chunks
|
|
101
|
+
const reader = ssr.getReader();
|
|
102
|
+
let text = '';
|
|
103
|
+
let at = -1;
|
|
104
|
+
while (at < 0) {
|
|
105
|
+
const { done, value } = await reader.read();
|
|
106
|
+
if (done)
|
|
107
|
+
break;
|
|
108
|
+
text += value;
|
|
109
|
+
at = text.indexOf('<div id="app"');
|
|
110
|
+
}
|
|
111
|
+
const out = new TextEncoder();
|
|
112
|
+
return new ReadableStream({
|
|
113
|
+
start(controller) {
|
|
114
|
+
controller.enqueue(out.encode(start + text.slice(0, at) + between + data + text.slice(at)));
|
|
115
|
+
},
|
|
116
|
+
async pull(controller) {
|
|
117
|
+
const { done, value } = await reader.read();
|
|
118
|
+
if (!done)
|
|
119
|
+
return controller.enqueue(out.encode(value));
|
|
120
|
+
controller.enqueue(out.encode(after));
|
|
121
|
+
controller.close();
|
|
122
|
+
},
|
|
123
|
+
// the visitor left: React stops (its abort reaches `onError`: not an error of the page)
|
|
124
|
+
cancel(reason) {
|
|
125
|
+
live = false;
|
|
126
|
+
return reader.cancel(reason);
|
|
127
|
+
},
|
|
128
|
+
});
|
|
77
129
|
}
|
package/dist/server/errors.d.ts
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
import type { Context } from 'hono';
|
|
2
|
-
/** the error page's id: `app/routes/_error.tsx` */
|
|
3
|
-
export declare const ERROR_PAGE = "_error";
|
|
4
2
|
/**
|
|
5
3
|
* The answer to an unmatched URL or a thrown error (installed by `createApp`):
|
|
6
4
|
* - API clients: the `HTTPException`'s response, or plain text
|
package/dist/server/errors.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { HTTPException } from 'hono/http-exception';
|
|
2
2
|
import { settings } from './document.js';
|
|
3
|
-
import { wantsPage } from './http.js';
|
|
3
|
+
import { nonceOf, wantsPage } from './http.js';
|
|
4
4
|
import { renderPage } from './protocol.js';
|
|
5
5
|
/** the error page's id: `app/routes/_error.tsx` */
|
|
6
|
-
|
|
6
|
+
const ERROR_PAGE = '_error';
|
|
7
7
|
const TEXT = {
|
|
8
8
|
401: 'Unauthorized',
|
|
9
9
|
403: 'Forbidden',
|
|
10
10
|
404: 'Not Found',
|
|
11
|
+
413: 'Content Too Large',
|
|
11
12
|
419: 'Page Expired',
|
|
12
13
|
429: 'Too Many Requests',
|
|
13
14
|
503: 'Service Unavailable',
|
|
@@ -49,7 +50,7 @@ function report(c, error) {
|
|
|
49
50
|
.slice(1)
|
|
50
51
|
.map((line) => line.trim())
|
|
51
52
|
.filter(Boolean);
|
|
52
|
-
const nonce = c
|
|
53
|
+
const nonce = nonceOf(c);
|
|
53
54
|
const url = new URL(c.req.url);
|
|
54
55
|
const frame = (line) => {
|
|
55
56
|
const own = /\/app\//.test(line) && !line.includes('node_modules');
|
package/dist/server/flash.d.ts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
import type { Context, MiddlewareHandler } from 'hono';
|
|
2
2
|
import type { Flash } from '../types.js';
|
|
3
|
-
/** https, directly or behind a proxy that says so */
|
|
4
|
-
export declare const isSecure: (c: Context) => boolean;
|
|
5
3
|
/** Flash data for the next page (`usePage().flash`), typed by `Register['flash']`. */
|
|
6
4
|
export declare function flash(c: Context, data: Partial<Flash>): void;
|
|
7
5
|
/** Validation errors for the next page (its `errors` prop). */
|
package/dist/server/flash.js
CHANGED
|
@@ -8,7 +8,7 @@ const state = (c) => {
|
|
|
8
8
|
return s;
|
|
9
9
|
};
|
|
10
10
|
/** https, directly or behind a proxy that says so */
|
|
11
|
-
|
|
11
|
+
const isSecure = (c) => new URL(c.req.url).protocol === 'https:' ||
|
|
12
12
|
c.req.header('x-forwarded-proto')?.split(',')[0]?.trim() === 'https';
|
|
13
13
|
const cookieName = (c) => (isSecure(c) ? '__Host-fondu-flash' : 'fondu-flash');
|
|
14
14
|
/** Flash data for the next page (`usePage().flash`), typed by `Register['flash']`. */
|
package/dist/server/http.d.ts
CHANGED
|
@@ -3,6 +3,8 @@ import type { Context } from 'hono';
|
|
|
3
3
|
export declare const isPageRequest: (c: Context) => boolean;
|
|
4
4
|
/** a navigation or a document load (gets a page), not an API client (gets data) */
|
|
5
5
|
export declare const wantsPage: (c: Context) => boolean;
|
|
6
|
+
/** the request's Content Security Policy nonce (hono/secure-headers'), if it has one */
|
|
7
|
+
export declare const nonceOf: (c: Context) => string | undefined;
|
|
6
8
|
/** `url` as a URL of this site, or null (another site, unparsable) */
|
|
7
9
|
export declare function sameOrigin(c: Context, url: string | undefined): URL | null;
|
|
8
10
|
/** Back to the page the request came from (303), or `fallback` when there is none on this site. */
|
|
@@ -13,3 +15,5 @@ export declare const back: (c: Context, fallback?: string) => Response & import(
|
|
|
13
15
|
* unless they can't change (a `fetch()`'s): the copy.
|
|
14
16
|
*/
|
|
15
17
|
export declare function appendHeader(c: Context, name: string, value: string): void;
|
|
18
|
+
/** the build is prerendering (`FONDU_PRERENDER`: a Worker binding, or the environment of `node` / `bun dist/server/index.js`) */
|
|
19
|
+
export declare const isPrerendering: (c: Context) => boolean;
|
package/dist/server/http.js
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
export const isPageRequest = (c) => c.req.header('x-fondu') === 'true';
|
|
3
3
|
/** a navigation or a document load (gets a page), not an API client (gets data) */
|
|
4
4
|
export const wantsPage = (c) => isPageRequest(c) || (c.req.header('accept') ?? '').includes('text/html');
|
|
5
|
+
/** the request's Content Security Policy nonce (hono/secure-headers'), if it has one */
|
|
6
|
+
export const nonceOf = (c) => c.get('secureHeadersNonce');
|
|
5
7
|
/** `url` as a URL of this site, or null (another site, unparsable) */
|
|
6
8
|
export function sameOrigin(c, url) {
|
|
7
9
|
if (!url)
|
|
@@ -32,3 +34,6 @@ export function appendHeader(c, name, value) {
|
|
|
32
34
|
c.header(name, value, { append: true });
|
|
33
35
|
}
|
|
34
36
|
}
|
|
37
|
+
/** the build is prerendering (`FONDU_PRERENDER`: a Worker binding, or the environment of `node` / `bun dist/server/index.js`) */
|
|
38
|
+
export const isPrerendering = (c) => Boolean(c.env?.FONDU_PRERENDER ??
|
|
39
|
+
globalThis.process?.env?.FONDU_PRERENDER);
|