fondu 0.16.2 → 0.18.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.
@@ -49,7 +49,10 @@ export type Rendered = ReadableStream<Uint8Array> & {
49
49
  export declare function renderPage(page: Page, render: (element: ReactElement) => Promise<Rendered>): Promise<Rendered>;
50
50
  /** a form's field errors, as a page gets them (its `errors` prop): field name → message */
51
51
  export type Errors = Record<string, string>;
52
- /** the page on screen: its props (the shared ones, `errors`), its URL, its flash data */
52
+ /**
53
+ * The page on screen: its props (the shared ones, `errors`), its URL (path and query: it follows a shallow
54
+ * navigation, and the props do not), its flash data
55
+ */
53
56
  export declare function usePage<P = Shared>(): {
54
57
  component: string;
55
58
  props: P & {
@@ -198,7 +198,10 @@ export async function renderPage(page, render) {
198
198
  const view = await load(page.component);
199
199
  return render(createElement('div', { id: 'app' }, createElement(App, { initial: { page, view, mounts: 0 } })));
200
200
  }
201
- /** the page on screen: its props (the shared ones, `errors`), its URL, its flash data */
201
+ /**
202
+ * The page on screen: its props (the shared ones, `errors`), its URL (path and query: it follows a shallow
203
+ * navigation, and the props do not), its flash data
204
+ */
202
205
  export function usePage() {
203
206
  const page = useContext(PageContext);
204
207
  if (!page)
@@ -21,6 +21,10 @@ type StandardResult = {
21
21
  * the pointer)
22
22
  * - `errors`: the server's (the page's `errors` prop), each until its field is checked again, and the browser's;
23
23
  * by the server's keys (`email`, `user.name`)
24
+ * - an async schema: the form is sent once the schema has said yes to the values it was asked about. A result that
25
+ * comes late is dropped, and sends nothing: after a newer submit, a visit to another page, or the form leaving the
26
+ * screen, and when the fields are no longer what was checked (changed while the schema was working). That form is
27
+ * not sent unchecked, nor checked again for the user: submit it again
24
28
  * - `submitting`: this form is being sent
25
29
  * - `failed`: this form could not be sent (offline…): it stays, to send again
26
30
  *
@@ -31,6 +31,15 @@ function check(schema, value) {
31
31
  const errors = (r) => (r.issues ? issueErrors(r.issues) : {});
32
32
  return result instanceof Promise ? result.then(errors) : errors(result);
33
33
  }
34
+ /** a form's fields as one string, files by what identifies them: two snapshots of a form are equal if this is */
35
+ function snapshot(form, submitter) {
36
+ try {
37
+ return JSON.stringify([...new FormData(form, submitter ?? undefined)].map(([k, v]) => typeof v === 'string' ? [k, v] : [k, v.name, v.size, v.lastModified, v.type]));
38
+ }
39
+ catch {
40
+ return undefined; // a submitter that is no longer in the form: not what was checked
41
+ }
42
+ }
34
43
  /** a field's errors: its own, and those inside it (`tags` has `tags.0`'s) */
35
44
  const within = (key, errorKey) => errorKey === key || (key !== '' && errorKey.startsWith(`${key}.`));
36
45
  /**
@@ -44,6 +53,10 @@ const within = (key, errorKey) => errorKey === key || (key !== '' && errorKey.st
44
53
  * the pointer)
45
54
  * - `errors`: the server's (the page's `errors` prop), each until its field is checked again, and the browser's;
46
55
  * by the server's keys (`email`, `user.name`)
56
+ * - an async schema: the form is sent once the schema has said yes to the values it was asked about. A result that
57
+ * comes late is dropped, and sends nothing: after a newer submit, a visit to another page, or the form leaving the
58
+ * screen, and when the fields are no longer what was checked (changed while the schema was working). That form is
59
+ * not sent unchecked, nor checked again for the user: submit it again
47
60
  * - `submitting`: this form is being sent
48
61
  * - `failed`: this form could not be sent (offline…): it stays, to send again
49
62
  *
@@ -77,6 +90,11 @@ export function useForm(schema) {
77
90
  const dirty = useRef(new Set());
78
91
  const runs = useRef(new Map());
79
92
  const passed = useRef(false);
93
+ // which whole-form check may still send: each submit takes the next number, and so does what makes a pending one
94
+ // obsolete (a visit, the form leaving). The result of an older one is dropped
95
+ const generation = useRef(0);
96
+ // the checks of single fields that began before the whole form's result: that result is the newer word
97
+ const epoch = useRef(0);
80
98
  /** what a check found, for the fields it covers (`key`: one field and those inside it; else all) */
81
99
  const apply = (found, from, key) => {
82
100
  if (latest.current !== from)
@@ -130,14 +148,25 @@ export function useForm(schema) {
130
148
  if (element && Object.keys(server).length)
131
149
  focusFirst(element, server);
132
150
  }, [submitting, failed, server, element]);
151
+ // a visit to another page (a link, another form) or the form leaving the screen: a pending check can't send
152
+ const visiting = navigation.state === 'loading' || navigation.state === 'submitting';
153
+ useEffect(() => {
154
+ if (visiting)
155
+ generation.current++;
156
+ }, [visiting]);
157
+ useEffect(() => () => {
158
+ generation.current++;
159
+ }, []);
133
160
  const checkField = (form, key) => {
134
161
  if (!schema)
135
162
  return;
136
163
  const run = (runs.current.get(key) ?? 0) + 1;
137
164
  runs.current.set(key, run);
138
165
  const from = server;
166
+ const began = epoch.current;
139
167
  const done = (found) => {
140
- if (runs.current.get(key) === run)
168
+ // not after a newer check of the field, nor after the whole form's result (it began with these values or later)
169
+ if (runs.current.get(key) === run && epoch.current === began)
141
170
  apply(found, from, key);
142
171
  };
143
172
  const found = check(schema, () => fieldsOf(form));
@@ -159,6 +188,8 @@ export function useForm(schema) {
159
188
  const form = event.currentTarget;
160
189
  const submitter = event.nativeEvent.submitter;
161
190
  const from = server;
191
+ const mine = ++generation.current;
192
+ const before = snapshot(form, submitter);
162
193
  const found = check(schema, () => fieldsOf(form, submitter));
163
194
  const answer = (found) => {
164
195
  apply(found, from);
@@ -173,11 +204,21 @@ export function useForm(schema) {
173
204
  // an async schema: sent again once it says yes
174
205
  event.preventDefault();
175
206
  void found.then((found) => {
207
+ // obsolete (a newer submit, a visit, the form gone) or about other values than the form has now: it says
208
+ // nothing about what would be sent
209
+ if (generation.current !== mine || snapshot(form, submitter) !== before)
210
+ return;
211
+ epoch.current++;
176
212
  answer(found);
177
213
  if (Object.keys(found).length || latest.current !== from)
178
214
  return;
179
215
  passed.current = true;
180
- form.requestSubmit(submitter && 'form' in submitter ? submitter : null);
216
+ try {
217
+ form.requestSubmit(submitter && 'form' in submitter ? submitter : null);
218
+ }
219
+ finally {
220
+ passed.current = false; // a submit that was cancelled has not used it up
221
+ }
181
222
  });
182
223
  },
183
224
  },
@@ -47,11 +47,30 @@ export declare function loadDocument(href: string): void;
47
47
  * `replace`), anything else as a document. `keep`: the answer is shown as `reload()` shows its own, the page keeps
48
48
  * its state (a focused input, what was typed) and the scroll position, nothing is announced: a search box that
49
49
  * `navigate()`s to its query as it is typed. Another page's component is shown as any navigation's.
50
+ *
51
+ * `shallow`: the query and #fragment of the page on the screen change, and nothing is asked for: the page keeps its
52
+ * props, its state and the scroll position, `usePage().url` follows, and a changed #fragment fires `hashchange` (the
53
+ * browser doesn't scroll to it, and `:target` stays as it was). Only this page's own pathname; another page throws.
54
+ * Not with `keep`: a shallow navigation keeps the page anyway. Before the app has started, a document load. While a
55
+ * visit is being put on the screen (its URL is in the history, its page is not there yet), a normal navigation.
50
56
  */
51
- export declare function navigate(href: string, { replace, keep }?: {
57
+ export declare function navigate(href: string, options?: {
52
58
  replace?: boolean;
53
59
  keep?: boolean;
60
+ shallow?: false;
61
+ } | {
62
+ replace?: boolean;
63
+ keep?: never;
64
+ shallow: true;
54
65
  }): void;
66
+ /**
67
+ * Closes what `navigate(…, { shallow: true })` or a `data-shallow` link opened (a dialog, a drawer), one step. An
68
+ * entry that was pushed by a shallow navigation, from the entry below it: Back, to the page as it was. Any other (a
69
+ * document loaded at this URL, a reload, an entry replaced…): `to` in its place, a shallow navigation with `replace`
70
+ * (`to` is a URL of this page, as that takes it). Never leaves the page, and never adds an entry. A second call before
71
+ * the first one's Back has landed does nothing: a double click closes one level.
72
+ */
73
+ export declare function closeShallow(to: string): void;
55
74
  /** the page asked for again, its state and the scroll position kept */
56
75
  export declare function again(only?: string[]): void;
57
76
  export {};
@@ -1,6 +1,10 @@
1
1
  import { crlf } from '../form.js';
2
2
  import { pageDataPath, SCROLL_KEY, SCROLL_STORAGE } from '../paths.js';
3
3
  let visit;
4
+ /** the page on the screen at another URL of its own, nothing asked for (`navigate(url, { shallow: true })`) */
5
+ let shallowTo;
6
+ /** the URL of the page on the screen (its path and query): not `location`'s while a visit is being put on the screen */
7
+ let shownUrl;
4
8
  /** the props of the page on the screen asked for, quietly (`defer()`, `reload({ only })`) */
5
9
  let ask;
6
10
  /** a URL path is one of the app's pages (the client's, once it has started) */
@@ -29,17 +33,31 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
29
33
  // the page on the screen, and how many were put there (an answer for another is dropped)
30
34
  let on = initial;
31
35
  let shows = 0;
36
+ // The history entries (their keys) that show the page on the screen, at URLs of their own: the one that got it, the
37
+ // ones shallow navigations added, the browser's own #fragment entries. Back and Forward between them ask for
38
+ // nothing. A page put on the screen is its entry's alone: the others are normal entries again (Back asks)
39
+ let group = new Set();
40
+ // the URL the page's props are the loader's answer for: `on.url` changes with a shallow navigation, this does not
41
+ let answered = initial.url;
32
42
  const asking = new Set();
43
+ // each prop's newest answer put in the page: the request it came from (their order). An older request answering
44
+ // after it is dropped for that prop, as an answer for a page no longer there is
45
+ let requests = 0;
46
+ let answers = new Map();
33
47
  const put = async (page, fresh, stale) => {
34
48
  await show(page, fresh, stale);
35
49
  if (stale())
36
50
  return;
37
51
  on = page;
38
52
  shows++;
53
+ group = new Set([scroll.key()]);
54
+ answered = page.url;
39
55
  // the page they were for is gone
40
56
  for (const quiet of asking)
41
57
  quiet.abort();
58
+ answers = new Map();
42
59
  };
60
+ shownUrl = () => new URL(on.url, location.href);
43
61
  const headers = () => ({ 'X-Fondu': 'true', ...(version && { 'X-Fondu-Version': version }) });
44
62
  /** where a page's JSON is: its URL, or its file (a prerendered build) */
45
63
  const source = (url) => prerender ? pageDataPath(url.pathname) + url.search : url.pathname + url.search;
@@ -84,13 +102,14 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
84
102
  ask = async (names) => {
85
103
  const at = shows;
86
104
  const page = on;
105
+ const id = ++requests;
87
106
  const controller = new AbortController();
88
107
  asking.add(controller);
89
108
  // a prop asked for that is neither here nor coming (it failed): pending again, `<Deferred>` shows its fallback
90
109
  const absent = names.filter((n) => !Object.hasOwn(page.props, n) && !page.deferred?.includes(n));
91
110
  if (absent.length)
92
111
  void show((on = { ...page, deferred: [...(page.deferred ?? []), ...absent] }), false, () => shows !== at);
93
- let got = {};
112
+ let got;
94
113
  try {
95
114
  const response = await fetch(source(new URL(page.url, location.href)), {
96
115
  headers: {
@@ -102,20 +121,35 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
102
121
  });
103
122
  const answer = response.ok && response.headers.has('X-Fondu') ? (await response.json()) : null;
104
123
  if (answer?.component === page.component)
105
- got = Object.fromEntries(Object.entries(answer.props).filter(([key]) => names.includes(key)));
124
+ got = answer.props;
106
125
  }
107
126
  catch { } // offline, aborted
108
127
  asking.delete(controller);
109
128
  if (controller.signal.aborted || shows !== at)
110
129
  return;
130
+ // asked at the URL of a shallow entry, which the page has left since: not its answer
131
+ if (page.url !== answered && page.url !== on.url)
132
+ return;
133
+ // the props of this answer that no newer request has answered already
134
+ const take = names.filter((n) => got && Object.hasOwn(got, n) && id > (answers.get(n) ?? 0));
135
+ for (const n of take)
136
+ answers.set(n, id);
111
137
  const next = {
112
138
  ...on,
113
- props: { ...on.props, ...got },
139
+ props: { ...on.props, ...Object.fromEntries(take.map((n) => [n, got[n]])) },
114
140
  deferred: on.deferred?.filter((n) => !names.includes(n)),
115
141
  };
116
142
  on = next; // before the module is awaited: another answer merges into this one
117
- await show(next, false, () => shows !== at);
118
- if (shows === at)
143
+ // asked at the URL of a shallow entry, not at the one the page was loaded at: an answer of its own, and this
144
+ // entry's alone (those asked before the shallow navigation are the loader's answer still)
145
+ if (got && page.url !== answered) {
146
+ group = new Set([scroll.key()]);
147
+ answered = page.url;
148
+ }
149
+ // not once another answer has merged into the page since: its own show() has these props too
150
+ const stale = () => shows !== at || on !== next;
151
+ await show(next, false, stale);
152
+ if (!stale())
119
153
  keep(next);
120
154
  };
121
155
  /** a document load: in place of this entry, or after it */
@@ -229,6 +263,10 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
229
263
  const page = (await response.json());
230
264
  if (signal.aborted)
231
265
  return;
266
+ // A prerendered page's file is made without a query. Its answer, not redirected, is for the URL asked: the
267
+ // visitor's query stays (as at a document load); a redirect, which the server made, is its target's
268
+ if (!response.redirected && page.url === url.pathname)
269
+ page.url += url.search;
232
270
  if (version && page.version && page.version !== version)
233
271
  return documentLoad(page.url, options.history !== 'push');
234
272
  version = page.version;
@@ -238,6 +276,9 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
238
276
  const same = post && page.url === here;
239
277
  const errors = Object.keys(page.props.errors ?? {}).length > 0;
240
278
  const asked = url.pathname + url.search;
279
+ // asked for the entry on the screen, which a shallow navigation has since left for another URL: not its answer
280
+ if (options.history === 'none' && location.pathname + location.search !== asked)
281
+ return;
241
282
  // the kept page's entry: the server's page in its place, its state kept; redirected (signed out), anew
242
283
  // kept: the same component answers (another one mounts anew, and is scrolled to the top as a navigation's)
243
284
  const stay = options.keep && page.component === on.component;
@@ -297,7 +338,46 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
297
338
  }
298
339
  })();
299
340
  };
300
- /** the URL of a link the client may follow itself: same origin, this window, no download */
341
+ /**
342
+ * The page on the screen at a URL of its own (its query, its #fragment), nothing asked for: a new history entry, or
343
+ * this one's. The props stay the loader's answer for the URL that got the page; its `url` follows the address bar.
344
+ */
345
+ shallowTo = (url, replace) => {
346
+ // A visit whose URL is in the history already, its page not on the screen yet (its modules load): no URL of the
347
+ // page on the screen to change. A normal navigation, which supersedes that visit as any does
348
+ if (location.pathname + location.search !== on.url)
349
+ return navigate(url.href, { replace });
350
+ current?.abort(); // a visit still waiting for its answer: given up, as any newer navigation does
351
+ const was = location.href;
352
+ scroll.save();
353
+ const before = scroll.key();
354
+ replace ||= url.href === location.href;
355
+ scroll.write(url.href, replace, true);
356
+ scroll.commit();
357
+ scroll.save(); // the new entry starts where the page is
358
+ if (replace)
359
+ group.delete(before);
360
+ group.add(scroll.key());
361
+ settle(true);
362
+ // the browser fires no `hashchange` for pushState
363
+ if (new URL(was).hash !== url.hash)
364
+ dispatchEvent(new HashChangeEvent('hashchange', { oldURL: was, newURL: url.href }));
365
+ };
366
+ /**
367
+ * The page on the screen follows the address bar (its `url`; a shallow navigation also drops its flash and errors,
368
+ * which belonged to the answer before it), and is kept for the entry
369
+ */
370
+ const settle = (fresh) => {
371
+ const at = shows;
372
+ on = {
373
+ ...on,
374
+ url: location.pathname + location.search,
375
+ ...(fresh && { flash: {}, props: { ...on.props, errors: {} } }),
376
+ };
377
+ void show(on, false, () => shows !== at);
378
+ keep(on);
379
+ };
380
+ /** a link the client may follow itself (same origin, this window, no download): its URL; `soft`, a shallow one */
301
381
  const linkOf = (target) => {
302
382
  const link = target?.closest?.('a[href]');
303
383
  if (!(link instanceof HTMLAnchorElement))
@@ -307,7 +387,11 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
307
387
  const url = new URL(link.href);
308
388
  if (url.origin !== location.origin || !isWebUrl(url.href))
309
389
  return;
310
- return url;
390
+ // `data-shallow`: for the page on the screen's own URL (its query, its #fragment) a shallow navigation
391
+ return {
392
+ url,
393
+ soft: link.hasAttribute('data-shallow') && url.pathname === shownUrl().pathname,
394
+ };
311
395
  };
312
396
  // links: a plain click on a same-origin <a href>, which the page let through
313
397
  document.addEventListener('click', (event) => {
@@ -315,9 +399,14 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
315
399
  return;
316
400
  if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
317
401
  return;
318
- const url = linkOf(event.target);
319
- if (!url)
402
+ const link = linkOf(event.target);
403
+ if (!link)
320
404
  return;
405
+ const { url } = link;
406
+ if (link.soft) {
407
+ event.preventDefault();
408
+ return shallowTo(url, false);
409
+ }
321
410
  // a #fragment of this page: the browser scrolls to it (the position left saved for Back)
322
411
  if (url.pathname + url.search === location.pathname + location.search && url.hash) {
323
412
  scroll.save();
@@ -337,21 +426,21 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
337
426
  const RESTING = 80; // milliseconds the pointer rests
338
427
  let timer;
339
428
  document.addEventListener('mouseover', (event) => {
340
- const url = linkOf(event.target);
429
+ const link = linkOf(event.target);
341
430
  clearTimeout(timer);
342
- if (url && isPage(url.pathname))
431
+ if (link && !link.soft && isPage(link.url.pathname))
343
432
  timer = setTimeout(() => {
344
- preload(url.pathname);
345
- void prefetch(url);
433
+ preload(link.url.pathname);
434
+ void prefetch(link.url);
346
435
  }, RESTING);
347
436
  });
348
437
  document.addEventListener('mouseout', () => clearTimeout(timer));
349
438
  document.addEventListener('touchstart', (event) => {
350
- const url = linkOf(event.target);
351
- if (!url || !isPage(url.pathname))
439
+ const link = linkOf(event.target);
440
+ if (!link || link.soft || !isPage(link.url.pathname))
352
441
  return;
353
- preload(url.pathname);
354
- void prefetch(url);
442
+ preload(link.url.pathname);
443
+ void prefetch(link.url);
355
444
  }, { passive: true });
356
445
  }
357
446
  // forms: GET and POST to this origin, in this window, which the page let through
@@ -388,8 +477,21 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
388
477
  });
389
478
  // Back and Forward: the entry's page, where it was scrolled
390
479
  window.addEventListener('popstate', (event) => {
480
+ closing = false;
391
481
  const popped = scroll.pop(event.state);
482
+ // a visit on its way is given up by any Back or Forward, the browser's own #fragment entries too: its answer
483
+ // would put a page on the screen over the entry the visitor is at
484
+ current?.abort();
485
+ pending(null);
486
+ // an entry that shows the page on the screen, at a URL of its own: its URL, nothing asked for, the scroll where it
487
+ // is
488
+ if (!popped.fragment && popped.key && group.has(popped.key)) {
489
+ scroll.commit();
490
+ return settle(false);
491
+ }
392
492
  if (popped.fragment) {
493
+ if (!popped.key)
494
+ group.add(scroll.key()); // an entry the browser made (no key yet): of this page
393
495
  // a #fragment that names no element (a dialog's `#settings/account`) leaves the page where it is, as the browser does
394
496
  if (!popped.position && location.hash && !fragmentTarget(location.hash.slice(1)))
395
497
  return;
@@ -406,29 +508,65 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
406
508
  // manual; Firefox, a #fragment), and over the page's own (Firefox, at load, a page rendered in the browser at 0)
407
509
  window.addEventListener('pagehide', scroll.save);
408
510
  // the browser's own #fragment navigations: the entry gets its key
409
- window.addEventListener('hashchange', scroll.commit);
511
+ window.addEventListener('hashchange', () => {
512
+ // an entry the browser made (no key yet; a popstate may have given it one): of the page on the screen
513
+ if (scroll.commit())
514
+ group.add(scroll.key());
515
+ });
516
+ addEventListener('pageshow', () => (closing = false));
410
517
  // a page rendered on the server is where it belongs already, before its first paint: at its entry's position (its
411
518
  // document's script: a reload, Back from another site), else at its #fragment (the browser). One rendered here has
412
519
  // its content only now: its entry's position, or its #fragment's target
413
520
  const position = scroll.start();
521
+ group.add(scroll.key());
414
522
  if (!hydrated) {
415
523
  restore(position, location.hash, true);
416
524
  if (position)
417
525
  holdUntilLoaded(position);
418
526
  }
419
527
  keep(initial);
528
+ // A prerendered page's file is made without a query, and the document it hydrates is too: once it is hydrated, its URL
529
+ // is the browser's (a state the query holds works at a direct load; its loader never saw the query). A page
530
+ // rendered per request has its query in its URL already
531
+ if (location.pathname + location.search !== on.url)
532
+ settle(false);
420
533
  if (initial.deferred?.length)
421
534
  ask(initial.deferred);
422
535
  }
536
+ /**
537
+ * What this client adds to `history.state` (beside the scroll key, `paths.ts`), and what outlives a deploy: an entry's
538
+ * own state, read by the build that is running when the browser comes back to it.
539
+ * `__fondu_shallow: true`: the entry was pushed by a shallow navigation, from the entry below it, which showed the
540
+ * same page. `closeShallow()` goes back (one step) from such an entry; any other it replaces in place.
541
+ */
542
+ const SHALLOW = '__fondu_shallow';
543
+ /** `closeShallow()` has gone back, and the browser has not landed yet: a second call waits (until the entry is there) */
544
+ let closing = false;
423
545
  /**
424
546
  * Scroll positions, per history entry (a key in `history.state`), in memory and in sessionStorage (a reload, a page
425
547
  * of another site and back): the browser's restoration is off. Each belongs to the entry on the screen, even once
426
- * the browser has started a traversal away from it.
548
+ * the browser has started a traversal away from it. The last 50 are kept (the page cache's number), their keys in
549
+ * the order they were used in `STORAGE` itself; an entry replaced by another page forgets its own.
427
550
  */
428
551
  function scrollPositions() {
429
552
  const KEY = SCROLL_KEY;
430
553
  const STORAGE = SCROLL_STORAGE;
431
554
  const positions = new Map();
555
+ const forget = (key) => {
556
+ positions.delete(key);
557
+ try {
558
+ sessionStorage.removeItem(STORAGE + key);
559
+ }
560
+ catch { }
561
+ };
562
+ /** the most recently used last: the oldest beyond 50 are forgotten */
563
+ const remember = (key, position) => {
564
+ positions.delete(key);
565
+ positions.set(key, position);
566
+ for (const old of positions.keys())
567
+ if (positions.size > 50)
568
+ forget(old);
569
+ };
432
570
  const keyOf = (state) => state &&
433
571
  typeof state === 'object' &&
434
572
  typeof state[KEY] === 'string'
@@ -455,9 +593,10 @@ function scrollPositions() {
455
593
  if (!rendered)
456
594
  return;
457
595
  const position = { x: scrollX, y: scrollY };
458
- positions.set(rendered, position);
596
+ remember(rendered, position);
459
597
  try {
460
598
  sessionStorage.setItem(STORAGE + rendered, JSON.stringify(position));
599
+ sessionStorage.setItem(STORAGE, JSON.stringify([...positions.keys()]));
461
600
  }
462
601
  catch { }
463
602
  };
@@ -471,16 +610,18 @@ function scrollPositions() {
471
610
  frame = requestAnimationFrame(() => {
472
611
  frame = 0;
473
612
  if (rendered === key)
474
- positions.set(key, { x: scrollX, y: scrollY });
613
+ remember(key, { x: scrollX, y: scrollY });
475
614
  });
476
615
  }, { passive: true });
477
- /** this entry's key, given one if it has none (a first visit, a #fragment the browser navigated to) */
616
+ /** this entry's key, given one if it has none (a first visit, a #fragment the browser navigated to): true if so */
478
617
  const commit = () => {
479
618
  let key = keyOf(history.state);
619
+ const added = !key;
480
620
  if (!key)
481
621
  history.replaceState({ ...history.state, [KEY]: (key = newKey()) }, '');
482
622
  rendered = key;
483
623
  renderedUrl = location.pathname + location.search;
624
+ return added;
484
625
  };
485
626
  return {
486
627
  save,
@@ -493,12 +634,43 @@ function scrollPositions() {
493
634
  */
494
635
  start() {
495
636
  history.scrollRestoration = 'manual';
637
+ // the positions saved before this document (the last 50, as left), in their order
638
+ try {
639
+ for (const key of JSON.parse(sessionStorage.getItem(STORAGE) ?? '[]')) {
640
+ const saved = read(key);
641
+ if (saved)
642
+ positions.set(key, saved);
643
+ }
644
+ }
645
+ catch { }
496
646
  commit();
497
647
  return read(rendered);
498
648
  },
499
- /** the page on the screen, at `url`: a new entry or this one */
500
- write(url, replace) {
501
- const state = { ...(replace ? history.state : {}), [KEY]: newKey() };
649
+ /**
650
+ * The page on the screen, at `url`: a new entry or this one. `shallow`: by a shallow navigation, which marks a
651
+ * new entry (SHALLOW); a replaced entry keeps its state, but another URL, by a navigation that is not
652
+ * shallow, takes the mark away: `closeShallow()` there must not go Back off it. A replaced entry is the same
653
+ * entry (its key stays) for a shallow navigation and an answer at its URL; another page is a new one, and
654
+ * nothing can visit the entry it replaced.
655
+ */
656
+ write(url, replace, shallow = false) {
657
+ const to = new URL(url, location.href);
658
+ // the same URL (a form's answer, reload()): the same overlay
659
+ const same = to.pathname + to.search === location.pathname + location.search;
660
+ const old = keyOf(history.state);
661
+ const kept = replace && old && (shallow || same);
662
+ const state = {
663
+ ...(replace ? history.state : {}),
664
+ [KEY]: kept ? old : newKey(),
665
+ };
666
+ if (replace && old && !kept)
667
+ forget(old);
668
+ if (shallow) {
669
+ if (!replace)
670
+ state[SHALLOW] = true;
671
+ }
672
+ else if (!same)
673
+ delete state[SHALLOW]; // another page: not a shallow entry
502
674
  if (replace)
503
675
  history.replaceState(state, '', url);
504
676
  else
@@ -600,14 +772,52 @@ export function loadDocument(href) {
600
772
  * `replace`), anything else as a document. `keep`: the answer is shown as `reload()` shows its own, the page keeps
601
773
  * its state (a focused input, what was typed) and the scroll position, nothing is announced: a search box that
602
774
  * `navigate()`s to its query as it is typed. Another page's component is shown as any navigation's.
775
+ *
776
+ * `shallow`: the query and #fragment of the page on the screen change, and nothing is asked for: the page keeps its
777
+ * props, its state and the scroll position, `usePage().url` follows, and a changed #fragment fires `hashchange` (the
778
+ * browser doesn't scroll to it, and `:target` stays as it was). Only this page's own pathname; another page throws.
779
+ * Not with `keep`: a shallow navigation keeps the page anyway. Before the app has started, a document load. While a
780
+ * visit is being put on the screen (its URL is in the history, its page is not there yet), a normal navigation.
603
781
  */
604
- export function navigate(href, { replace = false, keep = false } = {}) {
605
- const url = new URL(href, location.href);
782
+ export function navigate(href, options = {}) {
783
+ const { replace = false, keep = false, shallow = false } = options;
784
+ if (shallow && keep)
785
+ throw new Error('fondu: a shallow navigation takes no `keep`: the page stays as it is');
786
+ const shown = shownUrl?.();
787
+ // a shallow navigation is relative to the page on the screen, whose URL `location` may have left
788
+ const url = new URL(href, shallow ? (shown ?? location.href) : location.href);
789
+ if (shallow) {
790
+ if (url.origin !== location.origin || url.pathname !== (shown ?? location).pathname)
791
+ throw new Error(`fondu: a shallow navigation stays on this page (its query, its #fragment); ${url.origin === location.origin ? url.pathname : url.href} is another page: leave out \`shallow\``);
792
+ if (shallowTo)
793
+ return shallowTo(url, replace);
794
+ }
606
795
  const here = url.pathname + url.search === location.pathname + location.search;
607
- if (!visit || url.origin !== location.origin || !isAppPage?.(url.pathname) || (here && url.hash))
608
- return replace ? location.replace(url.href) : location.assign(url.href); // a #fragment of this page: the browser's
796
+ if (shallow ||
797
+ !visit ||
798
+ url.origin !== location.origin ||
799
+ !isAppPage?.(url.pathname) ||
800
+ (here && url.hash))
801
+ return replace ? location.replace(url.href) : location.assign(url.href); // a #fragment of this page: the browser's; shallow: the app has not started
609
802
  visit(url.href, { history: replace || url.href === location.href ? 'replace' : 'push', keep });
610
803
  }
804
+ /**
805
+ * Closes what `navigate(…, { shallow: true })` or a `data-shallow` link opened (a dialog, a drawer), one step. An
806
+ * entry that was pushed by a shallow navigation, from the entry below it: Back, to the page as it was. Any other (a
807
+ * document loaded at this URL, a reload, an entry replaced…): `to` in its place, a shallow navigation with `replace`
808
+ * (`to` is a URL of this page, as that takes it). Never leaves the page, and never adds an entry. A second call before
809
+ * the first one's Back has landed does nothing: a double click closes one level.
810
+ */
811
+ export function closeShallow(to) {
812
+ if (closing)
813
+ return;
814
+ if (history.state?.[SHALLOW] === true) {
815
+ closing = true;
816
+ history.back();
817
+ }
818
+ else
819
+ navigate(to, { shallow: true, replace: true });
820
+ }
611
821
  /** the page asked for again, its state and the scroll position kept */
612
822
  export function again(only) {
613
823
  if (!visit)
package/dist/client.d.ts CHANGED
@@ -63,7 +63,7 @@ type Args<P extends string> = [ParamNames<P>] extends [never] ? {} extends Query
63
63
  export declare function href<P extends Href>(path: P, ...[options]: Args<P>): string;
64
64
  export { usePage, useNavigation, reload, Deferred, __entry, renderPage, type Errors, type Navigation, } from './client/app.js';
65
65
  export { useForm } from './client/form.js';
66
- export { loadDocument, navigate, type Page } from './client/navigation.js';
66
+ export { closeShallow, loadDocument, navigate, type Page } from './client/navigation.js';
67
67
  export type { ProgressOptions } from './client/progress.js';
68
68
  type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
69
69
  /** no generated types (or none of routes): everything is loose, as `Href` is */
@@ -102,13 +102,13 @@ type BodyArg<M extends string, B> = M extends 'GET' ? {
102
102
  } : {
103
103
  body: B;
104
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> ? {
105
+ /** `method`: omitted is GET, so it is left out only for a call that is GET: any other method, or a union, names it */
106
+ type MethodArg<M extends string> = [M] extends ['GET'] ? {
107
107
  method?: M;
108
108
  } : {
109
109
  method: M;
110
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>>> & {
111
+ type FetchOptions<P extends string, M extends HttpMethod> = ParamArgs<P> & MethodArg<M> & QueryArg<QueryOfHandler<HandlerOf<P, M>>> & BodyArg<M, BodyOfHandler<HandlerOf<P, M>>> & {
112
112
  headers?: HeadersInit;
113
113
  signal?: AbortSignal;
114
114
  };
package/dist/client.js CHANGED
@@ -25,7 +25,7 @@ function buildUrl(path, params, query, hash) {
25
25
  }
26
26
  export { usePage, useNavigation, reload, Deferred, __entry, renderPage, } from './client/app.js';
27
27
  export { useForm } from './client/form.js';
28
- export { loadDocument, navigate } from './client/navigation.js';
28
+ export { closeShallow, loadDocument, navigate } from './client/navigation.js';
29
29
  /** a non-2xx answer: `status`, `data` (the parsed body: a 422's `{ errors }`) and the `response` */
30
30
  export class FetchError extends Error {
31
31
  status;
package/dist/paths.js CHANGED
@@ -19,10 +19,13 @@ 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
+ // the options of href() and fetch(), next to the params
23
+ for (const segment of segments) {
24
+ const name = /^\[{1,2}(?:\.\.\.)?(\w+)\]{1,2}$/.exec(segment)?.[1];
25
+ const api = name && RESERVED[name];
26
+ if (api)
27
+ throw new Error(`fondu: routes/${file}: a param can't be named ${name} (${api}'s option); rename the file's [${name}]`);
28
+ }
26
29
  const pattern = (withOptional) => '/' +
27
30
  segments
28
31
  .filter((s) => withOptional || !optional.includes(s))
@@ -33,6 +36,15 @@ export function routePatterns(file) {
33
36
  .join('/');
34
37
  return optional.length ? [pattern(false), pattern(true)] : [pattern(true)];
35
38
  }
39
+ /** the names a param can't have, and the function whose option each is: `href()`'s and `fetch()`'s */
40
+ const RESERVED = Object.assign(Object.create(null), {
41
+ query: 'href()',
42
+ hash: 'href()',
43
+ method: 'fetch()',
44
+ body: 'fetch()',
45
+ headers: 'fetch()',
46
+ signal: 'fetch()',
47
+ });
36
48
  const ROUTE_EXTENSION = /\.(?:tsx?|mdx)$/;
37
49
  /**
38
50
  * a path inside `routes/` that is a route file: `.ts` (server code: handlers) or `.tsx`, `.mdx` (a page), but
@@ -1,5 +1,19 @@
1
1
  import { endsInIndex, fillPattern, PAGE_DATA, pathOfPageData } from '../paths.js';
2
2
  import { isPrerendering } from './http.js';
3
+ /**
4
+ * A param's value becomes a file name (`/items/:id` → `items/<id>.html`): not a path of its own. A `/` or a `\`
5
+ * in it (Windows' separator) would make a directory of it, or leave the build's directory (`../../x`); a catch-all
6
+ * is the path of its segments, each of which is a name. Throws, naming the value.
7
+ */
8
+ function fileNames(pattern, params) {
9
+ for (const [, name, catchAll] of pattern.matchAll(/:(\w+)(\{[^}]*\})?/g)) {
10
+ const value = String(params[name]);
11
+ for (const part of catchAll ? value.split('/') : [value])
12
+ if (part === '.' || part === '..' || part.includes('\\') || (!catchAll && part.includes('/')))
13
+ throw new Error(`param "${name}" is ${JSON.stringify(value)}: a prerendered URL is a file, and its names have no ` +
14
+ `separators (/ or \\) and are not . or ..`);
15
+ }
16
+ }
3
17
  /** The paths to prerender, and what stops a route from being prerendered (the build fails on those) */
4
18
  export async function prerenderPaths(routes) {
5
19
  const paths = new Set();
@@ -28,8 +42,11 @@ export async function prerenderPaths(routes) {
28
42
  continue;
29
43
  }
30
44
  try {
31
- for (const params of await setting())
32
- add(fillPattern(route.pattern, params));
45
+ for (const params of await setting()) {
46
+ const path = fillPattern(route.pattern, params);
47
+ fileNames(route.pattern, params);
48
+ add(path);
49
+ }
33
50
  }
34
51
  catch (error) {
35
52
  problems.push(`${where}: ${error instanceof Error ? error.message : String(error)}`);
@@ -135,10 +135,13 @@ function askedFor(c, id) {
135
135
  !isPageRequest(c) ||
136
136
  c.req.header('x-fondu-component') !== id)
137
137
  return;
138
- return only
139
- .split(',')
140
- .map((name) => name.trim())
141
- .filter(Boolean);
138
+ // each name once, in the order first given: a name asked twice does not run its loader twice
139
+ return [
140
+ ...new Set(only
141
+ .split(',')
142
+ .map((name) => name.trim())
143
+ .filter(Boolean)),
144
+ ];
142
145
  }
143
146
  /** an http(s) URL, as `to` resolves from the request's */
144
147
  function webUrl(c, to) {
@@ -150,17 +153,22 @@ function webUrl(c, to) {
150
153
  }
151
154
  }
152
155
  // ---- the protocol middleware (installed by createApp)
156
+ /**
157
+ * Every header that selects what a navigation answers: the page object (`X-Fondu`), the 409 of an old build
158
+ * (`X-Fondu-Version`), a partial answer (`X-Fondu-Only`, for `X-Fondu-Component`'s page)
159
+ */
160
+ const NAVIGATION_VARY = 'X-Fondu, X-Fondu-Version, X-Fondu-Only, X-Fondu-Component';
153
161
  const versionCheck = async (c, next) => {
154
162
  // a navigation of a client built from other assets: the page loads as a document
155
163
  if (version &&
156
164
  c.req.method === 'GET' &&
157
165
  isPageRequest(c) &&
158
166
  c.req.header('x-fondu-version') !== version) {
159
- return c.body(null, 409, { 'X-Fondu-Location': c.req.url, Vary: 'X-Fondu' });
167
+ return c.body(null, 409, { 'X-Fondu-Location': c.req.url, Vary: NAVIGATION_VARY });
160
168
  }
161
169
  await next();
162
170
  // a URL answers a navigation and a document differently: caches keep them apart
163
- appendHeader(c, 'Vary', isPageRequest(c) ? 'X-Fondu, X-Fondu-Only' : 'X-Fondu');
171
+ appendHeader(c, 'Vary', isPageRequest(c) ? NAVIGATION_VARY : 'X-Fondu');
164
172
  // an empty answer to a form (an action that returns nothing to show, `c.body(null)`): back to the page. Its body
165
173
  // isn't read to tell (a stream's would be, to its end)
166
174
  if (isPageRequest(c) && c.res.status === 200 && !c.res.headers.has('x-fondu') && !c.res.body)
@@ -65,7 +65,7 @@ export function routeTable(modules, append) {
65
65
  : 'Move one, or list the values of a param: `export const params = { name: [...] }`'));
66
66
  byKey.set(key, route);
67
67
  }
68
- return routes.sort((a, b) => rank(a.pattern).localeCompare(rank(b.pattern)));
68
+ return routes.sort((a, b) => compare(a.pattern, b.pattern));
69
69
  }
70
70
  function paramsOf(file, mod) {
71
71
  const params = mod?.params;
@@ -81,8 +81,23 @@ function paramsOf(file, mod) {
81
81
  }
82
82
  // a catch-all takes the rest of the path: never a trailing slash
83
83
  const withSlash = (pattern, append) => append && pattern !== '/' && !pattern.endsWith('{.+}') ? pattern + '/' : pattern;
84
- /** sort key: static segments, then params with listed values, then params, then catch-alls */
85
- const rank = (pattern) => pattern
86
- .split('/')
87
- .map((s) => (s.endsWith('{.+}') ? '3' : s.includes('{') ? '1' : s.startsWith(':') ? '2' : '0') + s)
88
- .join('/');
84
+ /** a segment's specificity: static, then a param with listed values, then a param, then a catch-all */
85
+ const priority = (s) => s.endsWith('{.+}') ? 3 : s.includes('{') ? 1 : s.startsWith(':') ? 2 : 0;
86
+ /**
87
+ * Hono's order: the specificity of each segment, from the first (static segments of another spelling are other
88
+ * URLs: alphabetical); a param's name decides only between patterns equally specific at every segment, so
89
+ * renaming a param never changes which route answers
90
+ */
91
+ function compare(a, b) {
92
+ const x = a.split('/');
93
+ const y = b.split('/');
94
+ for (let i = 0; i < Math.min(x.length, y.length); i++) {
95
+ const d = priority(x[i]) - priority(y[i]);
96
+ if (d)
97
+ return d;
98
+ // two static segments that differ: the routes are apart, any order is right (the alphabetical one is steady)
99
+ if (priority(x[i]) === 0 && x[i] !== y[i])
100
+ return x[i] < y[i] ? -1 : 1;
101
+ }
102
+ return x.length - y.length || (a < b ? -1 : a > b ? 1 : 0);
103
+ }
@@ -32,3 +32,5 @@ export interface FonduOptions {
32
32
  /** what fondu's server code imports from Hono (test/hono.test.ts keeps the list complete) */
33
33
  export declare const HONO: string[];
34
34
  export default function fondu(options: FonduOptions): PluginOption[];
35
+ /** the code of dist/server/index.js: `paths` are the client build's files and directories (`/robots.txt`, `/assets`) */
36
+ export declare function entryCode(options: FonduOptions, paths: string[]): string;
@@ -131,7 +131,8 @@ function dependencies(root = '') {
131
131
  * Node / Bun: the server build's entry, dist/server/index.js. The client build's files first (found next to the
132
132
  * server bundle wherever it runs from; hashed files never change), then the app. Node: @hono/node-server's serve()
133
133
  * on `PORT` (else the option), saying where it listens, with a graceful shutdown on SIGTERM / SIGINT (10 s). Bun
134
- * serves the default export itself and reads `PORT` (with the app's `websocket`, if it has one).
134
+ * serves the default export itself, on `PORT` (else the option; Bun's own default without one), with the app's
135
+ * `websocket`, if it has one.
135
136
  * With `prerender`, the pages the build wrote are served from their files first, with the headers it decided
136
137
  * (`prerender.json`, next to this entry).
137
138
  */
@@ -154,44 +155,51 @@ function serverEntry(options) {
154
155
  .filter((e) => e.name !== '.vite')
155
156
  .map((e) => (e.isDirectory() ? `/${e.name}/*` : `/${e.name}`))
156
157
  : [];
157
- const bun = options.target === 'bun';
158
- return [
159
- `import { Hono } from 'hono'`,
160
- `import { serveStatic } from '${bun ? 'hono/bun' : '@hono/node-server/serve-static'}'`,
161
- `import { fileURLToPath } from 'node:url'`,
162
- `import app from '${SERVER.slice(1)}'`,
163
- `const clientRoot = fileURLToPath(new URL('../client', import.meta.url))`,
164
- `const main = new Hono()`,
165
- `main.use('/assets/*', async (c, next) => { await next(); if (c.res.ok) c.header('Cache-Control', 'public, max-age=31536000, immutable') })`,
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)
168
- ...(options.prerender
169
- ? [
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))`,
174
- ]
175
- : []),
176
- ...paths.map((p) => `main.use(${JSON.stringify(p)}, serveStatic({ root: clientRoot }))`),
177
- `main.all('*', (c) => app.fetch(c.req.raw, c.env))`,
178
- ...(bun
179
- ? [
180
- `export default app.websocket ? { fetch: main.fetch, websocket: app.websocket } : main`,
181
- ]
182
- : [
183
- `import { serve } from '@hono/node-server'`,
184
- `const server = serve({ fetch: main.fetch, port: Number(process.env.PORT) || ${options.port ?? 3000} }, (info) => console.log(\`Listening on http://localhost:\${info.port}\`))`,
185
- `const shutdown = () => { server.close(() => process.exit(0)); setTimeout(() => process.exit(1), 10_000).unref() }`,
186
- `process.on('SIGINT', shutdown)`,
187
- `process.on('SIGTERM', shutdown)`,
188
- `export default main`,
189
- ]),
190
- ].join('\n');
158
+ return entryCode(options, paths);
191
159
  },
192
160
  },
193
161
  };
194
162
  }
163
+ /** the code of dist/server/index.js: `paths` are the client build's files and directories (`/robots.txt`, `/assets`) */
164
+ export function entryCode(options, paths) {
165
+ const bun = options.target === 'bun';
166
+ return [
167
+ `import { Hono } from 'hono'`,
168
+ `import { serveStatic } from '${bun ? 'hono/bun' : '@hono/node-server/serve-static'}'`,
169
+ `import { fileURLToPath } from 'node:url'`,
170
+ `import app from '${SERVER.slice(1)}'`,
171
+ `const clientRoot = fileURLToPath(new URL('../client', import.meta.url))`,
172
+ `const main = new Hono()`,
173
+ `main.use('/assets/*', async (c, next) => { await next(); if (c.res.ok) c.header('Cache-Control', 'public, max-age=31536000, immutable') })`,
174
+ // prerender: the pages the build wrote are files, with the headers it decided (prerender.json, written after
175
+ // this server was built: not there while the build prerenders, so the app renders them then)
176
+ ...(options.prerender
177
+ ? [
178
+ `import { existsSync, readFileSync } from 'node:fs'`,
179
+ `import { staticPages } from ${JSON.stringify(staticModule)}`,
180
+ `const prerendered = fileURLToPath(new URL('./prerender.json', import.meta.url))`,
181
+ `if (existsSync(prerendered)) main.use('*', staticPages(serveStatic, clientRoot, JSON.parse(readFileSync(prerendered, 'utf8')).headers))`,
182
+ ]
183
+ : []),
184
+ ...paths.map((p) => `main.use(${JSON.stringify(p)}, serveStatic({ root: clientRoot }))`),
185
+ `main.all('*', (c) => app.fetch(c.req.raw, c.env))`,
186
+ ...(bun
187
+ ? [
188
+ // Bun serves the default export: its `port` (`PORT` first, as on Node), else Bun's own default (PORT, 3000)
189
+ options.port === undefined
190
+ ? `export default app.websocket ? { fetch: main.fetch, websocket: app.websocket } : main`
191
+ : `export default { fetch: main.fetch, port: Number(process.env.PORT) || ${Number(options.port)}, ...(app.websocket && { websocket: app.websocket }) }`,
192
+ ]
193
+ : [
194
+ `import { serve } from '@hono/node-server'`,
195
+ `const server = serve({ fetch: main.fetch, port: Number(process.env.PORT) || ${options.port ?? 3000} }, (info) => console.log(\`Listening on http://localhost:\${info.port}\`))`,
196
+ `const shutdown = () => { server.close(() => process.exit(0)); setTimeout(() => process.exit(1), 10_000).unref() }`,
197
+ `process.on('SIGINT', shutdown)`,
198
+ `process.on('SIGTERM', shutdown)`,
199
+ `export default main`,
200
+ ]),
201
+ ].join('\n');
202
+ }
195
203
  function runtimePlugins(options) {
196
204
  return [
197
205
  {
@@ -38,6 +38,17 @@ export declare function prerender(start: () => Promise<Server>, clientDir: strin
38
38
  }): Promise<undefined>;
39
39
  /** Cloudflare: the built Worker, in the app's own wrangler (fondu does not depend on it) */
40
40
  export declare const worker: (root: string, workerConfig: string) => () => Promise<Server>;
41
- /** Node / Bun: `node dist/server/index.js` (or `bun`), on a free port, until it answers */
42
- export declare const nodeServer: (root: string, runtime: 'node' | 'bun') => () => Promise<Server>;
41
+ /** how long the built server may take to answer, in ms: to start (a wall-clock deadline), and each request, its body read included */
42
+ export interface Deadlines {
43
+ startup: number;
44
+ request: number;
45
+ }
46
+ /**
47
+ * Node / Bun: `node dist/server/index.js` (or `bun`), on a free port, until it answers. This function owns the child
48
+ * until it returns the server: whatever fails before (no such executable, an exit, no answer by the deadline), the
49
+ * child is stopped first. Each request has a deadline of its own, which a body read is within too (its signal).
50
+ */
51
+ export declare const nodeServer: (root: string, runtime: string, { startup, request }?: Deadlines) => () => Promise<Server>;
52
+ /** the files of these pages (decoded), all of which stay inside `dir`, each once and none a directory of another */
53
+ export declare function outputProblems(paths: string[], dir: string): string[];
43
54
  export {};
@@ -3,7 +3,7 @@ import { createHash } from 'node:crypto';
3
3
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
4
4
  import { createRequire } from 'node:module';
5
5
  import { createServer } from 'node:net';
6
- import { dirname, join, resolve } from 'node:path';
6
+ import { dirname, join, resolve, sep } from 'node:path';
7
7
  import { pathToFileURL } from 'node:url';
8
8
  import { PAGE_DATA, staticFiles } from '../paths.js';
9
9
  /** the response headers a static document keeps: the security headers (hono/secure-headers' and the like) */
@@ -101,6 +101,10 @@ export async function prerender(start, clientDir, logger, where) {
101
101
  logger.warn('fondu: prerender is on, and no route has `export const prerender`');
102
102
  return;
103
103
  }
104
+ // every file to write, known before the first: all inside the client directory, none two pages' (or a directory)
105
+ const unsafe = outputProblems(paths, clientDir);
106
+ if (unsafe.length)
107
+ return fail(unsafe);
104
108
  let security;
105
109
  const errors = [];
106
110
  for (const path of paths) {
@@ -145,6 +149,12 @@ export async function prerender(start, clientDir, logger, where) {
145
149
  writeFileSync(file, withHeaderRules(own, security ?? {}));
146
150
  }
147
151
  }
152
+ catch (error) {
153
+ // a request, or the read of its body, that did not finish: the deadline of the server's fetch
154
+ if (timedOut(error))
155
+ fail([`the server did not finish an answer in time (${error.message})`]);
156
+ throw error;
157
+ }
148
158
  finally {
149
159
  await server.dispose();
150
160
  }
@@ -167,35 +177,56 @@ export const worker = (root, workerConfig) => async () => {
167
177
  await started.ready;
168
178
  return {
169
179
  // a Worker that throws as it starts: wrangler logs it, then its requests never answer
180
+ // the signal covers the body's read too, as the Node / Bun server's does (the timer below, its headers only)
170
181
  fetch: (path, headers = {}) => {
171
182
  let timer;
172
183
  const late = new Promise((_, reject) => {
173
184
  timer = setTimeout(() => reject(new Error(`the Worker did not answer ${path} (an error above?)`)), 60_000);
174
185
  });
175
186
  return Promise.race([
176
- started.fetch(new URL(path, 'http://localhost').href, { headers, redirect: 'manual' }),
187
+ started.fetch(new URL(path, 'http://localhost').href, {
188
+ headers,
189
+ redirect: 'manual',
190
+ signal: AbortSignal.timeout(60_000),
191
+ }),
177
192
  late,
178
193
  ]).finally(() => clearTimeout(timer));
179
194
  },
180
195
  dispose: () => started.dispose(),
181
196
  };
182
197
  };
183
- /** Node / Bun: `node dist/server/index.js` (or `bun`), on a free port, until it answers */
184
- export const nodeServer = (root, runtime) => async () => {
198
+ /** a failed request: the server did not answer in time (the timeout and the abort of a signal are DOMExceptions) */
199
+ const timedOut = (error) => error instanceof DOMException && (error.name === 'TimeoutError' || error.name === 'AbortError');
200
+ /**
201
+ * Node / Bun: `node dist/server/index.js` (or `bun`), on a free port, until it answers. This function owns the child
202
+ * until it returns the server: whatever fails before (no such executable, an exit, no answer by the deadline), the
203
+ * child is stopped first. Each request has a deadline of its own, which a body read is within too (its signal).
204
+ */
205
+ export const nodeServer = (root, runtime, { startup, request } = { startup: 30_000, request: 60_000 }) => async () => {
185
206
  const port = await freePort();
186
207
  const child = spawn(runtime, ['dist/server/index.js'], {
187
208
  cwd: root,
188
209
  env: { ...process.env, PORT: String(port), FONDU_PRERENDER: '1', NODE_ENV: 'production' },
189
210
  stdio: ['ignore', 'pipe', 'pipe'],
190
211
  });
212
+ // the last of what it wrote: the reason it gives for failing to start, not all of what a long build writes
191
213
  let output = '';
192
- child.stdout.on('data', (d) => (output += d));
193
- child.stderr.on('data', (d) => (output += d));
214
+ const keep = (d) => (output = (output + d).slice(-16_384));
215
+ child.stdout.on('data', keep);
216
+ child.stderr.on('data', keep);
217
+ // a child that cannot be spawned (no such executable) emits `error`, and, unhandled, that ends the build's process
218
+ let spawnError;
219
+ child.on('error', (error) => (spawnError = error));
194
220
  const base = `http://127.0.0.1:${port}`;
221
+ const gone = () => child.exitCode !== null || child.signalCode !== null || spawnError;
195
222
  const server = {
196
- fetch: (path, headers = {}) => fetch(base + path, { headers, redirect: 'manual' }),
223
+ fetch: (path, headers = {}) => fetch(base + path, {
224
+ headers,
225
+ redirect: 'manual',
226
+ signal: AbortSignal.timeout(request),
227
+ }),
197
228
  dispose: async () => {
198
- if (child.exitCode !== null)
229
+ if (gone())
199
230
  return;
200
231
  const exited = new Promise((r) => child.once('exit', r));
201
232
  child.kill();
@@ -204,17 +235,32 @@ export const nodeServer = (root, runtime) => async () => {
204
235
  clearTimeout(force);
205
236
  },
206
237
  };
207
- for (let tries = 0;; tries++) {
208
- if (child.exitCode !== null || tries === 200)
209
- throw new Error(`the server (${runtime} dist/server/index.js) did not start:\n${output.trim()}`);
210
- try {
211
- await fetch(base + '/__fondu/prerender');
212
- return server;
213
- }
214
- catch {
215
- await new Promise((r) => setTimeout(r, 50));
238
+ try {
239
+ const deadline = Date.now() + startup;
240
+ for (;;) {
241
+ if (spawnError)
242
+ throw new Error(`the server (${runtime} dist/server/index.js) did not start: ${spawnError.message}`);
243
+ if (child.exitCode !== null || child.signalCode !== null || Date.now() >= deadline)
244
+ throw new Error(`the server (${runtime} dist/server/index.js) did not start${gone() ? '' : `: no answer within ${startup / 1000} s`}:\n${output.trim()}`);
245
+ try {
246
+ // an answer, any, or the next try: a server that takes the connection and sends nothing is one try
247
+ const left = Math.max(1, deadline - Date.now());
248
+ const res = await fetch(base + '/__fondu/prerender', {
249
+ redirect: 'manual',
250
+ signal: AbortSignal.timeout(Math.min(2000, left)),
251
+ });
252
+ await res.body?.cancel();
253
+ return server;
254
+ }
255
+ catch {
256
+ await new Promise((r) => setTimeout(r, 50));
257
+ }
216
258
  }
217
259
  }
260
+ catch (error) {
261
+ await server.dispose();
262
+ throw error;
263
+ }
218
264
  };
219
265
  const freePort = () => new Promise((resolve, reject) => {
220
266
  const s = createServer();
@@ -224,7 +270,47 @@ const freePort = () => new Promise((resolve, reject) => {
224
270
  s.close(() => resolve(port));
225
271
  });
226
272
  });
273
+ /** the files of these pages (decoded), all of which stay inside `dir`, each once and none a directory of another */
274
+ export function outputProblems(paths, dir) {
275
+ const problems = [];
276
+ const owner = new Map();
277
+ for (const path of paths) {
278
+ let files;
279
+ try {
280
+ files = Object.values(staticFiles(path));
281
+ }
282
+ catch {
283
+ problems.push(`${path}: not a valid URL path (it does not decode)`);
284
+ continue;
285
+ }
286
+ for (const file of files) {
287
+ if (file.includes('\\') || !inside(dir, file)) {
288
+ problems.push(`${path}: its file (${JSON.stringify(file)}) is not inside the build's directory`);
289
+ continue;
290
+ }
291
+ const other = owner.get(file);
292
+ if (other !== undefined)
293
+ problems.push(`${path} and ${other} are the same file (${file})`);
294
+ else
295
+ owner.set(file, path);
296
+ }
297
+ }
298
+ // a page's file that is another's directory (`/a.html` is `a.html.html`, but `/a` is `a.html`: `/a.html/b` its child)
299
+ for (const [file, path] of owner)
300
+ for (let at = file.indexOf('/'); at !== -1; at = file.indexOf('/', at + 1)) {
301
+ const other = owner.get(file.slice(0, at));
302
+ if (other !== undefined)
303
+ problems.push(`${path} needs ${file.slice(0, at)} to be a directory, the file of ${other}`);
304
+ }
305
+ return problems;
306
+ }
307
+ const inside = (dir, file) => {
308
+ const to = resolve(dir, file);
309
+ return to.startsWith(resolve(dir) + sep);
310
+ };
227
311
  function write(dir, file, content) {
312
+ if (!inside(dir, file))
313
+ throw new Error(`fondu: ${JSON.stringify(file)} is not inside ${dir}`);
228
314
  const to = join(dir, file);
229
315
  mkdirSync(dirname(to), { recursive: true });
230
316
  writeFileSync(to, content);
@@ -79,16 +79,19 @@ function references(node, out = new Set(), scopes = []) {
79
79
  case 'FunctionDeclaration':
80
80
  case 'FunctionExpression':
81
81
  case 'ArrowFunctionExpression': {
82
- const scope = new Set();
82
+ // the parameters' scope (a function expression's own name, the parameters): what their default expressions
83
+ // see. The body's own declarations are another scope, inside it: a default never reaches them
84
+ const params = new Set();
83
85
  if (n.type === 'FunctionExpression')
84
- bound(n.id, []).forEach((x) => scope.add(x));
86
+ bound(n.id, []).forEach((x) => params.add(x));
85
87
  for (const p of n.params)
86
- bound(p).forEach((x) => scope.add(x));
87
- vars(n.body, scope);
88
+ bound(p).forEach((x) => params.add(x));
89
+ const body = new Set();
90
+ vars(n.body, body);
88
91
  if (n.body.type === 'BlockStatement')
89
- lexical(n.body.body, scope);
90
- visit(n.params, [...scopes, scope]);
91
- visit(n.body, [...scopes, scope]);
92
+ lexical(n.body.body, body);
93
+ visit(n.params, [...scopes, params]);
94
+ visit(n.body, [...scopes, params, body]);
92
95
  return out;
93
96
  }
94
97
  case 'ClassDeclaration':
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fondu",
3
- "version": "0.16.2",
3
+ "version": "0.18.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",