fondu 0.1.3 → 0.3.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.
@@ -0,0 +1,28 @@
1
+ import type { Plugin } from 'vite';
2
+ /** the browser's event for "the current page's props may have changed" (the client entry: Inertia's reload) */
3
+ export declare const PROPS_EVENT = "fondu:props";
4
+ /** the global the dev preamble reads: the named exports of each page module (`__getReactRefreshIgnoredExports`) */
5
+ export declare const PAGE_EXPORTS = "__fondu_pageExports";
6
+ type Node = {
7
+ file: string | null;
8
+ importers: Set<Node>;
9
+ };
10
+ /**
11
+ * What a change to a module reaches on the server, through the app's own modules only (app/, not node_modules nor
12
+ * fondu): a route (`app/routes/…`: what it renders may have changed), and the document (`app/server.ts`, reached
13
+ * other than through a route or the pages' entry). `app/app.tsx` is the pages' entry: the browser's own HMR.
14
+ */
15
+ export declare function reach(start: Iterable<Node>, root: string): {
16
+ routes: boolean;
17
+ document: boolean;
18
+ };
19
+ /**
20
+ * Dev: a change updates what it changes, without reloading the page where it can.
21
+ * - The browser's code: React Fast Refresh (`@vitejs/plugin-react`), MDX pages too. A page module's other exports
22
+ * (an MDX page's `toc`) are left out of Fast Refresh's check: the server reads them, and the next rule applies.
23
+ * - What a route depends on: the browser asks for the page's props again (Inertia's `router.reload()`), its state
24
+ * and scroll kept, as React Router's "Hot Data Revalidation".
25
+ * - The document (`server.ts` and what only it imports): the page reloads.
26
+ */
27
+ export declare function hmr(): Plugin;
28
+ export {};
@@ -0,0 +1,106 @@
1
+ import { relative, sep } from 'node:path';
2
+ import { isPageFile } from '../paths.js';
3
+ /** the browser's event for "the current page's props may have changed" (the client entry: Inertia's reload) */
4
+ export const PROPS_EVENT = 'fondu:props';
5
+ /** the global the dev preamble reads: the named exports of each page module (`__getReactRefreshIgnoredExports`) */
6
+ export const PAGE_EXPORTS = '__fondu_pageExports';
7
+ /**
8
+ * What a change to a module reaches on the server, through the app's own modules only (app/, not node_modules nor
9
+ * fondu): a route (`app/routes/…`: what it renders may have changed), and the document (`app/server.ts`, reached
10
+ * other than through a route or the pages' entry). `app/app.tsx` is the pages' entry: the browser's own HMR.
11
+ */
12
+ export function reach(start, root) {
13
+ const found = { routes: false, document: false };
14
+ const seen = new Set();
15
+ const queue = [...start];
16
+ while (queue.length) {
17
+ const mod = queue.shift();
18
+ if (seen.has(mod) || !mod.file)
19
+ continue;
20
+ seen.add(mod);
21
+ const rel = relative(root, mod.file).split(sep).join('/');
22
+ if (rel.startsWith('..') || rel.includes('node_modules/') || !rel.startsWith('app/'))
23
+ continue;
24
+ if (rel.startsWith('app/routes/'))
25
+ found.routes = true;
26
+ else if (rel === 'app/server.ts')
27
+ found.document = true;
28
+ else if (rel !== 'app/app.tsx')
29
+ queue.push(...mod.importers);
30
+ }
31
+ return found;
32
+ }
33
+ /**
34
+ * Dev: a change updates what it changes, without reloading the page where it can.
35
+ * - The browser's code: React Fast Refresh (`@vitejs/plugin-react`), MDX pages too. A page module's other exports
36
+ * (an MDX page's `toc`) are left out of Fast Refresh's check: the server reads them, and the next rule applies.
37
+ * - What a route depends on: the browser asks for the page's props again (Inertia's `router.reload()`), its state
38
+ * and scroll kept, as React Router's "Hot Data Revalidation".
39
+ * - The document (`server.ts` and what only it imports): the page reloads.
40
+ */
41
+ export function hmr() {
42
+ let root = process.cwd();
43
+ return {
44
+ name: 'fondu:hmr',
45
+ apply: 'serve',
46
+ configResolved(c) {
47
+ root = c.root;
48
+ },
49
+ // the named exports of a page module, for the dev preamble's `__getReactRefreshIgnoredExports`
50
+ transform: {
51
+ order: 'post',
52
+ handler(code, id) {
53
+ if (this.environment.config.consumer !== 'client')
54
+ return;
55
+ const file = id.split('?')[0];
56
+ const rel = relative(`${root}/app/pages`, file).split(sep).join('/');
57
+ if (rel.startsWith('..') || !isPageFile(rel))
58
+ return;
59
+ const names = namedExports(this.parse(code));
60
+ if (!names.length)
61
+ return;
62
+ return {
63
+ code: `${code}\n;(window.${PAGE_EXPORTS} ??= {})[${JSON.stringify(file)}] = ${JSON.stringify(names)};\n`,
64
+ map: null,
65
+ };
66
+ },
67
+ },
68
+ hotUpdate({ file, server }) {
69
+ if (this.environment.name !== 'client')
70
+ return;
71
+ const servers = Object.values(server.environments).filter((env) => env.name !== 'client');
72
+ const onServer = servers.flatMap((env) => [...(env.moduleGraph.getModulesByFile(file) ?? [])]);
73
+ if (!onServer.length)
74
+ return; // the browser's only (or a file a stylesheet watches, as Tailwind's sources)
75
+ const { routes, document } = reach(onServer, root);
76
+ const client = this.environment;
77
+ if (document) {
78
+ client.hot.send({ type: 'full-reload' });
79
+ return [];
80
+ }
81
+ // once the server's modules are updated (they are, in this same update, after the browser's)
82
+ if (routes)
83
+ setTimeout(() => client.hot.send(PROPS_EVENT, {}));
84
+ const inBrowser = [...(client.moduleGraph.getModulesByFile(file) ?? [])].some((m) => m.type === 'js');
85
+ if (!inBrowser)
86
+ return [];
87
+ },
88
+ };
89
+ }
90
+ /** the names a module exports other than `default` */
91
+ function namedExports(program) {
92
+ const names = [];
93
+ for (const node of program.body) {
94
+ if (node.type !== 'ExportNamedDeclaration')
95
+ continue;
96
+ const declaration = node.declaration;
97
+ if (declaration?.id)
98
+ names.push(declaration.id.name);
99
+ for (const d of declaration?.declarations ?? [])
100
+ if (d.id.type === 'Identifier')
101
+ names.push(d.id.name);
102
+ for (const s of node.specifiers ?? [])
103
+ names.push(s.exported.name ?? s.exported.value);
104
+ }
105
+ return names.filter((n) => n !== 'default');
106
+ }
@@ -15,5 +15,12 @@ export interface FonduOptions {
15
15
  /** `false`: pages render in the browser only, no server render is built (an admin app). Per route: `withoutSsr()` */
16
16
  ssr?: boolean;
17
17
  react?: ReactOptions;
18
+ /**
19
+ * Routes with `export const prerender` (or under a `_middleware.ts` with it) are written as static files at build
20
+ * time, and visits read them; the server (the Worker) answers the other pages
21
+ */
22
+ prerender?: boolean;
18
23
  }
