fondu 0.13.0 → 0.15.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.
@@ -1,19 +1,25 @@
1
1
  import type { Context, Handler, MiddlewareHandler } from 'hono';
2
2
  import { type Input, type Schemas } from './validate.js';
3
- type Final<S extends Schemas> = (c: Context, input: Input<S>) => Response | Promise<Response>;
3
+ type Final<S extends Schemas, R extends Response = Response> = (c: Context, input: Input<S>) => R | Promise<R>;
4
4
  type Handlers = Array<Handler | MiddlewareHandler>;
5
5
  /** @internal a type only, never a value: the schemas a `withValidator` handler checks, for `href()`'s `query` */
6
6
  export declare const schemasOf: unique symbol;
7
- /** handlers of `withValidator`: with their schemas, in the type only (`href()` types the query by them) */
8
- export type Validated<S extends Schemas> = Handlers & {
7
+ /** @internal a type only, never a value: the response the handler returns, for `fetch()`'s answer */
8
+ export declare const answerOf: unique symbol;
9
+ /**
10
+ * handlers of `withValidator`: with their schemas and the response they return, in the type only (`href()` types
11
+ * the query by the schemas, `fetch()` the answer by the response)
12
+ */
13
+ export type Validated<S extends Schemas, R extends Response = Response> = Handlers & {
9
14
  readonly [schemasOf]?: S;
15
+ readonly [answerOf]?: R;
10
16
  };
11
17
  /** overloads, as Hono's `createHandlers` has them: the last handler's parameters are typed reliably */
12
18
  interface WithInput<S extends Schemas> {
13
- (handler: Final<S>): Validated<S>;
14
- (m1: MiddlewareHandler, handler: Final<S>): Validated<S>;
15
- (m1: MiddlewareHandler, m2: MiddlewareHandler, handler: Final<S>): Validated<S>;
16
- (m1: MiddlewareHandler, m2: MiddlewareHandler, m3: MiddlewareHandler, handler: Final<S>): Validated<S>;
19
+ <R extends Response>(handler: Final<S, R>): Validated<S, R>;
20
+ <R extends Response>(m1: MiddlewareHandler, handler: Final<S, R>): Validated<S, R>;
21
+ <R extends Response>(m1: MiddlewareHandler, m2: MiddlewareHandler, handler: Final<S, R>): Validated<S, R>;
22
+ <R extends Response>(m1: MiddlewareHandler, m2: MiddlewareHandler, m3: MiddlewareHandler, handler: Final<S, R>): Validated<S, R>;
17
23
  }
18
24
  /**
19
25
  * Validated input for the handler, after the middleware (a guard runs before the request body is read):
@@ -15,3 +15,5 @@ export declare const back: (c: Context, fallback?: string) => Response & import(
15
15
  * unless they can't change (a `fetch()`'s): the copy.
16
16
  */
17
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;
@@ -34,3 +34,6 @@ export function appendHeader(c, name, value) {
34
34
  c.header(name, value, { append: true });
35
35
  }
36
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);
@@ -1,12 +1,5 @@
1
- import { endsInIndex, fillPattern, PAGE_DATA, pathOfPageData, staticFiles } from '../paths.js';
2
- import { isPageRequest, nonceOf } from './http.js';
3
- /** Node / Bun: reads a file of the client build (`docs/intro.html`), or null; set by the built server's entry */
4
- const STATIC_FILES = Symbol.for('fondu.staticFiles');
5
- /**
6
- * a prerendered page's file: no hidden one (`.vite/manifest.json`), nothing above the client build (`..`), no empty segment; `\\`
7
- * separates segments too (Windows)
8
- */
9
- const isStaticFile = (file) => file.split(/[\\/]/).every((s) => s !== '' && !s.startsWith('.'));
1
+ import { endsInIndex, fillPattern, PAGE_DATA, pathOfPageData } from '../paths.js';
2
+ import { isPrerendering } from './http.js';
10
3
  /** The paths to prerender, and what stops a route from being prerendered (the build fails on those) */
