fondu 0.11.0 → 0.12.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 CHANGED
@@ -38,12 +38,13 @@ packages/fondu the package
38
38
  packages/create-fondu `bun create fondu`
39
39
  apps/demo Fondu's features, one page each — Workers, D1, Better Auth, coss ui
40
40
  apps/site fondu.dev: the docs, MDX and static pages on Workers
41
+ apps/conformance fondu/client against the browsers without JavaScript (Playwright: Chromium, Firefox, WebKit)
41
42
  ```
42
43
 
43
44
  ```bash
44
45
  bun install # also builds packages/fondu (the examples use the built package, like a real app)
45
46
  bun run test # the package: a small app with app.request(), the routes, the client
46
- bun run typecheck # the package, the demo (with apps/demo/e2e/types.ts) and the site
47
+ bun run typecheck # the package, the demo (with apps/demo/e2e/types.ts), the site and apps/conformance
47
48
  bun run check # format (oxfmt), lint (oxlint), typecheck
48
49
  bun run dev # rebuild packages/fondu on change
49
50
  ```
@@ -14,9 +14,23 @@ export declare function __entry(pageModules: Record<string, Loader>, layouts: Re
14
14
  }): void;
15
15
  /**
16
16
  * @internal The page a URL most likely is, by its route file's patterns (static segments first): its modules load with its
17
- * data. Only a guess (a param's listed values are the server's), so the page shown is the one the server says.
17
+ * data, and a link to a URL that is none (a file, an HTTP route) is left to the browser. Only a guess (a param's
18
+ * listed values are the server's), so the page shown is the one the server says.
18
19
  */
19
20
  export declare function pageAt(pathname: string): string | undefined;
21
+ /** a navigation on its way, or none: `useNavigation()` */
22
+ export type Navigation = {
23
+ state: 'idle';
24
+ to: null;
25
+ form: null;
26
+ } | {
27
+ /** `submitting`: a form's POST; `loading`: any other (a link, a GET form, `navigate()`, `reload()`) */
28
+ state: 'loading' | 'submitting';
29
+ /** where to: a path, its query and fragment (`/users/7?tab=posts`) */
30
+ to: string;
31
+ /** the form being sent (a GET form's too), else null */
32
+ form: HTMLFormElement | null;
33
+ };
20
34
  /** @internal the server render of a page: the head tags its components render (`<title>`…), and `<div id="app">` */
21
35
  export declare function renderPage(page: Page, renderToString: (element: ReactElement) => string): Promise<{
22
36
  head: string;
@@ -33,8 +47,11 @@ export declare function usePage<P = Shared>(): {
33
47
  url: string;
34
48
  flash: Partial<Flash>;
35
49
  };
36
- /** true while a navigation or a form's submission is on its way */
37
- export declare function useNavigating(): boolean;
50
+ /**
51
+ * The navigation on its way: `state` is `idle`, `loading` (a link, `navigate()`…) or `submitting` (a form's POST),
52
+ * from the click or the submit until the next page is on the screen; `to`, where to; `form`, the form being sent.
53
+ */
54
+ export declare function useNavigation(): Navigation;
38
55
  /** this page's props asked for again: the page keeps its state and the scroll position */
39
56
  export declare function reload(): void;
40
57
  export {};
@@ -70,7 +70,8 @@ class Failed extends Component {
70
70
  }
71
71
  /**
72
72
  * @internal The page a URL most likely is, by its route file's patterns (static segments first): its modules load with its
73
- * data. Only a guess (a param's listed values are the server's), so the page shown is the one the server says.
73
+ * data, and a link to a URL that is none (a file, an HTTP route) is left to the browser. Only a guess (a param's
74
+ * listed values are the server's), so the page shown is the one the server says.
74
75
  */
75
76
  export function pageAt(pathname) {
76
77
  const parts = pathname.split('/').filter(Boolean);
@@ -102,17 +103,17 @@ export function pageAt(pathname) {
102
103
  }
103
104
  return best?.id;
104
105
  }
105
- // ---- pending navigations, for useNavigating()
106
- let navigating = false;
107
- let submitting = false;
106
+ const IDLE = { state: 'idle', to: null, form: null };
107
+ let navigation = IDLE;
108
108
  const listeners = new Set();
109
109
  const subscribe = (listener) => {
110
110
  listeners.add(listener);
111
111
  return () => listeners.delete(listener);
112
112
  };
113
- function setNavigating(value, form) {
114
- navigating = value;
115
- submitting = form;
113
+ function setNavigation(next) {
114
+ navigation = next
115
+ ? { state: next.post ? 'submitting' : 'loading', to: next.to, form: next.form }
116
+ : IDLE;
116
117
  for (const l of listeners)
117
118
  l();
118
119
  }
@@ -121,7 +122,7 @@ function setNavigating(value, form) {
121
122
  function start(settings) {
122
123
  const progress = settings.progress;
123
124
  if (progress)
124
- subscribe(progressBar(progress, () => navigating && (progress.forms !== false || !submitting)));
125
+ subscribe(progressBar(progress, () => navigation.state !== 'idle' && (progress.forms !== false || navigation.form === null)));
125
126
  const data = document.querySelector('script[data-page="app"]')?.textContent;
126
127
  const root = document.getElementById('app');
127
128
  if (!data || !root)
@@ -134,18 +135,21 @@ function start(settings) {
134
135
  // dev: the stylesheet the server gave the page until its layouts brought their CSS (they have now)
135
136
  document.querySelector('[data-fondu-dev-css]')?.remove();
136
137
  const app = createElement(App, { initial: { page: initial, view, mounts: 0 } });
138
+ const hydrated = root.hasChildNodes(); // rendered on the server
137
139
  // navigations start once the page is on the screen (hydrated)
138
140
  mounted = (set) => {
139
141
  mounted = undefined;
140
142
  startNavigation({
141
143
  initial,
142
144
  prerender: settings.prerender,
143
- pending: setNavigating,
145
+ pending: setNavigation,
144
146
  preload(pathname) {
145
147
  const page = pageAt(pathname);
146
148
  if (page)
147
149
  load(page).catch(() => { });
148
150
  },
151
+ isPage: (pathname) => pageAt(pathname) !== undefined,
152
+ hydrated,
149
153
  async show(page, fresh, stale) {
150
154
  const view = await load(page.component);
151
155
  if (stale())
@@ -154,7 +158,7 @@ function start(settings) {
154
158
  },
155
159
  });
156
160
  };
157
- if (root.hasChildNodes())
161
+ if (hydrated)
158
162
  hydrateRoot(root, app);
159
163
  else
160
164
  createRoot(root).render(app);
@@ -175,9 +179,12 @@ export function usePage() {
175
179
  throw new Error('fondu: usePage() is for components of a page');
176
180
  return page;
177
181
  }
178
- /** true while a navigation or a form's submission is on its way */
179
- export function useNavigating() {
180
- return useSyncExternalStore(subscribe, () => navigating, () => false);
182
+ /**
183
+ * The navigation on its way: `state` is `idle`, `loading` (a link, `navigate()`…) or `submitting` (a form's POST),
184
+ * from the click or the submit until the next page is on the screen; `to`, where to; `form`, the form being sent.
185
+ */
186
+ export function useNavigation() {
187
+ return useSyncExternalStore(subscribe, () => navigation, () => IDLE);
181
188
  }
182
189
  /** this page's props asked for again: the page keeps its state and the scroll position */
183
190
  export function reload() {
@@ -0,0 +1,43 @@
1
+ import { type ChangeEvent, type FocusEvent, type FormEvent } from 'react';
2
+ import { type Issue } from '../form.js';
3
+ import { type Errors } from './app.js';
4
+ /** A Standard Schema (zod, valibot, arktype…), the part `useForm` uses */
5
+ interface Schema {
6
+ readonly '~standard': {
7
+ readonly validate: (value: unknown) => StandardResult | Promise<StandardResult>;
8
+ };
9
+ }
10
+ type StandardResult = {
11
+ readonly issues?: ReadonlyArray<Issue> | undefined;
12
+ };
13
+ /**
14
+ * A plain `<form>`, checked in the browser by the schema the server checks it with (any Standard Schema), its fields
15
+ * read as the server reads them (`tags[]`, `user[name]`). Spread `form` on the `<form>`, `field(name)` on each field:
16
+ *
17
+ * - on submit, an invalid form isn't sent, and its first field to fix gets the focus; a valid one is sent by Fondu's
18
+ * client. Back with the server's errors, the first field to fix gets the focus too
19
+ * - a field is checked as it is left for another with something typed, and again as it changes while it is wrong,
20
+ * so a fixed one loses its message (not as it is left for the submit button: the message would move it from under
21
+ * the pointer)
22
+ * - `errors`: the server's (the page's `errors` prop), each until its field is checked again, and the browser's;
23
+ * by the server's keys (`email`, `user.name`)
24
+ * - `submitting`: this form is being sent
25
+ *
26
+ * Without a schema: the server's errors and `submitting` only. Without JavaScript, the form is sent as it is, and the
27
+ * server's check answers.
28
+ */
29
+ export declare function useForm(schema?: Schema): {
30
+ form: {
31
+ ref: (form: HTMLFormElement | null) => void;
32
+ onSubmit: (event: FormEvent<HTMLFormElement>) => void;
33
+ };
34
+ field: (name: string) => {
35
+ name: string;
36
+ 'aria-invalid': true | undefined;
37
+ onBlur: (event: FocusEvent<Element>) => void;
38
+ onChange: (event: ChangeEvent<Element>) => void;
39
+ };
40
+ errors: Errors;
41
+ submitting: boolean;
42
+ };
43
+ export {};
@@ -0,0 +1,206 @@
1
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState, } from 'react';
2
+ import { fieldKey, formObject, issueErrors, MalformedForm } from '../form.js';
3
+ import { useNavigation, usePage } from './app.js';
4
+ /** a form's fields as the server reads them: its body for a POST (`withValidator({ body })`), its query for a GET */
5
+ function fieldsOf(form, submitter) {
6
+ const data = new FormData(form, submitter ?? undefined);
7
+ // as the browser sends them: line breaks as CRLF (a <textarea>'s)
8
+ const crlf = (text) => text.replace(/\r\n|\r|\n/g, '\r\n');
9
+ const entries = [...data].map(([k, v]) => [crlf(k), typeof v === 'string' ? crlf(v) : v]);
10
+ const method = (submitter?.getAttribute('formmethod') ??
11
+ form.getAttribute('method') ??
12
+ 'get').toLowerCase();
13
+ if (method === 'post')
14
+ return formObject(entries);
15
+ // a query, as Hono's `c.req.query()`: each name's first value, a file by its name
16
+ const query = Object.create(null);
17
+ for (const [k, v] of entries)
18
+ query[k] ??= typeof v === 'string' ? v : v.name;
19
+ return query;
20
+ }
21
+ /** the schema's errors for these fields; none for fields that can't be one object (the server answers those) */
22
+ function check(schema, value) {
23
+ let fields;
24
+ try {
25
+ fields = value();
26
+ }
27
+ catch (error) {
28
+ if (error instanceof MalformedForm)
29
+ return {};
30
+ throw error;
31
+ }
32
+ const result = schema['~standard'].validate(fields);
33
+ const errors = (r) => (r.issues ? issueErrors(r.issues) : {});
34
+ return result instanceof Promise ? result.then(errors) : errors(result);
35
+ }
36
+ /** a field's errors: its own, and those inside it (`tags` has `tags.0`'s) */
37
+ const within = (key, errorKey) => errorKey === key || (key !== '' && errorKey.startsWith(`${key}.`));
38
+ /**
39
+ * A plain `<form>`, checked in the browser by the schema the server checks it with (any Standard Schema), its fields
40
+ * read as the server reads them (`tags[]`, `user[name]`). Spread `form` on the `<form>`, `field(name)` on each field:
41
+ *
42
+ * - on submit, an invalid form isn't sent, and its first field to fix gets the focus; a valid one is sent by Fondu's
43
+ * client. Back with the server's errors, the first field to fix gets the focus too
44
+ * - a field is checked as it is left for another with something typed, and again as it changes while it is wrong,
45
+ * so a fixed one loses its message (not as it is left for the submit button: the message would move it from under
46
+ * the pointer)
47
+ * - `errors`: the server's (the page's `errors` prop), each until its field is checked again, and the browser's;
48
+ * by the server's keys (`email`, `user.name`)
49
+ * - `submitting`: this form is being sent
50
+ *
51
+ * Without a schema: the server's errors and `submitting` only. Without JavaScript, the form is sent as it is, and the
52
+ * server's check answers.
53
+ */
54
+ export function useForm(schema) {
55
+ const server = usePage().props.errors;
56
+ const navigation = useNavigation();
57
+ const [element, setElement] = useState(null);
58
+ // the browser's messages (undefined: checked, fine), for these server errors: a new answer starts over
59
+ const [checked, setChecked] = useState({
60
+ for: server,
61
+ own: {},
62
+ });
63
+ // the server's errors on the screen, for a check that ends after a new answer
64
+ const latest = useRef(server);
65
+ useLayoutEffect(() => {
66
+ latest.current = server;
67
+ }, [server]);
68
+ const own = checked.for === server ? checked.own : {};
69
+ const errors = Object.create(null);
70
+ // own keys only: a field may be named like what objects inherit (`toString`)
71
+ for (const [k, m] of Object.entries(server))
72
+ if (!Object.hasOwn(own, k))
73
+ errors[k] = m;
74
+ for (const [k, m] of Object.entries(own))
75
+ if (m)
76
+ errors[k] = m;
77
+ const errorOf = (key) => Object.keys(errors).find((k) => within(key, k));
78
+ const dirty = useRef(new Set());
79
+ const runs = useRef(new Map());
80
+ const passed = useRef(false);
81
+ /** what a check found, for the fields it covers (`key`: one field and those inside it; else all) */
82
+ const apply = (found, from, key) => {
83
+ if (latest.current !== from)
84
+ return; // a new answer of the server since
85
+ setChecked((now) => {
86
+ const before = now.for === from ? now.own : {};
87
+ const next = { ...before };
88
+ const covered = (k) => key === undefined || within(key, k);
89
+ // a field's check settles the server's error too; the whole form's, what it can say (not a taken address)
90
+ for (const k of [...Object.keys(before), ...(key === undefined ? [] : Object.keys(from))])
91
+ if (covered(k))
92
+ next[k] = undefined;
93
+ for (const [k, m] of Object.entries(found))
94
+ if (covered(k))
95
+ next[k] = m;
96
+ return { for: from, own: next };
97
+ });
98
+ };
99
+ const focusFirst = (form, found) => {
100
+ const keys = Object.keys(found).filter((k) => k !== '');
101
+ for (const el of form.elements)
102
+ if (el instanceof HTMLElement &&
103
+ 'name' in el &&
104
+ typeof el.name === 'string' &&
105
+ el.name &&
106
+ keys.some((k) => within(fieldKey(el.name), k)))
107
+ return el.focus();
108
+ };
109
+ const validates = schema !== undefined;
110
+ const ref = useCallback((form) => {
111
+ setElement(form);
112
+ // its messages, in the page's language, not the browser's (without JavaScript, the browser's checks stay)
113
+ if (form && validates)
114
+ form.noValidate = true;
115
+ }, [validates]);
116
+ const submitting = navigation.form !== null && navigation.form === element;
117
+ // back with the server's errors: the first field to fix gets the focus
118
+ const sent = useRef(false);
119
+ useEffect(() => {
120
+ if (submitting) {
121
+ sent.current = true;
122
+ return;
123
+ }
124
+ if (!sent.current)
125
+ return;
126
+ sent.current = false;
127
+ if (element && Object.keys(server).length)
128
+ focusFirst(element, server);
129
+ }, [submitting, server, element]);
130
+ const checkField = (form, key) => {
131
+ if (!schema)
132
+ return;
133
+ const run = (runs.current.get(key) ?? 0) + 1;
134
+ runs.current.set(key, run);
135
+ const from = server;
136
+ const done = (found) => {
137
+ if (runs.current.get(key) === run)
138
+ apply(found, from, key);
139
+ };
140
+ const found = check(schema, () => fieldsOf(form));
141
+ if (found instanceof Promise)
142
+ void found.then(done);
143
+ else
144
+ done(found);
145
+ };
146
+ return {
147
+ form: {
148
+ ref,
149
+ onSubmit(event) {
150
+ if (!schema)
151
+ return;
152
+ if (passed.current) {
153
+ passed.current = false; // checked already: sent
154
+ return;
155
+ }
156
+ const form = event.currentTarget;
157
+ const submitter = event.nativeEvent.submitter;
158
+ const from = server;
159
+ const found = check(schema, () => fieldsOf(form, submitter));
160
+ const answer = (found) => {
161
+ apply(found, from);
162
+ if (Object.keys(found).length)
163
+ focusFirst(form, found);
164
+ };
165
+ if (!(found instanceof Promise)) {
166
+ if (Object.keys(found).length)
167
+ event.preventDefault();
168
+ return answer(found);
169
+ }
170
+ // an async schema: sent again once it says yes
171
+ event.preventDefault();
172
+ void found.then((found) => {
173
+ answer(found);
174
+ if (Object.keys(found).length || latest.current !== from)
175
+ return;
176
+ passed.current = true;
177
+ form.requestSubmit(submitter && 'form' in submitter ? submitter : null);
178
+ });
179
+ },
180
+ },
181
+ field: (name) => {
182
+ const key = fieldKey(name);
183
+ return {
184
+ name,
185
+ 'aria-invalid': errorOf(key) !== undefined || undefined,
186
+ onBlur(event) {
187
+ // left for another field: not for the submit button, nor another window
188
+ const to = event.relatedTarget;
189
+ if (!(to instanceof HTMLElement) || to.type === 'submit')
190
+ return;
191
+ const form = event.currentTarget.form ?? element;
192
+ if (form && dirty.current.has(key))
193
+ checkField(form, key);
194
+ },
195
+ onChange(event) {
196
+ dirty.current.add(key);
197
+ const form = event.currentTarget.form ?? element;
198
+ if (form && errorOf(key) !== undefined)
199
+ checkField(form, key);
200
+ },
201
+ };
202
+ },
203
+ errors,
204
+ submitting,
205
+ };
206
+ }
@@ -15,22 +15,37 @@ interface Options {
15
15
  show: (page: Page, fresh: boolean, stale: () => boolean) => Promise<void>;
16
16
  /** `fondu({ prerender: true })`: GET navigations read `/_fondu/pages/<path>.json` */
17
17
  prerender: boolean;
18
- /** a navigation started (true; `form`: a form's submission) or ended (false) */
19
- pending: (pending: boolean, form: boolean) => void;
18
+ /** a navigation started (to `to`: a path, its query and fragment; `form`: a form's submission) or ended (null) */
19
+ pending: (navigation: {
20
+ to: string;
21
+ form: HTMLFormElement | null;
22
+ post: boolean;
23
+ } | null) => void;
20
24
  /** a GET navigation to `pathname` started: its page's modules may load with its data */
21
25
  preload: (pathname: string) => void;
26
+ /** a URL path is one of the app's pages (by the route files' patterns): its links are the client's */
27
+ isPage: (pathname: string) => boolean;
28
+ /** the page was rendered on the server (hydrated), not in the browser */
29
+ hydrated: boolean;
22
30
  }
23
31
  /**
24
32
  * Same-origin links and forms, Back and Forward, through the History API (as Void's client, MIT): the page fetched
25
33
  * as JSON, its URL in the history, the page shown in place, then the scroll position (Fondu's own, per history entry:
26
34
  * the browsers' differ). What isn't for it (another site, a new tab, a download, a modified click) is the browser's.
27
35
  */
28
- export declare function startNavigation({ initial, show, prerender, pending, preload }: Options): void;
36
+ export declare function startNavigation({ initial, show, prerender, pending, preload, isPage, hydrated, }: Options): void;
29
37
  /**
30
38
  * `href` loaded as a document. Every other navigation is the client's, links and forms: this is for what a page
31
39
  * can't change in place (`<html lang>`: another language).
32
40
  */
33
41
  export declare function loadDocument(href: string): void;
42
+ /**
43
+ * `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
44
+ * `replace`), anything else as a document
45
+ */
46
+ export declare function navigate(href: string, { replace }?: {
47
+ replace?: boolean;
48
+ }): void;
34
49
  /** the page asked for again, its state and the scroll position kept */
