fondu 0.9.5 → 0.10.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.
Files changed (51) hide show
  1. package/README.md +7 -12
  2. package/dist/client/app.d.ts +40 -0
  3. package/dist/client/app.js +162 -0
  4. package/dist/client/navigation.d.ts +35 -0
  5. package/dist/client/navigation.js +210 -0
  6. package/dist/client/progress.d.ts +16 -0
  7. package/dist/client/progress.js +51 -0
  8. package/dist/client.d.ts +4 -15
  9. package/dist/client.js +3 -47
  10. package/dist/index.d.ts +3 -4
  11. package/dist/index.js +3 -4
  12. package/dist/paths.d.ts +10 -7
  13. package/dist/paths.js +15 -15
  14. package/dist/server/app.d.ts +4 -5
  15. package/dist/server/app.js +81 -16
  16. package/dist/server/document.d.ts +3 -3
  17. package/dist/server/document.js +7 -6
  18. package/dist/server/errors.d.ts +4 -2
  19. package/dist/server/errors.js +21 -10
  20. package/dist/server/flash.d.ts +4 -7
  21. package/dist/server/flash.js +9 -14
  22. package/dist/server/handler.d.ts +1 -1
  23. package/dist/server/handler.js +1 -1
  24. package/dist/server/http.d.ts +7 -5
  25. package/dist/server/http.js +15 -6
  26. package/dist/server/prerender.d.ts +1 -1
  27. package/dist/server/prerender.js +6 -6
  28. package/dist/server/protocol.d.ts +22 -35
  29. package/dist/server/protocol.js +65 -195
  30. package/dist/server/routes.d.ts +1 -1
  31. package/dist/server/validate.d.ts +7 -9
  32. package/dist/server/validate.js +8 -21
  33. package/dist/types.d.ts +10 -6
  34. package/dist/virtual.d.ts +3 -5
  35. package/dist/vite/hmr.d.ts +3 -3
  36. package/dist/vite/hmr.js +5 -5
  37. package/dist/vite/index.d.ts +9 -5
  38. package/dist/vite/index.js +158 -79
  39. package/dist/vite/prerender.d.ts +7 -3
  40. package/dist/vite/prerender.js +49 -16
  41. package/dist/vite/strip.d.ts +21 -0
  42. package/dist/vite/strip.js +301 -0
  43. package/dist/vite/typegen.d.ts +3 -2
  44. package/dist/vite/typegen.js +6 -10
  45. package/package.json +2 -9
  46. package/dist/server/props.d.ts +0 -85
  47. package/dist/server/props.js +0 -44
  48. package/dist/vite/layouts.d.ts +0 -10
  49. package/dist/vite/layouts.js +0 -110
  50. package/dist/vite/vitest-cache.d.ts +0 -19
  51. package/dist/vite/vitest-cache.js +0 -30
