fondu 0.14.0 → 0.16.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.
@@ -42,10 +42,11 @@ export type Rendered = ReadableStream<Uint8Array> & {
42
42
  };
43
43
  /**
44
44
  * @internal the server render of a page, streamed: the tags its components hoist (`<title>`…) first, then
45
- * `<div id="app">`, then `after` (markup of the document's, in the shell: right after the page), then what the
46
- * Suspense boundaries that were not ready add. Rejects if the shell fails to render.
45
+ * `<div id="app">`, then what the Suspense boundaries that were not ready add. Rejects if the shell fails to render.
46
+ * The tree is the browser's (`hydrateRoot(#app, <App/>)`): `<div id="app"><App/></div>` and nothing beside it, as
47
+ * `useId()` is the position in the tree (a sibling of the page forks it: every id would differ).
47
48
  */
48
- export declare function renderPage(page: Page, render: (element: ReactElement) => Promise<Rendered>, after?: ReactElement): Promise<Rendered>;
49
+ export declare function renderPage(page: Page, render: (element: ReactElement) => Promise<Rendered>): Promise<Rendered>;
49
50
  /** a form's field errors, as a page gets them (its `errors` prop): field name → message */
50
51
  export type Errors = Record<string, string>;
51
52
  /** the page on screen: its props (the shared ones, `errors`), its URL, its flash data */
@@ -1,4 +1,4 @@
1
- import { Component, createContext, createElement, Fragment, useContext, useLayoutEffect, useState, useSyncExternalStore, } from 'react';
1
+ import { Component, createContext, createElement, useContext, useLayoutEffect, useState, useSyncExternalStore, } from 'react';
2
2
  import { flushSync } from 'react-dom';
3
3
  import { createRoot, hydrateRoot } from 'react-dom/client';
4
4
  import { decoded, layoutsOf, pageId, routePatterns } from '../paths.js';
@@ -170,12 +170,13 @@ function start(settings) {
170
170
  }
171
171
  /**
172
172
  * @internal the server render of a page, streamed: the tags its components hoist (`<title>`…) first, then
173
- * `<div id="app">`, then `after` (markup of the document's, in the shell: right after the page), then what the
174
- * Suspense boundaries that were not ready add. Rejects if the shell fails to render.
173
+ * `<div id="app">`, then what the Suspense boundaries that were not ready add. Rejects if the shell fails to render.
174
+ * The tree is the browser's (`hydrateRoot(#app, <App/>)`): `<div id="app"><App/></div>` and nothing beside it, as
175
+ * `useId()` is the position in the tree (a sibling of the page forks it: every id would differ).
175
176
  */