35
50
  export declare function again(): void;
36
51
  export {};
@@ -1,11 +1,13 @@
1
1
  import { pageDataPath, SCROLL_KEY, SCROLL_STORAGE } from '../paths.js';
2
2
  let visit;
3
+ /** a URL path is one of the app's pages (the client's, once it has started) */
4
+ let isAppPage;
3
5
  /**
4
6
  * Same-origin links and forms, Back and Forward, through the History API (as Void's client, MIT): the page fetched
5
7
  * as JSON, its URL in the history, the page shown in place, then the scroll position (Fondu's own, per history entry:
6
8
  * the browsers' differ). What isn't for it (another site, a new tab, a download, a modified click) is the browser's.
7
9
  */
8
- export function startNavigation({ initial, show, prerender, pending, preload }) {
10
+ export function startNavigation({ initial, show, prerender, pending, preload, isPage, hydrated, }) {
9
11
  const scroll = scrollPositions();
10
12
  let version = initial.version;
11
13
  let current;
@@ -32,6 +34,7 @@ export function startNavigation({ initial, show, prerender, pending, preload })
32
34
  else
33
35
  location.assign(url);
34
36
  };
37
+ isAppPage = isPage;
35
38
  visit = (href, options) => {
36
39
  current?.abort();
37
40
  const controller = (current = new AbortController());
@@ -46,14 +49,14 @@ export function startNavigation({ initial, show, prerender, pending, preload })
46
49
  // a kept page is on the screen at once: the server's comes quietly, no pending state (the navigation it
47
50
  // interrupted, aborted, ends here)
48
51
  const shown = options.kept;
49
- // the form being sent is aria-busy: for its submit buttons' pending state (CSS, or useNavigating()), and for
52
+ // the form being sent is aria-busy: for its submit buttons' pending state (CSS, or useNavigation()), and for
50
53
  // assistive technology
51
54
  form?.setAttribute('aria-busy', 'true');
52
- pending(!shown, form !== null);
55
+ pending(shown ? null : { to: url.pathname + url.search + url.hash, form, post });
53
56
  const done = () => {
54
57
  form?.removeAttribute('aria-busy');
55
58
  if (!shown && current === controller)
56
- pending(false, false);
59
+ pending(null);
57
60
  };
58
61
  if (!post)
59
62
  preload(url.pathname);
@@ -189,6 +192,9 @@ export function startNavigation({ initial, show, prerender, pending, preload })
189
192
  scroll.save();
190
193
  return;
191
194
  }
195
+ // a URL that is none of the app's pages (a file, /llms.txt; an HTTP route; nothing at all): the browser's
196
+ if (!isPage(url.pathname))
197
+ return;
192
198
  event.preventDefault();
193
199
  visit(url.href, { history: url.href === location.href ? 'replace' : 'push' });
194
200
  });