@@ -0,0 +1,301 @@
1
+ import { relative, sep } from 'node:path';
2
+ import { isPageFile } from '../paths.js';
3
+ /** the exports of a page's route file that are server code: the browser gets the page (default) alone */
4
+ export const SERVER_EXPORTS = new Set([
5
+ 'loader',
6
+ 'action',
7
+ 'actions',
8
+ 'prerender',
9
+ 'params',
10
+ 'GET',
11
+ 'POST',
12
+ 'PUT',
13
+ 'PATCH',
14
+ 'DELETE',
15
+ 'OPTIONS',
16
+ ]);
17
+ const nameOf = (n) => (n.name ?? n.value);
18
+ /** the names a declaration binds: `const { a, b: [c] } = …` → a, c */
19
+ function bound(node, out = []) {
20
+ if (!node)
21
+ return out;
22
+ switch (node.type) {
23
+ case 'Identifier':
24
+ out.push(node.name);
25
+ break;
26
+ case 'VariableDeclaration':
27
+ for (const d of node.declarations)
28
+ bound(d.id, out);
29
+ break;
30
+ case 'FunctionDeclaration':
31
+ case 'ClassDeclaration':
32
+ bound(node.id, out);
33
+ break;
34
+ case 'ObjectPattern':
35
+ for (const p of node.properties)
36
+ bound((p.type === 'RestElement' ? p.argument : p.value), out);
37
+ break;
38
+ case 'ArrayPattern':
39
+ for (const e of node.elements)
40
+ bound(e, out);
41
+ break;
42
+ case 'RestElement':
43
+ bound(node.argument, out);
44
+ break;
45
+ case 'AssignmentPattern':
46
+ bound(node.left, out);
47
+ break;
48
+ }
49
+ return out;
50
+ }
51
+ /**
52
+ * The names a node refers to that it does not bind itself: `function f(a) { return a + b }` → b (and f's own
53
+ * scopes: parameters, `var`s, block declarations, a catch's parameter). What a pattern binds is not a reference;
54
+ * nor a property's name, a label, a member's property. Errs on the side of a name referred to, never the other way.
55
+ */
56
+ function references(node, out = new Set(), scopes = []) {
57
+ const visit = (n, inner = scopes) => references(n, out, inner);
58
+ if (Array.isArray(node)) {
59
+ for (const n of node)
60
+ visit(n);
61
+ return out;
62
+ }
63
+ if (!node || typeof node !== 'object' || typeof node.type !== 'string')
64
+ return out;
65
+ const n = node;
66
+ switch (n.type) {
67
+ case 'Identifier':
68
+ if (!scopes.some((s) => s.has(n.name)))
69
+ out.add(n.name);
70
+ return out;
71
+ case 'MemberExpression':
72
+ visit(n.object);
73
+ if (n.computed)
74
+ visit(n.property);
75
+ return out;
76
+ case 'Property':
77
+ case 'MethodDefinition':
78
+ case 'PropertyDefinition':
79
+ case 'AccessorProperty':
80
+ if (n.computed)
81
+ visit(n.key);
82
+ visit(n.value);
83
+ return out;
84
+ case 'LabeledStatement':
85
+ visit(n.body);
86
+ return out;
87
+ case 'BreakStatement':
88
+ case 'ContinueStatement':
89
+ case 'MetaProperty':
90
+ return out;
91
+ case 'FunctionDeclaration':
92
+ case 'FunctionExpression':
93
+ case 'ArrowFunctionExpression': {
94
+ const scope = new Set();
95
+ if (n.type === 'FunctionExpression')
96
+ bound(n.id, []).forEach((x) => scope.add(x));
97
+ for (const p of n.params)
98
+ bound(p).forEach((x) => scope.add(x));
99
+ vars(n.body, scope);
100
+ if (n.body.type === 'BlockStatement')
101
+ lexical(n.body.body, scope);
102
+ visit(n.params, [...scopes, scope]);
103
+ visit(n.body, [...scopes, scope]);
104
+ return out;
105
+ }
106
+ case 'ClassDeclaration':
107
+ case 'ClassExpression': {
108
+ visit(n.superClass);
109
+ visit(n.decorators);
110
+ visit(n.body, [...scopes, new Set(bound(n.id))]);
111
+ return out;
112
+ }
113
+ case 'BlockStatement':
114
+ case 'StaticBlock':
115
+ visit(n.body, [...scopes, lexical(n.body)]);
116
+ return out;
117
+ case 'SwitchStatement':
118
+ visit(n.discriminant);
119
+ visit(n.cases, [
120
+ ...scopes,
121
+ lexical(n.cases.flatMap((c) => c.consequent)),
122
+ ]);
123
+ return out;
124
+ case 'ForStatement':
125
+ case 'ForInStatement':
126
+ case 'ForOfStatement': {
127
+ const head = (n.init ?? n.left);
128
+ const scope = head?.type === 'VariableDeclaration' && head.kind !== 'var'
129
+ ? new Set(bound(head))
130
+ : new Set();
131
+ for (const key of ['init', 'test', 'update', 'left', 'right', 'body'])
132
+ visit(n[key], [...scopes, scope]);
133
+ return out;
134
+ }
135
+ case 'CatchClause': {
136
+ const scope = new Set(bound(n.param));
137
+ visit(n.param, [...scopes, scope]);
138
+ visit(n.body, [...scopes, scope]);
139
+ return out;
140
+ }
141
+ }
142
+ for (const key in n)
143
+ if (key !== 'type' && key !== 'start' && key !== 'end')
144
+ visit(n[key]);
145
+ return out;
146
+ }
147
+ /** the `var`s of a function's body (and its blocks: they are the function's), not of the functions in it */
148
+ function vars(node, scope) {
149
+ if (Array.isArray(node))
150
+ for (const n of node)
151
+ vars(n, scope);
152
+ else if (node && typeof node === 'object' && typeof node.type === 'string') {
153
+ const n = node;
154
+ if (/Function|Class/.test(n.type))
155
+ return;
156
+ if (n.type === 'VariableDeclaration' && n.kind === 'var')
157
+ bound(n).forEach((x) => scope.add(x));
158
+ for (const key in n)
159
+ if (key !== 'type' && key !== 'start' && key !== 'end')
160
+ vars(n[key], scope);
161
+ }
162
+ }
163
+ /** the names a block's statements declare for the block: `let`, `const`, functions, classes */
164
+ function lexical(statements, scope = new Set()) {
165
+ for (const s of statements)
166
+ if ((s.type === 'VariableDeclaration' && s.kind !== 'var') ||
167
+ s.type === 'FunctionDeclaration' ||
168
+ s.type === 'ClassDeclaration')
169
+ bound(s).forEach((x) => scope.add(x));
170
+ return scope;
171
+ }
172
+ /**
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
175
+ * name the code kept refers to keeps its declaration, so what is left over is at worst unused code, which
176
+ * Fondu's server-only guard stops when it is server code (`*.server.ts`, `routes/*.ts`). Lines stay where they were.
177
+ */
178
+ export function stripServerCode(code, program, file) {
179
+ const fail = (why) => {
180
+ throw new Error(`fondu: routes/${file}: ${why}`);
181
+ };
182
+ // the server exports removed, by name: code left that names one would keep it in the browser, or fail there
183
+ const removed = new Set();
184
+ const parts = program.body.map((node) => ({
185
+ node,
186
+ declares: [],
187
+ uses: node.type === 'ImportDeclaration' ? new Set() : references(node),
188
+ }));
189
+ for (const part of parts) {
190
+ const { node } = part;
191
+ if (node.type === 'ExportAllDeclaration')
192
+ fail('`export *` is not for a route file');
193
+ if (node.type === 'ExportNamedDeclaration') {
194
+ const declaration = node.declaration;
195
+ if (declaration) {
196
+ const declared = bound(declaration);
197
+ const server = declared.filter((n) => SERVER_EXPORTS.has(n));
198
+ if (server.length && server.length !== declared.length)
199
+ fail(`declare ${server.join(', ')} on a line of their own`);
200
+ if (server.length) {
201
+ part.text = '';
202
+ for (const name of server)
203
+ removed.add(name);
204
+ }
205
+ continue;
206
+ }
207
+ const specifiers = node.specifiers;
208
+ const kept = specifiers.filter((s) => !SERVER_EXPORTS.has(nameOf(s.exported)));
209
+ if (kept.length === specifiers.length)
210
+ continue;
211
+ const source = node.source
212
+ ? ` from ${code.slice(node.source.start, node.source.end)}`
213
+ : '';
214
+ part.text = kept.length
215
+ ? `export { ${kept.map((s) => code.slice(s.start, s.end)).join(', ')} }${source};`
216
+ : '';
217
+ // what it exported is only named here now: an import or a declaration it named may go too
218
+ part.uses = references(kept.map((s) => s.local));
219
+ continue;
220
+ }
221
+ if (node.type === 'ImportDeclaration' && node.specifiers.length)
222
+ part.declares = node.specifiers.map((s) => nameOf(s.local));
223
+ else if (['VariableDeclaration', 'FunctionDeclaration', 'ClassDeclaration'].includes(node.type))
224
+ part.declares = bound(node);
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)
232
+ 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
+ }
247
+ }
248
+ }
249
+ for (const part of parts)
250
+ if (part.text !== '')
251
+ for (const name of removed)
252
+ if (part.uses.has(name))
253
+ fail(`${name} is server code, removed from the browser's copy: set it where it is declared`);
254
+ let out = '';
255
+ let at = 0;
256
+ for (const { node, text } of parts) {
257
+ if (text === undefined)
258
+ continue;
259
+ // the lines a removed statement took stay, empty: the line numbers of the rest don't change
260
+ const removed = code.slice(node.start, node.end);
261
+ out += code.slice(at, node.start) + text + '\n'.repeat(removed.split('\n').length - 1);
262
+ at = node.end;
263
+ }
264
+ return out + code.slice(at);
265
+ }
266
+ /** an import with these of its specifiers only: `import a, { b as c } from 'x'` */
267
+ function importOf(code, node, kept) {
268
+ const source = code.slice(node.source.start, node.source.end);
269
+ const first = kept[0];
270
+ if (first.type === 'ImportNamespaceSpecifier' && kept.length === 1)
271
+ return `import ${code.slice(first.start, first.end)} from ${source};`;
272
+ const byDefault = kept.find((s) => s.type === 'ImportDefaultSpecifier');
273
+ const named = kept.filter((s) => s.type === 'ImportSpecifier');
274
+ const namespace = kept.find((s) => s.type === 'ImportNamespaceSpecifier');
275
+ const clauses = [
276
+ byDefault && code.slice(byDefault.start, byDefault.end),
277
+ namespace && code.slice(namespace.start, namespace.end),
278
+ named.length && `{ ${named.map((s) => code.slice(s.start, s.end)).join(', ')} }`,
279
+ ].filter(Boolean);
280
+ return `import ${clauses.join(', ')} from ${source};`;
281
+ }
282
+ /** The browser's copy of every page's route file (`.tsx`, `.jsx` in `app/routes/`): its server code removed */
283
+ export function stripRoutes() {
284
+ let root = process.cwd();
285
+ return {
286
+ name: 'fondu:strip-routes',
287
+ enforce: 'post', // after the JSX is compiled: plain JavaScript to read
288
+ configResolved(c) {
289
+ root = c.root;
290
+ },
291
+ transform(code, id) {
292
+ if (this.environment.config.consumer !== 'client')
293
+ return;
294
+ const file = relative(`${root}/app/routes`, id.split('?')[0]).split(sep).join('/');
295
+ if (file.startsWith('..') || !isPageFile(file) || file.endsWith('.mdx'))
296
+ return;
297
+ const stripped = stripServerCode(code, this.parse(code), file);
298
+ return stripped === code ? undefined : { code: stripped, map: null };
299
+ },
300
+ };
301
+ }
@@ -1,7 +1,8 @@
1
1
  import type { Plugin } from 'vite';
