goaljs 0.4.0 → 0.5.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/README.md CHANGED
@@ -47,8 +47,9 @@ also cover [routes](https://goallabs.github.io/goal/routes),
47
47
  [components](https://goallabs.github.io/goal/components),
48
48
  [server functions](https://goallabs.github.io/goal/server-functions),
49
49
  [security](https://goallabs.github.io/goal/security),
50
- [how it works](https://goallabs.github.io/goal/how-it-works) and
51
- [performance](https://goallabs.github.io/goal/performance).
50
+ [how it works](https://goallabs.github.io/goal/how-it-works),
51
+ [performance](https://goallabs.github.io/goal/performance), and working in
52
+ [Vite](https://goallabs.github.io/goal/vite).
52
53
 
53
54
  ## Working on goal.js
54
55
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "goaljs",
3
- "version": "0.4.0",
3
+ "version": "0.5.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": {
package/src/app.js CHANGED
@@ -165,13 +165,13 @@ function match(routes, method, segs) {
165
165
  return allow.size ? { allow: [...allow] } : null;
166
166
  }
167
167
 
168
- /** The state a page kept for each component, sent with a live update; anything else counts as none. */
168
+ /** The state a page kept for each component, in order, sent with a live update; anything else counts as none. */
169
169
  function keptState(header) {
170
170
  try {
171
171
  const v = JSON.parse(header);
172
- return v && typeof v === 'object' ? v : {};
172
+ return Array.isArray(v) ? v : [];
173
173
  } catch {
174
- return {};
174
+ return [];
175
175
  }
176
176
  }
177
177
 
@@ -255,9 +255,13 @@ export function createApp(routes, { dev = false, staticDirs = [], config = {}, l
255
255
 
256
256
  const ctx = _$ctx(token);
257
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.
258
+ // goal dev: a live update (see hmr.js). Components render in the page's order, so each takes
259
+ // the next state the page kept for the same component; one the page didn't have starts anew.
259
260
  const kept = (ctx.hmr = keptState(req.headers['x-goal-hmr']));
260
- ctx.k = (chunk, i) => (kept[i]?.c === chunk ? kept[i].s : null);
261
+ ctx.k = (chunk) => {
262
+ const j = kept.findIndex((x) => x?.c === chunk);
263
+ return j < 0 ? null : kept.splice(0, j + 1).pop().s;
264
+ };
261
265
  }
262
266
  const request = { method, path: url.pathname, url, params: m.params, query: Object.fromEntries(url.searchParams), headers: req.headers, cookies, form, files, json: body };
263
267
  const cookie = (name, value, opts) => setCookies.push(serializeCookie(name, value, opts));
package/src/hmr.js CHANGED
@@ -31,9 +31,8 @@ export function hmr(d, w, connect = (url) => new w.EventSource(url)) {
31
31
  const events = (doc) => JSON.parse(doc.querySelector('meta[name="goal-events"]')?.content || '[]');
32
32
 
33
33
  async function update() {
34
- const kept = {}; // by instance number: which component, and its state now
35
- for (const el of d.querySelectorAll('[m-c]'))
36
- kept[el.getAttribute('m-i')] = { c: el.getAttribute('m-c').split('?')[0], s: el.$s ?? JSON.parse(el.getAttribute('m-s') || '{}') };
34
+ const kept = []; // in the page's order: which component, and its state now
35
+ for (const el of d.querySelectorAll('[m-c]')) kept.push({ c: el.getAttribute('m-c').split('?')[0], s: el.$s ?? JSON.parse(el.getAttribute('m-s') || '{}') });
37
36
  const header = JSON.stringify(kept);
38
37
  if (header.length > 8000) return w.location.reload(); // more than a request header should carry
39
38
  const res = await w.fetch(w.location.href, { headers: { 'x-goal-hmr': header } });
package/src/vite.js CHANGED
@@ -7,10 +7,10 @@
7
7
  // Vite serves the app: its modules and the public folder. Any other request goes to the app's routes
8
8
  // and server functions, read from the .goal files with Vite's SSR loader and answered the way goal dev
9
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.
10
+ // module of its own (/ui/Panel.goal.Panel.client.js), and so is each file's render module
11
+ // (/ui/Panel.goal.render.js), which the browser renders components from. The .goal files themselves
12
+ // are never served. When a file changes, the open pages are told as goal dev tells them (see hmr.js):
13
+ // a stylesheet is swapped in place, and code renders the page again with each component's state.
14
14
 
15
15
  import { readFileSync, readdirSync } from 'node:fs';
16
16
  import { dirname, join, relative, resolve, sep } from 'node:path';
@@ -21,6 +21,7 @@ import { createApp } from './app.js';
21
21
 
22
22
  const SRC = dirname(fileURLToPath(import.meta.url)); // compiled code imports the helpers from here
23
23
  const SKIP = new Set(['node_modules', 'dist', 'public']);
24
+ const MODULE = /^(.*\.goal)\.(?:([A-Za-z_$][\w$]*)\.client|render)\.js$/; // see resolveId
24
25
  const slash = (p) => p.split(sep).join('/');
25
26
 
26
27
  /** The .goal files under `dir`, as paths from `root`. */
@@ -42,6 +43,22 @@ export function goal({ config = {} } = {}) {
42
43
  const tell = (m) => {
43
44
  for (const res of pages) res.write(`data: ${JSON.stringify(m)}\n\n`);
44
45
  };
46
+ const build = (file, source = readFileSync(file, 'utf8')) => {
47
+ const rel = slash(relative(root, file));
48
+ return compile(source, {
49
+ file: rel,
50
+ base: rel.slice(0, -5),
51
+ rt: join(SRC, 'rt.js'),
52
+ keyed: join(SRC, 'keyed.js'),
53
+ dev: true,
54
+ chunk: (n) => `/${rel}.${n}.client.js?v=${version}`,
55
+ serverFunctions: (spec) => {
56
+ const target = resolve(dirname(file), spec);
57
+ const names = desugar(readFileSync(target, 'utf8'), spec).serverFns.filter((f) => f.exported).map((f) => f.name);
58
+ return { base: slash(relative(root, target)).slice(0, -5), names };
59
+ },
60
+ });
61
+ };
45
62
 
46
63
  return {
47
64
  name: 'goal',
@@ -49,34 +66,32 @@ export function goal({ config = {} } = {}) {
49
66
  configResolved(c) {
50
67
  root = c.root;
51
68
  },
69
+ // A component's browser code: /ui/Panel.goal.Panel.client.js; a file's render module, imported as
70
+ // goal-render:./Panel.goal: /ui/Panel.goal.render.js. Both are made from the .goal file.
52
71
  resolveId(id, importer) {
53
- if (id.startsWith('goal-render:')) return `${resolve(dirname(importer), id.slice(12))}?goal-render&v=${version}`;
72
+ if (id.startsWith('goal-render:')) return `${resolve(dirname(importer), id.slice(12))}.render.js?v=${version}`;
73
+ const [path, query] = id.split('?');
74
+ if (MODULE.test(path)) return (path.startsWith(root) ? path : join(root, path)) + (query ? `?${query}` : '');
75
+ },
76
+ load(id) {
77
+ const m = MODULE.exec(id.split('?')[0]);
78
+ if (!m) return;
79
+ const r = build(m[1]);
80
+ return m[2] ? r.clients.find((c) => c.name === m[2]).code : r.render;
54
81
  },
82
+ // The server's code, for Vite's SSR loader.
55
83
  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`);
84
+ if (!id.endsWith('.goal')) return;
85
+ if (!opts?.ssr) throw new Error(`browser code can't import the .goal file ${slash(relative(root, id))}; move shared helpers into a .js file`);
86
+ return build(id, source).server;
77
87
  },
78
88
  configureServer(server) {
79
- // After Vite's own middleware: what it doesn't serve, the app answers.
89
+ // Before Vite's own middleware: the .goal files stay on the server, as with goal build.
90
+ server.middlewares.use((req, res, next) => {
91
+ if (!/\.goal(\?|$)/.test(req.url)) return next();
92
+ res.writeHead(404).end();
93
+ });
94
+ // After it: what Vite doesn't serve, the app answers.
80
95
  return () =>
81
96
  server.middlewares.use(async (req, res) => {
82
97
  if (req.url === '/_goal/hmr') {