@@ -236,27 +242,21 @@ export function startNavigation({ initial, show, prerender, pending, preload })
236
242
  kept: kept.get(popped.key ?? ''),
237
243
  });
238
244
  });
239
- // leaving the document (a reload, another site): its position, and the browser's restoration back on for this
240
- // entry, so a reload or Back to it is scrolled at first paint, as any document
241
- window.addEventListener('pagehide', () => {
242
- scroll.save();
243
- history.scrollRestoration = 'auto';
244
- });
245
- window.addEventListener('pageshow', (event) => {
246
- if (event.persisted)
247
- history.scrollRestoration = 'manual'; // back from the back/forward cache
248
- });
245
+ // leaving the document (a reload, another site): its position, put back by the document when it is loaded again.
246
+ // The browser's own restoration stays off: engines restore at times of their own, or not (WebKit, an entry once
247
+ // manual; Firefox, a #fragment), and over the page's own (Firefox, at load, a page rendered in the browser at 0)
248
+ window.addEventListener('pagehide', scroll.save);
249
249
  // the browser's own #fragment navigations: the entry gets its key
250
250
  window.addEventListener('hashchange', scroll.commit);
251
- // an entry with a position (a reload, Back from another site): that position, the #fragment's target or not, as
252
- // the browser restores it; otherwise, a first visit, the #fragment's target (rendered by now)
253
- const { position, restored } = scroll.start();
254
- if (position) {
255
- if (!restored)
256
- window.scrollTo(position.x, position.y);
251
+ // a page rendered on the server is where it belongs already, before its first paint: at its entry's position (its
252
+ // document's script: a reload, Back from another site), else at its #fragment (the browser). One rendered here has
253
+ // its content only now: its entry's position, or its #fragment's target
254
+ const position = scroll.start();
255
+ if (!hydrated) {
256
+ restore(position, location.hash, true);
257
+ if (position)
258
+ holdUntilLoaded(position);
257
259
  }
258
- else
259
- restore(null, location.hash, true);
260
260
  keep(initial);
261
261
  }
