goaljs 0.3.0 → 0.4.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "goaljs",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "goal.js: var is state, let/const are computed, server-rendered and resumable",
5
5
  "homepage": "https://goallabs.github.io/goal/",
6
6
  "repository": {
@@ -44,6 +44,14 @@
44
44
  "happy-dom": "^21.0.4",
45
45
  "vitest": "^5.1.1"
46
46
  },
47
+ "peerDependencies": {
48
+ "vite": ">=6"
49
+ },
50
+ "peerDependenciesMeta": {
51
+ "vite": {
52
+ "optional": true
53
+ }
54
+ },
47
55
  "bin": {
48
56
  "goal": "bin/goal.js"
49
57
  },
@@ -53,6 +61,7 @@
53
61
  "./rt": "./src/rt.js",
54
62
  "./loader": "./src/loader.js",
55
63
  "./build": "./src/build.js",
56
- "./keyed": "./src/keyed.js"
64
+ "./keyed": "./src/keyed.js",
65
+ "./vite": "./src/vite.js"
57
66
  }
58
67
  }
package/src/app.js CHANGED
@@ -13,7 +13,7 @@
13
13
  import { randomBytes, timingSafeEqual } from 'node:crypto';
14
14
  import { readFileSync, statSync } from 'node:fs';
15
15
  import { extname, resolve, sep } from 'node:path';
16
- import { Html, _$ctx } from './rt.js';
16
+ import { isHtml, _$ctx } from './rt.js';
17
17
  import { page } from './server.js';
18
18
 