2
+ export declare function walk(dir: string, out?: string[], base?: string): string[];
2
3
  /**
3
- * The registry the types are read from: page name → module, URL pattern → route module. Only `typeof import`s; an
4
- * MDX page's keeps its extension, which `declare module '*.mdx'` (@types/mdx) types.
4
+ * The registry the types are read from: URL pattern → route module (`href()`). Only `typeof import`s; an MDX page's
5
+ * keeps its extension, which `declare module '*.mdx'` (@types/mdx) types.
5
6
  */
6
7
  export declare function generateTypes(root: string): string;
7
8
  export declare function writeTypes(root: string): void;
@@ -1,8 +1,8 @@
1
1
  import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { join, relative, sep } from 'node:path';
3
- import { isPageFile, isRouteFile, routePatterns } from '../paths.js';
3
+ import { isRouteFile, routePatterns } from '../paths.js';
4
4
  const OUT = 'app/fondu.gen.d.ts';
5
- function walk(dir, out = [], base = dir) {
5
+ export function walk(dir, out = [], base = dir) {
6
6
  if (!existsSync(dir))
7
7
  return out;
8
8
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
@@ -15,21 +15,17 @@ function walk(dir, out = [], base = dir) {
15
15
  return out;
16
16
  }
17
17
  /**
18
- * The registry the types are read from: page name → module, URL pattern → route module. Only `typeof import`s; an
19
- * MDX page's keeps its extension, which `declare module '*.mdx'` (@types/mdx) types.
18
+ * The registry the types are read from: URL pattern → route module (`href()`). Only `typeof import`s; an MDX page's
19
+ * keeps its extension, which `declare module '*.mdx'` (@types/mdx) types.
20
20
  */
21
21
  export function generateTypes(root) {
22
- const pages = walk(join(root, 'app/pages')).filter(isPageFile).sort();
23
22
  const routes = walk(join(root, 'app/routes')).filter(isRouteFile).sort();
24
23
  const line = (key, path) => ` ${JSON.stringify(key)}: typeof import(${JSON.stringify(path)})`;
25
24
  return `// Generated by fondu (vite dev / vite build). Commit it; do not edit.
26
25
  declare module 'fondu' {
27
26
  interface Register {
28
- pages: {
29
- ${pages.map((f) => line(f.replace(/\.(?:[jt]sx|mdx)$/, ''), `./pages/${f.replace(/\.[jt]sx$/, '')}`)).join('\n')}
30
- }
31
27
  routes: {
32
- ${routes.flatMap((f) => patternsOf(f).map((p) => line(p, `./routes/${f.replace(/\.ts$/, '')}`))).join('\n')}
28
+ ${routes.flatMap((f) => patternsOf(f).map((p) => line(p, `./routes/${f.replace(/\.(?:ts|[jt]sx)$/, '')}`))).join('\n')}
33
29
  }
34
30
  }
35
31
  }
@@ -64,7 +60,7 @@ export function typegen() {
64
60
  configureServer(server) {
65
61
  const onChange = (file) => {
66
62
  const rel = relative(root, file).split(sep).join('/');
67
- if (rel.startsWith('app/pages/') || rel.startsWith('app/routes/'))
63
+ if (rel.startsWith('app/routes/'))
68
64
  writeTypes(root);
69
65
  };
70
66
  server.watcher.on('add', onChange);
package/package.json CHANGED
@@ -1,15 +1,13 @@
1
1
  {
2
2
  "name": "fondu",
3
- "version": "0.9.5",
4
- "description": "A small meta-framework for full-stack React apps, built on Hono, Vite and Inertia. It runs on Bun, Cloudflare Workers and Node.",
3
+ "version": "0.10.0",
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",
7
7
  "cloudflare-workers",
8
8
  "fondujs",
9
9
  "hono",
10
10
  "honojs",
11
- "inertia",
12
- "inertiajs",
13
11
  "nodejs",
14
12
  "react",
15
13
  "ssr",
@@ -50,12 +48,9 @@
50
48
  },
51
49
  "dependencies": {
52
50
  "@hono/vite-dev-server": "^0.26.1",
53
- "@inertiajs/vite": "^3.9.1",
54
51
  "@vitejs/plugin-react": "^6.1.2"
55
52
  },
56
53
  "devDependencies": {
57
- "@inertiajs/core": "3.9.1",
58
- "@inertiajs/react": "3.9.1",
59
54
  "@types/node": "26.6.5",
60
55
  "@types/react": "19.3.0",
61
56
  "@types/react-dom": "19.3.0",
@@ -66,8 +61,6 @@
66
61
  "zod": "4.6.7"
67
62
  },
68
63
  "peerDependencies": {
69
- "@inertiajs/core": "^3.9.0",
70
- "@inertiajs/react": "^3.9.0",
71
64
  "hono": "^4.13.0",
72
65
  "react": "^19.0.0",
73
66
  "react-dom": "^19.0.0",
@@ -1,85 +0,0 @@
1
- /**
2
- * Inertia's prop types (the names are Inertia's: what the client docs call them). A plain value is always sent;
3
- * a function is called only when its prop is sent.
4
- *
5
- * - `optional(fn)`: never on a full visit, only when a partial reload names it (`only`)
6
- * - `always(value)`: sent on partial reloads too, even when not asked for
7
- * - `defer(fn, { group?, rescue? })`: left out of the page, fetched by the client right after it renders (one
8
- * request per group); `rescue`: if it throws, the page still loads and `<Deferred>` shows its `rescue` slot
9
- * - `merge(value, { path?, matchOn? })` / `prepend(…)` / `deepMerge(value, { matchOn? })`: partial reloads merge into
10
- * what the client holds; `path`: the list to merge, inside the prop (`'data'`); `matchOn`: the field, from the
11
- * prop, that finds an item to replace (`'id'`, `'data.id'`)
12
- * - `once(fn, { key?, ttl?, fresh? })`: computed once; later requests say the client holds it and it is skipped
13
- * (`fresh`: send it anyway)
14
- * - `scroll(fn, { pageName? })`: a page of a list for `<InfiniteScroll>`; `fn` returns `{ data, currentPage,
15
- * previousPage, nextPage }` for the page in the query (`?page=`)
16
- *
17
- * They combine as Inertia's do (Laravel's `->once()`, `->merge()`, `->defer()`), by wrapping one in another:
18
- * `once(defer(fn))`, `once(optional(fn))`, `once(merge(fn))`, `merge(defer(fn))` (and `deepMerge`, `prepend`),
19
- * `defer(scroll(fn))`.
20
- */
21
- declare const PROP: unique symbol;
22
- declare const BRAND: unique symbol;
23
- type Resolver<T> = () => T | Promise<T>;
24
- export type Lazy<T> = T | Resolver<T>;
25
- export interface Paginated<T> {
26
- data: T[];
27
- currentPage: number | string;
28
- previousPage: number | string | null;
29
- nextPage: number | string | null;
30
- }
31
- export interface PropSpec {
32
- [PROP]: true;
33
- value: Lazy<unknown>;
34
- optional?: true;
35
- always?: true;
36
- defer?: {
37
- group: string;
38
- rescue: boolean;
39
- };
40
- once?: {
41
- key?: string;
42
- ttl?: number;
43
- fresh?: boolean;
44
- };
45
- merge?: {
46
- strategy: 'append' | 'prepend' | 'deep';
47
- paths: string[];
48
- matchOn: string[];
49
- };
50
- scroll?: {
51
- pageName: string;
52
- };
53
- }
54
- /** A prop with an Inertia behaviour; at the type level it stands for the value it resolves to. */
55
- export type Prop<T> = T & {
56
- readonly [BRAND]: true;
57
- };
58
- export declare const propSpec: (value: unknown) => PropSpec | null;
59
- export declare const optional: <T>(value: Resolver<T>) => Prop<T>;
60
- export declare const always: <T>(value: Lazy<T>) => Prop<T>;
61
- export declare const defer: <T>(value: Resolver<T> | Prop<T>, { group, rescue }?: {
62
- group?: string;
63
- rescue?: boolean;
64
- }) => Prop<T>;
65
- export declare const once: <T>(value: Resolver<T> | Prop<T>, options?: {
66
- key?: string;
67
- ttl?: number;
68
- fresh?: boolean;
69
- }) => Prop<T>;
70
- export declare const scroll: <T>(value: Resolver<Paginated<T>>, { pageName }?: {
71
- pageName?: string;
72
- }) => Prop<Paginated<T>>;
73
- export declare const merge: <T>(value: Lazy<T> | Prop<T>, options?: {
74
- path?: string | string[];
75
- matchOn?: string | string[];
76
- }) => Prop<T>;
77
- export declare const prepend: <T>(value: Lazy<T> | Prop<T>, options?: {
78
- path?: string | string[];
79
- matchOn?: string | string[];
80
- }) => Prop<T>;
81
- export declare const deepMerge: <T>(value: Lazy<T> | Prop<T>, options?: {
82
- matchOn?: string | string[];
83
- }) => Prop<T>;
84
- export declare const resolve: (value: Lazy<unknown>) => Promise<unknown>;
85
- export {};
@@ -1,44 +0,0 @@
1
- /**
2
- * Inertia's prop types (the names are Inertia's: what the client docs call them). A plain value is always sent;
3
- * a function is called only when its prop is sent.
4
- *
5
- * - `optional(fn)`: never on a full visit, only when a partial reload names it (`only`)
6
- * - `always(value)`: sent on partial reloads too, even when not asked for
7
- * - `defer(fn, { group?, rescue? })`: left out of the page, fetched by the client right after it renders (one
8
- * request per group); `rescue`: if it throws, the page still loads and `<Deferred>` shows its `rescue` slot
9
- * - `merge(value, { path?, matchOn? })` / `prepend(…)` / `deepMerge(value, { matchOn? })`: partial reloads merge into
10
- * what the client holds; `path`: the list to merge, inside the prop (`'data'`); `matchOn`: the field, from the
11
- * prop, that finds an item to replace (`'id'`, `'data.id'`)
12
- * - `once(fn, { key?, ttl?, fresh? })`: computed once; later requests say the client holds it and it is skipped
13
- * (`fresh`: send it anyway)
14
- * - `scroll(fn, { pageName? })`: a page of a list for `<InfiniteScroll>`; `fn` returns `{ data, currentPage,
15
- * previousPage, nextPage }` for the page in the query (`?page=`)
16
- *
17
- * They combine as Inertia's do (Laravel's `->once()`, `->merge()`, `->defer()`), by wrapping one in another:
18
- * `once(defer(fn))`, `once(optional(fn))`, `once(merge(fn))`, `merge(defer(fn))` (and `deepMerge`, `prepend`),
19
- * `defer(scroll(fn))`.
20
- */
21
- const PROP = Symbol.for('fondu.prop');
22
- export const propSpec = (value) => typeof value === 'object' && value !== null && PROP in value ? value : null;
23
- /** a new prop, or `kind` added to the one it wraps when Inertia combines them (`can`: the kinds it may wrap) */
24
- function make(name, value, add, can) {
25
- const inner = propSpec(value);
26
- if (!inner)
27
- return { [PROP]: true, value, ...add };
28
- const kinds = Object.keys(inner).filter((k) => k !== 'value');
29
- const other = kinds.find((k) => !can.includes(k));
30
- if (other)
31
- throw new Error(`fondu: ${name}() can't wrap ${other}()`);
32
- return { ...inner, ...add };
33
- }
34
- export const optional = (value) => make('optional', value, { optional: true }, []);
35
- export const always = (value) => make('always', value, { always: true }, []);
36
- export const defer = (value, { group = 'default', rescue = false } = {}) => make('defer', value, { defer: { group, rescue } }, ['scroll']);
37
- export const once = (value, options = {}) => make('once', value, { once: options }, ['defer', 'optional', 'merge']);
38
- export const scroll = (value, { pageName = 'page' } = {}) => make('scroll', value, { scroll: { pageName } }, []);
39
- const list = (value) => [value ?? []].flat();
40
- const merger = (strategy) => (value, options = {}) => make(strategy === 'append' ? 'merge' : 'prepend', value, { merge: { strategy, paths: list(options.path), matchOn: list(options.matchOn) } }, ['defer', 'once']);
41
- export const merge = merger('append');
42
- export const prepend = merger('prepend');
43
- export const deepMerge = (value, options = {}) => make('deepMerge', value, { merge: { strategy: 'deep', paths: [], matchOn: list(options.matchOn) } }, ['defer', 'once']);
44
- export const resolve = async (value) => typeof value === 'function' ? value() : value;
@@ -1,10 +0,0 @@
1
- import type { Plugin } from 'vite';
2
- /** the `_layout.tsx` files around a page (its path in `app/pages/`), outermost first */
3
- export declare function layoutChain(root: string, page: string): string[];
4
- /**
5
- * `_layout.tsx` in a directory of `app/pages/` wraps the pages below it, outermost first: each page module imports
6
- * its chain and sets it as the component's `layout` (Inertia's page-level layout), unless the page set its own. So a
7
- * layout is in the chunks of its pages only, and stays mounted while visits stay among them. A page with no
8
- * `_layout.tsx` above it gets `createInertiaApp({ layout })`, as Inertia gives any page without its own.
9
- */
10
- export declare function layouts(): Plugin;
@@ -1,110 +0,0 @@
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
- /** the `_layout.tsx` files around a page (its path in `app/pages/`), outermost first */
6
- export function layoutChain(root, page) {
7
- return layoutsOf(page)
8
- .map((dir) => LAYOUT_EXTENSIONS.map((ext) => join(root, 'app/pages', dir, `_layout${ext}`)).find((f) => existsSync(f)))
9
- .filter((f) => f !== undefined);
10
- }
11
- /**
12
- * `_layout.tsx` in a directory of `app/pages/` wraps the pages below it, outermost first: each page module imports
13
- * its chain and sets it as the component's `layout` (Inertia's page-level layout), unless the page set its own. So a
14
- * layout is in the chunks of its pages only, and stays mounted while visits stay among them. A page with no
15
- * `_layout.tsx` above it gets `createInertiaApp({ layout })`, as Inertia gives any page without its own.
16
- */
17
- export function layouts() {
18
- let root = process.cwd();
19
- const pagesDir = () => join(root, 'app/pages');
20
- return {
21
- name: 'fondu:layouts',
22
- enforce: 'post', // after the JSX and MDX are compiled: plain JavaScript to read
23
- configResolved(c) {
24
- root = c.root;
25
- },
26
- transform(code, id) {
27
- const rel = relative(pagesDir(), id.split('?')[0]).split(sep).join('/');
28
- if (rel.startsWith('..') || !isPageFile(rel))
29
- return;
30
- const found = defaultExport(this.parse(code), code);
31
- // a component put in app/pages/ by mistake would be a page, named and typed: an error instead
32
- if (!found) {
33
- this.error(`fondu: app/pages/${rel} has no default export. A page is its module's default export; a file in app/pages/ that is not a page goes elsewhere (components/, say), or its name starts with _`);
34
- }
35
- if (found.name === undefined)
36
- return;
37
- const chain = layoutChain(root, rel);
38
- // a re-exported component is wrapped with no layout above too: the app's default layout for this page, not the
39
- // layouts its other page set on it
40
- if (!chain.length)
41
- return found.wrapped ? { code: found.code, map: null } : undefined;
42
- // added at the end (imports are hoisted) and within a line: the lines stay where they were (`map: null`)
43
- const imports = chain
44
- .map((f, i) => `import __fondu_layout_${i} from ${JSON.stringify(f)};`)
45
- .join('\n');
46
- const set = `${found.name}.layout ??= [${chain.map((_, i) => `__fondu_layout_${i}`).join(', ')}];`;
47
- return { code: `${found.code}\n${imports}\n${set}\n`, map: null };
48
- },
49
- // dev: a `_layout.tsx` added or removed changes the chains of the pages below it: every module transformed anew
50
- configureServer(server) {
51
- const changed = (file) => {
52
- const rel = relative(pagesDir(), file).split(sep).join('/');
53
- if (rel.startsWith('..') || !/(^|\/)_layout\.[jt]sx$/.test(rel))
54
- return;
55
- for (const env of Object.values(server.environments))
56
- env.moduleGraph.invalidateAll();
57
- server.hot.send({ type: 'full-reload' });
58
- };
59
- server.watcher.on('add', changed);
60
- server.watcher.on('unlink', changed);
61
- },
62
- };
63
- }
64
- const nameOf = (n) => n.name ?? n.value;
65
- /**
66
- * The name of the module's default export, to set `layout` on: a named function or class as it is; an anonymous one,
67
- * or an expression, given a name first (`const __fondu_page = …`, exported at the end). A component re-exported from
68
- * another module (`export { default } from './edit.tsx'`) is wrapped in one of this page's own: two pages may share a
69
- * component under different layouts. `name: undefined`: a default export to leave alone (`export * as default`).
70
- */
71
- function defaultExport(program, code) {
72
- for (const node of program.body) {
73
- if (node.type === 'ExportAllDeclaration' && node.exported)
74
- if (nameOf(node.exported) === 'default')
75
- return { name: undefined, code };
76
- if (node.type === 'ExportNamedDeclaration') {
77
- const specifiers = node.specifiers;
78
- const specifier = specifiers.find((sp) => nameOf(sp.exported) === 'default');
79
- if (!specifier)
80
- continue;
81
- if (!node.source)
82
- return { name: nameOf(specifier.local), code };
83
- const source = code.slice(node.source.start, node.source.end);
84
- const others = specifiers.filter((sp) => sp !== specifier);
85
- const kept = others.length
86
- ? `export { ${others.map((sp) => code.slice(sp.start, sp.end)).join(', ')} } from ${source};`
87
- : '';
88
- const local = nameOf(specifier.local);
89
- const imported = /^[A-Za-z_$][\w$]*$/.test(local) ? local : JSON.stringify(local);
90
- return {
91
- name: '__fondu_page',
92
- wrapped: true,
93
- code: `${code.slice(0, node.start)}${kept}${code.slice(node.end)}\n` +
94
- `import { ${imported} as __fondu_shared } from ${source};\n` +
95
- `import { createElement as __fondu_h } from 'react';\n` +
96
- `const __fondu_page = (props) => __fondu_h(__fondu_shared, props);\n` +
97
- `export default __fondu_page;`,
98
- };
99
- }
100
- if (node.type !== 'ExportDefaultDeclaration')
101
- continue;
102
- const declaration = node.declaration;
103
- if (declaration.id)
104
- return { name: declaration.id.name, code };
105
- return {
106
- name: '__fondu_page',
107
- code: `${code.slice(0, node.start)}const __fondu_page = ${code.slice(declaration.start)}\nexport default __fondu_page;`,
108
- };
109
- }
110
- }
@@ -1,19 +0,0 @@
1
- import type { Plugin } from 'vite';
2
- type CacheKeyGenerator = (context: {
3
- id: string;
4
- }) => string | false | undefined;
5
- type CacheKeyContext = {
6
- defineCacheKeyGenerator?: (generator: CacheKeyGenerator) => void;
7
- /** Vitest 4's name for it */
8
- experimental_defineCacheKeyGenerator?: (generator: CacheKeyGenerator) => void;
9
- };
10
- /**
11
- * Vitest's file cache keys a transformed module by its code. Two modules' transforms read more than that, so the next
12
- * run would see them as they were: a page's layout chain (the `_layout.tsx` files above it) goes in its key; the
13
- * entry, `app/app.tsx`, is not cached, its transform writing the list of pages (`@inertiajs/vite`'s glob) and the code
14
- * Fondu's options add. Vitest itself skips only modules whose own code has `import.meta.glob`.
15
- */
16
- export declare function vitestCache(entry: string): Plugin & {
17
- configureVitest(context: CacheKeyContext): void;
18
- };
19
- export {};