11
4
  export async function prerenderPaths(routes) {
12
5
  const paths = new Set();
@@ -49,47 +42,11 @@ export async function prerenderPaths(routes) {
49
42
  * a navigation), and, while the build prerenders (`FONDU_PRERENDER` set), the paths to write.
50
43
  */
51
44
  export function prerenderRoutes(app, routes, version) {
52
- // Node / Bun: a prerendered page from its file, before the routes and behind the app's security headers (on
53
- // Cloudflare, Workers Static Assets serve the files before the Worker runs). The built server says how to read them.
54
- app.use(async (c, next) => {
55
- const read = globalThis[STATIC_FILES];
56
- if (!read || (c.req.method !== 'GET' && c.req.method !== 'HEAD'))
57
- return next();
58
- const data = pathOfPageData(c.req.path) !== null; // a navigation, rewritten to the page object by fondu/client
59
- if (!data && (isPageRequest(c) || !(c.req.header('accept') ?? '').includes('text/html')))
60
- return next();
61
- // a URL ending in index is never a static document: that file is its directory's page (the routes answer it)
62
- if (!data && endsInIndex(c.req.path))
63
- return next();
64
- let file;
65
- try {
66
- file = data ? decodeURIComponent(c.req.path).slice(1) : staticFiles(c.req.path).html;
67
- }
68
- catch {
69
- return next(); // not a path a file could have
70
- }
71
- if (!isStaticFile(file))
72
- return next();
73
- const body = await read(file);
74
- if (!body)
75
- return next();
76
- c.header('Cache-Control', 'private, no-cache');
77
- if (data)
78
- c.header('X-Fondu', 'true');
79
- // the document's own tags have the build's nonce (the build dropped any other): this response's instead, as the
80
- // security headers give it a new one
81
- const nonce = nonceOf(c);
82
- if (!data && nonce) {
83
- const html = new TextDecoder()
84
- .decode(body)
85
- .replace(/(<(?:script|link)\b[^>]*\snonce=")[^"]*"/gi, `$1${nonce}"`);
86
- return c.html(html, 200);
87
- }
88
- return c.body(body, 200, {
89
- 'Content-Type': data ? 'application/json' : 'text/html; charset=UTF-8',
90
- });
91
- });
92
45
  app.get(`${PAGE_DATA}/*`, (c) => {
46
+ // a prefetch is for a static page's file only (served before the app, which is not reached): a page without
47
+ // one is asked for at the click, and no loader runs for a page that may not be visited
48
+ if (c.req.header('X-Fondu-Prefetch') === 'true')
49
+ return c.body(null, 204, { 'Cache-Control': 'no-store' });
93
50
  const path = pathOfPageData(c.req.path);
94
51
  // a page object's own URL is not a page: no page object of a page object (and so on)
95
52
  if (!path || path.startsWith('/_fondu/'))
@@ -107,9 +64,7 @@ export function prerenderRoutes(app, routes, version) {
107
64
  });
108
65
  app.get('/__fondu/prerender', async (c) => {
109
66
  // set for the build only: a Worker binding, or the environment of `node` / `bun dist/server/index.js`
110
- const env = c.env?.FONDU_PRERENDER ??
111
- globalThis.process?.env?.FONDU_PRERENDER;
112
- if (!env)
67
+ if (!isPrerendering(c))
113
68
  return c.notFound();
114
69
  return c.json({ version, ...(await prerenderPaths(routes())) });
115
70
  });
@@ -9,6 +9,19 @@ type Shareable<T> = {
9
9
  };
10
10
  /** Props every page of this request gets (a middleware calls it: the signed-in user…); a function when one renders */
11
11
  export declare function share(c: Context, props: Shareable<Shared>): void;
12
+ /** a prop the page gets with a second request: `defer(fn)` in `render()`'s props */
13
+ declare class DeferredProp<T> {
14
+ readonly type?: T;
15
+ readonly load: () => T | PromiseLike<T>;
16
+ constructor(load: () => T | PromiseLike<T>);
17
+ }
18
+ export type { DeferredProp };
19
+ /**
20
+ * A prop of the page that is not sent with it: `render(c, Page, { user, stats: defer(() => loadStats()) })`. The page
21
+ * renders without it (optional in the component's props); the client asks for it once the page is on the screen, and
22
+ * `fn` runs only for that request.
23
+ */
24
+ export declare function defer<T>(fn: () => T | PromiseLike<T>): DeferredProp<T>;
12
25
  /** a page: a component, its props what it receives (a function component, or a class one) */
13
26
  type PageComponent<P> = ((props: P) => ReactNode | Promise<ReactNode>) | (new (props: P) => Component<P>);
14
27
  /** the props a page names: not an index signature (a page without props takes `Record<string, never>`) */
@@ -46,8 +59,10 @@ type JsonInput<T> = IsAny<T> extends true ? T : T extends Json | undefined ? T |
46
59
  type NotJsonError = 'fondu: the page receives this prop as JSON (a Date as a string, a Map as {}): type it as such';
47
60
  /** a page's props as `render` takes them: what becomes each as JSON, or an error for a type JSON can't deliver */
48
61
  export type Delivered<P> = {
49
- [K in keyof P]: Arrives<P[K]> extends true ? JsonInput<P[K]> : NotJsonError;
62
+ [K in keyof P]: Arrives<P[K]> extends true ? JsonInput<P[K]> | Deferrable<P, K> : NotJsonError;
50
63
  };
64
+ /** `defer()` for a prop the page takes as optional: it renders without it */
65
+ type Deferrable<P, K extends keyof P> = {} extends Pick<P, K> ? DeferredProp<JsonInput<Exclude<P[K], undefined>>> : never;
51
66
  type RequiredKeys<T> = {
52
67
  [K in keyof T]-?: object extends Pick<T, K> ? never : K;
53
68
  }[keyof T];
@@ -67,4 +82,3 @@ export declare function render<P extends object>(c: Context, page: PageComponent
67
82
  /** @internal the page `id` (a route file without its extension) with these props: `render()`, the error page */
68
83
  export declare function renderPage(c: Context, id: string, props: Record<string, unknown>, options?: RenderOptions): Promise<Response>;
69
84
  export declare const protocol: MiddlewareHandler[];
70
- export {};
@@ -1,12 +1,34 @@
1
1
  import { version } from 'virtual:fondu/assets';
2
2
  import { renderDocument } from './document.js';
3
3
  import { flashCookie, takeCarried } from './flash.js';
4
- import { appendHeader, back, isPageRequest, sameOrigin } from './http.js';
4
+ import { appendHeader, back, isPageRequest, isPrerendering, sameOrigin } from './http.js';
5
5
  const shared = new WeakMap();
6
6
  /** Props every page of this request gets (a middleware calls it: the signed-in user…); a function when one renders */
7
7
  export function share(c, props) {
8
8
  shared.set(c, { ...shared.get(c), ...props });
9
9
  }
10
+ // ---- deferred props (`defer`): left out of a page, asked for by a request of their own
11
+ // As Inertia's deferred props, with rescue always on (a function that throws is logged and its prop left out); no groups
12
+ /** a prop the page gets with a second request: `defer(fn)` in `render()`'s props */
13
+ class DeferredProp {
14
+ load;
15
+ constructor(load) {
16
+ this.load = load;
17
+ }
18
+ }
19
+ Object.defineProperty(DeferredProp.prototype, 'toJSON', {
20
+ value() {
21
+ throw new Error('fondu: defer() is for a prop of render(), at the top (not in share(), not inside a prop)');
22
+ },
23
+ });
24
+ /**
25
+ * A prop of the page that is not sent with it: `render(c, Page, { user, stats: defer(() => loadStats()) })`. The page
26
+ * renders without it (optional in the component's props); the client asks for it once the page is on the screen, and
27
+ * `fn` runs only for that request.
28
+ */
29
+ export function defer(fn) {
30
+ return new DeferredProp(fn);
31
+ }
10
32
  // the pages of app/routes/ (createApp): a component → its ids; and, per request, the page of the route answering it
11
33
  // (the ids: a page may be the default export of several, `export { default } from './index.tsx'`)
12
34
  const pageIds = new WeakMap();
@@ -39,18 +61,56 @@ export function render(c, page, ...[props = {}, options = {}]) {
39
61
  }
40
62
  /** @internal the page `id` (a route file without its extension) with these props: `render()`, the error page */
41
63
  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
- ]));
47
- const page = {
48
- component: id,
49
- props: { ...Object.fromEntries(fromShared), ...props, errors: carried.errors },
50
- url: pageUrl(c),
51
- version,
52
- flash: carried.flash,
53
- };
64
+ const only = askedFor(c, id);
65
+ const deferred = Object.keys(props).filter((k) => props[k] instanceof DeferredProp);
66
+ let page;
67
+ if (only) {
68
+ // a partial request: what was asked for, and nothing the page already has (no shared props, no errors, no flash:
69
+ // the cookie is the next page's)
70
+ const wanted = only.filter((k) => Object.hasOwn(props, k));
71
+ const entries = await Promise.all(wanted.map(async (key) => {
72
+ const value = props[key];
73
+ if (!(value instanceof DeferredProp))
74
+ return [[key, value]];
75
+ try {
76
+ return [[key, await value.load()]];
77
+ }
78
+ catch (error) {
79
+ console.error(`[fondu] the deferred prop "${key}" of "${id}" failed:`, error);
80
+ return [];
81
+ }
82
+ }));
83
+ page = {
84
+ component: id,
85
+ props: Object.fromEntries(entries.flat()),
86
+ url: pageUrl(c),
87
+ version,
88
+ flash: {},
89
+ };
90
+ }
91
+ else {
92
+ const carried = takeCarried(c);
93
+ const fromShared = await Promise.all(Object.entries(shared.get(c) ?? {}).map(async ([key, value]) => [
94
+ key,
95
+ typeof value === 'function' ? await value() : value,
96
+ ]));
97
+ // a static page has all its data: what is deferred is awaited
98
+ const now = isPrerendering(c);
99
+ const own = Object.fromEntries(await Promise.all(Object.entries(props)
100
+ .filter(([key]) => now || !deferred.includes(key))
101
+ .map(async ([key, value]) => [
102
+ key,
103
+ value instanceof DeferredProp ? await value.load() : value,
104
+ ])));
105
+ page = {
106
+ component: id,
107
+ props: { ...Object.fromEntries(fromShared), ...own, errors: carried.errors },
108
+ url: pageUrl(c),
109
+ version,
110
+ flash: carried.flash,
111
+ ...(deferred.length && !now && { deferred }),
112
+ };
113
+ }
54
114
  // a page is this visitor's: not stored by shared caches, revalidated by the browser (unless the route said otherwise)
55
115
  if (!c.res.headers.has('Cache-Control'))
56
116
  c.header('Cache-Control', 'private, no-cache');
@@ -58,7 +118,27 @@ export async function renderPage(c, id, props, options = {}) {
58
118
  c.header('X-Fondu', 'true');
59
119
  return c.json(page, (options.status ?? 200));
60
120
  }
61
- return c.html(await renderDocument(c, page), (options.status ?? 200));
121
+ const status = (options.status ?? 200);
122
+ const document = await renderDocument(c, page, isPrerendering(c));
123
+ return typeof document === 'string'
124
+ ? c.html(document, status)
125
+ : c.body(document, status, { 'Content-Type': 'text/html; charset=UTF-8' });
126
+ }
127
+ /**
128
+ * The props a partial request asks for (`X-Fondu-Only: stats,feed`), if it is one: a navigation, a GET, for the
129
+ * component this route renders
130
+ */
131
+ function askedFor(c, id) {
132
+ const only = c.req.header('x-fondu-only');
133
+ if (!only ||
134
+ c.req.method !== 'GET' ||
135
+ !isPageRequest(c) ||
136
+ c.req.header('x-fondu-component') !== id)
137
+ return;
138
+ return only
139
+ .split(',')
140
+ .map((name) => name.trim())
141
+ .filter(Boolean);
62
142
  }
63
143
  /** an http(s) URL, as `to` resolves from the request's */
64
144
  function webUrl(c, to) {
@@ -80,7 +160,7 @@ const versionCheck = async (c, next) => {
80
160
  }
81
161
  await next();
82
162
  // a URL answers a navigation and a document differently: caches keep them apart
83
- appendHeader(c, 'Vary', 'X-Fondu');
163
+ appendHeader(c, 'Vary', isPageRequest(c) ? 'X-Fondu, X-Fondu-Only' : 'X-Fondu');
84
164
  // an empty answer to a form (an action that returns nothing to show, `c.body(null)`): back to the page. Its body
85
165
  // isn't read to tell (a stream's would be, to its end)
86
166
  if (isPageRequest(c) && c.res.status === 200 && !c.res.headers.has('x-fondu') && !c.res.body)
@@ -10,9 +10,11 @@ export interface RouteModule {
10
10
  params?: Params;
11
11
  /** a `_middleware.ts`: the middleware; a page: its component */
12
12
  default?: Handlers;
13
+ /** a page's route file (`.tsx`): GET, POST, POST `?name` */
13
14
  loader?: Handlers;
14
15
  action?: Handlers;
15
16
  actions?: Record<string, Handlers>;
17
+ /** a `.ts` route file: the HTTP methods */
16
18
  GET?: Handlers;
17
19
  POST?: Handlers;
18
20
  PUT?: Handlers;
@@ -34,6 +36,6 @@ export interface Route {
34
36
  * by segment, static before a param with listed values, before any param, before a catch-all. Throws, at startup,
35
37
  * on what would answer the wrong way: two files for the same URLs (one would never answer, or answer without the
36
38
  * other's middleware), `params` that no route takes or that aren't single segments, an error page other than the
37
- * app's.
39
+ * app's, a `.jsx` file that would be a route, a layout or the error page (route files are TypeScript).
38
40
  */
39
41
  export declare function routeTable(modules: Record<string, RouteModule>, append: boolean): Route[];
@@ -6,11 +6,15 @@ const SEGMENT = /^[\w.~-]+$/;
6
6
  * by segment, static before a param with listed values, before any param, before a catch-all. Throws, at startup,
7
7
  * on what would answer the wrong way: two files for the same URLs (one would never answer, or answer without the
8
8
  * other's middleware), `params` that no route takes or that aren't single segments, an error page other than the
9
- * app's.
9
+ * app's, a `.jsx` file that would be a route, a layout or the error page (route files are TypeScript).
10
10
  */
11
11
  export function routeTable(modules, append) {
12
12
  const files = Object.keys(modules);
13
- const nested = files.find((f) => /\/_error\.[jt]sx$/.test(f));
13
+ const jsx = files.find((f) => f.endsWith('.jsx') &&
14
+ (isRouteFile(f.replace(/\.jsx$/, '.tsx')) || /(?:^|\/)_(?:layout|error)\.jsx$/.test(f)));
15
+ if (jsx)
16
+ throw new Error(`fondu: routes/${jsx}: route files are TypeScript; rename it to ${jsx.replace(/\.jsx$/, '.tsx')}`);
17
+ const nested = files.find((f) => f.endsWith('/_error.tsx'));
14
18
  if (nested)
15
19
  throw new Error(`fondu: routes/${nested} is never shown: the error page is routes/_error.tsx, one for the app`);
16
20
  const middlewareFiles = files.filter((f) => f.endsWith('/_middleware.ts'));
@@ -0,0 +1,14 @@
1
+ import type { MiddlewareHandler } from 'hono';
2
+ /** Hono's `serveStatic` of the runtime (`hono/bun`, `@hono/node-server/serve-static`), given by the built server's entry */
3
+ export type ServeStatic = (options: {
4
+ root: string;
5
+ rewriteRequestPath?: (path: string) => string;
6
+ }) => MiddlewareHandler;
7
+ /**
8
+ * Node / Bun: the prerendered pages as files, before the app: a document request (`Accept: text/html`, no `X-Fondu`)
9
+ * for `/docs/intro` is `docs/intro.html`, a page object (`/_fondu/pages/…`) its `.json`, each with the headers the
10
+ * build decided (`headers`: `dist/server/prerender.json`). No file, or no page request: the next handler (the app).
11
+ * A URL ending in `index` is never a document file (it would be its directory's). A path that still has an escaped
12
+ * reserved character (`%2F`…) after decoding is not served from a file: serveStatic refuses it, and the app answers.
13
+ */
14
+ export declare function staticPages(serveStatic: ServeStatic, clientRoot: string, headers: Record<string, string>): MiddlewareHandler;
@@ -0,0 +1,37 @@
1
+ import { endsInIndex, htmlFile, PAGE_DATA } from '../paths.js';
2
+ import { isPageRequest } from './http.js';
3
+ /** the headers on the response a file was served with (the runtimes differ in when `onFound` could set them) */
4
+ const withHeaders = (res, headers) => {
5
+ for (const [name, value] of Object.entries(headers))
6
+ res.headers.set(name, value);
7
+ };
8
+ /**
9
+ * Node / Bun: the prerendered pages as files, before the app: a document request (`Accept: text/html`, no `X-Fondu`)
10
+ * for `/docs/intro` is `docs/intro.html`, a page object (`/_fondu/pages/…`) its `.json`, each with the headers the
11
+ * build decided (`headers`: `dist/server/prerender.json`). No file, or no page request: the next handler (the app).
12
+ * A URL ending in `index` is never a document file (it would be its directory's). A path that still has an escaped
13
+ * reserved character (`%2F`…) after decoding is not served from a file: serveStatic refuses it, and the app answers.
14
+ */
15
+ export function staticPages(serveStatic, clientRoot, headers) {
16
+ const pageObject = serveStatic({ root: clientRoot });
17
+ const document = serveStatic({ root: clientRoot, rewriteRequestPath: htmlFile });
18
+ const serve = (middleware, own) => async (c, next) => {
19
+ const res = await middleware(c, next);
20
+ if (res instanceof Response)
21
+ withHeaders(res, { ...headers, ...own });
22
+ return res;
23
+ };
24
+ const pages = serve(pageObject, { 'Cache-Control': 'private, no-cache', 'X-Fondu': 'true' });
25
+ const documents = serve(document, { 'Cache-Control': 'private, no-cache' });
26
+ return (c, next) => {
27
+ if ((c.req.method !== 'GET' && c.req.method !== 'HEAD') || c.req.path.includes('\0'))
28
+ return next();
29
+ if (c.req.path.startsWith(`${PAGE_DATA}/`))
30
+ return pages(c, next);
31
+ if (isPageRequest(c) ||
32
+ !(c.req.header('accept') ?? '').includes('text/html') ||
33
+ endsInIndex(c.req.path))
34
+ return next();
35
+ return documents(c, next);
36
+ };
37
+ }
package/dist/virtual.d.ts CHANGED
@@ -10,7 +10,11 @@ declare module 'virtual:fondu/assets' {
10
10
  declare module 'virtual:fondu/ssr' {
11
11
  /** the server render of a page (null: `fondu({ ssr: false })`) */
12
12
  export const renderPage:
13
- | ((page: import('./client/navigation.js').Page) => Promise<{ head: string; body: string }>)
13
+ | ((
14
+ page: import('./client/navigation.js').Page,
15
+ options: { nonce?: string; onError?: (error: unknown) => void },
16
+ after?: import('react').ReactElement,
17
+ ) => Promise<import('./client/app.js').Rendered>)
14
18
  | null
15
19
  /** React's static markup of a JSX document (`react-dom/server`'s `renderToStaticMarkup`) */
16
20
  export function renderMarkup(element: import('react').ReactElement): string | Promise<string>
@@ -2,10 +2,10 @@ import { createHash } from 'node:crypto';
2
2
  import { appendFileSync, existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
3
3
  import { builtinModules, createRequire } from 'node:module';
4
4
  import { dirname, join, relative, resolve, sep } from 'node:path';
5
- import { pathToFileURL } from 'node:url';
5
+ import { fileURLToPath, pathToFileURL } from 'node:url';
6
6
  import devServer, { defaultOptions as devServerDefaults } from '@hono/vite-dev-server';
7
7
  import react, {} from '@vitejs/plugin-react';
8
- import { parseAst, transformWithOxc, } from 'vite';
8
+ import { normalizePath, parseAst, transformWithOxc, } from 'vite';
9
9
  import { isPageFile, layoutsOf, pageId } from '../paths.js';
10
10
  import { hmr, PAGE_EXPORTS, PROPS_EVENT } from './hmr.js';
11
11
  import { nodeServer, prerender, worker } from './prerender.js';
@@ -14,6 +14,7 @@ import { typegen, walk as walkFiles } from './typegen.js';
14
14
  /** what fondu's server code imports from Hono (test/hono.test.ts keeps the list complete) */
15
15
  export const HONO = [
16
16
  'hono',
17
+ 'hono/body-limit',
17
18
  'hono/combine',
18
19
  'hono/cookie',
19
20
  'hono/csrf',
@@ -31,18 +32,20 @@ const V = {
31
32
  ssr: 'virtual:fondu/ssr',
32
33
  serverEntry: 'virtual:fondu/server-entry',
33
34
  };
35
+ /** fondu's own `server/static.js`, imported by the built server's entry (by its path: it is not an export of the package) */
36
+ const staticModule = normalizePath(fileURLToPath(new URL('../server/static.js', import.meta.url)));
34
37
  const resolved = (id) => '\0' + id;
35
38
  /** the pages, for the app's entry: the route files of `app/routes/` that are React, but what isn't a route */
36
39
  const PAGES_GLOB = [
37
- '/app/routes/**/*.{tsx,jsx,mdx}',
40
+ '/app/routes/**/*.{tsx,mdx}',
38
41
  '!/app/routes/**/_*',
39
42
  '!/app/routes/**/_*/**',
40
- '!/app/routes/**/*.{test,spec}.{tsx,jsx}',
43
+ '!/app/routes/**/*.{test,spec}.tsx',
41
44
  ];
42
45
  /** the error page (`_error.tsx`: a page, though its name says it is no URL) */
43
- const ERROR_GLOB = '/app/routes/_error.{tsx,jsx}';
46
+ const ERROR_GLOB = '/app/routes/_error.tsx';
44
47
  /** and the layouts (`_layout.tsx`): the client puts a page in those of its directories */
45
- const LAYOUTS_GLOB = ['/app/routes/**/_layout.{tsx,jsx}', '!/app/routes/**/_*/**'];
48
+ const LAYOUTS_GLOB = ['/app/routes/**/_layout.tsx', '!/app/routes/**/_*/**'];
46
49
  /**
47
50
  * For the dependency scan: a page's route file as the browser gets it, its server code removed. The scan would find
48
51
  * the server's dependencies otherwise, and bundle them for the browser.
@@ -51,13 +54,13 @@ function scanRoutes(root) {
51
54
  return {
52
55
  name: 'fondu:scan-routes',
53
56
  load: {
54
- filter: { id: /\/app\/routes\/.*\.[jt]sx$/ },
57
+ filter: { id: /\/app\/routes\/.*\.tsx$/ },
55
58
  async handler(id) {
56
59
  const file = relative(`${root()}/app/routes`, id).split(sep).join('/');
57
60
  if (file.startsWith('..') || !isPageFile(file))
58
61
  return;
59
62
  const { code } = await transformWithOxc(readFileSync(id, 'utf8'), id, {
60
- lang: id.endsWith('.jsx') ? 'jsx' : 'tsx',
63
+ lang: 'tsx',
61
64
  jsx: { runtime: 'automatic' },
62
65
  });
63
66
  return {
@@ -129,6 +132,8 @@ function dependencies(root = '') {
129
132
  * server bundle wherever it runs from; hashed files never change), then the app. Node: @hono/node-server's serve()
130
133
  * on `PORT` (else the option), saying where it listens, with a graceful shutdown on SIGTERM / SIGINT (10 s). Bun
131
134
  * serves the default export itself and reads `PORT` (with the app's `websocket`, if it has one).
135
+ * With `prerender`, the pages the build wrote are served from their files first, with the headers it decided
136
+ * (`prerender.json`, next to this entry).
132
137
  */
133
138
  function serverEntry(options) {
134
139
  let root = process.cwd();
@@ -158,15 +163,17 @@ function serverEntry(options) {
158
163
  `const clientRoot = fileURLToPath(new URL('../client', import.meta.url))`,
159
164
  `const main = new Hono()`,
160
165
  `main.use('/assets/*', async (c, next) => { await next(); if (c.res.ok) c.header('Cache-Control', 'public, max-age=31536000, immutable') })`,
161
- ...paths.map((p) => `main.use(${JSON.stringify(p)}, serveStatic({ root: clientRoot }))`),
162
- // prerender: how the app reads the prerendered pages (fondu's server/prerender.ts)
166
+ // prerender: the pages the build wrote are files, with the headers it decided (prerender.json, written after
167
+ // this server was built: not there while the build prerenders, so the app renders them then)
163
168
  ...(options.prerender
164
169
  ? [
165
- `import { readFile } from 'node:fs/promises'`,
166
- `import { join as joinPath, sep } from 'node:path'`,
167
- `globalThis[Symbol.for('fondu.staticFiles')] = (file) => { const to = joinPath(clientRoot, file); return to.startsWith(clientRoot + sep) ? readFile(to).catch(() => null) : Promise.resolve(null) }`,
170
+ `import { existsSync, readFileSync } from 'node:fs'`,
171
+ `import { staticPages } from ${JSON.stringify(staticModule)}`,
172
+ `const prerendered = fileURLToPath(new URL('./prerender.json', import.meta.url))`,
173
+ `if (existsSync(prerendered)) main.use('*', staticPages(serveStatic, clientRoot, JSON.parse(readFileSync(prerendered, 'utf8')).headers))`,
168
174
  ]
169
175
  : []),
176
+ ...paths.map((p) => `main.use(${JSON.stringify(p)}, serveStatic({ root: clientRoot }))`),
170
177
  `main.all('*', (c) => app.fetch(c.req.raw, c.env))`,
171
178
  ...(bun
172
179
  ? [
@@ -292,7 +299,9 @@ function core(options) {
292
299
  const wrangler = resolve(config.root, env.config.build.outDir, 'wrangler.json');
293
300
  if (options.prerender && existsSync(wrangler)) {
294
301
  const clientDir = resolve(config.root, client.config.build.outDir);
295
- await prerender(worker(config.root, wrangler), clientDir, config.logger, true);
302
+ await prerender(worker(config.root, wrangler), clientDir, config.logger, {
303
+ headersFile: true,
304
+ });
296
305
  workerFirstForIndex(wrangler);
297
306
  }
298
307
  }
@@ -333,7 +342,7 @@ function core(options) {
333
342
  await builder.build(builder.environments.client);
334
343
  await builder.build(builder.environments.ssr);
335
344
  if (options.prerender)
336
- await prerender(nodeServer(config.root, target), resolve(config.root, 'dist/client'), config.logger, false);
345
+ await prerender(nodeServer(config.root, target), resolve(config.root, 'dist/client'), config.logger, { serverDir: resolve(config.root, 'dist/server') });
337
346
  },
338
347
  },
339
348
  };
@@ -342,7 +351,7 @@ function core(options) {
342
351
  // so the first page is not reloaded once they are optimized. The scan reads JavaScript: an MDX page is compiled
343
352
  // for it by the app's @mdx-js/rollup; the browser's, a page's route file without its server code
344
353
  configEnvironment(name, env) {
345
- const pages = ['app/routes/**/*.{tsx,jsx,mdx}'];
354
+ const pages = ['app/routes/**/*.{tsx,mdx}'];
346
355
  const mdx = { extensions: ['.mdx'], rolldownOptions: { plugins: [scanMdx(() => config)] } };
347
356
  if (name === 'client')
348
357
  return {
@@ -387,7 +396,7 @@ function core(options) {
387
396
  const env = server.environments.client;
388
397
  const css = [];
389
398
  try {
390
- const layouts = walkFiles(resolve(config.root, 'app/routes')).filter((f) => /(?:^|\/)_layout\.[jt]sx$/.test(f) &&
399
+ const layouts = walkFiles(resolve(config.root, 'app/routes')).filter((f) => /(?:^|\/)_layout\.tsx$/.test(f) &&
391
400
  !f
392
401
  .split('/')
393
402
  .slice(0, -1)
@@ -462,9 +471,9 @@ function core(options) {
462
471
  ? `export const renderPage = null\nexport const renderMarkup = async (el) => (await import('react-dom/server')).renderToStaticMarkup(el)`
463
472
  : [
464
473
  `import '${V.entry}'`,
465
- `import { renderToString, renderToStaticMarkup } from 'react-dom/server'`,
474
+ `import { renderToReadableStream, renderToStaticMarkup } from 'react-dom/server'`,
466
475
  `import { renderPage as render } from 'fondu/client'`,
467
- `export const renderPage = (page) => render(page, renderToString)`,
476
+ `export const renderPage = (page, options, after) => render(page, (el) => renderToReadableStream(el, options), after)`,
468
477
  `export { renderToStaticMarkup as renderMarkup }`,
469
478
  ].join('\n');
470
479
  if (id === resolved(V.assets))
@@ -548,11 +557,11 @@ function productionAssets(config, options) {
548
557
  const pages = {};
549
558
  for (const key of Object.keys(manifest)) {
550
559
  const file = key.startsWith('app/routes/') ? key.slice('app/routes/'.length) : undefined;
551
- if (!file || !(isPageFile(file) || /^_error\.[jt]sx$/.test(file)))
560
+ if (!file || !(isPageFile(file) || /^_error\.tsx$/.test(file)))
552
561
  continue;
553
562
  // the page's chunk, and its layouts' (loaded with it)
554
563
  const around = layoutsOf(file)
555
- .flatMap((dir) => ['tsx', 'jsx'].map((ext) => `app/routes/${dir ? `${dir}/` : ''}_layout.${ext}`))
564
+ .map((dir) => `app/routes/${dir ? `${dir}/` : ''}_layout.tsx`)
556
565
  .filter((k) => k in manifest);
557
566
  const all = [...around, key].map(tags);
558
567
  pages[pageId(file)] = { css: all.flatMap((t) => t.css), js: all.flatMap((t) => t.js) };
@@ -1,9 +1,8 @@
1
1
  import type { Logger } from 'vite';
2
2
  /**
3
- * A static document's own tags: those with the build's nonce (its Content Security Policy's). The nonce of a static
4
- * document is replaced (Cloudflare: its inline scripts by their hashes; Node / Bun: by each response's nonce), which
5
- * only these may get: a `nonce` the document has otherwise (in a page's markup) is dropped. Then the hashes of these
6
- * inline scripts.
3
+ * A static document's own tags: those with the build's nonce (its Content Security Policy's). The policy of a static
4
+ * document has no nonce: its inline scripts are allowed by their hashes instead, and only these tags may have had the
5
+ * nonce: a `nonce` the document has otherwise (in a page's markup) is dropped. Then the hashes of these inline scripts.
7
6
  */
8
7
  export declare function ownScripts(html: string, policy: string | undefined): {
9
8
  html: string;
@@ -28,10 +27,15 @@ interface Server {
28
27
  /**
29
28
  * After the build: the built server (the Worker in wrangler, or `node` / `bun dist/server/index.js`), started with
30
29
  * `FONDU_PRERENDER` set, lists the pages to prerender (`/__fondu/prerender`); each is asked for as a document and as
31
- * a navigation, and both are written to the client build. Cloudflare serves them before the Worker, with the security
32
- * headers written to `_headers`; Node and Bun before the routes, behind the app's own headers.
30
+ * a navigation, and both are written to the client build, with the security headers the build decided for them: one
31
+ * set, in `_headers` (Cloudflare serves the files before the Worker) or in `prerender.json` next to the built server
32
+ * (Node and Bun: its entry serves the files before the app).
33
33
  */
34
- export declare function prerender(start: () => Promise<Server>, clientDir: string, logger: Logger, headersFile: boolean): Promise<undefined>;
34
+ export declare function prerender(start: () => Promise<Server>, clientDir: string, logger: Logger, where: {
35
+ headersFile: true;
36
+ } | {
37
+ serverDir: string;
38
+ }): Promise<undefined>;
35
39
  /** Cloudflare: the built Worker, in the app's own wrangler (fondu does not depend on it) */
36
40
  export declare const worker: (root: string, workerConfig: string) => () => Promise<Server>;
37
41
  /** Node / Bun: `node dist/server/index.js` (or `bun`), on a free port, until it answers */