24
+ /** what fondu's server code imports from Hono (test/hono.test.ts keeps the list complete) */
25
+ export declare const HONO: string[];
19
26
  export default function fondu(options: FonduOptions): PluginOption[];
@@ -1,13 +1,28 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { appendFileSync, existsSync, readdirSync, readFileSync } from 'node:fs';
3
3
  import { createRequire } from 'node:module';
4
4
  import { dirname, join, resolve } from 'node:path';
5
5
  import { pathToFileURL } from 'node:url';
6
6
  import devServer, { defaultOptions as devServerDefaults } from '@hono/vite-dev-server';
7
7
  import inertia from '@inertiajs/vite';
8
8
  import react, {} from '@vitejs/plugin-react';
9
+ import { isPageFile } from '../paths.js';
10
+ import { hmr, PAGE_EXPORTS, PROPS_EVENT } from './hmr.js';
11
+ import { layouts } from './layouts.js';
12
+ import { nodeServer, prerender, worker } from './prerender.js';
9
13
  import { typegen } from './typegen.js';
10
14
  const ENTRY = 'app/app.tsx';
15
+ /** what fondu's server code imports from Hono (test/hono.test.ts keeps the list complete) */
16
+ export const HONO = [
17
+ 'hono',
18
+ 'hono/combine',
19
+ 'hono/cookie',
20
+ 'hono/csrf',
21
+ 'hono/factory',
22
+ 'hono/http-exception',
23
+ 'hono/secure-headers',
24
+ 'hono/trailing-slash',
25
+ ];
11
26
  const SERVER = './app/server.ts';