176
- export async function renderPage(page, render, after) {
177
+ export async function renderPage(page, render) {
177
178
  const view = await load(page.component);
178
- return render(createElement(Fragment, null, createElement('div', { id: 'app' }, createElement(App, { initial: { page, view, mounts: 0 } })), after));
179
+ return render(createElement('div', { id: 'app' }, createElement(App, { initial: { page, view, mounts: 0 } })));
179
180
  }
180
181
  /** the page on screen: its props (the shared ones, `errors`), its URL, its flash data */
181
182
  export function usePage() {
@@ -210,7 +211,7 @@ export function Deferred({ data, fallback = null, failed = fallback, children, }
210
211
  if (!page)
211
212
  throw new Error('fondu: <Deferred> is for components of a page');
212
213
  const names = [data].flat();
213
- if (names.every((name) => name in page.props))
214
+ if (names.every((name) => Object.hasOwn(page.props, name)))
214
215
  return children;
215
216
  return names.some((name) => page.deferred?.includes(name)) ? fallback : failed;
216
217
  }
@@ -44,10 +44,13 @@ export declare function startNavigation({ initial, show, prerender, pending, pre
44
44
  export declare function loadDocument(href: string): void;
45
45
  /**
46
46
  * `href` visited as a link to it would be: a page of the app in place (a new history entry, or this one's with
47
- * `replace`), anything else as a document
47
+ * `replace`), anything else as a document. `keep`: the answer is shown as `reload()` shows its own, the page keeps
48
+ * its state (a focused input, what was typed) and the scroll position, nothing is announced: a search box that
49
+ * `navigate()`s to its query as it is typed. Another page's component is shown as any navigation's.
48
50
  */
49
- export declare function navigate(href: string, { replace }?: {
51
+ export declare function navigate(href: string, { replace, keep }?: {
50
52
  replace?: boolean;
53
+ keep?: boolean;
51
54
  }): void;
52
55
  /** the page asked for again, its state and the scroll position kept */
53
56
  export declare function again(only?: string[]): void;
@@ -43,36 +43,43 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
43
43
  const headers = () => ({ 'X-Fondu': 'true', ...(version && { 'X-Fondu-Version': version }) });
44
44
  /** where a page's JSON is: its URL, or its file (a prerendered build) */
45
45
  const source = (url) => prerender ? pageDataPath(url.pathname) + url.search : url.pathname + url.search;
46
- // What a static page's file answered when the pointer rested on its link (`prerender`), by the URL a navigation
47
- // would ask for: read into memory, the last 20. A file runs nothing, so asking early costs the app nothing; the
48
- // click uses it once, and its version is checked as for any page object. A page without a file answers 204
49
- // (nothing kept: its data is asked for at the click, when its loader should run)
46
+ // What a link's page answered when asked early (`prerender`), by the URL a navigation would ask: its file (the
47
+ // text and the headers, read into memory), or null (no file: 204, its data is asked for at the click, when its
48
+ // loader should run). A file runs nothing, so asking early costs the app nothing. Asked once in 30 seconds
49
+ // (TanStack Router's default: a deploy in between is found at the click); the click waits for an answer on its
50
+ // way, and every click in the 30 seconds uses it, its version checked as for any page object. The last 20
51
+ const freshFor = 30_000;
50
52
  const prefetched = new Map();
51
- const prefetching = new Set();
52
- const prefetch = async (url) => {
53
+ const prefetch = (url) => {
53
54
  if (!prerender)
54
55
  return;
55
56
  const key = source(url);
56
- if (prefetched.has(key) || prefetching.has(key))
57
+ const entry = prefetched.get(key);
58
+ if (entry && Date.now() - entry.at < freshFor)
57
59
  return;
58
- prefetching.add(key);
59
- try {
60
- const response = await fetch(key, { headers: { ...headers(), 'X-Fondu-Prefetch': 'true' } });
61
- if (response.status === 200 && response.headers.has('X-Fondu')) {
62
- prefetched.set(key, new Response(await response.text(), { headers: response.headers }));
63
- if (prefetched.size > 20)
64
- prefetched.delete(prefetched.keys().next().value);
60
+ const answer = (async () => {
61
+ try {
62
+ const response = await fetch(key, { headers: { ...headers(), 'X-Fondu-Prefetch': 'true' } });
63
+ if (response.status === 200 && response.headers.has('X-Fondu'))
64
+ return { body: await response.text(), headers: response.headers };
65
65
  }
66
- }
67
- catch { } // offline: asked for at the click
68
- prefetching.delete(key);
66
+ catch {
67
+ // offline: asked for again
68
+ prefetched.delete(key);
69
+ }
70
+ return null;
71
+ })();
72
+ prefetched.delete(key);
73
+ prefetched.set(key, { answer, at: Date.now() });
74
+ if (prefetched.size > 20)
75
+ prefetched.delete(prefetched.keys().next().value);
69
76
  };
70
77
  /**
71
78
  * Props of the page on the screen, asked for with a request of its own: the loader's answer for the same
72
79
  * component, with these props only. Quiet: no navigation state, no history entry, no scroll; it is aborted when
73
80
  * another page is put on the screen, and an answer for a page no longer there is dropped; whatever isn't the
74
- * page's answer is a failure, never a navigation. What came is merged into the page, its state kept; what didn't is no longer pending (`<Deferred>`
75
- * says it failed)
81
+ * page's answer is a failure, never a navigation. What came is merged into the page, its state kept; what didn't
82
+ * is no longer pending (`<Deferred>` says it failed)
76
83
  */
77
84
  ask = async (names) => {
78
85
  const at = shows;
@@ -80,7 +87,7 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
80
87
  const controller = new AbortController();
81
88
  asking.add(controller);
82
89
  // a prop asked for that is neither here nor coming (it failed): pending again, `<Deferred>` shows its fallback
83
- const absent = names.filter((n) => !(n in page.props) && !page.deferred?.includes(n));
90
+ const absent = names.filter((n) => !Object.hasOwn(page.props, n) && !page.deferred?.includes(n));
84
91
  if (absent.length)
85
92
  void show((on = { ...page, deferred: [...(page.deferred ?? []), ...absent] }), false, () => shows !== at);
86
93
  let got = {};
@@ -150,9 +157,9 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
150
157
  if (!post)
151
158
  preload(url.pathname);
152
159
  const from = !post && prerender ? source(url) : url.pathname + url.search;
153
- // a GET that is not asked for again: the answer kept for it, once (never a form's POST, reload() or Back's)
154
- const early = !post && !options.keep && !shown ? prefetched.get(from) : undefined;
155
- prefetched.delete(from);
160
+ // a GET that is not asked for again: the answer kept for it (never a form's POST, reload() or Back's)
161
+ const found = !post && !options.keep && !shown ? prefetched.get(from) : undefined;
162
+ const entry = found && Date.now() - found.at < freshFor ? found : undefined;
156
163
  void (async () => {
157
164
  try {
158
165
  if (shown) {
@@ -163,13 +170,18 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
163
170
  announce();
164
171
  restore(options.scroll, url.hash);
165
172
  }
166
- const response = early ??
167
- (await fetch(from, {
173
+ // the file asked for early, waited for if it is on its way; none (null): the app is asked
174
+ const early = entry ? await entry.answer : null;
175
+ if (signal.aborted)
176
+ return;
177
+ const response = early
178
+ ? new Response(early.body, { headers: early.headers })
179
+ : await fetch(from, {
168
180
  method: post ? 'POST' : 'GET',
169
181
  body: options.body,
170
182
  headers: headers(),
171
183
  signal,
172
- }));
184
+ });
173
185
  if (signal.aborted)
174
186
  return;
175
187
  if (post)
@@ -227,15 +239,18 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
227
239
  const errors = Object.keys(page.props.errors ?? {}).length > 0;
228
240
  const asked = url.pathname + url.search;
229
241
  // the kept page's entry: the server's page in its place, its state kept; redirected (signed out), anew
230
- const fresh = shown ? asked !== page.url : !options.keep && !(same && errors);
242
+ // kept: the same component answers (another one mounts anew, and is scrolled to the top as a navigation's)
243
+ const stay = options.keep && page.component === on.component;
244
+ const fresh = shown ? asked !== page.url : !stay && !(same && errors);
231
245
  // the page stays (reload(), Back's, a form's answer): what it asked for isn't taken away while it is asked again
232
246
  if (!fresh && page.deferred)
233
247
  for (const name of page.deferred)
234
- if (name in on.props)
248
+ if (Object.hasOwn(on.props, name))
235
249
  page.props[name] ??= on.props[name];
236
250
  // its URL first, as the browser's own navigations: a page's render reads it (`location`, a URL's language);
237
- // a redirect's, the fragment asked for if it is still this page's
238
- const target = page.url + (asked === page.url ? url.hash : '');
251
+ // a redirect's, the fragment asked for if it is still this page's; a form's answer to the page it was sent
252
+ // from: its #fragment stays, a dialog the fragment opened with it
253
+ const target = page.url + (same ? location.hash : asked === page.url ? url.hash : '');
239
254
  // a form's answer at its URL replaces the entry; Back's or reload()'s page redirected elsewhere too
240
255
  const history = options.history === 'push' && same
241
256
  ? 'replace'
@@ -253,10 +268,10 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
253
268
  ask(page.deferred);
254
269
  if (shown && !fresh)
255
270
  return;
256
- if (!options.keep)
271
+ if (!stay)
257
272
  announce();
258
- // a page asked for again stays where it is: reload(), a form's answer at its URL
259
- if (options.keep || same)
273
+ // a page asked for again stays where it is: reload(), navigate() with `keep`, a form's answer at its URL
274
+ if (stay || same)
260
275
  return;
261
276
  // at once, the page in the DOM (show() renders it synchronously): no frame drawn where it doesn't belong
262
277
  restore(options.history === 'none' ? options.scroll : null, url.hash);
@@ -374,8 +389,12 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
374
389
  // Back and Forward: the entry's page, where it was scrolled
375
390
  window.addEventListener('popstate', (event) => {
376
391
  const popped = scroll.pop(event.state);
377
- if (popped.fragment)
392
+ if (popped.fragment) {
393
+ // a #fragment that names no element (a dialog's `#settings/account`) leaves the page where it is, as the browser does
394
+ if (!popped.position && location.hash && !fragmentTarget(location.hash.slice(1)))
395
+ return;
378
396
  return restore(popped.position, location.hash);
397
+ }
379
398
  visit(location.href, {
380
399
  history: 'none',
381
400
  scroll: popped.position,
@@ -578,14 +597,16 @@ export function loadDocument(href) {
578
597
  }
579
598
  /**
580
599
  * `href` visited as a link to it would be: a page of the app in place (a new history entry, or this one's with
581
- * `replace`), anything else as a document
600
+ * `replace`), anything else as a document. `keep`: the answer is shown as `reload()` shows its own, the page keeps
601
+ * its state (a focused input, what was typed) and the scroll position, nothing is announced: a search box that
602
+ * `navigate()`s to its query as it is typed. Another page's component is shown as any navigation's.
582
603
  */
583
- export function navigate(href, { replace = false } = {}) {
604
+ export function navigate(href, { replace = false, keep = false } = {}) {
584
605
  const url = new URL(href, location.href);
585
606
  const here = url.pathname + url.search === location.pathname + location.search;
586
607
  if (!visit || url.origin !== location.origin || !isAppPage?.(url.pathname) || (here && url.hash))
587
608
  return replace ? location.replace(url.href) : location.assign(url.href); // a #fragment of this page: the browser's
588
- visit(url.href, { history: replace || url.href === location.href ? 'replace' : 'push' });
609
+ visit(url.href, { history: replace || url.href === location.href ? 'replace' : 'push', keep });
589
610
  }
590
611
  /** the page asked for again, its state and the scroll position kept */
591
612
  export function again(only) {
package/dist/client.d.ts CHANGED
@@ -1,4 +1,6 @@
1
- import type { schemasOf } from './server/handler.js';
1
+ import type { TypedResponse } from 'hono';
2
+ import type { StatusCode } from 'hono/utils/http-status';
3
+ import type { answerOf, schemasOf } from './server/handler.js';
2
4
  import type { Routes } from './types.js';
3
5
  type Keys = keyof Routes & string;
4
6
  type Actions = {
@@ -22,9 +24,10 @@ type HandlersOf<P extends string> = P extends `${infer K}?${infer A}` ? K extend
22
24
  } ? G : never : never;
23
25
  /** a query value: what its schema takes (`unknown`, as a coercing schema's input: any) */
24
26
  type QueryValue = string | number | boolean | null | undefined;
25
- type QueryOf<P extends string> = HandlersOf<P> extends {
27
+ /** the query a handler's schema takes (a `withValidator` handler; any query otherwise) */
28
+ type QueryOfHandler<H> = [H] extends [{
26
29
  readonly [schemasOf]?: infer S;
27
- } ? S extends {
30
+ }] ? S extends {
28
31
  query: {
29
32
  '~standard': {
30
33
  types?: infer T;
@@ -35,17 +38,22 @@ type QueryOf<P extends string> = HandlersOf<P> extends {
35
38
  } ? {
36
39
  [K in keyof I]: unknown extends I[K] ? QueryValue : I[K];
37
40
  } : Record<string, QueryValue> : Record<string, QueryValue> : Record<string, QueryValue>;
41
+ type QueryOf<P extends string> = QueryOfHandler<HandlersOf<P>>;
42
+ /** `query`, required when its schema requires a field */
43
+ type QueryArg<Q> = {} extends Q ? {
44
+ query?: Q;
45
+ } : {
46
+ query: Q;
47
+ };
38
48
  /** `query` is required when its schema requires a field */
39
49
  type Extra<P extends string> = {
40
50
  hash?: string;
41
- } & ({} extends QueryOf<P> ? {
42
- query?: QueryOf<P>;
43
- } : {
44
- query: QueryOf<P>;
45
- });
46
- type Args<P extends string> = [ParamNames<P>] extends [never] ? {} extends QueryOf<P> ? [options?: Extra<P>] : [options: Extra<P>] : [params: {
51
+ } & QueryArg<QueryOf<P>>;
52
+ /** the params of a URL pattern, as the options take them */
53
+ type ParamArgs<P extends string> = {
47
54
  [K in ParamNames<P>]: string | number;
48
- } & Extra<P>];
55
+ };
56
+ type Args<P extends string> = [ParamNames<P>] extends [never] ? {} extends QueryOf<P> ? [options?: Extra<P>] : [options: Extra<P>] : [params: ParamArgs<P> & Extra<P>];
49
57
  /**
50
58
  * Typed URLs from `app/routes/` (as React Router's `href`): `href('/users/:id', { id })` → `'/users/7'`;
51
59
  * one of a file's `actions`: `href('/users/:id?delete', { id })`. Only patterns that exist; params are required.
@@ -57,3 +65,81 @@ export { usePage, useNavigation, reload, Deferred, __entry, renderPage, type Err
57
65
  export { useForm } from './client/form.js';
58
66
  export { loadDocument, navigate, type Page } from './client/navigation.js';
59
67
  export type { ProgressOptions } from './client/progress.js';
68
+ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
69
+ /** no generated types (or none of routes): everything is loose, as `Href` is */
70
+ type Loose = string extends Keys ? true : [Keys] extends [never] ? true : false;
71
+ /** the HTTP methods a route file exports (a page has none) */
72
+ type MethodsOf<P extends string> = Loose extends true ? HttpMethod : P extends Keys ? keyof Routes[P] & HttpMethod : never;
73
+ /**
74
+ * The URL patterns of route files that export an HTTP method (`.ts` files). A page's pattern is not one: a page's
75
+ * data is its props (its loader, `defer()`), and `fetch()` is for effects and events.
76
+ */
77
+ export type ApiPath = Loose extends true ? string : {
78
+ [P in Keys]: [MethodsOf<P>] extends [never] ? never : P;
79
+ }[Keys];
80
+ /** the handler of the route's method */
81
+ type HandlerOf<P extends string, M extends string> = Loose extends true ? unknown : P extends Keys ? Routes[P] extends {
82
+ [K in M]: infer H;
83
+ } ? H : never : never;
84
+ /** what the handler's `withValidator` body schema takes (any JSON when it has none) */
85
+ type BodyOfHandler<H> = [H] extends [{
86
+ readonly [schemasOf]?: infer S;
87
+ }] ? S extends {
88
+ body: {
89
+ '~standard': {
90
+ types?: infer T;
91
+ };
92
+ };
93
+ } ? NonNullable<T> extends {
94
+ input: infer I;
95
+ } ? I : unknown : unknown : unknown;
96
+ type BodyArg<M extends string, B> = M extends 'GET' ? {
97
+ body?: never;
98
+ } : {} extends B ? {
99
+ body?: B;
100
+ } : undefined extends B ? {
101
+ body?: B;
102
+ } : {
103
+ body: B;
104
+ };
105
+ /** `method`: omitted is GET, so required when the route has no GET */
106
+ type MethodArg<P extends string, M extends string> = 'GET' extends MethodsOf<P> ? {
107
+ method?: M;
108
+ } : {
109
+ method: M;
110
+ };
111
+ type FetchOptions<P extends string, M extends HttpMethod> = ParamArgs<P> & MethodArg<P, M> & QueryArg<QueryOfHandler<HandlerOf<P, M>>> & BodyArg<M, BodyOfHandler<HandlerOf<P, M>>> & {
112
+ headers?: HeadersInit;
113
+ signal?: AbortSignal;
114
+ };
115
+ /** the options are optional when nothing is required: no params, no `body`, `query` or `method` to give */
116
+ export type FetchArgs<P extends string, M extends HttpMethod> = {} extends FetchOptions<P, M> ? [options?: FetchOptions<P, M>] : [options: FetchOptions<P, M>];
117
+ /** what a handler returns, in the type: a `defineHandler(...)` tuple, a `withValidator` handler, a function */
118
+ type ReturnedBy<H> = typeof answerOf extends keyof H ? NonNullable<H[typeof answerOf & keyof H]> : H extends readonly [...unknown[], infer Last] ? Returned<Last> : Returned<H>;
119
+ type Returned<F> = F extends (...args: never[]) => infer R ? Exclude<Awaited<R>, void> : unknown;
120
+ /**
121
+ * The answer as JSON delivers it: Hono's `c.json(data)` is a `TypedResponse` whose data is already what JSON makes of
122
+ * it (a `Date` is a string, `undefined` fields are dropped). Any other answer (text, a redirect, a body, or a
123
+ * branch that is not `c.json`) is `unknown`.
124
+ */
125
+ type AnswerOfResponse<R> = [R] extends [never] ? unknown : [R] extends [TypedResponse<unknown, StatusCode, 'json'>] ? R extends TypedResponse<infer T, StatusCode, 'json'> ? T : never : unknown;
126
+ export type AnswerOf<P extends string, M extends string> = Loose extends true ? unknown : AnswerOfResponse<ReturnedBy<HandlerOf<P, M>>>;
127
+ /** a non-2xx answer: `status`, `data` (the parsed body: a 422's `{ errors }`) and the `response` */
128
+ export declare class FetchError extends Error {
129
+ readonly status: number;
130
+ readonly data: unknown;
131
+ readonly response: Response;
132
+ constructor(method: string, url: string, response: Response, data: unknown);
133
+ }
134
+ /**
135
+ * Calls a `.ts` route of the app from the browser (an effect, an event), typed by the route file: the params as
136
+ * `href()` takes them, `query` and `body` by the handler's `withValidator` schemas, `method` one the file exports
137
+ * (GET when left out), the answer by what the handler returns with `c.json()`, as JSON delivers it.
138
+ *
139
+ * const usage = await fetch('/api/usage')
140
+ * await fetch('/api/settings', { method: 'POST', body: { emails: false } })
141
+ *
142
+ * A non-2xx answer throws a `FetchError`. No retry, no cache. A page's data comes from its loader or `defer()`:
143
+ * called during the server render, it throws. (Follows Void's typed fetch.)
144
+ */
145
+ export declare function fetch<P extends ApiPath, M extends MethodsOf<P> & HttpMethod = Extract<MethodsOf<P>, 'GET'>>(path: P, ...[options]: FetchArgs<P, M>): Promise<AnswerOf<P, M>>;
package/dist/client.js CHANGED
@@ -7,6 +7,9 @@ import { fillPattern } from './paths.js';
7
7
  */
8
8
  export function href(path, ...[options]) {
9
9
  const { query, hash, ...params } = (options ?? {});
10
+ return buildUrl(path, params, query, hash);
11
+ }
12
+ function buildUrl(path, params, query, hash) {
10
13
  let url = fillPattern(path, params);
11
14
  const search = new URLSearchParams();
12
15
  for (const [name, value] of Object.entries(query ?? {}))
@@ -23,3 +26,65 @@ export function href(path, ...[options]) {
23
26
  export { usePage, useNavigation, reload, Deferred, __entry, renderPage, } from './client/app.js';
24
27
  export { useForm } from './client/form.js';
25
28
  export { loadDocument, navigate } from './client/navigation.js';
29
+ /** a non-2xx answer: `status`, `data` (the parsed body: a 422's `{ errors }`) and the `response` */
30
+ export class FetchError extends Error {
31
+ status;
32
+ data;
33
+ response;
34
+ constructor(method, url, response, data) {
35
+ super(`${method} ${url}: ${response.status}`);
36
+ this.name = 'FetchError';
37
+ this.status = response.status;
38
+ this.data = data;
39
+ this.response = response;
40
+ }
41
+ }
42
+ /**
43
+ * Calls a `.ts` route of the app from the browser (an effect, an event), typed by the route file: the params as
44
+ * `href()` takes them, `query` and `body` by the handler's `withValidator` schemas, `method` one the file exports
45
+ * (GET when left out), the answer by what the handler returns with `c.json()`, as JSON delivers it.
46
+ *
47
+ * const usage = await fetch('/api/usage')
48
+ * await fetch('/api/settings', { method: 'POST', body: { emails: false } })
49
+ *
50
+ * A non-2xx answer throws a `FetchError`. No retry, no cache. A page's data comes from its loader or `defer()`:
51
+ * called during the server render, it throws. (Follows Void's typed fetch.)
52
+ */
53
+ export async function fetch(path, ...[options]) {
54
+ if (typeof document === 'undefined')
55
+ throw new Error("fondu: fetch() from fondu/client is for the browser (effects, events); a page's data comes from its loader or defer()");
56
+ const { method = 'GET', query, body, headers, signal, ...params } = (options ?? {});
57
+ const url = buildUrl(path, params, query, undefined);
58
+ // a Headers object: the call's headers replace ours whatever their case
59
+ const all = new Headers({ Accept: 'application/json' });
60
+ if (body !== undefined)
61
+ all.set('Content-Type', 'application/json');
62
+ new Headers(headers).forEach((value, name) => all.set(name, value));
63
+ const response = await globalThis.fetch(url, {
64
+ method,
65
+ headers: all,
66
+ body: JSON.stringify(body),
67
+ signal,
68
+ });
69
+ const data = await readAnswer(response);
70
+ if (!response.ok)
71
+ throw new FetchError(method, url, response, data);
72
+ return data;
73
+ }
74
+ /** the answer's body: JSON when its content type says so, else text; none for 204 or an empty body */
75
+ async function readAnswer(response) {
76
+ const text = await response.text();
77
+ if (!text)
78
+ return undefined;
79
+ if (!/[/+]json\b/i.test(response.headers.get('content-type') ?? ''))
80
+ return text;
81
+ try {
82
+ return JSON.parse(text);
83
+ }
84
+ catch (error) {
85
+ // an error page that says it is JSON and isn't: its text is the data
86
+ if (!response.ok)
87
+ return text;
88
+ throw error;
89
+ }
90
+ }
@@ -28,8 +28,8 @@ export declare function checkExports(file: string, mod: Record<string, unknown>)
28
28
  * - server code, `.ts`: HTTP handlers only, `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS` (not `loader`,
29
29
  * `action`, `actions`: those are a page's)
30
30
  * `_middleware.ts` applies to its directory and below (`routes/_middleware.ts`: every request, 404s included).
31
- * Built in: CSRF protection, security headers, a request body limit, one URL per page (trailing slash), the error page. Your own 404 /
32
- * error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
31
+ * Built in: CSRF protection, security headers, a request body limit, one URL per page (trailing slash), the error
32
+ * page. Your own 404 / error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
33
33
  */
34
34
  export declare function createApp(options?: CreateAppOptions): Hono;
35
35
  export {};
@@ -94,8 +94,8 @@ function actionName(url) {
94
94
  * - server code, `.ts`: HTTP handlers only, `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS` (not `loader`,
95
95
  * `action`, `actions`: those are a page's)
96
96
  * `_middleware.ts` applies to its directory and below (`routes/_middleware.ts`: every request, 404s included).
97
- * Built in: CSRF protection, security headers, a request body limit, one URL per page (trailing slash), the error page. Your own 404 /
98
- * error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
97
+ * Built in: CSRF protection, security headers, a request body limit, one URL per page (trailing slash), the error
98
+ * page. Your own 404 / error handling: Hono's `app.notFound()` / `app.onError()` on the returned app.
99
99
  */
100
100
  export function createApp(options = {}) {
101
101
  const app = new Hono();
@@ -1,5 +1,5 @@
1
1
  import type { Context, MiddlewareHandler } from 'hono';
2
- import { type ReactElement } from 'react';
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.
@@ -1,4 +1,3 @@
1
- import { createElement } from 'react';
2
1
  import { assetTags } from 'virtual:fondu/assets';
3
2
  import { renderMarkup, renderPage } from 'virtual:fondu/ssr';
4
3
  import { SCROLL_KEY, SCROLL_STORAGE } from '../paths.js';
@@ -42,6 +41,14 @@ async function shell(template, c, nonce) {
42
41
  return html;
43
42
  return html.replace(/<script\b(?![^>]*\s(?:src|nonce)=)/gi, `<script nonce="${nonce}"`);
44
43
  }
44
+ let shellEndReported = false;
45
+ /** once per process: every request would say the same */
46
+ function shellEndLost() {
47
+ if (shellEndReported)
48
+ return;
49
+ shellEndReported = true;
50
+ console.error("[fondu] the end of the page's shell was not found in react-dom's output (bootstrapScriptContent): the document was sent whole, without its scroll script. Is react-dom a version Fondu supports?");
51
+ }
45
52
  /**
46
53
  * The document, streamed. First: the template's start, the stylesheets and the client's tags, the tags the page hoists
47
54
  * (React writes them before the page), the page data and the page's shell. Then what React adds as the Suspense
@@ -59,6 +66,8 @@ export async function renderDocument(c, page, whole = false) {
59
66
  if (after === undefined || more.length || html.indexOf(HEAD) > html.indexOf(BODY))
60
67
  throw new Error('fondu: the document must have `head` once, in <head>, and `body` once, in <body>');
61
68
  let ssr = null;
69
+ // per request: nothing the page renders can be it
70
+ const marker = crypto.randomUUID();
62
71
  // what fails in a boundary is for the browser to render, and is logged. The shell's failure is logged below, once:
63
72
  // React reports it to `onError` too, so what it reports is held until the shell is known to be there
64
73
  const pending = [];
@@ -68,10 +77,14 @@ export async function renderDocument(c, page, whole = false) {
68
77
  // a HEAD: Hono drops its body without cancelling it, so React would keep rendering for nothing
69
78
  if (renderPage && !browserOnly.has(c) && c.req.method !== 'HEAD') {
70
79
  // 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 } }));
80
+ const stream = await renderPage(JSON.parse(JSON.stringify(page)), {
81
+ nonce,
82
+ onError: (error) => (live ? late(error) : void pending.push(error)),
83
+ // React writes this as a script right after the shell, before what the boundaries add: where `restoreScroll`
84
+ // goes. Not as React's own script (it adds an `id`, and follows its `$RT` one), and not as a sibling of the
85
+ // page in the tree: the page alone is the browser's tree (`useId()`)
86
+ bootstrapScriptContent: marker,
87
+ });
75
88
  if (whole)
76
89
  await stream.allReady;
77
90
  ssr = stream.pipeThrough(new TextDecoderStream());
@@ -97,21 +110,59 @@ export async function renderDocument(c, page, whole = false) {
97
110
  const start = top + tags.replace(/<link rel="stylesheet"[^>]*>/g, '');
98
111
  if (!ssr)
99
112
  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
113
+ // React's own: the tags the page hoists, the page (`<div id="app"`), and the script of `marker`, the end of the
114
+ // shell (React writes the shell in as many chunks as it needs, so no chunk is its end): found across chunks.
115
+ // This relies on React writing `bootstrapScriptContent` as one inline `<script>` right after the shell. A React
116
+ // that writes it differently is reported (`shellEndLost`), not silently streamed without the scroll script.
117
+ // Only what is new is searched: from where the last search ended, less the marker's length (a marker cut between
118
+ // two chunks), so the work is linear in the shell, not quadratic
101
119
  const reader = ssr.getReader();
120
+ const closing = '</script>';
102
121
  let text = '';
103
- let at = -1;
104
- while (at < 0) {
122
+ let searchedTo = 0;
123
+ let open = -1;
124
+ let close = -1;
125
+ for (;;) {
105
126
  const { done, value } = await reader.read();
106
127
  if (done)
107
128
  break;
108
129
  text += value;
109
- at = text.indexOf('<div id="app"');
130
+ let from = Math.max(0, searchedTo - marker.length);
131
+ let hit = text.indexOf(marker, from);
132
+ while (hit >= 0) {
133
+ // `<script …>marker</script>`, and nothing else
134
+ const tagAt = text.lastIndexOf('<script', hit);
135
+ if (tagAt >= 0 && /^<script[^>]*>$/.test(text.slice(tagAt, hit))) {
136
+ const markerEnd = hit + marker.length;
137
+ // the closing tag may still be in the next chunk
138
+ if (text.length < markerEnd + closing.length)
139
+ break;
140
+ if (text.startsWith(closing, markerEnd)) {
141
+ open = tagAt;
142
+ close = markerEnd + closing.length;
143
+ }
144
+ }
145
+ if (close >= 0)
146
+ break;
147
+ from = hit + marker.length;
148
+ hit = text.indexOf(marker, from);
149
+ }
150
+ if (close >= 0)
151
+ break;
152
+ // a marker found but not complete yet is searched for again, from where it is
153
+ searchedTo = hit >= 0 ? hit : text.length;
110
154
  }
155
+ if (close < 0)
156
+ shellEndLost();
157
+ const at = Math.max(text.indexOf('<div id="app"'), 0);
158
+ const script = `<script${nonce ? ` nonce="${nonce}"` : ''}>${restoreScroll}</script>`;
159
+ // the position back for a page rendered here (one rendered in the browser has nothing to scroll yet): in the
160
+ // shell, right after the page, before what the boundaries add
161
+ const streamed = close < 0 ? text : text.slice(0, open) + script + text.slice(close);
111
162
  const out = new TextEncoder();
112
163
  return new ReadableStream({
113
164
  start(controller) {
114
- controller.enqueue(out.encode(start + text.slice(0, at) + between + data + text.slice(at)));
165
+ controller.enqueue(out.encode(start + streamed.slice(0, at) + between + data + streamed.slice(at)));
115
166
  },
116
167
  async pull(controller) {
117
168
  const { done, value } = await reader.read();
@@ -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):
package/dist/virtual.d.ts CHANGED
@@ -12,8 +12,11 @@ declare module 'virtual:fondu/ssr' {
12
12
  export const renderPage:
13
13
  | ((
14
14
  page: import('./client/navigation.js').Page,
15
- options: { nonce?: string; onError?: (error: unknown) => void },
16
- after?: import('react').ReactElement,
15
+ options: {
16
+ nonce?: string
17
+ onError?: (error: unknown) => void
18
+ bootstrapScriptContent?: string
19
+ },
17
20
  ) => Promise<import('./client/app.js').Rendered>)
18
21
  | null
19
22
  /** React's static markup of a JSX document (`react-dom/server`'s `renderToStaticMarkup`) */
@@ -473,7 +473,7 @@ function core(options) {
473
473
  `import '${V.entry}'`,
474
474
  `import { renderToReadableStream, renderToStaticMarkup } from 'react-dom/server'`,
475
475
  `import { renderPage as render } from 'fondu/client'`,
476
- `export const renderPage = (page, options, after) => render(page, (el) => renderToReadableStream(el, options), after)`,
476
+ `export const renderPage = (page, options) => render(page, (el) => renderToReadableStream(el, options))`,
477
477
  `export { renderToStaticMarkup as renderMarkup }`,
478
478
  ].join('\n');
479
479
  if (id === resolved(V.assets))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fondu",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "description": "A small meta-framework for full-stack React apps, built on Hono and Vite. It runs on Bun, Cloudflare Workers and Node.",
5
5
  "keywords": [
6
6
  "bun",