19
19
  const TYPES = {
@@ -254,11 +254,15 @@ export function createApp(routes, { dev = false, staticDirs = [], config = {}, l
254
254
  if (m.allow) return send(405, HTML, errorPage('Method not allowed'), { allow: m.allow.join(', ') });
255
255
 
256
256
  const ctx = _$ctx(token);
257
- if (dev && req.headers['x-goal-hmr']) ctx.hmr = keptState(req.headers['x-goal-hmr']); // goal dev: a live update (see hmr.js)
257
+ if (dev && req.headers['x-goal-hmr']) {
258
+ // goal dev: a live update (see hmr.js). Each component gets the state the page kept for it.
259
+ const kept = (ctx.hmr = keptState(req.headers['x-goal-hmr']));
260
+ ctx.k = (chunk, i) => (kept[i]?.c === chunk ? kept[i].s : null);
261
+ }
258
262
  const request = { method, path: url.pathname, url, params: m.params, query: Object.fromEntries(url.searchParams), headers: req.headers, cookies, form, files, json: body };
259
263
  const cookie = (name, value, opts) => setCookies.push(serializeCookie(name, value, opts));
260
264
  const out = await m.route.handler(request, { ctx, redirect, json, notFound, cookie });
261
- if (out instanceof Html) return send(200, HTML, page(out.s, [...ctx.ev], nonce, token, dev));
265
+ if (isHtml(out)) return send(200, HTML, page(out.s, [...ctx.ev], nonce, token, dev));
262
266
  if (out === undefined) return send(204);
263
267
  if (out?.[REPLY]) return send(out.status, out.type, out.body, out.headers);
264
268
  throw new Error('a route returns markup, redirect(), json(), notFound() or nothing');
package/src/build.js CHANGED
@@ -47,7 +47,11 @@ const noGoal = {
47
47
  };
48
48
 
49
49
  /** Client modules as esbuild entry points, each resolved from its .goal file's folder. */
50
- const entriesPlugin = (entries) => {
50
+ /**
51
+ * Client modules as esbuild entry points, each resolved from its .goal file's folder, and the render
52
+ * modules they import (`goal-render:./Panel.goal`, see renderModule in compiler.js), by .goal file.
53
+ */
54
+ const entriesPlugin = (entries, renders) => {
51
55
  // Each entry sits, in name, next to its .goal file, so source maps name that file from the app folder.
52
56
  const byPath = new Map([...entries.values()].map((e) => [join(e.dir, `${e.name}.goal.js`), e]));
53
57
  return {
@@ -55,6 +59,8 @@ const entriesPlugin = (entries) => {
55
59
  setup(b) {
56
60
  b.onResolve({ filter: /^goal-entry:/ }, (a) => ({ path: join(entries.get(a.path.slice(11)).dir, `${entries.get(a.path.slice(11)).name}.goal.js`) }));
57
61
  b.onLoad({ filter: /\.goal\.js$/ }, (a) => ({ contents: byPath.get(a.path).code, resolveDir: byPath.get(a.path).dir, loader: 'js' }));
62
+ b.onResolve({ filter: /^goal-render:/ }, (a) => ({ path: `${resolve(a.resolveDir, a.path.slice(12))}.render.js` }));
63
+ b.onLoad({ filter: /\.goal\.render\.js$/ }, (a) => ({ contents: renders.get(a.path.slice(0, -10)), resolveDir: dirname(a.path), loader: 'js' }));
58
64
  },
59
65
  };
60
66
  };
@@ -71,6 +77,7 @@ export async function build(app, { out = join(app, 'dist'), dev = false, publicP
71
77
  const routes = [];
72
78
  const routeFiles = [];
73
79
  const entries = new Map(); // client modules, by output name
80
+ const renders = new Map(); // render modules, by .goal file
74
81
  rmSync(out, { recursive: true, force: true });
75
82
  const all = files(app);
76
83
  // The server functions each .goal file exports, so files can import them from each other.
@@ -101,6 +108,7 @@ export async function build(app, { out = join(app, 'dist'), dev = false, publicP
101
108
  if (other) throw new Error(`${rel}: route ${route.method} ${route.path} is already in ${other.file}`);
102
109
  routes.push({ key, file: rel, label: `${route.method} ${route.path}` });
103
110
  }
111
+ renders.set(resolve(app, rel), r.render);
104
112
  for (const c of r.clients) entries.set(`${base}.${c.name}`, { code: c.code, dir: resolve(app, dirname(rel)), name: `${posix.basename(base)}.${c.name}` });
105
113
  }
106
114
  // All browser code in one bundle with code splitting: each component is its own file, and code
@@ -121,7 +129,7 @@ export async function build(app, { out = join(app, 'dist'), dev = false, publicP
121
129
  format: 'esm',
122
130
  write: false,
123
131
  logLevel: 'silent',
124
- plugins: [entriesPlugin(entries), noGoal],
132
+ plugins: [entriesPlugin(entries, renders), noGoal],
125
133
  })
126
134
  ).outputFiles;
127
135
  // A chunk with a keyed list imports the patcher from its own file, next to the chunks.
package/src/compiler.js CHANGED
@@ -36,7 +36,7 @@ import { URL_ATTRS, _$u } from './rt.js';
36
36
  export { GoalError };
37
37
 
38
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'];
39
+ const HELPERS = ['_$m', '_$h', '_$a', '_$e', '_$u', '_$pa', '_$ctx', '_$sf', '_$call', '_$hl', '_$L', '_$B', '_$f'];
40
40
  const ROUTE_HELPERS = ['redirect', 'json', 'notFound', 'cookie'];
41
41
  const FORM_METHODS = ['get', 'post', 'put', 'patch', 'delete'];
42
42
 
@@ -107,10 +107,12 @@ export function compile(source, opts = {}) {
107
107
  const server = transform(ast, 'server', o, d.routes);
108
108
  const client = transform(ast, 'client', o, d.routes);
109
109
  const clients = [];
110
+ const keys = new Map(); // the props each component's browser code reads: the page gets those
110
111
  for (const c of client.components.filter((c) => c.interactive)) {
111
- const { code, keys } = clientModule(client.program, c, o);
112
- clients.push({ name: c.name, code });
113
- server.components.find((s) => s.name === c.name).keys.elements.push(...keys.map((k) => t.stringLiteral(k)));
112
+ const m = clientModule(client.program, c, o);
113
+ clients.push({ name: c.name, code: m.code });
114
+ keys.set(c.name, m.keys);
115
+ server.components.find((s) => s.name === c.name).keys.elements.push(...m.keys.map((k) => t.stringLiteral(k)));
114
116
  }
115
117
 
116
118
  const body = server.program;
@@ -142,6 +144,7 @@ export function compile(source, opts = {}) {
142
144
  );
143
145
  return {
144
146
  server: emit(body.node),
147
+ render: renderModule(ast, o, d.routes, keys),
145
148
  clients,
146
149
  components: server.components.map(({ name, interactive, events }) => ({ name, interactive, events })),
147
150
  routes: d.routes.map(({ method, path }) => ({ method, path })),
@@ -314,7 +317,7 @@ function component(fn, program, mode, o) {
314
317
  const events = [...cx.events];
315
318
  const param = fn.node.params[0];
316
319
  const keys = t.arrayExpression([]); // the props the browser needs, filled in from the client module
317
- 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 };
320
+ 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, b: !!cx.b };
318
321
  program.pushContainer('body', cx.tpls);
319
322
 
320
323
  if (mode === 'server') {
@@ -324,7 +327,7 @@ function component(fn, program, mode, o) {
324
327
  const pre = [];
325
328
  if (param) pre.push(t.variableDeclaration('let', [t.variableDeclarator(patternOf(param), pId)]));
326
329
  pre.push(t.variableDeclaration('const', [t.variableDeclarator(cx.iId, t.updateExpression('++', t.memberExpression(cx.cId, t.identifier('i'))))]));
327
- if (o.dev && interactive && state.length) pre.push(keptState(fn, cx, o.chunk(name).split('?')[0], state));
330
+ if ((o.dev || o.render) && interactive && state.length) pre.push(keptState(fn, cx, o.chunk(name).split('?')[0], state));
328
331
  if (events.length) pre.push(t.expressionStatement(t.callExpression(t.memberExpression(cx.cId, t.identifier('e')), [t.valueToNode(events)])));
329
332
  if (cx.dyn) {
330
333
  // The server only numbers the handlers made while rendering; the browser keeps them.
@@ -344,13 +347,13 @@ function component(fn, program, mode, o) {
344
347
  const patternOf = (param) => (t.isAssignmentPattern(param) ? param.left : param);
345
348
 
346
349
  /**
347
- * goal dev: a live update renders the page again with the state each component had in the browser
348
- * (ctx.hmr, by instance number). When this instance is the same component, its vars start from that
349
- * state instead of their initial values; a var it didn't have starts as written.
350
+ * A component rendered again keeps its state: in goal dev, for a live update (the page sends it, see
351
+ * app.js), and in the browser, where a parent renders it again (the loader finds it, see _$B). ctx.k
352
+ * gives the state the component in this place had; its vars start from it instead of their initial
353
+ * values, and a var it didn't have starts as written.
350
354
  */
351
355
  function keptState(fn, cx, chunk, state) {
352
356
  const kept = t.identifier('_$o');
353
- const at = t.memberExpression(t.memberExpression(cx.cId, t.identifier('hmr')), cx.iId, true);
354
357
  for (const name of state) {
355
358
  const d = fn.scope.getBinding(name).path.node;
356
359
  d.init = t.conditionalExpression(
@@ -359,11 +362,9 @@ function keptState(fn, cx, chunk, state) {
359
362
  d.init ?? t.identifier('undefined'),
360
363
  );
361
364
  }
362
- // _$c.hmr?.[_$i]?.c === chunk ? _$c.hmr[_$i].s : null
363
- const cOf = t.optionalMemberExpression(t.optionalMemberExpression(t.memberExpression(cx.cId, t.identifier('hmr')), cx.iId, true, true), t.identifier('c'), false, true);
364
- return t.variableDeclaration('const', [
365
- t.variableDeclarator(kept, t.conditionalExpression(t.binaryExpression('===', cOf, t.stringLiteral(chunk)), t.memberExpression(at, t.identifier('s')), t.nullLiteral())),
366
- ]);
365
+ // const _$o = _$c.k?.(chunk, _$i);
366
+ const call = t.optionalCallExpression(t.memberExpression(cx.cId, t.identifier('k')), [t.stringLiteral(chunk), cx.iId], true);
367
+ return t.variableDeclaration('const', [t.variableDeclarator(kept, call)]);
367
368
  }
368
369
 
369
370
  const ROOT = Symbol('root attributes');
@@ -474,11 +475,14 @@ function element(p, cx, top, root, row) {
474
475
  if (!t.isJSXIdentifier(nameNode)) fail('use plain tag names and component names, like <div> or <Counter>', nameNode);
475
476
  const tag = nameNode.name;
476
477
  if (/^[A-Z]/.test(tag)) {
477
- if (cx.kind === 'route' || (cx.kind === 'component' && top && !root)) return componentCall(p, cx, tag);
478
+ if (cx.kind === 'route') return componentCall(p, cx, tag, false);
479
+ if (cx.kind === 'component' && !root && !row && !cx.inRow) return componentCall(p, cx, tag, top);
478
480
  fail(
479
- cx.kind === 'component'
480
- ? `place <${tag}> in the fixed part of a component: not as its root, not inside {...}`
481
- : `<${tag}> goes in a route or in the fixed part of a component`,
481
+ cx.kind !== 'component'
482
+ ? `<${tag}> goes in a route or in a component`
483
+ : root
484
+ ? `a component's root is an element: put <${tag}> inside one`
485
+ : `<${tag}> can't go inside a keyed list's row yet`,
482
486
  p.node,
483
487
  );
484
488
  }
@@ -518,10 +522,10 @@ function element(p, cx, top, root, row) {
518
522
  ons.push([`${ev}:r${row.hs.length}`]); // the row's own handler, found from the row at run time
519
523
  row.hs.push(v.node.expression);
520
524
  } else if (top) {
521
- ons.push([`${ev}:${cx.hs.length}`]);
525
+ ons.push([`${ev}:${cx.hs.length}`, ...owner(cx)]);
522
526
  cx.hs.push(v.node.expression);
523
527
  } else {
524
- ons.push([`${ev}:`, t.callExpression(t.identifier('_$hd'), [v.node.expression])]);
528
+ ons.push([`${ev}:`, t.callExpression(t.identifier('_$hd'), [v.node.expression]), ...owner(cx)]);
525
529
  cx.dyn++;
526
530
  }
527
531
  continue;
@@ -628,15 +632,43 @@ const changes = (e, cx) => uses(e, cx.scope, cx.reactive) || uses(e, cx.scope, c
628
632
  /** A `{...}` hole: in the fixed part of a component, one that can change becomes a binding between markers. */
629
633
  function hole(c, cx, top, parts) {
630
634
  const dyn = cx.dyn;
635
+ cx.at = cx.binds?.length; // in a component, the binding it becomes: components rendered in it look for theirs there
631
636
  inner(c.get('expression'), cx);
632
637
  const ex = t.callExpression(t.identifier('_$h'), [c.node.expression]);
633
638
  if (top && (cx.dyn > dyn || changes(c.get('expression'), cx))) {
639
+ if (readsChildren(c.get('expression'), cx))
640
+ fail('put {children} in the fixed part of the component: they belong to its parent, so a {...} hole that renders again can\'t hold them', c.node);
634
641
  const k = cx.binds.length;
635
642
  cx.binds.push({ k: [0, k], e: ex });
636
643
  parts.push('<!--', cx.iId, `.${k}-->`, ex, '<!--/-->');
637
644
  } else parts.push(ex);
638
645
  }
639
646
 
647
+ /** In children's markup, a handler names the component it belongs to: m-on="click:0@<instance>". */
648
+ const owner = (cx, always) => {
649
+ if (!cx.own && !always) return [];
650
+ if (cx.mode !== 'client') return ['@', cx.iId];
651
+ cx.b = true; // rendered in the browser: the instance running now (rt.js)
652
+ return ['@', t.callExpression(t.memberExpression(t.memberExpression(t.identifier('_$B'), t.identifier('r')), t.identifier('getAttribute')), [t.stringLiteral('m-i')])];
653
+ };
654
+
655
+ /** Does the code at `path` read the component's children prop? */
656
+ function readsChildren(path, cx) {
657
+ let hit = false;
658
+ const check = (p) => {
659
+ const b = p.scope.getBinding(p.node.name);
660
+ if (b?.kind !== 'param' || b.scope !== cx.scope) return;
661
+ if (p.node.name === 'children' || (p.parentPath.isMemberExpression({ object: p.node, computed: false }) && p.parent.property.name === 'children')) hit = true;
662
+ };
663
+ if (path.isIdentifier()) check(path);
664
+ path.traverse({
665
+ Identifier(p) {
666
+ if (p.isReferencedIdentifier()) check(p);
667
+ },
668
+ });
669
+ return hit;
670
+ }
671
+
640
672
  const isMap = (e) => e.isCallExpression() && t.isMemberExpression(e.node.callee, { computed: false }) && e.node.callee.property.name === 'map';
641
673
 
642
674
  /** The `.map(...)` call whose callback returns this element, when the element is a list row. */
@@ -784,28 +816,71 @@ function markup(p, cx) {
784
816
  return t.callExpression(t.identifier('_$m'), [template(parts)]);
785
817
  }
786
818
 
787
- function componentCall(p, cx, tag) {
788
- if (p.node.children.some((c) => !t.isJSXText(c) || cleanText(c.value) !== ''))
789
- fail(`passing children to <${tag}> comes in the next milestone`, p.node);
819
+ /**
820
+ * A component in markup. On the server it renders there; in a {...} hole the browser renders it too,
821
+ * with the browser context (_$B, from the file's render module). In the fixed part of a component,
822
+ * one whose props read state becomes a hole of its own, rendered again when they change.
823
+ */
824
+ function componentCall(p, cx, tag, top) {
790
825
  const props = [];
826
+ let live = false; // a prop reads state
791
827
  for (const a of p.get('openingElement.attributes')) {
792
828
  if (a.isJSXSpreadAttribute()) fail('spread props are not supported yet', a.node);
793
829
  if (!t.isJSXIdentifier(a.node.name)) fail('namespaced props are not supported', a.node);
794
830
  const name = a.node.name.name;
795
- if (/^on/i.test(name)) fail(`a component can't take a function prop (${name}) yet`, a.node);
796
831
  const v = a.get('value');
832
+ // A function prop: a handler of this component, which the child calls from its own handlers.
833
+ if (/^on/.test(name) || (v.isJSXExpressionContainer() && v.get('expression').isFunction())) {
834
+ if (!cx.hs) fail(`a function prop (${name}) goes to a component inside a component, where it runs as a handler`, a.node);
835
+ if (!v.isJSXExpressionContainer()) fail(`${name} takes a function: ${name}={(x) => ...}`, a.node);
836
+ let h;
837
+ if (top) {
838
+ h = t.numericLiteral(cx.hs.length);
839
+ cx.hs.push(v.node.expression);
840
+ } else {
841
+ h = t.callExpression(t.identifier('_$hd'), [v.node.expression]);
842
+ cx.dyn++;
843
+ }
844
+ props.push(t.objectProperty(t.stringLiteral(name), t.callExpression(t.identifier('_$f'), [h, owner(cx, true)[1]])));
845
+ continue;
846
+ }
797
847
  let value;
798
848
  if (!v.node) value = t.booleanLiteral(true);
799
849
  else if (v.isStringLiteral()) value = v.node;
800
850
  else if (v.isJSXExpressionContainer()) {
801
- if (uses(v.get('expression'), cx.scope, cx.reactive))
802
- fail(`prop \`${name}\` depends on state; props that change come in the next milestone`, a.node);
851
+ if (top && changes(v.get('expression'), cx)) live = true;
803
852
  inner(v.get('expression'), cx);
804
853
  value = v.node.expression;
805
854
  } else fail('a prop value is "text" or {expression}', a.node);
806
855
  props.push(t.objectProperty(t.stringLiteral(name), value));
807
856
  }
808
- return [t.callExpression(t.identifier(tag), [t.objectExpression(props), cx.cId])];
857
+ // Children: markup of this component, given to the child as `children`. Their bindings and
858
+ // handlers are this component's (owner), wherever the child puts them.
859
+ if (p.node.children.some((c) => !t.isJSXText(c) || cleanText(c.value) !== '')) {
860
+ if (cx.kind === 'route') {
861
+ const parts = [];
862
+ children(p, cx, false, parts);
863
+ props.push(t.objectProperty(t.stringLiteral('children'), t.callExpression(t.identifier('_$m'), [template(parts)])));
864
+ } else {
865
+ const parts = [];
866
+ const was = cx.own;
867
+ cx.own = true;
868
+ children(p, cx, top && !live, parts);
869
+ cx.own = was;
870
+ props.push(t.objectProperty(t.stringLiteral('children'), t.callExpression(t.identifier('_$m'), [template(parts)])));
871
+ }
872
+ }
873
+ // In the browser it renders in a hole: this one's own, or the hole it is in.
874
+ let ctx = cx.cId;
875
+ if (cx.mode === 'client' && (live || !top)) {
876
+ cx.b = true;
877
+ ctx = t.callExpression(t.memberExpression(t.identifier('_$B'), t.identifier('h')), [t.numericLiteral(live ? cx.binds.length : cx.at)]);
878
+ }
879
+ const call = t.callExpression(t.identifier(tag), [t.objectExpression(props), ctx]);
880
+ if (!live) return [call];
881
+ const k = cx.binds.length;
882
+ cx.binds.push({ k: [0, k], e: call }); // the render's HTML, as the hole's value
883
+ return ['<!--', cx.iId, `.${k}-->`, call, '<!--/-->'];
809
884
  }
810
885
 
811
886
  // Text in markup, with whitespace cleaned the way React does it.
@@ -854,16 +929,48 @@ function importHelpers(rt) {
854
929
  return t.importDeclaration(HELPERS.map((h) => t.importSpecifier(t.identifier(h), t.identifier(h))), t.stringLiteral(rt));
855
930
  }
856
931
 
932
+ /** Components imported from a .goal file render in the browser from its render module (see renderModule). */
933
+ function renderImport(s) {
934
+ if (t.isImportDeclaration(s) && s.source.value.endsWith('.goal') && s.specifiers.every((x) => /^[A-Z]/.test(x.local.name))) s.source = t.stringLiteral(`goal-render:${s.source.value}`);
935
+ return s;
936
+ }
937
+
938
+ /**
939
+ * A file's components as the browser renders them, inside a {...} hole or with props that change:
940
+ * the server's templates, each component keeping the state of the one in its place (keptState).
941
+ * Routes and server functions stay on the server, and so does whatever the components don't use.
942
+ */
943
+ function renderModule(ast, o, routes, keys) {
944
+ const r = transform(ast, 'server', { ...o, render: true }, routes);
945
+ for (const c of r.components) c.keys.elements.push(...(keys.get(c.name) ?? []).map((k) => t.stringLiteral(k)));
946
+ const names = new Set(r.components.map((c) => c.name));
947
+ const server = new Set([...routes.map((x) => x.name), ...o.own]);
948
+ const body = [importHelpers(o.rt)];
949
+ for (const s of r.program.node.body) {
950
+ const d = t.isExportNamedDeclaration(s) || t.isExportDefaultDeclaration(s) ? s.declaration : s;
951
+ if (t.isFunctionDeclaration(d) && server.has(d.id.name)) continue;
952
+ if (t.isFunctionDeclaration(d) && names.has(d.id.name)) body.push(t.exportNamedDeclaration(t.cloneNode(d, true)));
953
+ else if (t.isStatement(d)) body.push(renderImport(t.cloneNode(d, true)));
954
+ }
955
+ const file = t.file(t.program(body));
956
+ prune(programPath(file), names);
957
+ return emit(file);
958
+ }
959
+
857
960
  function clientModule(program, info, o) {
858
961
  const body = [importHelpers(o.rt)];
962
+ const others = []; // the file's other components: it renders them from the file's render module
859
963
  let comp;
860
964
  for (const s of program.node.body) {
861
965
  const d = t.isExportNamedDeclaration(s) || t.isExportDefaultDeclaration(s) ? s.declaration : s;
862
966
  if (t.isFunctionDeclaration(d) && (/^[A-Z]/.test(d.id.name) || o.own.has(d.id.name))) {
863
967
  if (d.id.name === info.name) comp = d;
864
- } 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
968
+ else if (!o.own.has(d.id.name)) others.push(d.id.name);
969
+ } else if (t.isStatement(d) && !/^_\$t\d/.test(d.declarations?.[0].id.name)) body.push(renderImport(t.cloneNode(d, true))); // `export { a }` and `export default expr` are dropped
865
970
  }
866
971
  body.push(...info.tpls.map((x) => t.cloneNode(x, true)), ...clientComponent(comp, info)); // row templates before _$k reads them
972
+ if (others.length) body.splice(1, 0, t.importDeclaration(others.map((n) => t.importSpecifier(t.identifier(n), t.identifier(n))), t.stringLiteral(`goal-render:./${o.file.split('/').at(-1)}`)));
973
+ if (info.b) body.push(t.exportNamedDeclaration(null, [t.exportSpecifier(t.identifier('_$B'), t.identifier('_$B'))], t.stringLiteral(o.rt))); // the loader gives renders the state they keep
867
974
  if (info.binds.some((b) => b.k[0] === 0)) body.push(t.exportNamedDeclaration(null, [t.exportSpecifier(t.identifier('_$hm'), t.identifier('_$hm'))], t.stringLiteral(o.rt)));
868
975
  if (info.binds.some((b) => b.k[0] === 2))
869
976
  body.push(
@@ -963,6 +1070,8 @@ const pure = (n) =>
963
1070
  (t.isTemplateLiteral(n) ? n.expressions.every(pure) : t.isLiteral(n)) ||
964
1071
  (t.isMemberExpression(n) && pure(n.object) && (!n.computed || pure(n.property))) ||
965
1072
  ((t.isBinaryExpression(n) || t.isLogicalExpression(n)) && pure(n.left) && pure(n.right)) ||
1073
+ (t.isArrayExpression(n) && n.elements.every(pure)) ||
1074
+ (t.isObjectExpression(n) && n.properties.every((p) => t.isObjectProperty(p) && !p.computed && pure(p.value))) ||
966
1075
  (t.isConditionalExpression(n) && pure(n.test) && pure(n.consequent) && pure(n.alternate));
967
1076
 
968
1077
  /** Which props the browser code reads: only those are written into the page. */
package/src/loader.js CHANGED
@@ -22,7 +22,9 @@ export function boot(d, events, load = (u) => import(u)) {
22
22
  };
23
23
  for (const t of ['pointerover', 'focusin']) d.addEventListener(t, warm, true);
24
24
  // A run of the component from its state: [values, handlers, read the state, the state read].
25
+ // When it renders components in the browser (m._$B, rt.js), they look for theirs inside it.
25
26
  const run = (m, r) => {
27
+ if (m._$B) m._$B.r = r;
26
28
  const x = m.default(r.$s, r.$p);
27
29
  x[3] = x[2]();
28
30
  return x;
@@ -32,41 +34,67 @@ export function boot(d, events, load = (u) => import(u)) {
32
34
  const todo = [];
33
35
  for (let el = e.target; el.getAttribute; el = el.parentNode)
34
36
  for (const pair of (el.getAttribute('m-on') || '').split(' ')) {
35
- const [type, h] = pair.split(':');
37
+ const [type, at] = pair.split(':');
36
38
  if (type !== e.type) continue;
37
39
  if (type === 'submit') e.preventDefault(); // must happen now, before the module loads
38
- todo.push([el.closest('[m-c]'), h, el]);
40
+ const [h, owner] = at.split('@'); // a handler in children's markup names the component it belongs to
41
+ todo.push([owner ? el.closest(`[m-i="${owner}"]`) : el.closest('[m-c]'), h, el]);
42
+ }
43
+ for (const r of new Set(todo.map((x) => x[0])))
44
+ await act(
45
+ r,
46
+ todo.filter((t) => t[0] === r).map(([, h, el]) => (m, x) => (h[0] === 'r' ? m._$lh(el, r, x, h, e) : x[1][h](e))), // r: a keyed list row's handler (keyed.js)
47
+ );
48
+ };
49
+ // Runs handlers of the component at root r (each call gets its module and run), saves the state
50
+ // they changed and patches it, and again when the calls to server functions they made answer.
51
+ const act = async (r, calls) => {
52
+ const m = await get(r);
53
+ r.$s ||= json(r, 'm-s');
54
+ r.$p ||= props(r);
55
+ const x = (r.$x ||= run(m, r));
56
+ const save = () => {
57
+ const now = x[2]();
58
+ if (!r.$x) {
59
+ // Its parent rendered it again while it waited (rt.js): start from what the page shows now.
60
+ r.$s = json(r, 'm-s');
61
+ r.$p = props(r);
62
+ r.$x = run(m, r);
63
+ }
64
+ for (const k in now) if (now[k] !== x[3][k]) r.$s[k] = now[k]; // only what these handlers changed
65
+ x[3] = now;
66
+ };
67
+ const update = () => {
68
+ const y = run(m, r);
69
+ patch(d, r, m, r.$x[0], y[0]);
70
+ r.$x = y;
71
+ };
72
+ const outs = calls.map((f) => f(m, x));
73
+ save();
74
+ update();
75
+ if (outs.some((o) => o?.then))
76
+ try {
77
+ await Promise.all(outs); // calls to server functions
78
+ } finally {
79
+ save();
80
+ update();
81
+ }
82
+ };
83
+ // A component's props. A function prop is written {$h, $i}: calling it runs handler $h of the
84
+ // component that gave it, instance $i (see _$f in rt.js).
85
+ const props = (r) =>
86
+ JSON.parse(r.getAttribute('m-p') || '{}', (k, v) => (v?.$h === undefined ? v : (...a) => act(d.querySelector(`[m-i="${v.$i}"]`), [(m, x) => x[1][v.$h](...a)])));
87
+ // The page's events, and those of components rendered in the browser later (rt.js).
88
+ const on = new Set();
89
+ const listen = (list) => {
90
+ for (const ev of list)
91
+ if (!on.has(ev)) {
92
+ on.add(ev);
93
+ d.addEventListener(ev, go, true);
39
94
  }
40
- for (const r of new Set(todo.map((x) => x[0]))) {
41
- const m = await get(r);
42
- r.$s ||= json(r, 'm-s');
43
- r.$p ||= json(r, 'm-p');
44
- const x = (r.$x ||= run(m, r));
45
- const save = () => {
46
- const now = x[2]();
47
- for (const k in now) if (now[k] !== x[3][k]) r.$s[k] = now[k]; // only what these handlers changed
48
- x[3] = now;
49
- };
50
- const update = () => {
51
- const y = run(m, r);
52
- patch(d, r, m, r.$x[0], y[0]);
53
- r.$x = y;
54
- };
55
- const outs = todo
56
- .filter((t) => t[0] === r)
57
- .map(([, h, el]) => (h[0] === 'r' ? m._$lh(el, r, x, h, e) : x[1][h](e))); // r: a keyed list row's handler (keyed.js)
58
- save();
59
- update();
60
- if (outs.some((o) => o?.then))
61
- try {
62
- await Promise.all(outs); // calls to server functions
63
- } finally {
64
- save();
65
- update();
66
- }
67
- }
68
95
  };
69
- for (const ev of events) d.addEventListener(ev, go, true);
96
+ listen(events);
97
+ d.addEventListener('goal:listen', (e) => listen(e.detail));
70
98
  }
71
99
 
72
100
  /** Updates the bindings whose value changed between `a` and `b`. */
package/src/rt.js CHANGED
@@ -10,15 +10,21 @@ export const _$e = (v) => {
10
10
  };
11
11
 
12
12
  /** Compiled markup: HTML that is already safe, so `_$h` doesn't escape it again. */
13
+ const MARKUP = Symbol.for('goal.markup'); // the same in every copy of this module (Vite loads its own)
14
+
13
15
  export class Html {
14
16
  constructor(s) {
15
17
  this.s = s;
18
+ this[MARKUP] = true;
16
19
  }
17
20
  toString() {
18
21
  return this.s;
19
22
  }
20
23
  }
21
24
 
25
+ /** Is it markup a compiled template made, whichever copy of this module made it? */
26
+ export const isHtml = (v) => v?.[MARKUP] === true;
27
+
22
28
  /** Marks a compiled template as markup. Only compiled code makes these. */
23
29
  export const _$m = (s) => new Html(s);
24
30
 
@@ -79,6 +85,55 @@ export const _$ctx = (t = '') => ({
79
85
  },
80
86
  });
81
87
 
88
+ /**
89
+ * The context of components rendered in the browser: inside a {...} hole, or with props that change.
90
+ * Their instance numbers start where no server render reaches, their forms get the page's CSRF
91
+ * token, and the loader starts listening for their events.
92
+ */
93
+ export const _$B = {
94
+ i: 1e6,
95
+ r: null, // the component running now: the loader sets it before each run
96
+ /**
97
+ * The context for the components rendered in hole `n` of the component running now. Each one
98
+ * keeps the state of the component in its place, if it is the same (see keptState in compiler.js):
99
+ * the components in that hole now, in order. One where there was none starts as written.
100
+ */
101
+ h(n) {
102
+ const r = this.r;
103
+ const d = r.ownerDocument;
104
+ const w = d.createTreeWalker(r, 128);
105
+ let c;
106
+ while ((c = w.nextNode()) && c.data !== `${r.getAttribute('m-i')}.${n}`);
107
+ const q = [];
108
+ for (let x = c.nextSibling; x.nodeType !== 8 || x.data !== '/'; x = x.nextSibling)
109
+ if (x.nodeType === 1) q.push(...(x.hasAttribute('m-c') ? [x] : []), ...x.querySelectorAll('[m-c]'));
110
+ const b = this;
111
+ return {
112
+ get i() {
113
+ return b.i;
114
+ },
115
+ set i(v) {
116
+ b.i = v;
117
+ },
118
+ t: d.querySelector('meta[name="goal-csrf"]').content, // a page with components that run has it
119
+ e: (list) => d.dispatchEvent(new CustomEvent('goal:listen', { detail: list })),
120
+ k: (chunk) => {
121
+ const j = q.findIndex((x) => x.getAttribute('m-c').split('?')[0] === chunk);
122
+ if (j < 0) return null;
123
+ const x = q.splice(0, j + 1).pop();
124
+ return x.$s ?? JSON.parse(x.getAttribute('m-s')); // only a component with state asks
125
+ },
126
+ };
127
+ },
128
+ };
129
+
130
+ /**
131
+ * A function prop: handler `h` of the component instance `i` that gives it. It runs nothing where it
132
+ * is made; the page gets {$h, $i}, and the loader turns that into a function that runs the handler
133
+ * in that component, as an event would.
134
+ */
135
+ export const _$f = (h, i) => Object.assign(() => {}, { toJSON: () => ({ $h: h, $i: i }) });
136
+
82
137
  /** The server's rendering of a keyed list (see keyed.js): each row through its template. */
83
138
  export const _$hl = (rows, tpl) => rows.map(tpl).join('');
84
139
 
@@ -145,6 +200,9 @@ function same(a, b) {
145
200
  for (const { name } of [...a.attributes]) if (!b.hasAttribute(name)) attr(a, name, null);
146
201
  for (const { name, value } of b.attributes) if (a.getAttribute(name) !== value) attr(a, name, value);
147
202
  kids(a, a.firstChild, null, b);
203
+ // A component rendered again in the browser, with its state now (see _$B.k): its attributes say
204
+ // all, so the loader reads it afresh on its next event.
205
+ if (a.hasAttribute('m-c')) a.$s = a.$p = a.$x = a.$m = undefined;
148
206
  }
149
207
 
150
208
  /** An attribute that changed. As when the page is rendered, a form control's value and checked follow it. */
package/src/vite.js ADDED
@@ -0,0 +1,107 @@
1
+ // goal.js in Vite's dev server:
2
+ //
3
+ // // vite.config.js
4
+ // import { goal } from 'goaljs/vite';
5
+ // export default { plugins: [goal()] };
6
+ //
7
+ // Vite serves the app: its modules and the public folder. Any other request goes to the app's routes
8
+ // and server functions, read from the .goal files with Vite's SSR loader and answered the way goal dev
9
+ // answers them: error details, the security defaults, live updates. Each component's browser code is a
10
+ // module of its own (`/ui/Panel.goal?goal-client=Panel`), and so is each file's render module
11
+ // (`?goal-render`), which the browser renders components from. When a file changes, the open pages are
12
+ // told as goal dev tells them (see hmr.js): a stylesheet is swapped in place, and code renders the page
13
+ // again with each component's state.
14
+
15
+ import { readFileSync, readdirSync } from 'node:fs';
16
+ import { dirname, join, relative, resolve, sep } from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
18
+ import { compile } from './compiler.js';
19
+ import { desugar } from './syntax.js';
20
+ import { createApp } from './app.js';
21
+
22
+ const SRC = dirname(fileURLToPath(import.meta.url)); // compiled code imports the helpers from here
23
+ const SKIP = new Set(['node_modules', 'dist', 'public']);
24
+ const slash = (p) => p.split(sep).join('/');
25
+
26
+ /** The .goal files under `dir`, as paths from `root`. */
27
+ function goals(dir, root) {
28
+ return readdirSync(dir, { withFileTypes: true }).flatMap((d) => {
29
+ if (d.isDirectory()) return SKIP.has(d.name) ? [] : goals(join(dir, d.name), root);
30
+ return d.name.endsWith('.goal') ? [slash(relative(root, join(dir, d.name)))] : [];
31
+ });
32
+ }
33
+
34
+ /**
35
+ * @param {{ config?: { csp?: string | false, csrf?: boolean, bodyLimit?: number } }} [options]
36
+ * config: what goal.config.js would hold (see app.js)
37
+ */
38
+ export function goal({ config = {} } = {}) {
39
+ let root;
40
+ let version = 1; // in the URL of each component's module: a page updated live loads the new code
41
+ const pages = new Set(); // the pages listening for live updates
42
+ const tell = (m) => {
43
+ for (const res of pages) res.write(`data: ${JSON.stringify(m)}\n\n`);
44
+ };
45
+
46
+ return {
47
+ name: 'goal',
48
+ config: () => ({ appType: 'custom' }), // the app's routes answer pages, not an index.html
49
+ configResolved(c) {
50
+ root = c.root;
51
+ },
52
+ resolveId(id, importer) {
53
+ if (id.startsWith('goal-render:')) return `${resolve(dirname(importer), id.slice(12))}?goal-render&v=${version}`;
54
+ },
55
+ transform(source, id, opts) {
56
+ const [file, query] = id.split('?');
57
+ if (!file.endsWith('.goal')) return;
58
+ const rel = slash(relative(root, file));
59
+ const r = compile(source, {
60
+ file: rel,
61
+ base: rel.slice(0, -5),
62
+ rt: join(SRC, 'rt.js'),
63
+ keyed: join(SRC, 'keyed.js'),
64
+ dev: true,
65
+ chunk: (n) => `/${rel}?goal-client=${n}&v=${version}`,
66
+ serverFunctions: (spec) => {
67
+ const target = resolve(dirname(file), spec);
68
+ const names = desugar(readFileSync(target, 'utf8'), spec).serverFns.filter((f) => f.exported).map((f) => f.name);
69
+ return { base: slash(relative(root, target)).slice(0, -5), names };
70
+ },
71
+ });
72
+ const q = new URLSearchParams(query);
73
+ if (q.has('goal-client')) return r.clients.find((c) => c.name === q.get('goal-client')).code;
74
+ if (q.has('goal-render')) return r.render;
75
+ if (opts?.ssr) return r.server;
76
+ throw new Error(`browser code can't import the .goal file ${rel}; move shared helpers into a .js file`);
77
+ },
78
+ configureServer(server) {
79
+ // After Vite's own middleware: what it doesn't serve, the app answers.
80
+ return () =>
81
+ server.middlewares.use(async (req, res) => {
82
+ if (req.url === '/_goal/hmr') {
83
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' });
84
+ res.write(': goal dev\n\n');
85
+ pages.add(res);
86
+ req.on('close', () => pages.delete(res));
87
+ return;
88
+ }
89
+ let routes;
90
+ try {
91
+ routes = (await Promise.all(goals(root, root).map((f) => server.ssrLoadModule(`/${f}`)))).flatMap((m) => m._$routes ?? []);
92
+ } catch (e) {
93
+ res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
94
+ return res.end(e.message); // a compile error: the page shows it over itself (hmr.js)
95
+ }
96
+ createApp(routes, { dev: true, config, log: (e) => server.config.logger.error(e.stack) })(req, res);
97
+ });
98
+ },
99
+ handleHotUpdate({ file, server }) {
100
+ if (!/\.(goal|m?js|json|css)$/.test(file) || file.includes('/node_modules/')) return;
101
+ version++;
102
+ server.moduleGraph.invalidateAll(); // the server code reads the new files
103
+ tell({ type: file.endsWith('.css') ? 'css' : 'update', version });
104
+ return []; // the pages update themselves
105
+ },
106
+ };
107
+ }