12
27
  const DEV_CSS = '/@fondu/dev.css';
13
28
  const V = { assets: 'virtual:fondu/assets', ssr: 'virtual:fondu/ssr' };
@@ -18,7 +33,7 @@ const resolved = (id) => '\0' + id;
18
33
  */
19
34
  const inertiaInProcess = {
20
35
  package: '@inertiajs/react',
21
- extensions: ['.tsx', '.jsx'],
36
+ extensions: ['.tsx', '.jsx', '.mdx'],
22
37
  extractDefault: true,
23
38
  ssr: (configureCall) => `
24
39
  import { renderToString } from 'react-dom/server'
@@ -29,15 +44,56 @@ export default async function renderPage(page) {
29
44
  }
30
45
  `,
31
46
  };
47
+ /** For the dependency scan: an MDX page as the JavaScript @mdx-js/rollup makes of it (nothing without it) */
48
+ function scanMdx(config) {
49
+ return {
50
+ name: 'fondu:scan-mdx',
51
+ load: {
52
+ filter: { id: /\.mdx$/ },
53
+ async handler(id) {
54
+ const hook = config().plugins.find((p) => p.name === '@mdx-js/rollup')?.transform;
55
+ const transform = typeof hook === 'function' ? hook : hook?.handler;
56
+ const out = await transform?.call(this, readFileSync(id, 'utf8'), id);
57
+ return { code: typeof out === 'string' ? out : String(out?.code ?? ''), moduleType: 'js' };
58
+ },
59
+ },
60
+ };
61
+ }
62
+ /**
63
+ * The Worker never mounts or hydrates a page, but @inertiajs/react imports `react-dom/client` (createRoot,
64
+ * hydrateRoot) at its top: the whole of React's browser renderer in the Worker, evaluated at every start. There, it
65
+ * is a module that says so if called (about a third of the Worker, and of its start in dev)
66
+ */
67
+ const REACT_DOM_CLIENT = '\0fondu:react-dom-client';
68
+ function serverReactDomClient() {
69
+ return {
70
+ name: 'fondu:server-react-dom-client',
71
+ enforce: 'pre',
72
+ applyToEnvironment: (env) => env.config.consumer === 'server',
73
+ resolveId: { filter: { id: /^react-dom\/client$/ }, handler: () => REACT_DOM_CLIENT },
74
+ load: {
75
+ filter: { id: /^\0fondu:react-dom-client$/ },
76
+ handler: () => [
77
+ `const browserOnly = (name) => () => { throw new Error('fondu: react-dom/client ' + name + '() runs in the browser, not in the server') }`,
78
+ `export const createRoot = browserOnly('createRoot')`,
79
+ `export const hydrateRoot = browserOnly('hydrateRoot')`,
80
+ `export const version = ''`,
81
+ ].join('\n'),
82
+ },
83
+ };
84
+ }
32
85
  export default function fondu(options) {
33
86
  const node = options.target !== 'cloudflare';
34
87
  return [
35
- react(options.react),
88
+ // .mdx too: MDX pages and components get Fast Refresh (as MDX's own docs set it up)
89
+ react({ include: /\.(?:[jt]sx?|mdx)$/, ...options.react }),
36
90
  // `ssr: {}`: the server transform without an entry, so without @inertiajs/vite's dev SSR endpoint (Laravel's model)
37
91
  inertia({ ssr: options.ssr === false ? false : {}, frameworks: inertiaInProcess }),
38
92
  core(options),
93
+ layouts(),
94
+ hmr(),
39
95
  typegen(),
40
- ...(node ? runtimePlugins(options) : []),
96
+ ...(node ? runtimePlugins(options) : [serverReactDomClient()]),
41
97
  ];
42
98
  }