262
262
  /**
@@ -327,16 +327,13 @@ function scrollPositions() {
327
327
  /** the key of the entry on the screen */
328
328
  key: () => rendered,
329
329
  /**
330
- * The document's entry: its key; where it was scrolled, if it was (an entry this client pushed, loaded again: a
331
- * reload, Back from another site past it), and whether the browser or the document's script put it back already
330
+ * The document's entry: its key, and where it was scrolled, if it was (an entry this client pushed, loaded again:
331
+ * a reload, Back from another site past it)
332
332
  */
333
333
  start() {
334
- // restored already, by the browser or the document's own script: the page is scrolled (one rendered in the
335
- // browser was empty for them, it has its content only now)
336
- const restored = scrollX !== 0 || scrollY !== 0;
337
334
  history.scrollRestoration = 'manual';
338
335
  commit();
339
- return { position: read(rendered), restored };
336
+ return read(rendered);
340
337
  },
341
338
  /** the page on the screen, at `url`: a new entry or this one */
342
339
  write(url, replace) {
@@ -369,6 +366,20 @@ function restore(position, hash, first = false) {
369
366
  if (!first)
370
367
  window.scrollTo(0, 0);
371
368
  }
369
+ /**
370
+ * A position kept until the page has loaded: browsers scroll on their own until then (Firefox, a page rendered in
371
+ * the browser back to the top), as the document's script does it for a page rendered on the server. Not once the
372
+ * visitor has scrolled, typed or clicked.
373
+ */
374
+ function holdUntilLoaded(position) {
375
+ if (document.readyState === 'complete')
376
+ return;
377
+ let held = true;
378
+ const off = () => (held = false);
379
+ for (const type of ['wheel', 'touchstart', 'keydown', 'mousedown'])
380
+ addEventListener(type, off, { once: true, passive: true });
381
+ addEventListener('load', () => setTimeout(() => held && window.scrollTo(position.x, position.y)));
382
+ }
372
383
  /** the element a #fragment names: decoded, or as it is (`#100%` doesn't decode); null for none */
373
384
  function fragmentTarget(fragment) {
374
385
  try {
@@ -423,6 +434,17 @@ function fileName(disposition) {
423
434
  export function loadDocument(href) {
424
435
  location.assign(href);
425
436
  }
437
+ /**
438
+ * `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
439
+ * `replace`), anything else as a document
440
+ */
441
+ export function navigate(href, { replace = false } = {}) {
442
+ const url = new URL(href, location.href);
443
+ const here = url.pathname + url.search === location.pathname + location.search;
444
+ if (!visit || url.origin !== location.origin || !isAppPage?.(url.pathname) || (here && url.hash))
445
+ return replace ? location.replace(url.href) : location.assign(url.href); // a #fragment of this page: the browser's
446
+ visit(url.href, { history: replace || url.href === location.href ? 'replace' : 'push' });
447
+ }
426
448
  /** the page asked for again, its state and the scroll position kept */
427
449
  export function again() {
428
450
  if (visit)
@@ -11,6 +11,6 @@ export interface ProgressOptions {
11
11
  * The bar: shown once a navigation has run for `delay`, growing towards the end while it runs (one long CSS
12
12
  * transition, slower as it gets there), filled, then faded out, when it is done. Drawn with CSSOM styles (no
13
13
  * stylesheet, nothing for a Content Security Policy to refuse), above the page, out of the accessibility tree:
14
- * `useNavigating()` is the app's way to say it in its own words. With reduced motion, a still bar.
14
+ * `useNavigation()` is the app's way to say it in its own words. With reduced motion, a still bar.
15
15
  */
16
16
  export declare function progressBar({ delay, color }: ProgressOptions, pending: () => boolean): () => void;
@@ -2,7 +2,7 @@
2
2
  * The bar: shown once a navigation has run for `delay`, growing towards the end while it runs (one long CSS
3
3
  * transition, slower as it gets there), filled, then faded out, when it is done. Drawn with CSSOM styles (no
4
4
  * stylesheet, nothing for a Content Security Policy to refuse), above the page, out of the accessibility tree:
5
- * `useNavigating()` is the app's way to say it in its own words. With reduced motion, a still bar.
5
+ * `useNavigation()` is the app's way to say it in its own words. With reduced motion, a still bar.
6
6
  */
7
7
  export function progressBar({ delay = 350, color = 'currentColor' }, pending) {
8
8
  const still = matchMedia('(prefers-reduced-motion: reduce)');
package/dist/client.d.ts CHANGED
@@ -1,8 +1,10 @@
1
+ import type { schemasOf } from './server/handler.js';
1
2
  import type { Routes } from './types.js';
2
3
  /**
3
4
  * Typed URLs from `app/routes/` (as React Router's `href`): `href('/users/:id', { id })` → `'/users/7'`;
4
5
  * 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')}>`.
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' })`.
6
8
  */
7
9
  type Keys = keyof Routes & string;
8
10
  type Actions = {
@@ -12,10 +14,42 @@ type Actions = {
12
14
  }[Keys];
13
15
  export type Href = [Keys] extends [never] ? string : Keys | Actions;
14
16
  type ParamNames<P extends string> = P extends `${string}:${infer Name}{${string}}${infer Rest}` ? Name | ParamNames<Rest> : P extends `${string}:${infer Name}/${infer Rest}` ? Name | ParamNames<`/${Rest}`> : P extends `${string}:${infer Name}?${string}` ? Name : P extends `${string}:${infer Name}` ? Name : never;
15
- type Args<P extends string> = [ParamNames<P>] extends [never] ? [] : [params: {
17
+ /** the handlers answering a GET of the URL (its page's `loader`, a `.ts` file's `GET`), or the action's */
18
+ type HandlersOf<P extends string> = P extends `${infer K}?${infer A}` ? K extends Keys ? Routes[K] extends {
19
+ actions: infer As;
20
+ } ? As[A & keyof As] : never : never : P extends Keys ? Routes[P] extends {
21
+ loader: infer L;
22
+ } ? L : Routes[P] extends {
23
+ GET: infer G;
24
+ } ? G : never : never;
25
+ /** a query value: what its schema takes (`unknown`, as a coercing schema's input: any) */
26
+ type QueryValue = string | number | boolean | null | undefined;
27
+ type QueryOf<P extends string> = HandlersOf<P> extends {
28
+ readonly [schemasOf]?: infer S;
29
+ } ? S extends {
30
+ query: {
31
+ '~standard': {
32
+ types?: infer T;
33
+ };
34
+ };
35
+ } ? NonNullable<T> extends {
36
+ input: infer I extends object;
37
+ } ? {
38
+ [K in keyof I]: unknown extends I[K] ? QueryValue : I[K];
39
+ } : Record<string, QueryValue> : Record<string, QueryValue> : Record<string, QueryValue>;
40
+ /** `query` is required when its schema requires a field */
41
+ type Extra<P extends string> = {
42
+ hash?: string;
43
+ } & ({} extends QueryOf<P> ? {
44
+ query?: QueryOf<P>;
45
+ } : {
46
+ query: QueryOf<P>;
47
+ });
48
+ type Args<P extends string> = [ParamNames<P>] extends [never] ? {} extends QueryOf<P> ? [options?: Extra<P>] : [options: Extra<P>] : [params: {
16
49
  [K in ParamNames<P>]: string | number;
17
- }];
18
- export declare function href<P extends Href>(path: P, ...[params]: Args<P>): string;
19
- export { usePage, useNavigating, reload, __entry, renderPage, type Errors } from './client/app.js';
20
- export { loadDocument, type Page } from './client/navigation.js';
50
+ } & Extra<P>];
51
+ 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';
53
+ export { useForm } from './client/form.js';
54
+ export { loadDocument, navigate, type Page } from './client/navigation.js';
21
55
  export type { ProgressOptions } from './client/progress.js';
package/dist/client.js CHANGED
@@ -1,6 +1,19 @@
1
1
  import { fillPattern } from './paths.js';
2
- export function href(path, ...[params]) {
3
- return fillPattern(path, params);
2
+ export function href(path, ...[options]) {
3
+ const { query, hash, ...params } = (options ?? {});
4
+ let url = fillPattern(path, params);
5
+ const search = new URLSearchParams();
6
+ for (const [name, value] of Object.entries(query ?? {}))
7
+ for (const v of [value].flat())
8
+ if (v !== undefined && v !== null)
9
+ search.append(name, String(v));
10
+ const qs = search.toString();
11
+ if (qs)
12
+ url += (url.includes('?') ? '&' : '?') + qs;
13
+ if (hash)
14
+ url += `#${encodeURI(hash)}`;
15
+ return url;
4
16
  }
5
- export { usePage, useNavigating, reload, __entry, renderPage } from './client/app.js';
6
- export { loadDocument } from './client/navigation.js';
17
+ export { usePage, useNavigation, reload, __entry, renderPage, } from './client/app.js';
18
+ export { useForm } from './client/form.js';
19
+ export { loadDocument, navigate } from './client/navigation.js';
package/dist/form.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Form fields as one object, the same in the server (`readBody`, `withValidator`) and in the browser (`useForm`): a
3
+ * schema checked in the browser sees what the server's will.
4
+ */
5
+ /** a body that can't be one object: a 400 on the server */
6
+ export declare class MalformedForm extends Error {
7
+ }
8
+ type Entry = [string, FormDataEntryValue];
9
+ /**
10
+ * Form fields with PHP-style names, as forms write them (`notify[]`, `user[name]`); files are `File`s, empty file
11
+ * 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
12
+ * highest one so far. Names that would change the object itself (`__proto__`…) are ignored. Throws `MalformedForm`
13
+ * for fields that can't be one object (`a=1&a[b]=2`, names nested deeper than 32).
14
+ */
15
+ export declare function formObject(entries: Iterable<Entry>): Record<string, unknown>;
16
+ /** A Standard Schema's issue, the part used here */
17
+ export interface Issue {
18
+ readonly message: string;
19
+ readonly path?: ReadonlyArray<PropertyKey | {
20
+ readonly key: PropertyKey;
21
+ }> | undefined;
22
+ }
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
+ /** a field name's key in the errors: `user[name]` → `user.name`, `tags[]` → `tags` */
26
+ export declare const fieldKey: (name: string) => string;
27
+ /** each field's first message (no prototype: a field named `toString` is a field like any other) */
28
+ export declare function issueErrors(issues: ReadonlyArray<Issue>): Record<string, string>;
29
+ export {};
package/dist/form.js ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Form fields as one object, the same in the server (`readBody`, `withValidator`) and in the browser (`useForm`): a
3
+ * schema checked in the browser sees what the server's will.
4
+ */
5
+ /** how deep form field names nest (`a[b][c]`: 3) */
6
+ const DEPTH = 32;
7
+ /** a body that can't be one object: a 400 on the server */
8
+ export class MalformedForm extends Error {
9
+ }
10
+ /**
11
+ * Form fields with PHP-style names, as forms write them (`notify[]`, `user[name]`); files are `File`s, empty file
12
+ * 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
13
+ * highest one so far. Names that would change the object itself (`__proto__`…) are ignored. Throws `MalformedForm`
14
+ * for fields that can't be one object (`a=1&a[b]=2`, names nested deeper than 32).
15
+ */
16
+ export function formObject(entries) {
17
+ const body = Object.create(null);
18
+ // `a[]`: each object's next index, the highest one so far + 1 (counted, not looked for: a body of many is linear)
19
+ const next = new WeakMap();
20
+ const isObject = (v) => typeof v === 'object' && !isFile(v) && !Array.isArray(v);
21
+ for (const [key, value] of entries) {
22
+ if (typeof value !== 'string' && value.size === 0 && value.name === '')
23
+ continue;
24
+ const path = key.replace(/\]/g, '').split('[');
25
+ if (path.length > DEPTH)
26
+ throw new MalformedForm(`a field name nests deeper than ${DEPTH}`);
27
+ if (path.some((p) => p === '__proto__' || p === 'constructor' || p === 'prototype'))
28
+ continue;
29
+ let target = body;
30
+ path.forEach((segment, i) => {
31
+ const name = segment === '' ? String(next.get(target) ?? 0) : segment;
32
+ if (/^\d+$/.test(name))
33
+ next.set(target, Math.max(next.get(target) ?? 0, Number(name) + 1));
34
+ const has = Object.hasOwn(target, name);
35
+ if (i === path.length - 1) {
36
+ if (has && isObject(target[name]))
37
+ throw new MalformedForm(`\`${key}\` is both a value and an object`);
38
+ target[name] = has ? [target[name], value].flat() : value; // given again: a list
39
+ }
40
+ else {
41
+ if (!has)
42
+ target[name] = Object.create(null);
43
+ else if (!isObject(target[name]))
44
+ throw new MalformedForm(`\`${key}\` is both a value and an object`);
45
+ target = target[name];
46
+ }
47
+ });
48
+ }
49
+ return arrays(body);
50
+ }
51
+ const isFile = (v) => typeof File !== 'undefined' && v instanceof File;
52
+ /** objects whose keys are 0..n-1 become arrays */
53
+ const arrays = (value) => {
54
+ if (typeof value !== 'object' || value === null || isFile(value) || Array.isArray(value))
55
+ return value;
56
+ const entries = Object.entries(value).map(([k, v]) => [k, arrays(v)]);
57
+ const isList = entries.length > 0 && entries.every(([k], i) => k === String(i));
58
+ return isList ? entries.map(([, v]) => v) : Object.fromEntries(entries);
59
+ };
60
+ /** an issue's field: its path joined with dots (`user.name`, `tags.0`); the form's own issues are `''` */
61
+ export const issueKey = (path) => (path ?? []).map((p) => String(typeof p === 'object' ? p.key : p)).join('.');
62
+ /** a field name's key in the errors: `user[name]` → `user.name`, `tags[]` → `tags` */
63
+ export const fieldKey = (name) => name.replace(/\]/g, '').split('[').filter(Boolean).join('.');
64
+ /** each field's first message (no prototype: a field named `toString` is a field like any other) */
65
+ export function issueErrors(issues) {
66
+ const errors = Object.create(null);
67
+ for (const issue of issues)
68
+ errors[issueKey(issue.path)] ??= issue.message;
69
+ return errors;
70
+ }
package/dist/paths.js CHANGED
@@ -19,6 +19,10 @@ export function routePatterns(file) {
19
19
  throw new Error(`fondu: routes/${file}: an optional catch-all isn't a route; index.ts and [...path].ts are`);
20
20
  if (optional.length > 1)
21
21
  throw new Error(`fondu: routes/${file} has ${optional.length} optional segments; one at most`);
22
+ // href()'s options, next to the params
23
+ const reserved = segments.find((s) => /^\[{1,2}(?:\.\.\.)?(?:query|hash)\]{1,2}$/.test(s));
24
+ if (reserved)
25
+ throw new Error(`fondu: routes/${file}: a param can't be named ${reserved.replace(/[[\].]/g, '')} (href()'s query and hash); rename it`);
22
26
  const pattern = (withOptional) => '/' +
23
27
  segments
24
28
  .filter((s) => withOptional || !optional.includes(s))
@@ -18,10 +18,11 @@ export const withoutSsr = () => async (c, next) => {
18
18
  const pageScript = (page) => `<script data-page="app" type="application/json">${JSON.stringify(page).replace(/\//g, '\\/').replace(/</g, '\\u003c')}</script>`;
19
19
  /**
20
20
  * A reload, Back to a page of another site: this entry's position, where fondu/client left it, before the first
21
- * paint (the stylesheets are in: the page is laid out). The browser may not restore it itself (Safari: the client's
22
- * own restoration, off until the page is left, is still off for it), and the client would only once it runs.
21
+ * paint (the stylesheets are in: the page is laid out), and again once the page has loaded: browsers scroll on
22
+ * their own until then (to the #fragment, WebKit and Firefox), fondu/client keeping their restoration off. Not once
23
+ * the visitor has scrolled, typed or clicked: their own scrolling wins.
23
24
  */
24
- const restoreScroll = (nonce) => `<script${nonce ? ` nonce="${nonce}"` : ''}>try{var k=history.state&&history.state[${JSON.stringify(SCROLL_KEY)}],p=k&&JSON.parse(sessionStorage.getItem(${JSON.stringify(SCROLL_STORAGE)}+k));p&&!scrollY&&scrollTo(+p.x||0,+p.y||0)}catch(e){}</script>`;
25
+ const restoreScroll = (nonce) => `<script${nonce ? ` nonce="${nonce}"` : ''}>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){}</script>`;
25
26
  // where the page goes, in the document a template returns: replaced before the page is in, so a page's content is
26
27
  // never read as one
27
28
  const HEAD = 'fondu:document-head';
@@ -2,12 +2,18 @@ import type { Context, Handler, MiddlewareHandler } from 'hono';
2
2
  import { type Input, type Schemas } from './validate.js';
3
3
  type Final<S extends Schemas> = (c: Context, input: Input<S>) => Response | Promise<Response>;
4
4
  type Handlers = Array<Handler | MiddlewareHandler>;
5
+ /** @internal a type only, never a value: the schemas a `withValidator` handler checks, for `href()`'s `query` */
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 & {
9
+ readonly [schemasOf]?: S;
10
+ };
5
11
  /** overloads, as Hono's `createHandlers` has them: the last handler's parameters are typed reliably */
6
12
  interface WithInput<S extends Schemas> {
7
- (handler: Final<S>): Handlers;
8
- (m1: MiddlewareHandler, handler: Final<S>): Handlers;
9
- (m1: MiddlewareHandler, m2: MiddlewareHandler, handler: Final<S>): Handlers;
10
- (m1: MiddlewareHandler, m2: MiddlewareHandler, m3: MiddlewareHandler, handler: Final<S>): Handlers;
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>;
11
17
  }
12
18
  /**
13
19
  * Validated input for the handler, after the middleware (a guard runs before the request body is read):
@@ -34,11 +34,9 @@ export declare class ValidationError extends Error {
34
34
  }
35
35
  export declare function validationErrorResponse(c: Context, error: ValidationError): Response;
36
36
  /**
37
- * A request body as one object: JSON, or form fields with PHP-style names, as forms write them (`notify[]`,
38
- * `user[name]`); files are `File`s, empty file inputs are left out. A name given again is a list (`a=1&a=2`,
39
- * `a[b]=1&a[b]=2`); `[]` is the index after the highest one so far. Names that would change the object itself
40
- * (`__proto__`…) are ignored. A body that can't be one object (JSON or form data that doesn't parse,
41
- * `a=1&a[b]=2`, names nested deeper than 32) is a 400.
37
+ * A request body as one object: JSON, or form fields as `formObject` reads them (the browser's `useForm` too). A body
38
+ * that can't be one object (JSON or form data that doesn't parse, `a=1&a[b]=2`, names nested deeper than 32) is a
39
+ * 400.
42
40
  */
43
41
  export declare function readBody(c: Context): Promise<unknown>;
44
42
  /** What `withValidator` checks: the request body (JSON or form), the query, the route params. */
@@ -1,4 +1,5 @@
1
1
  import { HTTPException } from 'hono/http-exception';
2
+ import { formObject, issueErrors, MalformedForm } from '../form.js';
2
3
  import { flashErrors } from './flash.js';
3
4
  import { back, wantsPage } from './http.js';
4
5
  /**
@@ -20,14 +21,10 @@ export function validationErrorResponse(c, error) {
20
21
  flashErrors(c, error.errors);
21
22
  return back(c);
22
23
  }
23
- /** how deep form field names nest (`a[b][c]`: 3) */
24
- const DEPTH = 32;
25
24
  /**
26
- * A request body as one object: JSON, or form fields with PHP-style names, as forms write them (`notify[]`,
27
- * `user[name]`); files are `File`s, empty file inputs are left out. A name given again is a list (`a=1&a=2`,
28
- * `a[b]=1&a[b]=2`); `[]` is the index after the highest one so far. Names that would change the object itself
29
- * (`__proto__`…) are ignored. A body that can't be one object (JSON or form data that doesn't parse,
30
- * `a=1&a[b]=2`, names nested deeper than 32) is a 400.
25
+ * A request body as one object: JSON, or form fields as `formObject` reads them (the browser's `useForm` too). A body
26
+ * that can't be one object (JSON or form data that doesn't parse, `a=1&a[b]=2`, names nested deeper than 32) is a
27
+ * 400.
31
28
  */
32
29
  export async function readBody(c) {
33
30
  const malformed = (why) => new HTTPException(400, { message: `Malformed request body: ${why}` });
@@ -37,49 +34,13 @@ export async function readBody(c) {
37
34
  if (!type.includes('multipart/form-data') && !type.includes('application/x-www-form-urlencoded'))
38
35
  return {};
39
36
  const form = await c.req.formData().catch(() => Promise.reject(malformed('invalid form data')));
40
- const body = Object.create(null);
41
- // `a[]`: each object's next index, the highest one so far + 1 (counted, not looked for: a body of many is linear)
42
- const next = new WeakMap();
43
- const isObject = (v) => typeof v === 'object' && !(v instanceof File) && !Array.isArray(v);
44
- for (const [key, value] of form.entries()) {
45
- if (typeof value !== 'string' && value.size === 0 && value.name === '')
46
- continue;
47
- const path = key.replace(/\]/g, '').split('[');
48
- if (path.length > DEPTH)
49
- throw malformed(`a field name nests deeper than ${DEPTH}`);
50
- if (path.some((p) => p === '__proto__' || p === 'constructor' || p === 'prototype'))
51
- continue;
52
- let target = body;
53
- path.forEach((segment, i) => {
54
- const name = segment === '' ? String(next.get(target) ?? 0) : segment;
55
- if (/^\d+$/.test(name))
56
- next.set(target, Math.max(next.get(target) ?? 0, Number(name) + 1));
57
- const has = Object.hasOwn(target, name);
58
- if (i === path.length - 1) {
59
- if (has && isObject(target[name]))
60
- throw malformed(`\`${key}\` is both a value and an object`);
61
- target[name] = has ? [target[name], value].flat() : value; // given again: a list
62
- }
63
- else {
64
- if (!has)
65
- target[name] = Object.create(null);
66
- else if (!isObject(target[name]))
67
- throw malformed(`\`${key}\` is both a value and an object`);
68
- target = target[name];
69
- }
70
- });
37
+ try {
38
+ return formObject(form.entries());
39
+ }
40
+ catch (error) {
41
+ throw error instanceof MalformedForm ? malformed(error.message) : error;
71
42
  }
72
- return arrays(body);
73
43
  }
74
- /** objects whose keys are 0..n-1 become arrays */
75
- const arrays = (value) => {
76
- if (typeof value !== 'object' || value === null || value instanceof File || Array.isArray(value))
77
- return value;
78
- const entries = Object.entries(value).map(([k, v]) => [k, arrays(v)]);
79
- const isList = entries.length > 0 && entries.every(([k], i) => k === String(i));
80
- return isList ? entries.map(([, v]) => v) : Object.fromEntries(entries);
81
- };
82
- const pathOf = (path) => (path ?? []).map((p) => String(typeof p === 'object' ? p.key : p)).join('.');
83
44
  /**
84
45
  * The validation step of `withValidator`: a middleware, and the validated input of its request. Params that don't
85
46
  * fit the schema are a 404 (`/users/abc` names no user); invalid body or query fields are a `ValidationError`.
@@ -101,8 +62,8 @@ export function validator(schemas) {
101
62
  if (result.issues && key === 'params')
102
63
  throw new HTTPException(404);
103
64
  if (result.issues)
104
- for (const issue of result.issues)
105
- errors[pathOf(issue.path)] ??= issue.message;
65
+ for (const [k, m] of Object.entries(issueErrors(result.issues)))
66
+ errors[k] ??= m;
106
67
  else
107
68
  input[key] = result.value;
108
69
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fondu",
3
- "version": "0.11.0",
3
+ "version": "0.12.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",
@@ -54,6 +54,7 @@
54
54
  "@types/node": "26.6.5",
55
55
  "@types/react": "19.3.0",
56
56
  "@types/react-dom": "19.3.0",
57
+ "fast-check": "4.3.0",
57
58
  "hono": "4.13.13",
58
59
  "typescript": "7.0.2",
59
60
  "vite": "8.3.4",