fondu 0.10.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,26 @@
1
1
  /**
2
2
  * The bar: shown once a navigation has run for `delay`, growing towards the end while it runs (one long CSS
3
- * transition, slower as it gets there), filled and faded out when it is done. Drawn with CSSOM styles (no stylesheet,
4
- * nothing for a Content Security Policy to refuse), above the page, out of the accessibility tree: `useNavigating()`
5
- * is the app's way to say it in its own words. With reduced motion, a still bar.
3
+ * transition, slower as it gets there), filled, then faded out, when it is done. Drawn with CSSOM styles (no
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.
6
6
  */
7
7
  export function progressBar({ delay = 350, color = 'currentColor' }, pending) {
8
8
  const still = matchMedia('(prefers-reduced-motion: reduce)');
9
9
  let bar;
10
10
  let wait;
11
+ const bars = new Set(); // on the screen, the one fading out included
12
+ // leaving the document: no bar kept in the back/forward cache, to be seen again on Back
13
+ addEventListener('pagehide', () => {
14
+ clearTimeout(wait);
15
+ wait = bar = undefined;
16
+ for (const el of bars)
17
+ el.remove();
18
+ bars.clear();
19
+ });
11
20
  const show = () => {
12
21
  wait = undefined;
13
22
  const el = (bar = document.createElement('div')); // a new one: the last may still be fading out
23
+ bars.add(el);
14
24
  Object.assign(el.style, {
15
25
  position: 'fixed',
16
26
  inset: '0 0 auto',
@@ -36,11 +46,14 @@ export function progressBar({ delay = 350, color = 'currentColor' }, pending) {
36
46
  bar = undefined;
37
47
  if (!el)
38
48
  return;
39
- // from where it is: a transition starts from the value on the screen
40
- el.style.transition = 'transform 200ms ease-out, opacity 200ms 100ms';
49
+ // filled from where it is (a transition starts from the value on the screen), then faded out
50
+ el.style.transition = 'transform 200ms ease-out, opacity 200ms 200ms';
41
51
  el.style.transform = 'scaleX(1)';
42
52
  el.style.opacity = '0';
43
- setTimeout(() => el.remove(), 400);
53
+ setTimeout(() => {
54
+ el.remove();
55
+ bars.delete(el);
56
+ }, 450);
44
57
  };
45
58
  return () => {
46
59
  if (!pending())
package/dist/paths.d.ts CHANGED
@@ -25,10 +25,22 @@ export declare function layoutsOf(file: string): string[];
25
25
  export declare function middlewareFor(file: string, middleware: readonly string[]): string[];
26
26
  /** `/users/:id` + `{ id: 7 }` → `/users/7`; catch-alls keep their slashes */
27
27
  export declare function fillPattern(pattern: string, params?: Record<string, string | number>): string;
28
+ /** fondu/client's scroll positions: each history entry's key in `history.state`, its position in sessionStorage */
29
+ export declare const SCROLL_KEY = "__fondu";
30
+ export declare const SCROLL_STORAGE = "fondu-scroll:";
28
31
  /** where prerendered pages keep their page objects (`fondu({ prerender: true })`) */
29
32
  export declare const PAGE_DATA = "/_fondu/pages";
30
- /** a page's URL path → the URL of its page object: `/docs/intro` → `/_fondu/pages/docs/intro.json` (`/` → `/index`) */
33
+ /**
34
+ * a page's URL path → the URL of its page object, one for one whatever the app's trailing slashes: `/docs/intro` →
35
+ * `/_fondu/pages/docs/intro.json`; a trailing slash is `index` (`/docs/` → `…/docs/index.json`, `/` →
36
+ * `…/index.json`), and a last segment named index (or ~index…) gets one more `~` (`/items/index` → `…/items/~index.json`)
37
+ */
31
38
  export declare function pageDataPath(path: string): string;
39
+ /**
40
+ * a path whose last segment is index (`/index`, `/docs/%69ndex`): its static file would be its directory's
41
+ * (`index.html`, `docs/index.html`), which is another page
42
+ */
43
+ export declare const endsInIndex: (path: string) => boolean;
32
44
  /** the other way: `/_fondu/pages/docs/intro.json` → `/docs/intro`; null for any other path */
33
45
  export declare function pathOfPageData(pathname: string): string | null;
34
46
  /** the files of a prerendered page: `/docs/intro` → `docs/intro.html` and `_fondu/pages/docs/intro.json` (decoded) */
package/dist/paths.js CHANGED
@@ -9,10 +9,11 @@
9
9
  * - `_middleware.ts` applies to its directory
10
10
  */
11
11
  export function routePatterns(file) {
12
- const segments = file
13
- .replace(ROUTE_EXTENSION, '')
14
- .split('/')
15
- .filter((s) => s !== '' && s !== 'index' && !/^\(.+\)$/.test(s));
12
+ const parts = file.replace(ROUTE_EXTENSION, '').split('/');
13
+ // the file named index is its directory; a directory named index is a segment like any other
14
+ if (parts.at(-1) === 'index')
15
+ parts.pop();
16
+ const segments = parts.filter((s) => s !== '' && !/^\(.+\)$/.test(s));
16
17
  const optional = segments.filter((s) => /^\[\[(?:\.\.\.)?\w+\]\]$/.test(s));
17
18
  if (optional.some((s) => s.startsWith('[[...')))
18
19
  throw new Error(`fondu: routes/${file}: an optional catch-all isn't a route; index.ts and [...path].ts are`);
@@ -72,16 +73,46 @@ export function fillPattern(pattern, params = {}) {
72
73
  return parts.map(encodeURIComponent).join('/');
73
74
  });
74
75
  }
76
+ /** fondu/client's scroll positions: each history entry's key in `history.state`, its position in sessionStorage */
77
+ export const SCROLL_KEY = '__fondu';
78
+ export const SCROLL_STORAGE = 'fondu-scroll:';
75
79
  /** where prerendered pages keep their page objects (`fondu({ prerender: true })`) */
76
80
  export const PAGE_DATA = '/_fondu/pages';
77
- /** a page's URL path → the URL of its page object: `/docs/intro` → `/_fondu/pages/docs/intro.json` (`/` → `/index`) */
81
+ /**
82
+ * a page's URL path → the URL of its page object, one for one whatever the app's trailing slashes: `/docs/intro` →
83
+ * `/_fondu/pages/docs/intro.json`; a trailing slash is `index` (`/docs/` → `…/docs/index.json`, `/` →
84
+ * `…/index.json`), and a last segment named index (or ~index…) gets one more `~` (`/items/index` → `…/items/~index.json`)
85
+ */
78
86
  export function pageDataPath(path) {
79
- return `${PAGE_DATA}${path.endsWith('/') ? path + 'index' : path}.json`;
87
+ const last = path.slice(path.lastIndexOf('/') + 1);
88
+ // as the server reads it, decoded: `%69ndex` is index too (written as it, of unreserved characters)
89
+ const named = path.endsWith('/')
90
+ ? `${path}index`
91
+ : /^~*index$/.test(decoded(last))
92
+ ? `${path.slice(0, -last.length)}~${decoded(last)}`
93
+ : path;
94
+ return `${PAGE_DATA}${named}.json`;
80
95
  }
96
+ /** a URL segment decoded, or as it is if it doesn't decode */
97
+ function decoded(segment) {
98
+ try {
99
+ return decodeURIComponent(segment);
100
+ }
101
+ catch {
102
+ return segment;
103
+ }
104
+ }
105
+ /**
106
+ * a path whose last segment is index (`/index`, `/docs/%69ndex`): its static file would be its directory's
107
+ * (`index.html`, `docs/index.html`), which is another page
108
+ */
109
+ export const endsInIndex = (path) => decoded(path.slice(path.lastIndexOf('/') + 1)) === 'index';
81
110
  /** the other way: `/_fondu/pages/docs/intro.json` → `/docs/intro`; null for any other path */
82
111
  export function pathOfPageData(pathname) {
83
112
  const m = pathname.match(/^\/_fondu\/pages(\/.+)\.json$/);
84
- return m ? m[1].replace(/\/index$/, '/') : null;
113
+ if (!m)
114
+ return null;
115
+ return m[1].replace(/(?<=\/)index$/, '').replace(/(?<=\/)~(~*index)$/, '$1');
85
116
  }
86
117
  /** the files of a prerendered page: `/docs/intro` → `docs/intro.html` and `_fondu/pages/docs/intro.json` (decoded) */
87
118
  export function staticFiles(path) {
@@ -1,5 +1,6 @@
1
1
  import { assetTags } from 'virtual:fondu/assets';
2
2
  import { renderMarkup, renderPage } from 'virtual:fondu/ssr';
3
+ import { SCROLL_KEY, SCROLL_STORAGE } from '../paths.js';
3
4
  const defaultTemplate = ({ head, body }) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">${head}</head><body>${body}</body></html>`;
4
5
  /** the options of the app (`createApp`) a request belongs to */
5
6
  export const settings = new WeakMap();
@@ -15,6 +16,13 @@ export const withoutSsr = () => async (c, next) => {
15
16
  };
16
17
  /** the page data, `/` and `<` escaped (no `</script>` in it), no HTML entities */
17
18
  const pageScript = (page) => `<script data-page="app" type="application/json">${JSON.stringify(page).replace(/\//g, '\\/').replace(/</g, '\\u003c')}</script>`;
19
+ /**
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), 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.
24
+ */
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>`;
18
26
  // where the page goes, in the document a template returns: replaced before the page is in, so a page's content is
19
27
  // never read as one
20
28
  const HEAD = 'fondu:document-head';
@@ -46,11 +54,24 @@ export async function renderDocument(c, page) {
46
54
  }
47
55
  // the page data first: the client reads the first `script[data-page]` in the document, so nothing in the page's
48
56
  // content can come before it
49
- const body = pageScript(page) + (ssr?.body ?? '<div id="app"></div>');
57
+ // the position back for a page rendered here (one rendered in the browser has nothing to scroll yet)
58
+ const body = pageScript(page) + (ssr ? ssr.body + restoreScroll(nonce) : '<div id="app"></div>');
50
59
  const template = settings.get(c)?.document ?? defaultTemplate;
51
60
  const html = await shell(template, c, nonce);
52
61
  const [before, between, after, ...more] = html.split(new RegExp(`${HEAD}|${BODY}`));
53
62
  if (after === undefined || more.length || html.indexOf(HEAD) > html.indexOf(BODY))
54
63
  throw new Error('fondu: the document must have `head` once, in <head>, and `body` once, in <body>');
55
- return before + (ssr?.head ?? '') + assetTags(page.component, nonce) + between + body + after;
64
+ // the stylesheets first, right after <meta charset>: found, and asked for, before anything else of the head, the
65
+ // document's own tags included (React puts a JSX document's links and metas before `head`). A browser that lays
66
+ // the page out early (Firefox's, with its tools open) has them sooner
67
+ const tags = assetTags(page.component, nonce);
68
+ const css = tags.match(/<link rel="stylesheet"[^>]*>/g)?.join('') ?? '';
69
+ const charset = /<meta charset=[^>]*>/i;
70
+ const top = css && charset.test(before) ? before.replace(charset, (meta) => meta + css) : before + css;
71
+ return (top +
72
+ tags.replace(/<link rel="stylesheet"[^>]*>/g, '') +
73
+ (ssr?.head ?? '') +
74
+ between +
75
+ body +
76
+ after);
56
77
  }
@@ -80,5 +80,7 @@ import { createHotContext } from '${import.meta.env.BASE_URL}@vite/client'
80
80
  const hot = createHotContext('/@fondu/error-report')
81
81
  hot.on('fondu:props', () => location.reload())
82
82
  hot.on('vite:afterUpdate', () => location.reload())
83
+ // Back and Forward to the app's entries before it (this document may be given them): their URL as a document
84
+ addEventListener('popstate', () => location.reload())
83
85
  </script></body></html>`;
84
86
  }
@@ -1,4 +1,4 @@
1
- import { fillPattern, PAGE_DATA, pathOfPageData, staticFiles } from '../paths.js';
1
+ import { endsInIndex, fillPattern, PAGE_DATA, pathOfPageData, staticFiles } from '../paths.js';
2
2
  import { isPageRequest } from './http.js';
3
3
  /** Node / Bun: reads a file of the client build (`docs/intro.html`), or null; set by the built server's entry */
4
4
  const STATIC_FILES = Symbol.for('fondu.staticFiles');
@@ -19,16 +19,21 @@ export async function prerenderPaths(routes) {
19
19
  continue;
20
20
  }
21
21
  const dynamic = route.pattern.includes(':');
22
+ // a page whose URL ends in index: its file would be its directory's page's (index.html), another page
23
+ const add = (path) => endsInIndex(path)
24
+ ? problems.push(`${where}: ${path} ends in index, so its static file would be the page of its directory: ` +
25
+ `leave it out of \`prerender\``)
26
+ : paths.add(path);
22
27
  if (setting === true) {
23
28
  if (dynamic)
24
29
  problems.push(`${where} is dynamic: \`export const prerender = () => [{ …params }]\` lists its pages, or \`= false\``);
25
30
  else
26
- paths.add(route.pattern);
31
+ add(route.pattern);
27
32
  continue;
28
33
  }
29
34
  try {
30
35
  for (const params of await setting())
31
- paths.add(fillPattern(route.pattern, params));
36
+ add(fillPattern(route.pattern, params));
32
37
  }
33
38
  catch (error) {
34
39
  problems.push(`${where}: ${error instanceof Error ? error.message : String(error)}`);
@@ -50,6 +55,9 @@ export function prerenderRoutes(app, routes, version) {
50
55
  const data = pathOfPageData(c.req.path) !== null; // a navigation, rewritten to the page object by fondu/client
51
56
  if (!data && (isPageRequest(c) || !(c.req.header('accept') ?? '').includes('text/html')))
52
57
  return next();
58
+ // a URL ending in index is never a static document: that file is its directory's page (the routes answer it)
59
+ if (!data && endsInIndex(c.req.path))
60
+ return next();
53
61
  let file;
54
62
  try {
55
63
  file = data ? decodeURIComponent(c.req.path).slice(1) : staticFiles(c.req.path).html;
@@ -81,7 +89,7 @@ export function prerenderRoutes(app, routes, version) {
81
89
  app.get(`${PAGE_DATA}/*`, (c) => {
82
90
  const path = pathOfPageData(c.req.path);
83
91
  // a page object's own URL is not a page: no page object of a page object (and so on)
84
- if (!path || path.startsWith(`${PAGE_DATA}/`))
92
+ if (!path || path.startsWith('/_fondu/'))
85
93
  return c.notFound();
86
94
  const url = new URL(c.req.url);
87
95
  url.pathname = path;
@@ -81,23 +81,25 @@ const versionCheck = async (c, next) => {
81
81
  await next();
82
82
  // a URL answers a navigation and a document differently: caches keep them apart
83
83
  appendHeader(c, 'Vary', 'X-Fondu');
84
- // an empty answer to a form (an action that returns nothing to show): back to the page
85
- if (isPageRequest(c) &&
86
- c.res.status === 200 &&
87
- !c.res.headers.has('x-fondu') &&
88
- (await c.res.clone().text()) === '')
84
+ // an empty answer to a form (an action that returns nothing to show, `c.body(null)`): back to the page. Its body
85
+ // isn't read to tell (a stream's would be, to its end)
86
+ if (isPageRequest(c) && c.res.status === 200 && !c.res.headers.has('x-fondu') && !c.res.body)
89
87
  c.res = back(c);
90
88
  const to = c.res.headers.get('location');
91
89
  if (isPageRequest(c) && c.res.status >= 300 && c.res.status < 400 && to) {
92
90
  // to another site: fetch() can't follow it (CORS), the client loads it as a document; http(s) only (a browser
93
91
  // follows no redirect to `javascript:`, and neither does the client)
94
- if (!sameOrigin(c, to)) {
92
+ const here = sameOrigin(c, to);
93
+ if (!here) {
95
94
  if (webUrl(c, to))
96
95
  c.res = c.body(null, 409, { 'X-Fondu-Location': to });
97
96
  }
98
- // to a #fragment: fetch() follows it, the fragment lost (a Response's URL has none); the client follows
97
+ // to a #fragment: fetch() follows it, the fragment lost (a Response's URL has none); the client follows, from
98
+ // this site's root (a relative Location is the request's, not the page's on the screen)
99
99
  else if (to.includes('#'))
100
- c.res = c.body(null, 200, { 'X-Fondu-Redirect': to });
100
+ c.res = c.body(null, 200, {
101
+ 'X-Fondu-Redirect': here.pathname.replace(/^\/+/, '/') + here.search + here.hash,
102
+ });
101
103
  }
102
104
  };
103
105
  export const protocol = [flashCookie, versionCheck];
@@ -35,9 +35,10 @@ export declare class ValidationError extends Error {
35
35
  export declare function validationErrorResponse(c: Context, error: ValidationError): Response;
36
36
  /**
37
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. Names that would change the object itself
39
- * (`__proto__`…) are ignored. A body that can't be one object (JSON that doesn't parse, `a=1&a[b]=2`, names nested
40
- * deeper than 32) is a 400.
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.
41
42
  */
42
43
  export declare function readBody(c: Context): Promise<unknown>;
43
44
  /** What `withValidator` checks: the request body (JSON or form), the query, the route params. */
@@ -24,19 +24,23 @@ export function validationErrorResponse(c, error) {
24
24
  const DEPTH = 32;
25
25
  /**
26
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. Names that would change the object itself
28
- * (`__proto__`…) are ignored. A body that can't be one object (JSON that doesn't parse, `a=1&a[b]=2`, names nested
29
- * deeper than 32) is a 400.
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.
30
31
  */
31
32
  export async function readBody(c) {
32
33
  const malformed = (why) => new HTTPException(400, { message: `Malformed request body: ${why}` });
33
- const type = c.req.header('content-type') ?? '';
34
+ const type = (c.req.header('content-type') ?? '').toLowerCase();
34
35
  if (type.includes('application/json'))
35
36
  return c.req.json().catch(() => Promise.reject(malformed('invalid JSON')));
36
37
  if (!type.includes('multipart/form-data') && !type.includes('application/x-www-form-urlencoded'))
37
38
  return {};
38
- const form = await c.req.formData();
39
+ const form = await c.req.formData().catch(() => Promise.reject(malformed('invalid form data')));
39
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);
40
44
  for (const [key, value] of form.entries()) {
41
45
  if (typeof value !== 'string' && value.size === 0 && value.name === '')
42
46
  continue;
@@ -47,25 +51,19 @@ export async function readBody(c) {
47
51
  continue;
48
52
  let target = body;
49
53
  path.forEach((segment, i) => {
50
- const name = segment === '' ? String(Object.keys(target).length) : segment; // `a[]`: the next index
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));
51
57
  const has = Object.hasOwn(target, name);
52
58
  if (i === path.length - 1) {
53
- if (has &&
54
- typeof target[name] === 'object' &&
55
- !(target[name] instanceof File) &&
56
- !Array.isArray(target[name]))
59
+ if (has && isObject(target[name]))
57
60
  throw malformed(`\`${key}\` is both a value and an object`);
58
- if (has && path.length === 1)
59
- target[name] = [target[name], value].flat(); // `a=1&a=2`
60
- else
61
- target[name] = value;
61
+ target[name] = has ? [target[name], value].flat() : value; // given again: a list
62
62
  }
63
63
  else {
64
64
  if (!has)
65
65
  target[name] = Object.create(null);
66
- else if (typeof target[name] !== 'object' ||
67
- target[name] instanceof File ||
68
- Array.isArray(target[name]))
66
+ else if (!isObject(target[name]))
69
67
  throw malformed(`\`${key}\` is both a value and an object`);
70
68
  target = target[name];
71
69
  }
@@ -94,8 +92,9 @@ export function validator(schemas) {
94
92
  query: () => c.req.query(),
95
93
  params: () => c.req.param(),
96
94
  };
97
- const input = {};
98
- const errors = {};
95
+ // no prototype: a field named `toString` or `constructor` is a field like any other
96
+ const input = Object.create(null);
97
+ const errors = Object.create(null);
99
98
  for (const key of Object.keys(schemas)) {
100
99
  const result = await schemas[key]['~standard'].validate(await values[key]());
101
100
  // route params that don't fit: the URL names nothing here
@@ -1,5 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { appendFileSync, existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { appendFileSync, existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
3
3
  import { builtinModules, createRequire } from 'node:module';
4
4
  import { dirname, join, relative, resolve, sep } from 'node:path';
5
5
  import { pathToFileURL } from 'node:url';
@@ -294,6 +294,7 @@ function core(options) {
294
294
  if (options.prerender && existsSync(wrangler)) {
295
295
  const clientDir = resolve(config.root, client.config.build.outDir);
296
296
  await prerender(worker(config.root, wrangler), clientDir, config.logger, true);
297
+ workerFirstForIndex(wrangler);
297
298
  }
298
299
  }
299
300
  },
@@ -495,6 +496,20 @@ const isServerOnly = (id, root) => {
495
496
  (file.startsWith(`${root}/app/routes/`) && file.endsWith('.ts')) ||
496
497
  file === `${root}/app/server.ts`);
497
498
  };
499
+ /**
500
+ * The built Worker's config: URLs ending in index go to the Worker first. Static assets would answer them with the
501
+ * page of their directory (`/docs/index` → `docs/index.html`, redirected to `/docs/`), while a route (a param's value)
502
+ * may be theirs. Added to the app's own `run_worker_first`, unless it is `true` (every request first) already.
503
+ */
504
+ function workerFirstForIndex(file) {
505
+ const config = JSON.parse(readFileSync(file, 'utf8'));
506
+ const assets = (config.assets ??= {});
507
+ if (assets.run_worker_first === true)
508
+ return;
509
+ const own = Array.isArray(assets.run_worker_first) ? assets.run_worker_first : [];
510
+ assets.run_worker_first = [...new Set([...own, '/index', '/*/index'])];
511
+ writeFileSync(file, JSON.stringify(config));
512
+ }
498
513
  const nonceAttr = `\${nonce ? \` nonce="\${nonce}"\` : ''}`;
499
514
  function devAssets(base) {
500
515
  const preamble = `import RefreshRuntime from "${base}@react-refresh";RefreshRuntime.injectIntoGlobalHook(window);window.$RefreshReg$=()=>{};window.$RefreshSig$=()=>(type)=>type;window.__vite_plugin_react_preamble_installed__=true;window.__getReactRefreshIgnoredExports=({id})=>window.${PAGE_EXPORTS}?.[id]??[]`;
@@ -9,7 +9,7 @@ type Node = {
9
9
  };
10
10
  /**
11
11
  * The browser's copy of a page's route file: its server exports removed (`loader`, `action`, `actions`…), then
12
- * what only they used: imports and top-level declarations no other code names, until none is left. Conservative: a
12
+ * what only they used: the imports and top-level declarations the code kept doesn't reach. Conservative: a
13
13
  * name the code kept refers to keeps its declaration, so what is left over is at worst unused code, which
14
14
  * Fondu's server-only guard stops when it is server code (`*.server.ts`, `routes/*.ts`). Lines stay where they were.
15
15
  */
@@ -171,7 +171,7 @@ function lexical(statements, scope = new Set()) {
171
171
  }
172
172
  /**
173
173
  * The browser's copy of a page's route file: its server exports removed (`loader`, `action`, `actions`…), then
174
- * what only they used: imports and top-level declarations no other code names, until none is left. Conservative: a
174
+ * what only they used: the imports and top-level declarations the code kept doesn't reach. Conservative: a
175
175
  * name the code kept refers to keeps its declaration, so what is left over is at worst unused code, which
176
176
  * Fondu's server-only guard stops when it is server code (`*.server.ts`, `routes/*.ts`). Lines stay where they were.
177
177
  */
@@ -223,28 +223,33 @@ export function stripServerCode(code, program, file) {
223
223
  else if (['VariableDeclaration', 'FunctionDeclaration', 'ClassDeclaration'].includes(node.type))
224
224
  part.declares = bound(node);
225
225
  }
226
- // what nobody names goes, until nothing more does
227
- for (let changed = true; changed;) {
228
- changed = false;
229
- const live = (part) => part.text !== '';
230
- for (const part of parts) {
231
- if (!live(part) || !part.declares.length)
226
+ // what the code kept reaches stays, the rest goes: declarations that only name each other (a loader's helpers
227
+ // calling one another) go together
228
+ const kept = (part) => part.text !== '';
229
+ const live = new Set(parts.filter((part) => kept(part) && !part.declares.length));
230
+ const reached = new Set();
231
+ for (const queue = [...live]; queue.length;)
232
+ for (const name of queue.pop().uses) {
233
+ if (reached.has(name))
232
234
  continue;
233
- const used = (name) => parts.some((other) => other !== part && live(other) && other.uses.has(name));
234
- if (part.node.type === 'ImportDeclaration') {
235
- const specifiers = part.node.specifiers;
236
- const kept = specifiers.filter((s) => used(nameOf(s.local)));
237
- if (kept.length === part.declares.length)
238
- continue;
239
- changed = true;
240
- part.declares = kept.map((s) => nameOf(s.local));
241
- part.text = kept.length ? importOf(code, part.node, kept) : '';
242
- }
243
- else if (!part.declares.some(used)) {
244
- changed = true;
245
- part.text = '';
246
- }
235
+ reached.add(name);
236
+ for (const part of parts)
237
+ if (kept(part) && !live.has(part) && part.declares.includes(name)) {
238
+ live.add(part);
239
+ queue.push(part);
240
+ }
241
+ }
242
+ for (const part of parts) {
243
+ if (!kept(part) || !part.declares.length)
244
+ continue;
245
+ if (part.node.type === 'ImportDeclaration') {
246
+ const specifiers = part.node.specifiers;
247
+ const used = specifiers.filter((s) => reached.has(nameOf(s.local)));
248
+ if (used.length < specifiers.length)
249
+ part.text = used.length ? importOf(code, part.node, used) : '';
247
250
  }
251
+ else if (!live.has(part))
252
+ part.text = '';
248
253
  }
249
254
  for (const part of parts)
250
255
  if (part.text !== '')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fondu",
3
- "version": "0.10.0",
3
+ "version": "0.11.1",
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",