goaljs 0.0.0-stage → 0.1.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.
@@ -0,0 +1,987 @@
1
+ // The goal.js compiler.
2
+ //
3
+ // A component is a top-level function with a capitalised name that ends in `return <element>`:
4
+ //
5
+ // export function Counter({ start }) {
6
+ // var count = start; // state
7
+ // const double = count * 2; // computed
8
+ // return (
9
+ // <div>
10
+ // <button onclick={() => count++}>+</button>
11
+ // {if (count > 9) <p>big: {double}</p> else <p>{double}</p>}
12
+ // </div>
13
+ // );
14
+ // }
15
+ //
16
+ // route GET /users/{id} { return <main><Counter start={Number(id)} /></main>; }
17
+ // server function save(text) { ... } called from a handler as save(text): no async, no fetch
18
+ //
19
+ // compile() turns one .goal file into
20
+ // - a server module: each component becomes `Name(props, ctx)` returning HTML, with markers around
21
+ // the parts that depend on state, and the state and the props the browser needs written into its
22
+ // root element; each route becomes a handler in `_$routes`;
23
+ // - one client module per interactive component: `default(state, props)` is the component as it was
24
+ // written (its `var`s start from the state), returning [binding values, handlers, read the state].
25
+ // The loader runs a handler, saves the state, runs the body again, and patches the bindings whose
26
+ // value changed. Nothing runs until the first event.
27
+ // Both carry source maps back to the .goal file, so a debugger shows the code as it was written.
28
+
29
+ import { parse } from '@babel/parser';
30
+ import traverse from '@babel/traverse';
31
+ import { generate } from '@babel/generator';
32
+ import * as t from '@babel/types';
33
+ import { desugar, errorAt, GoalError } from './syntax.js';
34
+ import { URL_ATTRS, _$u } from './rt.js';
35
+
36
+ export { GoalError };
37
+
38
+ const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
39
+ const HELPERS = ['_$m', '_$h', '_$a', '_$e', '_$u', '_$pa', '_$ctx', '_$sf', '_$call', '_$hl', '_$L'];
40
+ const ROUTE_HELPERS = ['redirect', 'json', 'notFound', 'cookie'];
41
+ const FORM_METHODS = ['get', 'post', 'put', 'patch', 'delete'];
42
+
43
+ let SRC; // the file being compiled: { source, file }
44
+
45
+ /** An error at a node; positions are already in the .goal source (see relocate). */
46
+ function fail(message, node) {
47
+ throw errorAt(SRC.source, SRC.file, node.loc.start.index, message);
48
+ }
49
+
50
+ /** Moves every node's position from the desugared code back to the .goal source. */
51
+ function relocate(ast, source, map, file) {
52
+ const starts = [0];
53
+ for (let i = 0; i < source.length; i++) if (source[i] === '\n') starts.push(i + 1);
54
+ const pos = (index) => {
55
+ const at = map(index);
56
+ let lo = 0;
57
+ let hi = starts.length - 1;
58
+ while (lo < hi) {
59
+ const mid = (lo + hi + 1) >> 1;
60
+ if (starts[mid] <= at) lo = mid;
61
+ else hi = mid - 1;
62
+ }
63
+ return { line: lo + 1, column: at - starts[lo], index: at };
64
+ };
65
+ t.traverseFast(ast, (n) => {
66
+ n.loc = { start: pos(n.loc.start.index), end: pos(n.loc.end.index), filename: file, identifierName: n.loc.identifierName };
67
+ });
68
+ }
69
+
70
+ /** Code with an inline source map back to the .goal source. */
71
+ function emit(node) {
72
+ const out = generate(node, { sourceMaps: true, sourceFileName: SRC.file.split('/').at(-1) }, SRC.source);
73
+ return `${out.code}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${Buffer.from(JSON.stringify(out.map)).toString('base64')}\n`;
74
+ }
75
+
76
+ /**
77
+ * Compiles one .goal file.
78
+ * @param {string} source
79
+ * @param {{ file?: string, base?: string, rt?: string, list?: string, chunk?: (name: string) => string,
80
+ * serverFunctions?: (specifier: string) => { base: string, names: string[] } | null }} [opts]
81
+ * file: the name in errors and source maps; base: the file's path without .goal, which names its
82
+ * server functions' URLs (/_m/<base>/<name>); rt and keyed: where compiled code imports the helpers
83
+ * and the keyed list patcher from;
84
+ * chunk: the URL the browser loads a component's client module from; serverFunctions: the server
85
+ * functions another .goal file exports, for imports of it.
86
+ */
87
+ export function compile(source, opts = {}) {
88
+ const file = opts.file ?? 'input.goal';
89
+ const base = opts.base ?? file.replace(/\.goal$/, '');
90
+ const o = { file, rt: opts.rt ?? 'goaljs/rt', keyed: opts.keyed ?? 'goaljs/keyed', chunk: opts.chunk ?? ((n) => `/${n}.js`), sfns: new Map() };
91
+ const d = desugar(source, file);
92
+ SRC = { source, file };
93
+ const ast = parse(d.code, { sourceType: 'module', plugins: ['jsx'] });
94
+ relocate(ast, source, d.map, file.split('/').at(-1)); // source maps name the file next to the compiled one
95
+
96
+ // Server functions this file can call: its own, and the ones it imports from other .goal files.
97
+ for (const f of d.serverFns) o.sfns.set(f.name, `/_m/${base}/${f.name}`);
98
+ for (const s of ast.program.body) {
99
+ if (!t.isImportDeclaration(s) || !s.source.value.endsWith('.goal')) continue;
100
+ const other = opts.serverFunctions?.(s.source.value);
101
+ for (const sp of s.specifiers)
102
+ if (other && t.isImportSpecifier(sp) && other.names.includes(sp.imported.name)) o.sfns.set(sp.local.name, `/_m/${other.base}/${sp.imported.name}`);
103
+ }
104
+ o.own = new Set(d.serverFns.map((f) => f.name));
105
+
106
+ const server = transform(ast, 'server', o, d.routes);
107
+ const client = transform(ast, 'client', o, d.routes);
108
+ const clients = [];
109
+ for (const c of client.components.filter((c) => c.interactive)) {
110
+ const { code, keys } = clientModule(client.program, c, o);
111
+ clients.push({ name: c.name, code });
112
+ server.components.find((s) => s.name === c.name).keys.elements.push(...keys.map((k) => t.stringLiteral(k)));
113
+ }
114
+
115
+ const body = server.program;
116
+ body.unshiftContainer('body', importHelpers(o.rt));
117
+ const endpoints = d.serverFns.map((f) => ({ name: f.name, path: o.sfns.get(f.name) }));
118
+ if (d.routes.length || endpoints.length)
119
+ body.pushContainer(
120
+ 'body',
121
+ t.exportNamedDeclaration(
122
+ t.variableDeclaration('const', [
123
+ t.variableDeclarator(
124
+ t.identifier('_$routes'),
125
+ t.arrayExpression([
126
+ ...d.routes.map((r) => routeEntry(r.method, r.path, t.identifier(r.name))),
127
+ ...endpoints.map((f) =>
128
+ routeEntry(
129
+ 'POST',
130
+ f.path,
131
+ t.arrowFunctionExpression(
132
+ [t.identifier('r'), t.identifier('x')],
133
+ t.callExpression(t.identifier('_$call'), [t.identifier(f.name), t.identifier('r'), t.identifier('x')]),
134
+ ),
135
+ ),
136
+ ),
137
+ ]),
138
+ ),
139
+ ]),
140
+ ),
141
+ );
142
+ return {
143
+ server: emit(body.node),
144
+ clients,
145
+ components: server.components.map(({ name, interactive, events }) => ({ name, interactive, events })),
146
+ routes: d.routes.map(({ method, path }) => ({ method, path })),
147
+ serverFunctions: endpoints,
148
+ };
149
+ }
150
+
151
+ const routeEntry = (method, path, handler) =>
152
+ t.objectExpression([
153
+ t.objectProperty(t.identifier('method'), t.stringLiteral(method)),
154
+ t.objectProperty(t.identifier('path'), t.stringLiteral(path)),
155
+ t.objectProperty(t.identifier('handler'), handler),
156
+ ]);
157
+
158
+ // ---------------------------------------------------------------------------------------------
159
+ // Whole-file transform. Each mode works on its own deep copy of the file, so both copies have
160
+ // fresh scope information and the same traversal order (binding and handler numbers match).
161
+
162
+ function transform(ast, mode, o, routes) {
163
+ const program = programPath(t.cloneNode(ast, true));
164
+ o.tplN = 0; // row templates are numbered the same way in both modes
165
+ const byName = new Map(routes.map((r) => [r.name, r]));
166
+ const routeFns = program.get('body').filter((s) => s.isFunctionDeclaration() && byName.has(s.node.id.name));
167
+ for (const r of routeFns) if (mode === 'client') r.remove();
168
+ const comps = componentPaths(program);
169
+ for (const fn of comps) clientRules(fn);
170
+ serverCalls(program, comps, o);
171
+ const components = comps.map((fn) => component(fn, program, mode, o));
172
+ if (mode === 'server') for (const r of routeFns) route(r, byName.get(r.node.id.name), program);
173
+ // Markup outside components and routes (helpers that return markup) becomes plain templates.
174
+ program.traverse(jsxVisitor({ kind: 'module', hs: null, scope: program.scope, program: program.scope, reactive: new Set() }));
175
+ return { program, components };
176
+ }
177
+
178
+ function programPath(file) {
179
+ let found;
180
+ traverse(file, {
181
+ Program(p) {
182
+ found = p;
183
+ p.stop();
184
+ },
185
+ });
186
+ return found;
187
+ }
188
+
189
+ function componentPaths(program) {
190
+ const out = [];
191
+ for (const s of program.get('body')) {
192
+ const isExport = s.isExportNamedDeclaration() || s.isExportDefaultDeclaration();
193
+ const d = isExport ? s.get('declaration') : s;
194
+ if (!d.isFunctionDeclaration()) continue;
195
+ if (!d.node.id) fail('give the function a name: export default function Page() { ... }', d.node);
196
+ if (/^[A-Z]/.test(d.node.id.name)) out.push(d);
197
+ }
198
+ return out;
199
+ }
200
+
201
+ // ---------------------------------------------------------------------------------------------
202
+ // Server functions. A call in an event handler becomes `await _$sf(url, [args])`, a request to the
203
+ // server, and the handler waits for it; a call in a route or another server function is awaited.
204
+ // Nobody writes async, await or fetch for it.
205
+
206
+ /** Components run in the browser, where data comes from server functions: no async, no fetch. */
207
+ function clientRules(comp) {
208
+ if (comp.node.async) fail("a component can't be async: call a server function from an event handler, and goal.js waits for it", comp.node);
209
+ comp.traverse({
210
+ Function(p) {
211
+ if (p.node.async) fail('no async in components: call a server function, and goal.js waits for it', p.node);
212
+ },
213
+ Identifier(p) {
214
+ if (p.node.name === 'fetch' && p.isReferencedIdentifier() && !p.scope.hasBinding('fetch'))
215
+ fail('call a server function instead of fetch: server function load() { ... } in a .goal file', p.node);
216
+ },
217
+ });
218
+ }
219
+
220
+ function serverCalls(program, comps, o) {
221
+ const made = new Set(); // functions in components that now wait for the server
222
+ const visit = (call, url) => {
223
+ const fn = call.getFunctionParent();
224
+ if (!fn) fail('call a server function from a route, another server function or an event handler', call.node);
225
+ const comp = comps.find((c) => c.node === fn.node || fn.isDescendant(c));
226
+ if (!comp) {
227
+ if (!fn.node.async) fail('call a server function from a route, another server function or an event handler', call.node);
228
+ if (url && !call.parentPath.isAwaitExpression()) call.replaceWith(t.awaitExpression(call.node));
229
+ return;
230
+ }
231
+ if (fn.node === comp.node) fail("a server function can't run while a component renders: call it from an event handler, or load the data in the route", call.node);
232
+ const parent = fn.parentPath;
233
+ const handler = parent.isJSXExpressionContainer() && parent.parentPath.isJSXAttribute() && /^on/.test(parent.parent.name.name);
234
+ const declared = fn.isFunctionDeclaration() ? fn : parent.isVariableDeclarator() ? parent : null;
235
+ const top = declared && (fn.isFunctionDeclaration() ? fn.parent : declared.parentPath.parent) === comp.node.body;
236
+ if (!handler && !top) fail('call server functions in an event handler, or in a function declared at the top of the component', call.node);
237
+ fn.node.async = true;
238
+ const args = t.arrayExpression(call.node.arguments);
239
+ if (url) call.replaceWith(t.awaitExpression(t.callExpression(t.identifier('_$sf'), [t.stringLiteral(url), args])));
240
+ else call.replaceWith(t.awaitExpression(call.node)); // a call to a function made to wait just above
241
+ if (!top) return;
242
+ // Calls to this function wait for it too.
243
+ const b = comp.scope.getBinding(fn.isFunctionDeclaration() ? fn.node.id.name : parent.node.id.name);
244
+ if (!made.has(b)) {
245
+ made.add(b);
246
+ for (const r of b.referencePaths) if (r.parentPath.isCallExpression({ callee: r.node })) visit(r.parentPath, null);
247
+ }
248
+ };
249
+ program.traverse({
250
+ CallExpression(p) {
251
+ const callee = p.node.callee;
252
+ if (t.isIdentifier(callee) && o.sfns.has(callee.name) && p.scope.getBinding(callee.name)?.scope === program.scope) visit(p, o.sfns.get(callee.name));
253
+ },
254
+ });
255
+ }
256
+
257
+ // ---------------------------------------------------------------------------------------------
258
+ // Routes: server-only handlers, run once per request.
259
+
260
+ function route(fn, meta, program) {
261
+ for (const [name, b] of Object.entries(fn.scope.bindings))
262
+ if (b.kind === 'var') fail(`\`${name}\`: state (var) belongs in a component, because a route runs once per request. Use let or const`, b.path.node);
263
+ for (const p of meta.params) if (fn.scope.hasOwnBinding(p)) fail(`\`${p}\` is already the route's path parameter {${p}}`, fn.scope.getBinding(p).identifier);
264
+
265
+ const cId = t.identifier('_$c');
266
+ fn.get('body').traverse(jsxVisitor({ kind: 'route', hs: null, scope: fn.scope, program: program.scope, reactive: new Set(), cId }));
267
+
268
+ const x = t.identifier('_$x');
269
+ const pre = [t.variableDeclaration('const', [t.variableDeclarator(cId, t.memberExpression(x, t.identifier('ctx')))])];
270
+ const helpers = ROUTE_HELPERS.filter((n) => !fn.scope.hasBinding(n));
271
+ if (helpers.length) pre.push(t.variableDeclaration('const', [t.variableDeclarator(t.objectPattern(helpers.map(shorthand)), x)]));
272
+ if (meta.params.length)
273
+ pre.push(t.variableDeclaration('const', [t.variableDeclarator(t.objectPattern(meta.params.map(shorthand)), t.memberExpression(t.identifier('request'), t.identifier('params')))]));
274
+ fn.get('body').unshiftContainer('body', pre);
275
+ }
276
+
277
+ const shorthand = (n) => t.objectProperty(t.identifier(n), t.identifier(n), false, true);
278
+
279
+ // ---------------------------------------------------------------------------------------------
280
+ // One component.
281
+
282
+ function component(fn, program, mode, o) {
283
+ const name = fn.node.id.name;
284
+ const { state, reactive, withHandlers } = analyze(fn);
285
+ const cx = {
286
+ kind: 'component',
287
+ scope: fn.scope,
288
+ program: program.scope,
289
+ reactive,
290
+ withHandlers,
291
+ dyn: 0, // handlers made while rendering, e.g. one per list item
292
+ offset: t.numericLiteral(0), // where they start: after the fixed handlers
293
+ binds: [], // { k: [kind, n, attr?], e: expression } kind 0: child, 1: attribute
294
+ hs: [], // handler expressions, in the order they appear
295
+ events: new Set(),
296
+ elems: 0,
297
+ iId: t.identifier('_$i'),
298
+ cId: t.identifier('_$c'),
299
+ tpls: [], // row templates of keyed lists, as module-level declarations
300
+ cache: [], // keyed lists whose rows the browser keeps from run to run
301
+ mode,
302
+ o,
303
+ };
304
+
305
+ const body = fn.get('body');
306
+ const ret = body.get('body').at(-1);
307
+ const rootParts = element(ret.get('argument'), cx, true, true);
308
+ ret.get('argument').replaceWith(t.nullLiteral());
309
+ body.traverse(jsxVisitor(cx)); // other markup in the body: helpers, saved fragments
310
+
311
+ cx.offset.value = cx.hs.length;
312
+ const interactive = cx.binds.length > 0 || cx.hs.length > 0 || cx.dyn > 0;
313
+ const events = [...cx.events];
314
+ const param = fn.node.params[0];
315
+ const keys = t.arrayExpression([]); // the props the browser needs, filled in from the client module
316
+ const info = { name, interactive, events, state, binds: cx.binds, hs: cx.hs, param, keys, dyn: cx.dyn, offset: cx.offset, tpls: cx.tpls, cache: cx.cache };
317
+ program.pushContainer('body', cx.tpls);
318
+
319
+ if (mode === 'server') {
320
+ const pId = t.identifier('_$p');
321
+ const parts = rootParts.flatMap((x) => (x === ROOT ? (interactive ? rootAttrs(cx, o.chunk(name), state, param, pId, keys) : []) : [x]));
322
+ ret.get('argument').replaceWith(template(parts));
323
+ const pre = [];
324
+ if (param) pre.push(t.variableDeclaration('let', [t.variableDeclarator(patternOf(param), pId)]));
325
+ pre.push(t.variableDeclaration('const', [t.variableDeclarator(cx.iId, t.updateExpression('++', t.memberExpression(cx.cId, t.identifier('i'))))]));
326
+ if (events.length) pre.push(t.expressionStatement(t.callExpression(t.memberExpression(cx.cId, t.identifier('e')), [t.valueToNode(events)])));
327
+ if (cx.dyn) {
328
+ // The server only numbers the handlers made while rendering; the browser keeps them.
329
+ pre.push(t.variableDeclaration('let', [t.variableDeclarator(t.identifier('_$n'), t.numericLiteral(0))]));
330
+ pre.push(
331
+ t.variableDeclaration('const', [
332
+ t.variableDeclarator(t.identifier('_$hd'), t.arrowFunctionExpression([], t.binaryExpression('+', cx.offset, t.updateExpression('++', t.identifier('_$n'))))),
333
+ ]),
334
+ );
335
+ }
336
+ body.unshiftContainer('body', pre);
337
+ fn.node.params = [t.assignmentPattern(pId, t.objectExpression([])), t.assignmentPattern(cx.cId, t.callExpression(t.identifier('_$ctx'), []))];
338
+ }
339
+ return info;
340
+ }
341
+
342
+ const patternOf = (param) => (t.isAssignmentPattern(param) ? param.left : param);
343
+
344
+ const ROOT = Symbol('root attributes');
345
+
346
+ function rootAttrs(cx, url, state, param, pId, keys) {
347
+ const parts = [` m-c="${escAttr(url)}" m-i="`, cx.iId, '"'];
348
+ if (state.length)
349
+ parts.push(
350
+ ' m-s="',
351
+ t.callExpression(t.identifier('_$e'), [
352
+ t.callExpression(t.memberExpression(t.identifier('JSON'), t.identifier('stringify')), [t.objectExpression(state.map(shorthand))]),
353
+ ]),
354
+ '"',
355
+ );
356
+ if (param) parts.push(t.callExpression(t.identifier('_$pa'), [pId, keys]));
357
+ return parts;
358
+ }
359
+
360
+ // The rules, and which bindings depend on state.
361
+ function analyze(fn) {
362
+ const node = fn.node;
363
+ if (node.generator) fail("a component can't be a generator", node);
364
+ if (node.params.length > 1) fail('a component takes one parameter, its props', node.params[1]);
365
+ const stmts = fn.get('body.body');
366
+ const last = stmts.at(-1);
367
+ if (!last || !last.isReturnStatement() || !last.get('argument').isJSXElement())
368
+ fail('a component ends with `return <element>` (one element, not a fragment)', last ? last.node : node);
369
+ fn.get('body').traverse({
370
+ ReturnStatement(p) {
371
+ if (p.node !== last.node && p.getFunctionParent() === fn) fail('a component has one return, at the end', p.node);
372
+ },
373
+ });
374
+
375
+ const state = [];
376
+ const deps = new Map();
377
+ for (const [name, b] of Object.entries(fn.scope.bindings)) {
378
+ if (b.kind === 'var') {
379
+ const d = b.path;
380
+ if (!t.isIdentifier(d.node.id)) fail('declare state one name at a time: var name = value', d.node);
381
+ if (d.parentPath.parent !== node.body) fail(`declare \`var ${name}\` at the top of the component, not inside a block`, d.node);
382
+ for (const v of b.constantViolations) {
383
+ if (v.getFunctionParent() === fn) fail(`\`${name}\` is state: change it in an event handler, not while rendering`, v.node);
384
+ if (!v.isUpdateExpression() && !(v.isAssignmentExpression() && t.isIdentifier(v.node.left)))
385
+ fail(`change state with \`${name} = value\`, not by destructuring`, v.node);
386
+ }
387
+ state.push(name);
388
+ } else if (b.kind === 'let' || b.kind === 'const' || b.kind === 'hoisted') {
389
+ for (const v of b.constantViolations)
390
+ if (v.getFunctionParent() !== fn) fail(`\`${name}\` is computed from state, so a handler can't change it. Declare it with \`var\` to make it state`, v.node);
391
+ deps.set(name, [b.path, ...b.constantViolations.map((v) => topStatement(v, node.body))]);
392
+ }
393
+ }
394
+
395
+ // Names whose markup has event handlers: a hole that uses one is rendered in the browser too.
396
+ const withHandlers = new Set();
397
+ for (const [name, paths] of deps) {
398
+ let found = false;
399
+ paths[0].traverse({
400
+ JSXAttribute(a) {
401
+ if (/^on/.test(a.node.name.name)) found = true;
402
+ },
403
+ });
404
+ if (found) withHandlers.add(name);
405
+ }
406
+
407
+ const reactive = new Set(state);
408
+ for (let grew = true; grew; ) {
409
+ grew = false;
410
+ for (const [name, paths] of deps)
411
+ if (!reactive.has(name) && paths.some((p) => uses(p, fn.scope, reactive))) {
412
+ reactive.add(name);
413
+ grew = true;
414
+ }
415
+ }
416
+ return { state, reactive, withHandlers };
417
+ }
418
+
419
+ function topStatement(p, body) {
420
+ while (p.parent !== body) p = p.parentPath;
421
+ return p;
422
+ }
423
+
424
+ /** Does the code at `path` read any of `names`, as bound in `scope`? */
425
+ function uses(path, scope, names) {
426
+ let hit = false;
427
+ const check = (p) => {
428
+ if (names.has(p.node.name) && p.scope.getBinding(p.node.name)?.scope === scope) hit = true;
429
+ };
430
+ if (path.isIdentifier()) check(path);
431
+ path.traverse({
432
+ Identifier(p) {
433
+ if (p.isReferencedIdentifier()) check(p);
434
+ },
435
+ });
436
+ return hit;
437
+ }
438
+
439
+ // ---------------------------------------------------------------------------------------------
440
+ // Markup to HTML templates.
441
+ //
442
+ // `top` is the fixed part of a component: its root and the elements around the holes. There, holes
443
+ // and attributes that depend on state become bindings with markers. Inside a hole (a `{...}` child)
444
+ // everything is a plain template, and the whole hole is rendered again when it changes.
445
+
446
+ function element(p, cx, top, root, row) {
447
+ const rowRoot = row && p.node === row.root;
448
+ const nameNode = p.node.openingElement.name;
449
+ if (!t.isJSXIdentifier(nameNode)) fail('use plain tag names and component names, like <div> or <Counter>', nameNode);
450
+ const tag = nameNode.name;
451
+ if (/^[A-Z]/.test(tag)) {
452
+ if (cx.kind === 'route' || (cx.kind === 'component' && top && !root)) return componentCall(p, cx, tag);
453
+ fail(
454
+ cx.kind === 'component'
455
+ ? `place <${tag}> in the fixed part of a component: not as its root, not inside {...}`
456
+ : `<${tag}> goes in a route or in the fixed part of a component`,
457
+ p.node,
458
+ );
459
+ }
460
+ if (tag === 'script') fail("<script> isn't allowed: goal.js writes the page's scripts. Put the code in a component", p.node);
461
+ if (tag === 'style') fail('put CSS in a file under public/ and link it: <link rel="stylesheet" href="/style.css" />', p.node);
462
+
463
+ const parts = ['<' + tag];
464
+ const ons = []; // m-on entries: "click:0" for a fixed handler, or parts that number one made while rendering
465
+ let id;
466
+ let method;
467
+ for (const a of p.get('openingElement.attributes')) {
468
+ if (a.isJSXSpreadAttribute()) fail('spread attributes are not supported yet', a.node);
469
+ if (!t.isJSXIdentifier(a.node.name)) fail('namespaced attributes are not supported', a.node);
470
+ const name = a.node.name.name;
471
+ const v = a.get('value');
472
+ if (name === 'key') {
473
+ if (!v.isJSXExpressionContainer()) fail('a key is an expression: key={x.id}', a.node);
474
+ if (rowRoot) {
475
+ row.key = v.node.expression;
476
+ continue;
477
+ }
478
+ // Not a row the browser patches by key: fine for a list that never changes, which renders once.
479
+ const list = mapOf(p);
480
+ if (!list) fail('key goes on the outer element of a list row: items.map((x) => <li key={x.id}>...</li>)', a.node);
481
+ if (cx.inRow) fail("a keyed list can't go inside another list's row yet: drop this key, and the inner list is made again with its row", a.node);
482
+ if (cx.kind === 'component' && changes(list, cx))
483
+ fail('a keyed list that changes goes straight in the markup, or straight in an {if} or a ternary: <ul>{items.map((x) => <li key={x.id}>...</li>)}</ul>', a.node);
484
+ continue;
485
+ }
486
+ if (/^on/i.test(name)) {
487
+ if (/[A-Z]/.test(name)) fail(`write ${name.toLowerCase()}, the HTML name, not ${name}`, a.node);
488
+ if (!v.isJSXExpressionContainer()) fail(`${name} takes a function: ${name}={() => ...}. A string of code isn't allowed`, a.node);
489
+ if (!cx.hs) fail(cx.inRow ? 'put the handler on an element of the list row, not inside {...}' : 'event handlers go inside a component', a.node);
490
+ const ev = name.slice(2);
491
+ cx.events.add(ev);
492
+ if (row) {
493
+ ons.push([`${ev}:r${row.hs.length}`]); // the row's own handler, found from the row at run time
494
+ row.hs.push(v.node.expression);
495
+ } else if (top) {
496
+ ons.push([`${ev}:${cx.hs.length}`]);
497
+ cx.hs.push(v.node.expression);
498
+ } else {
499
+ ons.push([`${ev}:`, t.callExpression(t.identifier('_$hd'), [v.node.expression])]);
500
+ cx.dyn++;
501
+ }
502
+ continue;
503
+ }
504
+ if (name === 'className') fail('write class, as in HTML', a.node);
505
+ if (name === 'htmlFor') fail('write for, as in HTML', a.node);
506
+ if (name === 'srcdoc') fail("srcdoc isn't allowed: it puts raw HTML in the page", a.node);
507
+ if (tag === 'form' && name === 'method') {
508
+ if (!v.isStringLiteral()) fail('write the form method as text: method="post"', a.node);
509
+ method = v.node.value.toLowerCase();
510
+ if (!FORM_METHODS.includes(method)) fail(`a form's method is one of ${FORM_METHODS.join(', ')}`, a.node);
511
+ parts.push(` method="${method === 'get' ? 'get' : 'post'}"`);
512
+ } else if (!v.node) parts.push(' ' + name);
513
+ else if (v.isStringLiteral()) {
514
+ const s = v.node.value;
515
+ if (URL_ATTRS.has(name) && _$u(s) !== s) fail(`${name} can't be a ${s.split(':')[0].trim()}: URL`, a.node);
516
+ parts.push(` ${name}="${escAttr(s)}"`);
517
+ } else if (v.isJSXExpressionContainer() && row) {
518
+ const e = v.node.expression;
519
+ const val = URL_ATTRS.has(name) ? t.callExpression(t.identifier('_$u'), [e]) : e;
520
+ parts.push(t.callExpression(t.identifier('_$a'), [t.stringLiteral(name), rowValue(row, val, [1, [...row.path], name], v.get('expression'), cx)]));
521
+ } else if (v.isJSXExpressionContainer()) {
522
+ const e = v.get('expression');
523
+ if (top && uses(e, cx.scope, cx.reactive)) {
524
+ id ??= cx.elems++;
525
+ cx.binds.push({ k: [1, id, name], e: URL_ATTRS.has(name) ? t.callExpression(t.identifier('_$u'), [e.node]) : e.node });
526
+ }
527
+ parts.push(t.callExpression(t.identifier('_$a'), [t.stringLiteral(name), e.node]));
528
+ } else fail('an attribute value is "text" or {expression}', a.node);
529
+ }
530
+ if (ons.length) parts.push(' m-on="', ...ons.flatMap((o, i) => (i ? [' ', ...o] : o)), '"');
531
+ if (id !== undefined) parts.push(' m-x="', cx.iId, `.${id}"`);
532
+ if (rowRoot) parts.push(` m-r="${row.k}"`);
533
+ if (root) parts.push(ROOT);
534
+ parts.push('>');
535
+ if (method && method !== 'get') {
536
+ if (!(cx.kind === 'route' || (cx.kind === 'component' && top)))
537
+ fail('a form that sends data goes in a route, or in the fixed part of a component', p.node);
538
+ parts.push('<input type="hidden" name="_csrf" value="', t.callExpression(t.identifier('_$e'), [t.memberExpression(cx.cId, t.identifier('t'))]), '">');
539
+ if (method !== 'post') parts.push(`<input type="hidden" name="_method" value="${method}">`);
540
+ }
541
+ if (VOID.has(tag)) {
542
+ if (p.node.children.length) fail(`<${tag}> can't have children`, p.node);
543
+ return parts;
544
+ }
545
+ children(p, cx, top, parts, row);
546
+ parts.push(`</${tag}>`);
547
+ return parts;
548
+ }
549
+
550
+ /**
551
+ * A value of a list row: a row is [key, item, index, ...values], and the row template reads it as
552
+ * v[i]. A value that reads only the item, the index and module-level names depends on the item
553
+ * alone, so a row whose item is the same keeps it; any other (`row.id === selected`, or a local of
554
+ * the callback) is worked out on every run.
555
+ */
556
+ function rowValue(row, e, part, path, cx) {
557
+ row.parts.push(part);
558
+ row.outer.push(refs(path, (b) => b.scope !== cx.program && !(b.kind === 'param' && b.scope === row.scope)));
559
+ return t.memberExpression(t.identifier('v'), t.numericLiteral(row.vals.push(e) + 2), true);
560
+ }
561
+
562
+ /** Does the code at `path` read a name whose binding passes `test`? */
563
+ function refs(path, test) {
564
+ let hit = false;
565
+ const check = (p) => {
566
+ const b = p.scope.getBinding(p.node.name);
567
+ if (b && test(b)) hit = true;
568
+ };
569
+ if (path.isIdentifier()) check(path);
570
+ path.traverse({
571
+ Identifier(p) {
572
+ if (p.isReferencedIdentifier()) check(p);
573
+ },
574
+ });
575
+ return hit;
576
+ }
577
+
578
+ function children(p, cx, top, parts, row) {
579
+ let n = 0; // the element's index among its element children: a row value's path
580
+ for (const c of p.get('children')) {
581
+ if (c.isJSXText()) parts.push(cleanText(c.node.value));
582
+ else if (c.isJSXElement()) {
583
+ row?.path.push(n++);
584
+ parts.push(...element(c, cx, top, false, row));
585
+ row?.path.pop();
586
+ } else if (c.isJSXFragment()) {
587
+ if (row) row.whole = true; // element paths through a fragment are not tracked: a changed row is made again
588
+ children(c, cx, top, parts, row);
589
+ } else if (c.get('expression').isJSXEmptyExpression()) continue;
590
+ else if (row) {
591
+ // A hole in a row: the text of its element when it is the only child, otherwise the row is made again.
592
+ if (!p.node.children.every((x) => x === c.node || (t.isJSXText(x) && cleanText(x.value) === ''))) row.whole = true;
593
+ inner(c.get('expression'), { ...cx, hs: null, inRow: true });
594
+ parts.push(rowValue(row, t.callExpression(t.identifier('_$h'), [c.node.expression]), [0, [...row.path]], c.get('expression'), cx));
595
+ } else if (top && cx.kind === 'component' && keyedList(c, cx, parts)) continue;
596
+ else hole(c, cx, top, parts);
597
+ }
598
+ }
599
+
600
+ /** Does this expression read state, or a function that changes state? Then what it renders can change. */
601
+ const changes = (e, cx) => uses(e, cx.scope, cx.reactive) || uses(e, cx.scope, cx.withHandlers);
602
+
603
+ /** A `{...}` hole: in the fixed part of a component, one that can change becomes a binding between markers. */
604
+ function hole(c, cx, top, parts) {
605
+ const dyn = cx.dyn;
606
+ inner(c.get('expression'), cx);
607
+ const ex = t.callExpression(t.identifier('_$h'), [c.node.expression]);
608
+ if (top && (cx.dyn > dyn || changes(c.get('expression'), cx))) {
609
+ const k = cx.binds.length;
610
+ cx.binds.push({ k: [0, k], e: ex });
611
+ parts.push('<!--', cx.iId, `.${k}-->`, ex, '<!--/-->');
612
+ } else parts.push(ex);
613
+ }
614
+
615
+ const isMap = (e) => e.isCallExpression() && t.isMemberExpression(e.node.callee, { computed: false }) && e.node.callee.property.name === 'map';
616
+
617
+ /** The `.map(...)` call whose callback returns this element, when the element is a list row. */
618
+ function mapOf(p) {
619
+ let f = p.parentPath;
620
+ if (f.isReturnStatement()) f = f.parentPath.parentPath; // `return <li>` in the callback's body
621
+ return (f.isArrowFunctionExpression() || f.isFunctionExpression()) && f.listKey === 'arguments' && f.key === 0 && isMap(f.parentPath) ? f.parentPath : null;
622
+ }
623
+
624
+ /**
625
+ * Where a hole's keyed list is: the hole is the `.map(...)` call, or the call is one branch of a
626
+ * condition, `{if (c) items.map(...) else ...}` or `{c ? ... : items.map(...)}`. The other branch,
627
+ * unless it renders nothing, becomes a hole of its own right after the list.
628
+ */
629
+ function listIn(e) {
630
+ if (isMap(e)) return { map: e };
631
+ if (!e.isConditionalExpression()) return null;
632
+ const yes = isMap(e.get('consequent'));
633
+ if (!yes && !isMap(e.get('alternate'))) return null;
634
+ const other = e.node[yes ? 'alternate' : 'consequent'];
635
+ return { map: e.get(yes ? 'consequent' : 'alternate'), test: e.node.test, yes, other: t.isNullLiteral(other) ? null : other };
636
+ }
637
+
638
+ /**
639
+ * `{items.map((x, i) => <tr key={x.id}>...</tr>)}` in the fixed part of a component: a keyed list,
640
+ * patched by key in the browser (keyed.js), which only a component with one loads. A list without
641
+ * keys is a plain hole, made again as a whole when it changes. The row becomes a template (a
642
+ * module-level function of a row) and the callback returns [key, item, index, ...values] for each
643
+ * item. The row's handlers come from a second function of (item, index), called only for a row
644
+ * that gets an event. In a condition the list is the rows of its branch, or none.
645
+ */
646
+ function keyedList(c, cx, parts) {
647
+ const shape = listIn(c.get('expression'));
648
+ if (!shape) return false;
649
+ const e = shape.map;
650
+ const fn = e.get('arguments.0');
651
+ if (!fn || !(fn.isArrowFunctionExpression() || fn.isFunctionExpression())) return false;
652
+ let rowEl = fn.get('body');
653
+ let returns = 0;
654
+ let handlers = false;
655
+ fn.traverse({
656
+ ReturnStatement(r) {
657
+ if (r.getFunctionParent() === fn) returns++;
658
+ },
659
+ JSXAttribute(a) {
660
+ if (/^on/i.test(a.node.name.name)) handlers = true;
661
+ },
662
+ });
663
+ if (rowEl.isBlockStatement()) {
664
+ const last = rowEl.get('body').at(-1);
665
+ rowEl = returns === 1 && last?.isReturnStatement() ? last.get('argument') : null;
666
+ }
667
+ if (!rowEl?.isJSXElement()) return false;
668
+ if (!rowEl.node.openingElement.attributes.some((a) => t.isJSXAttribute(a) && a.name.name === 'key')) return false;
669
+ if (!handlers && !changes(c.get('expression'), cx)) return false;
670
+
671
+ const k = cx.binds.length;
672
+ cx.binds.push(null);
673
+ const row = { k, root: rowEl.node, scope: fn.scope, vals: [], hs: [], parts: [], outer: [], path: [], whole: false, key: null };
674
+ // Does the row read its index? Then a row moved to another index is worked out again.
675
+ const index = fn.node.params[1];
676
+ const byIndex = !!index && (!t.isIdentifier(index) || refs(rowEl, (b) => b.identifier === index));
677
+ const tplParts = element(rowEl, cx, false, false, row);
678
+ // The callback gets (item, index) as plain names: a pattern is taken apart inside it.
679
+ const params = fn.node.params;
680
+ const pre = [];
681
+ ['_$r', '_$j'].forEach((id, n) => {
682
+ if (t.isIdentifier(params[n])) return;
683
+ if (params[n]) pre.push(t.variableDeclaration('const', [t.variableDeclarator(params[n], t.identifier(id))]));
684
+ params[n] = t.identifier(id);
685
+ });
686
+ const result = (els) => (fn.get('body').isBlockStatement() ? t.blockStatement([...pre, ...fn.node.body.body.slice(0, -1), t.returnStatement(t.arrayExpression(els))]) : pre.length ? t.blockStatement([...pre, t.returnStatement(t.arrayExpression(els))]) : t.arrayExpression(els));
687
+ const rowHandlers = t.arrowFunctionExpression(params.map((x) => t.cloneNode(x)), t.cloneNode(result(row.hs), true));
688
+ const name = `_$t${cx.o.tplN++}`;
689
+ cx.tpls.push(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(name), t.arrowFunctionExpression([t.identifier('v')], template(tplParts)))]));
690
+ if (cx.mode === 'server') fn.node.body = result([row.key, params[0], params[1], ...row.vals]);
691
+ else {
692
+ // In the browser a row is kept from the last run when its item (and index, if it reads it) and
693
+ // the component values it reads are the same: then the list patch skips it at once.
694
+ const id = (n) => t.identifier(n + k);
695
+ const [item, idx] = params;
696
+ const kv = t.identifier('_$k');
697
+ const o = t.identifier('_$o');
698
+ const same = t.identifier('_$q');
699
+ const member = (n) => t.memberExpression(o, t.numericLiteral(n), true);
700
+ const and = (xs) => xs.reduce((x, y) => t.logicalExpression('&&', x, y));
701
+ const outer = row.vals.map((v, i) => (row.outer[i] ? t.identifier(`_$d${i}`) : null));
702
+ const vals = row.vals.map((v, i) => outer[i] ?? t.conditionalExpression(same, member(i + 3), v));
703
+ cx.cache.push(k);
704
+ fn.node.body = t.blockStatement([
705
+ ...(t.isBlockStatement(fn.node.body) ? [...pre, ...fn.node.body.body.slice(0, -1)] : pre),
706
+ t.variableDeclaration('const', [
707
+ t.variableDeclarator(kv, row.key),
708
+ t.variableDeclarator(o, t.callExpression(t.memberExpression(id('_$C'), t.identifier('get')), [kv])),
709
+ t.variableDeclarator(same, and([o, t.binaryExpression('===', member(1), item), ...(byIndex ? [t.binaryExpression('===', member(2), idx)] : [])])),
710
+ ...row.vals.flatMap((v, i) => (outer[i] ? [t.variableDeclarator(outer[i], v)] : [])),
711
+ ]),
712
+ t.variableDeclaration('const', [
713
+ t.variableDeclarator(
714
+ t.identifier('_$w'),
715
+ t.conditionalExpression(and([same, ...outer.flatMap((d, i) => (d ? [t.binaryExpression('===', member(i + 3), d)] : []))]), o, t.arrayExpression([kv, item, idx, ...vals])),
716
+ ),
717
+ ]),
718
+ t.expressionStatement(t.callExpression(t.memberExpression(id('_$N'), t.identifier('set')), [kv, t.identifier('_$w')])),
719
+ t.returnStatement(t.identifier('_$w')),
720
+ ]);
721
+ }
722
+ let list = e.node;
723
+ if (shape.test) {
724
+ // No rows while the condition says no: one empty array for the module, so a list that stays
725
+ // empty is the same value from run to run and the browser leaves it alone.
726
+ const none = t.identifier(`_$t${cx.o.tplN++}`);
727
+ cx.tpls.push(t.variableDeclaration('const', [t.variableDeclarator(none, t.arrayExpression([]))]));
728
+ list = t.conditionalExpression(shape.test, shape.yes ? list : none, shape.yes ? none : list);
729
+ }
730
+ cx.binds[k] = { k: [2, k, name, row.whole ? null : row.parts], e: t.callExpression(t.identifier('_$L'), [list, rowHandlers]) };
731
+ parts.push('<!--', cx.iId, `.${k}-->`, t.callExpression(t.identifier('_$hl'), [list, t.identifier(name)]), '<!--/-->');
732
+ if (shape.other) {
733
+ const other = t.cloneNode(shape.other, true);
734
+ const [after] = c.insertAfter(t.jsxExpressionContainer(t.conditionalExpression(t.cloneNode(shape.test, true), shape.yes ? t.nullLiteral() : other, shape.yes ? other : t.nullLiteral())));
735
+ hole(after, cx, true, parts);
736
+ }
737
+ return true;
738
+ }
739
+
740
+ /** Replaces the markup inside an expression with templates. */
741
+ function inner(e, cx) {
742
+ if (e.isJSXElement() || e.isJSXFragment()) e.replaceWith(markup(e, cx));
743
+ else e.traverse(jsxVisitor(cx));
744
+ }
745
+
746
+ function jsxVisitor(cx) {
747
+ return {
748
+ 'JSXElement|JSXFragment'(p) {
749
+ p.replaceWith(markup(p, cx));
750
+ p.skip();
751
+ },
752
+ };
753
+ }
754
+
755
+ function markup(p, cx) {
756
+ let parts = [];
757
+ if (p.isJSXElement()) parts = element(p, cx, false, false);
758
+ else children(p, cx, false, parts);
759
+ return t.callExpression(t.identifier('_$m'), [template(parts)]);
760
+ }
761
+
762
+ function componentCall(p, cx, tag) {
763
+ if (p.node.children.some((c) => !t.isJSXText(c) || cleanText(c.value) !== ''))
764
+ fail(`passing children to <${tag}> comes in the next milestone`, p.node);
765
+ const props = [];
766
+ for (const a of p.get('openingElement.attributes')) {
767
+ if (a.isJSXSpreadAttribute()) fail('spread props are not supported yet', a.node);
768
+ if (!t.isJSXIdentifier(a.node.name)) fail('namespaced props are not supported', a.node);
769
+ const name = a.node.name.name;
770
+ if (/^on/i.test(name)) fail(`a component can't take a function prop (${name}) yet`, a.node);
771
+ const v = a.get('value');
772
+ let value;
773
+ if (!v.node) value = t.booleanLiteral(true);
774
+ else if (v.isStringLiteral()) value = v.node;
775
+ else if (v.isJSXExpressionContainer()) {
776
+ if (uses(v.get('expression'), cx.scope, cx.reactive))
777
+ fail(`prop \`${name}\` depends on state; props that change come in the next milestone`, a.node);
778
+ inner(v.get('expression'), cx);
779
+ value = v.node.expression;
780
+ } else fail('a prop value is "text" or {expression}', a.node);
781
+ props.push(t.objectProperty(t.stringLiteral(name), value));
782
+ }
783
+ return [t.callExpression(t.identifier(tag), [t.objectExpression(props), cx.cId])];
784
+ }
785
+
786
+ // Text in markup, with whitespace cleaned the way React does it.
787
+ function cleanText(value) {
788
+ const lines = value.split(/\r\n|\n|\r/);
789
+ let last = 0;
790
+ lines.forEach((l, i) => {
791
+ if (/[^ \t]/.test(l)) last = i;
792
+ });
793
+ let out = '';
794
+ lines.forEach((line, i) => {
795
+ let s = line.replace(/\t/g, ' ');
796
+ if (i !== 0) s = s.replace(/^[ ]+/, '');
797
+ if (i !== lines.length - 1) s = s.replace(/[ ]+$/, '');
798
+ if (s) out += i !== last ? s + ' ' : s;
799
+ });
800
+ return out;
801
+ }
802
+
803
+ const escAttr = (s) => s.replace(/"/g, '&quot;');
804
+
805
+ /** Strings and expressions into one template literal. */
806
+ function template(parts) {
807
+ const quasis = [];
808
+ const exprs = [];
809
+ let s = '';
810
+ for (const x of parts) {
811
+ if (typeof x === 'string') s += x;
812
+ else {
813
+ quasis.push(s);
814
+ exprs.push(x);
815
+ s = '';
816
+ }
817
+ }
818
+ quasis.push(s);
819
+ return t.templateLiteral(
820
+ quasis.map((q, i) => t.templateElement({ raw: q.replace(/\\|`|\$\{/g, (m) => '\\' + m), cooked: q }, i === quasis.length - 1)),
821
+ exprs,
822
+ );
823
+ }
824
+
825
+ // ---------------------------------------------------------------------------------------------
826
+ // Client modules.
827
+
828
+ function importHelpers(rt) {
829
+ return t.importDeclaration(HELPERS.map((h) => t.importSpecifier(t.identifier(h), t.identifier(h))), t.stringLiteral(rt));
830
+ }
831
+
832
+ function clientModule(program, info, o) {
833
+ const body = [importHelpers(o.rt)];
834
+ let comp;
835
+ for (const s of program.node.body) {
836
+ const d = t.isExportNamedDeclaration(s) || t.isExportDefaultDeclaration(s) ? s.declaration : s;
837
+ if (t.isFunctionDeclaration(d) && (/^[A-Z]/.test(d.id.name) || o.own.has(d.id.name))) {
838
+ if (d.id.name === info.name) comp = d;
839
+ } else if (t.isStatement(d) && !/^_\$t\d/.test(d.declarations?.[0].id.name)) body.push(t.cloneNode(d, true)); // `export { a }` and `export default expr` are dropped
840
+ }
841
+ body.push(...info.tpls.map((x) => t.cloneNode(x, true)), ...clientComponent(comp, info)); // row templates before _$k reads them
842
+ if (info.binds.some((b) => b.k[0] === 2))
843
+ body.push(
844
+ t.exportNamedDeclaration(null, [t.exportSpecifier(t.identifier('_$lp'), t.identifier('_$lp'))], t.stringLiteral(o.keyed)),
845
+ t.exportNamedDeclaration(null, [t.exportSpecifier(t.identifier('_$lh'), t.identifier('_$lh'))], t.stringLiteral(o.rt)),
846
+ );
847
+ const file = t.file(t.program(body));
848
+ const prog = programPath(file);
849
+ const fn = prog.get('body').find((s) => s.isExportDefaultDeclaration()).get('declaration');
850
+ shake(fn);
851
+ const keys = propKeys(fn);
852
+ prune(prog, new Set(['_$k', info.name]));
853
+ return { code: emit(file), keys };
854
+ }
855
+
856
+ /**
857
+ * The component as written: each `var` starts from the state, the rest is the same body. It returns
858
+ * the binding values, the handlers, and a function that reads the state back after a handler.
859
+ */
860
+ function clientComponent(fn, info) {
861
+ const s = t.identifier('_$s');
862
+ const stmts = fn.body.body.slice(0, -1).map((st) => {
863
+ if (!t.isVariableDeclaration(st) || st.kind !== 'var') return st;
864
+ const decl = t.variableDeclaration(
865
+ 'var',
866
+ st.declarations.map((d) => Object.assign(t.variableDeclarator(d.id, t.memberExpression(s, t.identifier(d.id.name))), { loc: d.loc })),
867
+ );
868
+ decl.loc = st.loc;
869
+ return decl;
870
+ });
871
+ const pre = [];
872
+ if (info.dyn)
873
+ pre.push(
874
+ t.variableDeclaration('const', [t.variableDeclarator(t.identifier('_$H'), t.arrayExpression([]))]),
875
+ t.variableDeclaration('const', [
876
+ t.variableDeclarator(
877
+ t.identifier('_$hd'),
878
+ t.arrowFunctionExpression(
879
+ [t.identifier('f')],
880
+ t.binaryExpression('-', t.binaryExpression('+', info.offset, t.callExpression(t.memberExpression(t.identifier('_$H'), t.identifier('push')), [t.identifier('f')])), t.numericLiteral(1)),
881
+ ),
882
+ ),
883
+ ]),
884
+ );
885
+ // Each keyed list's rows from the last run (_$C), and this run's (_$N), kept on the state object.
886
+ for (const k of info.cache)
887
+ pre.push(
888
+ t.variableDeclaration('const', [
889
+ t.variableDeclarator(t.identifier('_$C' + k), t.logicalExpression('||', t.memberExpression(s, t.identifier('_$c' + k)), t.newExpression(t.identifier('Map'), []))),
890
+ t.variableDeclarator(t.identifier('_$N' + k), t.assignmentExpression('=', t.memberExpression(s, t.identifier('_$c' + k)), t.newExpression(t.identifier('Map'), []))),
891
+ ]),
892
+ );
893
+ const handlers = t.arrayExpression([...info.hs, ...(info.dyn ? [t.spreadElement(t.identifier('_$H'))] : [])]);
894
+ const read = t.arrowFunctionExpression([], t.objectExpression(info.state.map(shorthand)));
895
+ const result = t.arrayExpression([t.arrayExpression(info.binds.map((b) => b.e)), handlers, read]);
896
+ const f = t.functionDeclaration(t.identifier(info.name), [s, ...(info.param ? [info.param] : [])], t.blockStatement([...pre, ...stmts, t.returnStatement(result)]));
897
+ f.loc = fn.loc;
898
+ return [
899
+ t.exportNamedDeclaration(
900
+ t.variableDeclaration('const', [
901
+ t.variableDeclarator(
902
+ t.identifier('_$k'),
903
+ t.arrayExpression(
904
+ info.binds.map(({ k }) => (k[0] === 2 ? t.arrayExpression([t.numericLiteral(2), t.numericLiteral(k[1]), t.identifier(k[2]), t.valueToNode(k[3])]) : t.valueToNode(k))),
905
+ ),
906
+ ),
907
+ ]),
908
+ ),
909
+ t.exportDefaultDeclaration(t.cloneNode(f, true)),
910
+ ];
911
+ }
912
+
913
+ /** Removes computeds and functions in the client body that nothing reads. */
914
+ function shake(fn) {
915
+ for (let removed = true; removed; ) {
916
+ removed = false;
917
+ fn.scope.crawl();
918
+ for (const b of Object.values(fn.scope.bindings)) {
919
+ if (b.referenced || b.constantViolations.length) continue;
920
+ const p = b.path;
921
+ if (p.isVariableDeclarator() && pure(p.node.init) && p.parent.declarations.length === 1) {
922
+ p.parentPath.remove();
923
+ removed = true;
924
+ } else if (p.isFunctionDeclaration()) {
925
+ p.remove();
926
+ removed = true;
927
+ }
928
+ }
929
+ }
930
+ }
931
+
932
+ /** Code that can be dropped when its value is unused: no calls, no assignments. */
933
+ const pure = (n) =>
934
+ !n ||
935
+ t.isIdentifier(n) ||
936
+ t.isFunction(n) ||
937
+ (t.isTemplateLiteral(n) ? n.expressions.every(pure) : t.isLiteral(n)) ||
938
+ (t.isMemberExpression(n) && pure(n.object) && (!n.computed || pure(n.property))) ||
939
+ ((t.isBinaryExpression(n) || t.isLogicalExpression(n)) && pure(n.left) && pure(n.right)) ||
940
+ (t.isConditionalExpression(n) && pure(n.test) && pure(n.consequent) && pure(n.alternate));
941
+
942
+ /** Which props the browser code reads: only those are written into the page. */
943
+ function propKeys(fn) {
944
+ const param = fn.node.params[1];
945
+ if (!param) return [];
946
+ const pat = patternOf(param);
947
+ if (t.isIdentifier(pat)) {
948
+ const keys = new Set();
949
+ for (const r of fn.scope.getBinding(pat.name).referencePaths) {
950
+ const m = r.parentPath;
951
+ if (!m.isMemberExpression({ object: r.node }) || m.node.computed)
952
+ fail('read props as props.name, or destructure them, so goal.js knows which ones the browser needs', r.node);
953
+ keys.add(m.node.property.name);
954
+ }
955
+ return [...keys];
956
+ }
957
+ if (!t.isObjectPattern(pat)) fail('props are an object: write ({ name }) or (props)', pat);
958
+ const keys = [];
959
+ for (const prop of pat.properties) {
960
+ if (t.isRestElement(prop)) fail("an interactive component can't take ...rest props; name the ones it uses", prop);
961
+ if (prop.computed) fail('name each prop: { name }, not { [key] }', prop);
962
+ const names = Object.keys(t.getBindingIdentifiers(prop.value));
963
+ if (names.some((n) => fn.scope.getBinding(n).referenced)) keys.push(t.isIdentifier(prop.key) ? prop.key.name : prop.key.value);
964
+ }
965
+ return keys;
966
+ }
967
+
968
+ /** Removes imports and helper functions the component doesn't use, so they don't ship. */
969
+ function prune(prog, keep) {
970
+ for (let removed = true; removed; ) {
971
+ removed = false;
972
+ prog.scope.crawl();
973
+ for (const b of Object.values(prog.scope.bindings)) {
974
+ if (b.referenced || keep.has(b.identifier.name)) continue;
975
+ const p = b.path;
976
+ if (p.isImportSpecifier() || p.isImportDefaultSpecifier() || p.isImportNamespaceSpecifier()) {
977
+ const decl = p.parentPath;
978
+ p.remove();
979
+ if (!decl.node.specifiers.length) decl.remove();
980
+ removed = true;
981
+ } else if (p.isFunctionDeclaration() || (p.isVariableDeclarator() && pure(p.node.init) && p.parent.declarations.length === 1 && !b.constantViolations.length)) {
982
+ (p.isVariableDeclarator() ? p.parentPath : p).remove();
983
+ removed = true;
984
+ }
985
+ }
986
+ }
987
+ }