43
99
  async function buildPlugin(options) {
@@ -78,6 +134,14 @@ async function buildPlugin(options) {
78
134
  `const clientRoot = fileURLToPath(new URL('./client', import.meta.url))`,
79
135
  `${app}.use('/assets/*', async (c, next) => { await next(); if (c.res.ok) c.header('Cache-Control', 'public, max-age=31536000, immutable') })`,
80
136
  ...paths.map((p) => `${app}.use(${JSON.stringify(p)}, serveStatic({ root: clientRoot }))`),
137
+ // prerender: how the app reads the prerendered pages (fondu's server/prerender.ts), in the client build
138
+ ...(options.prerender
139
+ ? [
140
+ `import { readFile } from 'node:fs/promises'`,
141
+ `import { join as joinPath, sep } from 'node:path'`,
142
+ `globalThis[Symbol.for('fondu.staticFiles')] = (file) => { const to = joinPath(clientRoot, file); return to.startsWith(clientRoot + sep) ? readFile(to).catch(() => null) : Promise.resolve(null) }`,
143
+ ]
144
+ : []),
81
145
  ].join('\n');
82
146
  },
83
147
  ],
@@ -114,11 +178,13 @@ function runtimePlugins(options) {
114
178
  function core(options) {
115
179
  let config;
116
180
  let isBuild = false;
181
+ let serverBuild = false; // Node / Bun: `vite build`, after `vite build --mode client`
117
182
  return {
118
183
  name: 'fondu',
119
184
  enforce: 'pre',
120
185
  config(_user, env) {
121
186
  isBuild = env.command === 'build';
187
+ serverBuild = isBuild && options.target !== 'cloudflare' && env.mode !== 'client';
122
188
  const client = { manifest: true, rollupOptions: { input: ENTRY } };
123
189
  if (options.target === 'cloudflare') {
124
190
  return {
@@ -126,10 +192,22 @@ function core(options) {
126
192
  // the worker reads the client manifest: client first
127
193
  builder: {
128
194
  async buildApp(builder) {
129
- await builder.build(builder.environments.client);
130
- for (const env of Object.values(builder.environments))
131
- if (env.name !== 'client')
132
- await builder.build(env);
195
+ const client = builder.environments.client;
196
+ await builder.build(client);
197
+ // the client manifest is for the build (asset tags, the version): not a static asset to deploy
198
+ const ignore = resolve(config.root, client.config.build.outDir, '.assetsignore');
199
+ if (existsSync(ignore))
200
+ appendFileSync(ignore, '.vite\n');
201
+ for (const env of Object.values(builder.environments)) {
202
+ if (env.name === 'client')
203
+ continue;
204
+ await builder.build(env);
205
+ const wrangler = resolve(config.root, env.config.build.outDir, 'wrangler.json');
206
+ if (options.prerender && existsSync(wrangler)) {
207
+ const clientDir = resolve(config.root, client.config.build.outDir);
208
+ await prerender(worker(config.root, wrangler), clientDir, config.logger, true);
209
+ }
210
+ }
133
211
  },
134
212
  },
135
213
  ssr: { noExternal: ['fondu'] },
@@ -144,21 +222,27 @@ function core(options) {
144
222
  };
145
223
  },
146
224
  // dev: the dependencies are found before the first request (Vite scans index.html by default; an app has none),
147
- // so the first page is not reloaded once they are optimized
225
+ // so the first page is not reloaded once they are optimized. The scan reads JavaScript: an MDX page is compiled
226
+ // for it by the app's @mdx-js/rollup
148
227
  configEnvironment(name, env) {
149
- const pages = ['app/pages/**/*.tsx', 'app/pages/**/*.jsx'];
228
+ const pages = ['app/pages/**/*.{tsx,jsx,mdx}'];
229
+ const mdx = { extensions: ['.mdx'], rolldownOptions: { plugins: [scanMdx(() => config)] } };
150
230
  if (name === 'client')
151
- return { optimizeDeps: { entries: [ENTRY, ...pages] } };
231
+ return { optimizeDeps: { entries: [ENTRY, ...pages], ...mdx } };
152
232
  if (options.target !== 'cloudflare')
153
233
  return;
154
234
  // the Worker: fondu is not pre-bundled (its routes import it back: a bundle would hand them a half-loaded
155
- // module); react-dom/server is imported by @inertiajs/vite's generated render, which the scan does not see.
235
+ // module), so the scan does not see what it imports (HONO); nor react-dom/server, imported by @inertiajs/vite's
236
+ // generated render. Found late, they would restart the Worker in the middle of requests.
156
237
  // The build is minified, as Workers start faster with less code to parse
157
238
  return {
158
239
  optimizeDeps: {
159
240
  exclude: ['fondu'],
160
- include: options.ssr === false ? [] : ['react-dom/server'],
241
+ include: [...HONO, ...(options.ssr === false ? [] : ['react-dom/server'])],
161
242
  entries: [SERVER.slice(2), 'app/routes/**/*.ts', ENTRY, ...pages],
243
+ ...mdx,
244
+ // the pre-bundled @inertiajs/react too
245
+ rolldownOptions: { plugins: [...mdx.rolldownOptions.plugins, serverReactDomClient()] },
162
246
  },
163
247
  ...(env.build?.minify === undefined && { build: { minify: true } }),
164
248
  };
@@ -166,17 +250,13 @@ function core(options) {
166
250
  configResolved(c) {
167
251
  config = c;
168
252
  },
169
- // dev: server code changed (a module of the server only: routes/, *.server.ts…): reload the page; a page component:
170
- // React Fast Refresh (the client's HMR)
171
- handleHotUpdate({ server, file }) {
172
- const modules = (env) => [...(server.environments[env]?.moduleGraph.getModulesByFile(file) ?? [])];
173
- // the browser's code (not a file a stylesheet only watches, as Tailwind's sources), or no server's: leave it
174
- if (modules('client').some((m) => m.type === 'js'))
253
+ // Node / Bun: the server built, its pages to prerender written next to the client build's files
254
+ async closeBundle() {
255
+ if (!options.prerender || !serverBuild || options.target === 'cloudflare')
175
256
  return;
176
- if (!Object.keys(server.environments).some((env) => env !== 'client' && modules(env).length))
177
- return;
178
- server.hot.send({ type: 'full-reload' });
179
- return [];
257
+ serverBuild = false; // once
258
+ const clientDir = resolve(config.root, 'dist/client');
259
+ await prerender(nodeServer(config.root, options.target), clientDir, config.logger, false);
180
260
  },
181
261
  // dev: the CSS the client entry imports, as a stylesheet in the document, so a server-rendered page is styled
182
262
  // at first paint (Vite would add it only once the JS runs); removed once the entry has run
@@ -224,13 +304,32 @@ function core(options) {
224
304
  if (id === V.assets || id === V.ssr)
225
305
  return resolved(id);
226
306
  },
307
+ // the client entry: with prerender, page objects read from the prerendered files (fondu/client's `prerendered`);
308
+ // in dev, the page's props asked for again when what its route depends on changed (hmr.ts)
309
+ transform(code, id) {
310
+ if (this.environment.config.consumer !== 'client' || id !== resolve(config.root, ENTRY))
311
+ return;
312
+ const before = [
313
+ ...(options.prerender ? [`import { prerendered } from 'fondu/client';prerendered();`] : []),
314
+ ...(isBuild
315
+ ? []
316
+ : [
317
+ `import { router as __fondu_router } from '@inertiajs/react';`,
318
+ `import.meta.hot?.on(${JSON.stringify(PROPS_EVENT)}, () => __fondu_router.reload());`,
319
+ ]),
320
+ ];
321
+ if (before.length)
322
+ return { code: before.join('') + code, map: null };
323
+ },
227
324
  load(id) {
325
+ // and React's static markup for a JSX document (react-dom/server: the server render's, or loaded for it)
228
326
  if (id === resolved(V.ssr))
229
327
  return options.ssr === false
230
- ? 'export const renderPage = null'
231
- : `export { default as renderPage } from '/${ENTRY}'`;
328
+ ? `export const renderPage = null\nexport const renderMarkup = async (el) => (await import('react-dom/server')).renderToStaticMarkup(el)`
329
+ : `export { default as renderPage } from '/${ENTRY}'\nexport { renderToStaticMarkup as renderMarkup } from 'react-dom/server'`;
232
330
  if (id === resolved(V.assets))
233
- return isBuild ? productionAssets(config, options) : devAssets(config.base);
331
+ return ((isBuild ? productionAssets(config, options) : devAssets(config.base)) +
332
+ `\nexport const prerender = ${Boolean(options.prerender)}`);
234
333
  // the server-only guard: browser code must never import server code
235
334
  if (this.environment.config.consumer === 'client' && isServerOnly(id)) {
236
335
  this.error(`fondu: ${id.replace(config.root, '')} is server code (routes/, server.ts, *.server.ts) and cannot be imported by browser code`);
@@ -241,7 +340,7 @@ function core(options) {
241
340
  const isServerOnly = (id) => /\.server\.[cm]?[jt]sx?(\?.*)?$/.test(id) || /\/app\/(routes\/|server\.ts)/.test(id);
242
341
  const nonceAttr = `\${nonce ? \` nonce="\${nonce}"\` : ''}`;
243
342
  function devAssets(base) {
244
- const preamble = `import RefreshRuntime from "${base}@react-refresh";RefreshRuntime.injectIntoGlobalHook(window);window.$RefreshReg$=()=>{};window.$RefreshSig$=()=>(type)=>type;window.__vite_plugin_react_preamble_installed__=true`;
343
+ 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]??[]`;
245
344
  return `export const version = null
246
345
  export const pages = null
247
346
  export function assetTags(_component, nonce) {
@@ -277,8 +376,8 @@ function productionAssets(config, options) {
277
376
  const entry = tags(ENTRY);
278
377
  const pages = {};
279
378
  for (const key of Object.keys(manifest)) {
280
- const m = key.match(/^app\/pages\/(.+)\.[jt]sx$/);
281
- if (m)
379
+ const m = key.match(/^app\/pages\/(.+)\.(?:[jt]sx|mdx)$/);
380
+ if (m && isPageFile(key))
282
381
  pages[m[1]] = tags(key);
283
382
  }
284
383
  const version = createHash('sha256').update(text).digest('hex').slice(0, 16);
@@ -0,0 +1,8 @@
1
+ import type { Plugin } from 'vite';
2
+ /**
3
+ * `_layout.tsx` in a directory of `app/pages/` wraps the pages below it, outermost first: each page module imports
4
+ * its chain and sets it as the component's `layout` (Inertia's page-level layout), unless the page set its own. So a
5
+ * layout is in the chunks of its pages only, and stays mounted while visits stay among them. A page with no
6
+ * `_layout.tsx` above it gets `createInertiaApp({ layout })`, as Inertia gives any page without its own.
7
+ */
8
+ export declare function layouts(): Plugin;
@@ -0,0 +1,77 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join, relative, sep } from 'node:path';
3
+ import { isPageFile, layoutsOf } from '../paths.js';
4
+ const LAYOUT_EXTENSIONS = ['.tsx', '.jsx'];
5
+ /**
6
+ * `_layout.tsx` in a directory of `app/pages/` wraps the pages below it, outermost first: each page module imports
7
+ * its chain and sets it as the component's `layout` (Inertia's page-level layout), unless the page set its own. So a
8
+ * layout is in the chunks of its pages only, and stays mounted while visits stay among them. A page with no
9
+ * `_layout.tsx` above it gets `createInertiaApp({ layout })`, as Inertia gives any page without its own.
10
+ */
11
+ export function layouts() {
12
+ let root = process.cwd();
13
+ const pagesDir = () => join(root, 'app/pages');
14
+ // the `_layout.tsx` of a directory of app/pages/ ('' is the root), if there is one
15
+ const layoutFile = (dir) => LAYOUT_EXTENSIONS.map((ext) => join(pagesDir(), dir, `_layout${ext}`)).find((f) => existsSync(f));
16
+ return {
17
+ name: 'fondu:layouts',
18
+ enforce: 'post', // after the JSX and MDX are compiled: plain JavaScript to read
19
+ configResolved(c) {
20
+ root = c.root;
21
+ },
22
+ transform(code, id) {
23
+ const file = id.split('?')[0];
24
+ const rel = relative(pagesDir(), file).split(sep).join('/');
25
+ if (rel.startsWith('..') || !isPageFile(rel))
26
+ return;
27
+ const chain = layoutsOf(rel)
28
+ .map(layoutFile)
29
+ .filter((f) => f !== undefined);
30
+ if (!chain.length)
31
+ return;
32
+ const found = defaultExport(this.parse(code), code);
33
+ if (!found)
34
+ return;
35
+ // added at the end (imports are hoisted) and within a line: the lines stay where they were (`map: null`)
36
+ const imports = chain.map((f, i) => `import __fondu_layout_${i} from ${JSON.stringify(f)};`).join('\n');
37
+ const set = `${found.name}.layout ??= [${chain.map((_, i) => `__fondu_layout_${i}`).join(', ')}];`;
38
+ return { code: `${found.code}\n${imports}\n${set}\n`, map: null };
39
+ },
40
+ // dev: a `_layout.tsx` added or removed changes the chains of the pages below it: every module transformed anew
41
+ configureServer(server) {
42
+ const changed = (file) => {
43
+ const rel = relative(pagesDir(), file).split(sep).join('/');
44
+ if (rel.startsWith('..') || !/(^|\/)_layout\.[jt]sx$/.test(rel))
45
+ return;
46
+ for (const env of Object.values(server.environments))
47
+ env.moduleGraph.invalidateAll();
48
+ server.hot.send({ type: 'full-reload' });
49
+ };
50
+ server.watcher.on('add', changed);
51
+ server.watcher.on('unlink', changed);
52
+ },
53
+ };
54
+ }
55
+ /**
56
+ * The name of the module's default export, to set `layout` on: a named function or class as it is; an anonymous one,
57
+ * or an expression, given a name first (`const __fondu_page = …`, exported at the end)
58
+ */
59
+ function defaultExport(program, code) {
60
+ for (const node of program.body) {
61
+ if (node.type === 'ExportNamedDeclaration' && !node.source) {
62
+ const specifiers = node.specifiers;
63
+ const specifier = specifiers.find((sp) => sp.exported.name === 'default');
64
+ if (specifier)
65
+ return { name: specifier.local.name, code };
66
+ }
67
+ if (node.type !== 'ExportDefaultDeclaration')
68
+ continue;
69
+ const declaration = node.declaration;
70
+ if (declaration.id)
71
+ return { name: declaration.id.name, code };
72
+ return {
73
+ name: '__fondu_page',
74
+ code: `${code.slice(0, node.start)}const __fondu_page = ${code.slice(declaration.start)}\nexport default __fondu_page;`,
75
+ };
76
+ }
77
+ }
@@ -0,0 +1,28 @@
1
+ import type { Logger } from 'vite';
2
+ import { staticFiles } from '../paths.js';
3
+ export { staticFiles };
4
+ /** the hashes of a document's inline scripts that have the nonce (the document's own, as Fondu gave it) */
5
+ export declare function nonceScriptHashes(html: string): string[];
6
+ /**
7
+ * A Content Security Policy for a static document: no nonce (one for every visitor is none); the scripts that had it
8
+ * allowed by their hashes instead, and `'self'` scripts
9
+ */
10
+ export declare function staticPolicy(policy: string, hashes?: string[]): string;
11
+ /** the `_headers` rules: the documents' security headers, and the page objects' X-Inertia (Inertia requires it) */
12
+ export declare function headerRules(headers: Record<string, string>): string;
13
+ /** the built server, running for the prerender: fetch a path of it, stop it */
14
+ interface Server {
15
+ fetch(path: string, headers?: Record<string, string>): Promise<Response>;
16
+ dispose(): Promise<void>;
17
+ }
18
+ /**
19
+ * After the build: the built server (the Worker in wrangler, or `node` / `bun dist/index.js`), started with
20
+ * `FONDU_PRERENDER` set, lists the pages to prerender (`/__fondu/prerender`); each is asked for as a document and as
21
+ * a visit, and both are written to the client build. Cloudflare serves them before the Worker, with the security
22
+ * headers written to `_headers`; Node and Bun before the routes, behind the app's own headers.
23
+ */
24
+ export declare function prerender(start: () => Promise<Server>, clientDir: string, logger: Logger, headersFile: boolean): Promise<undefined>;
25
+ /** Cloudflare: the built Worker, in the app's own wrangler (fondu does not depend on it) */
26
+ export declare const worker: (root: string, workerConfig: string) => () => Promise<Server>;
27
+ /** Node / Bun: `node dist/index.js` (or `bun`), on a free port, until it answers */
28
+ export declare const nodeServer: (root: string, runtime: 'node' | 'bun') => () => Promise<Server>;