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.
package/src/keyed.js ADDED
@@ -0,0 +1,120 @@
1
+ // Keyed lists: `{items.map((x) => <tr key={x.id}>...</tr>)}` in a component. Each row is
2
+ // [key, item, index, ...values], and a row template turns a row into HTML. When the list changes,
3
+ // rows are matched by key: a kept row gets only its changed values written, new rows are made in
4
+ // one batch, rows that are gone are removed, and of the kept rows only those out of order are moved
5
+ // (the rest are the longest run already in order).
6
+
7
+ const set = (el, name, v, off = v == null || v === false) =>
8
+ name === 'value' ? (el.value = off ? '' : v)
9
+ : name === 'checked' ? (el.checked = !off)
10
+ : off ? el.removeAttribute(name)
11
+ : el.setAttribute(name, v === true ? '' : v);
12
+
13
+ /** Writes value `v` where `part` says, in `row`: a text (in place when it can be) or an attribute. */
14
+ const put = (row, [kind, path, name], v) => {
15
+ let el = row;
16
+ for (const p of path) el = el.children[p];
17
+ const x = el.firstChild;
18
+ if (kind) set(el, name, v);
19
+ else if (/[<&]/.test(v)) el.innerHTML = v;
20
+ else if (x?.nodeType === 3 && !x.nextSibling) x.data = v;
21
+ else el.textContent = v;
22
+ };
23
+
24
+ /**
25
+ * New rows, in a fragment. With `parts`, each is a copy of a blank row with its values written in
26
+ * (no HTML to parse); without, they are parsed from the template.
27
+ */
28
+ const make = (d, rows, tpl, parts) => {
29
+ const t = d.createElement('template');
30
+ if (!parts) {
31
+ t.innerHTML = rows.map(tpl).join('');
32
+ return t.content;
33
+ }
34
+ // The blank row: a space in each text part, so the value goes in a text node already there.
35
+ tpl.$b ||= ((t.innerHTML = tpl([, , , ...parts.map((p) => (p[0] ? null : ' '))])), d.importNode(t.content.firstChild, true)); // a node of the page
36
+ const f = d.createDocumentFragment();
37
+ for (const r of rows) {
38
+ const n = tpl.$b.cloneNode(true);
39
+ parts.forEach((part, k) => put(n, part, r[k + 3]));
40
+ f.appendChild(n);
41
+ }
42
+ return f;
43
+ };
44
+
45
+ /**
46
+ * Patches the keyed list after the comment `c`, from rows `a` to rows `b`. `parts` says where each
47
+ * value goes in a row: [0, path] the text of an element, [1, path, name] an attribute; null means a
48
+ * row whose values changed is made again from the template.
49
+ */
50
+ export function _$lp(d, c, a, b, tpl, parts) {
51
+ let old = [];
52
+ let end = c.nextSibling;
53
+ for (; end.data !== '/'; end = end.nextSibling) old.push(end); // rows are all elements, up to the end marker
54
+ const parent = end.parentNode;
55
+ // Writes a kept row's changed values in place; says no when the row has to be made again.
56
+ const keep = (r, o, n) => {
57
+ if (r !== o) for (let k = 3; k < r.length; k++) if (r[k] !== o[k]) if (parts) put(n, parts[k - 3], r[k]); else return;
58
+ return 1;
59
+ };
60
+ // Rows that stay where they were, at the start and at the end, are patched where they are.
61
+ let s = 0;
62
+ let ea = a.length;
63
+ let eb = b.length;
64
+ while (s < ea && s < eb && a[s][0] === b[s][0] && keep(b[s], a[s], old[s])) s++;
65
+ while (ea > s && eb > s && a[ea - 1][0] === b[eb - 1][0] && keep(b[eb - 1], a[ea - 1], old[ea - 1])) (ea--, eb--);
66
+ const stop = old[ea] || end;
67
+ a = a.slice(s, ea);
68
+ b = b.slice(s, eb);
69
+ old = old.slice(s, ea);
70
+ const at = new Map();
71
+ for (let i = 0; i < a.length; i++) at.set(a[i][0], i);
72
+ const nodes = [];
73
+ const from = []; // each row's old position, or -1 for a new one
74
+ const fresh = [];
75
+ const kept = [];
76
+ for (let i = 0; i < b.length; i++) {
77
+ const j = at.get(b[i][0]);
78
+ from[i] = -1;
79
+ if (j === undefined || kept[j] || !keep(b[i], a[j], old[j])) fresh.push(i); // kept[j]: a key used twice
80
+ else (nodes[i] = old[j]), (from[i] = j), (kept[j] = 1);
81
+ }
82
+ if (fresh.length === b.length) {
83
+ // Nothing in the middle kept: out with the old rows, in with the new, in one go each. When
84
+ // nothing at the ends was kept either, and the list is all its parent holds, clear it at once.
85
+ if (!s && stop === end && !c.previousSibling && !end.nextSibling) {
86
+ parent.textContent = '';
87
+ parent.append(c, end);
88
+ } else for (const n of old) n.remove();
89
+ if (b.length) parent.insertBefore(make(d, b, tpl, parts), stop);
90
+ return;
91
+ }
92
+ if (fresh.length)
93
+ [
94
+ ...make(
95
+ d,
96
+ fresh.map((i) => b[i]),
97
+ tpl,
98
+ parts,
99
+ ).children,
100
+ ].forEach((n, x) => (nodes[fresh[x]] = n));
101
+ old.forEach((n, j) => kept[j] || n.remove());
102
+ // The longest run of kept rows already in order stays; everything else is put in place.
103
+ const tails = [];
104
+ const prev = [];
105
+ from.forEach((j, i) => {
106
+ if (j < 0) return;
107
+ let lo = 0;
108
+ let hi = tails.length;
109
+ while (lo < hi) {
110
+ const mid = (lo + hi) >> 1;
111
+ if (from[tails[mid]] < j) lo = mid + 1;
112
+ else hi = mid;
113
+ }
114
+ prev[i] = tails[lo - 1];
115
+ tails[lo] = i;
116
+ });
117
+ const stay = [];
118
+ for (let i = tails.at(-1); i !== undefined; i = prev[i]) stay[i] = 1;
119
+ for (let i = nodes.length, next = stop; i--; next = nodes[i]) if (!stay[i]) parent.insertBefore(nodes[i], next);
120
+ }
package/src/loader.js ADDED
@@ -0,0 +1,101 @@
1
+ // The goal.js loader: the only script a page runs at start, and it only adds listeners.
2
+ //
3
+ // When an event reaches an element with `m-on="click:0"`, the loader finds the component root
4
+ // around it (`m-c` = the URL of its client module), loads that module once, reads the state the
5
+ // server wrote (`m-s`) and the props (`m-p`), runs the handlers, saves the state they changed, runs
6
+ // the component again and patches the bindings whose value changed. The last run stays on the root
7
+ // element, so the next event starts from it: one run of the component per event.
8
+
9
+ /**
10
+ * @param {Document} d
11
+ * @param {string[]} events the event types the page's components handle
12
+ * @param {(url: string) => Promise<any>} [load] how to load a client module
13
+ */
14
+ export function boot(d, events, load = (u) => import(u)) {
15
+ const mods = {};
16
+ const get = (r, u = r.getAttribute('m-c')) => (mods[u] ||= load(u));
17
+ const json = (r, a) => JSON.parse(r.getAttribute(a) || '{}');
18
+ // Start loading on intent (pointer over, focus), so the code is there by the first click or key.
19
+ const warm = (e) => {
20
+ const r = e.target.closest?.('[m-c]');
21
+ if (r) get(r);
22
+ };
23
+ for (const t of ['pointerover', 'focusin']) d.addEventListener(t, warm, true);
24
+ // A run of the component from its state: [values, handlers, read the state, the state read].
25
+ const run = (m, r) => {
26
+ const x = m.default(r.$s, r.$p);
27
+ x[3] = x[2]();
28
+ return x;
29
+ };
30
+ const go = async (e) => {
31
+ // The handlers on the way up, found before any runs (a handler may re-render the rest away).
32
+ const todo = [];
33
+ for (let el = e.target; el.getAttribute; el = el.parentNode)
34
+ for (const pair of (el.getAttribute('m-on') || '').split(' ')) {
35
+ const [type, h] = pair.split(':');
36
+ if (type !== e.type) continue;
37
+ if (type === 'submit') e.preventDefault(); // must happen now, before the module loads
38
+ todo.push([el.closest('[m-c]'), h, el]);
39
+ }
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
+ };
69
+ for (const ev of events) d.addEventListener(ev, go, true);
70
+ }
71
+
72
+ /** Updates the bindings whose value changed between `a` and `b`. */
73
+ function patch(d, r, m, a, b) {
74
+ const i = r.getAttribute('m-i');
75
+ m._$k.forEach(([kind, n, name, parts], j) => {
76
+ const v = b[j];
77
+ if (v === a[j]) return;
78
+ if (kind === 1) {
79
+ const q = `[m-x="${i}.${n}"]`;
80
+ const el = r.matches(q) ? r : r.querySelector(q);
81
+ const off = v == null || v === false;
82
+ if (name === 'value') el.value = off ? '' : v;
83
+ else if (name === 'checked') el.checked = !off;
84
+ else if (off) el.removeAttribute(name);
85
+ else el.setAttribute(name, v === true ? '' : v);
86
+ return;
87
+ }
88
+ // The hole's start marker, found once and kept on the root.
89
+ let c = (r.$m ||= {})[n];
90
+ if (!c) {
91
+ const w = d.createTreeWalker(r, 128);
92
+ while ((c = w.nextNode()) && c.data !== `${i}.${n}`);
93
+ r.$m[n] = c;
94
+ }
95
+ if (kind) return m._$lp(d, c, a[j], v, name, parts); // a keyed list
96
+ for (let x = c.nextSibling; x.nodeType !== 8 || x.data !== '/'; x = c.nextSibling) x.remove();
97
+ const tpl = d.createElement('template');
98
+ tpl.innerHTML = v;
99
+ c.after(tpl.content);
100
+ });
101
+ }
package/src/rt.js ADDED
@@ -0,0 +1,96 @@
1
+ // Helpers that compiled goal.js code calls, on the server and in client chunks.
2
+ // Names start with _$ so they can't clash with names in user code.
3
+
4
+ const ESC = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
5
+
6
+ /** Escapes a value for HTML text or a quoted attribute. */
7
+ export const _$e = (v) => {
8
+ const s = String(v);
9
+ return /[&<>"']/.test(s) ? s.replace(/[&<>"']/g, (c) => ESC[c]) : s;
10
+ };
11
+
12
+ /** Compiled markup: HTML that is already safe, so `_$h` doesn't escape it again. */
13
+ export class Html {
14
+ constructor(s) {
15
+ this.s = s;
16
+ }
17
+ toString() {
18
+ return this.s;
19
+ }
20
+ }
21
+
22
+ /** Marks a compiled template as markup. Only compiled code makes these. */
23
+ export const _$m = (s) => new Html(s);
24
+
25
+ /** Renders any `{value}` child: markup as HTML, lists joined, null/booleans as nothing, the rest escaped. */
26
+ export const _$h = (v) =>
27
+ typeof v === 'number' ? '' + v
28
+ : v instanceof Html ? v.s
29
+ : Array.isArray(v) ? v.map(_$h).join('')
30
+ : v == null || typeof v === 'boolean' ? ''
31
+ : _$e(v);
32
+
33
+ /** Attributes that hold a URL a browser may navigate to or load. */
34
+ export const URL_ATTRS = new Set(['href', 'src', 'action', 'formaction', 'poster', 'cite', 'data', 'manifest', 'background']);
35
+
36
+ /** The URL itself when it is relative or http(s)/mailto/tel; a harmless placeholder for javascript:, data: and the rest. */
37
+ export const _$u = (v) => {
38
+ if (v == null || typeof v === 'boolean') return v;
39
+ const m = /^([a-z][a-z0-9+.-]*):/i.exec(String(v).replace(/[\u0000- ]/g, ''));
40
+ return !m || /^(https?|mailto|tel)$/i.test(m[1]) ? v : 'about:invalid#blocked';
41
+ };
42
+
43
+ /** Renders an attribute: false/null leave it out, true writes it bare; URLs are checked. */
44
+ export const _$a = (name, v) => {
45
+ if (URL_ATTRS.has(name)) v = _$u(v);
46
+ return v == null || v === false ? '' : v === true ? ' ' + name : ` ${name}="${_$e(v)}"`;
47
+ };
48
+
49
+ /** Writes only the props a component's browser code reads, so the rest never reaches the page. */
50
+ export const _$pa = (props, keys) => {
51
+ if (!keys.length) return '';
52
+ const o = {};
53
+ for (const k of keys) if (Object.hasOwn(props, k)) o[k] = props[k];
54
+ return ` m-p="${_$e(JSON.stringify(o))}"`;
55
+ };
56
+
57
+ /**
58
+ * Calls a server function from the browser: what a call in an event handler compiles to. The
59
+ * request carries the page's CSRF token and comes from this site, so the server lets it through.
60
+ */
61
+ export const _$sf = async (url, args) => {
62
+ const token = document.querySelector('meta[name="goal-csrf"]')?.content ?? '';
63
+ const res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', 'x-csrf-token': token }, body: JSON.stringify(args) });
64
+ if (!res.ok) throw new Error(`server function ${url} failed: ${res.status}`);
65
+ return (await res.json()).v;
66
+ };
67
+
68
+ /** Runs a server function for a request from the browser: the arguments are a JSON array. */
69
+ export const _$call = async (fn, r, x) =>
70
+ Array.isArray(r.json) ? x.json({ v: (await fn(...r.json)) ?? null }) : x.json({ error: 'send the arguments as a JSON array' }, 400);
71
+
72
+ /** A render: numbers component instances, collects the page's events, and holds the CSRF token. */
73
+ export const _$ctx = (t = '') => ({
74
+ i: 0,
75
+ t,
76
+ ev: new Set(),
77
+ e(list) {
78
+ for (const x of list) this.ev.add(x);
79
+ },
80
+ });
81
+
82
+ /** The server's rendering of a keyed list (see keyed.js): each row through its template. */
83
+ export const _$hl = (rows, tpl) => rows.map(tpl).join('');
84
+
85
+ /** Runs a list row's handler `h` ("r0"): which row is it, counting from the list's start marker? */
86
+ export function _$lh(el, root, x, h, e) {
87
+ const row = el.closest('[m-r]');
88
+ const n = row.getAttribute('m-r');
89
+ let i = 0;
90
+ for (let s = row.previousSibling; s.data !== `${root.getAttribute('m-i')}.${n}`; s = s.previousSibling) i++; // rows are all elements
91
+ const list = x[0][n];
92
+ return list.h(list[i][1], i)[h.slice(1)](e); // its index now: a kept row may have moved
93
+ }
94
+
95
+ /** A keyed list in the browser: its rows, and `h(item, index)`, the handlers of one row. */
96
+ export const _$L = (rows, h) => ((rows.h = h), rows);
package/src/server.js ADDED
@@ -0,0 +1,38 @@
1
+ // Server rendering: HTML first, and the loader only when the page has something to handle.
2
+
3
+ import { readFileSync } from 'node:fs';
4
+ import { dirname, join } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { transformSync } from 'esbuild';
7
+ import { _$ctx, _$e } from './rt.js';
8
+
9
+ /** Renders a compiled component to HTML, with the events its page needs to listen to. */
10
+ export function render(Component, props = {}, ctx = _$ctx()) {
11
+ const html = Component(props, ctx);
12
+ return { html, events: [...ctx.ev] };
13
+ }
14
+
15
+ const EVENTS = '"__GOAL_EVENTS__"';
16
+ let loaderCode;
17
+ /** The loader, minified, starting itself; the page puts its events where EVENTS is. */
18
+ export function loaderScript() {
19
+ const src = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'loader.js'), 'utf8');
20
+ loaderCode ??= transformSync(`${src.replace('export function boot', 'function boot')}\nboot(document, ${EVENTS});`, { format: 'iife', minify: true }).code.trim();
21
+ return loaderCode;
22
+ }
23
+
24
+ /**
25
+ * A whole HTML document. Markup that starts with <html> is the document itself; anything else goes
26
+ * in a plain one. The loader goes in only when there are events, with the request's CSP nonce, and
27
+ * the CSRF token that server function calls send.
28
+ */
29
+ export function page(html, events, nonce, token = '') {
30
+ const script = events.length
31
+ ? `<meta name="goal-csrf" content="${_$e(token)}"><script type="module" nonce="${nonce}">${loaderScript().replace(EVENTS, JSON.stringify(events))}</script>`
32
+ : '';
33
+ if (/^<html[\s>]/.test(html)) {
34
+ const i = html.lastIndexOf('</body>');
35
+ return '<!doctype html>' + (i < 0 ? html + script : html.slice(0, i) + script + html.slice(i));
36
+ }
37
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>goal.js</title></head><body>${html}${script}</body></html>`;
38
+ }
package/src/syntax.js ADDED
@@ -0,0 +1,162 @@
1
+ // The .goal syntax on top of JavaScript and JSX:
2
+ //
3
+ // route GET /users/{id} { ... } a route, at the top level of a file
4
+ // {if (a) <p>A</p> else if (b) <p>B</p> else <p>C</p>} if/else as a value, inside markup
5
+ // server function addNote(text) { ... } runs on the server, called from the browser
6
+ //
7
+ // desugar() parses the file with acorn (extended for these two forms), and rewrites them into plain
8
+ // JavaScript + JSX with small text edits: a route becomes `async function _$r0(request, _$x) { ... }`
9
+ // an if becomes a chain of ternaries, and a server function becomes an async function. `map` turns a position in the output back into one in the
10
+ // source, so errors point at what the author wrote.
11
+
12
+ import { Parser, tokTypes as tt } from 'acorn';
13
+ import jsx from 'acorn-jsx';
14
+
15
+ export const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
16
+ const SERVER = /^server[ \t]+function[ \t]+([A-Za-z_$][\w$]*)/;
17
+ const SEGMENT = /^(?:[A-Za-z0-9\-._~]+|\{[A-Za-z_][A-Za-z0-9_]*\})$/;
18
+
19
+ export class GoalError extends Error {
20
+ constructor(message, file, line, column) {
21
+ super(`${file}:${line}:${column}: ${message}`);
22
+ this.name = 'GoalError';
23
+ this.file = file;
24
+ this.line = line;
25
+ this.column = column;
26
+ }
27
+ }
28
+
29
+ /** A GoalError at an offset in the source. */
30
+ export function errorAt(source, file, pos, message) {
31
+ const before = source.slice(0, pos).split('\n');
32
+ return new GoalError(message, file, before.length, before.at(-1).length + 1);
33
+ }
34
+
35
+ const Base = Parser.extend(jsx());
36
+
37
+ /**
38
+ * @returns {{ code: string, routes: { method: string, path: string, params: string[], name: string }[],
39
+ * serverFns: { name: string, exported: boolean }[], map: (pos: number) => number }}
40
+ */
41
+ export function desugar(source, file) {
42
+ const edits = [];
43
+ const routes = [];
44
+ const serverFns = [];
45
+ const fail = (pos, message) => {
46
+ throw errorAt(source, file, pos, message);
47
+ };
48
+
49
+ class GoalParser extends Base {
50
+ isServerFn() {
51
+ return this.type === tt.name && this.value === 'server' && SERVER.test(this.input.slice(this.start));
52
+ }
53
+
54
+ shouldParseExportStatement() {
55
+ if (!this.isServerFn()) return super.shouldParseExportStatement();
56
+ this.goalExport = true;
57
+ return true;
58
+ }
59
+
60
+ parseStatement(context, topLevel, exports) {
61
+ if (this.isServerFn()) {
62
+ if (!topLevel && !this.goalExport) fail(this.start, 'declare a server function at the top level of a file');
63
+ serverFns.push({ name: SERVER.exec(this.input.slice(this.start))[1], exported: !!this.goalExport });
64
+ this.goalExport = false;
65
+ edits.push({ at: this.start, del: 6, ins: 'async' });
66
+ const node = this.startNode();
67
+ this.next();
68
+ return this.parseFunctionStatement(node, true, true);
69
+ }
70
+ if (topLevel && this.type === tt.name && this.value === 'route' && /^route[ \t]+[A-Z]/.test(this.input.slice(this.start)))
71
+ return this.goalRoute();
72
+ return super.parseStatement(context, topLevel, exports);
73
+ }
74
+
75
+ goalRoute() {
76
+ const start = this.start;
77
+ const m = /^route[ \t]+(\S+)[ \t]+(\S+)[ \t]+\{/.exec(this.input.slice(start));
78
+ if (!m) fail(start, 'write a route as: route GET /path { ... }');
79
+ const [head, method, path] = m;
80
+ if (!METHODS.includes(method)) fail(start, `unknown method ${method}; use ${METHODS.join(', ')}`);
81
+ const segs = path === '/' ? [] : path.slice(1).split('/');
82
+ if (path[0] !== '/' || !segs.every((s) => SEGMENT.test(s)))
83
+ fail(start, `write the path with plain words and {name} parameters, like /users/{id} (not ${path})`);
84
+ const params = segs.filter((s) => s[0] === '{').map((s) => s.slice(1, -1));
85
+ for (const [i, p] of params.entries()) {
86
+ if (params.indexOf(p) !== i) fail(start, `the path names {${p}} twice`);
87
+ if (p === 'request') fail(start, 'name the path parameter something other than {request}');
88
+ }
89
+ const name = `_$r${routes.length}`;
90
+ routes.push({ method, path, params, name });
91
+ const brace = start + head.length - 1;
92
+ edits.push({ at: start, del: brace - start, ins: `async function ${name}(request, _$x) ` });
93
+ const node = this.startNode();
94
+ this.pos = brace;
95
+ this.next();
96
+ this.enterScope(2 | 4); // an async function's scope (acorn's SCOPE_FUNCTION | SCOPE_ASYNC)
97
+ node.body = this.parseBlock(false);
98
+ this.exitScope();
99
+ return this.finishNode(node, 'GoalRoute');
100
+ }
101
+
102
+ jsx_parseExpressionContainer() {
103
+ const node = this.startNode();
104
+ this.next();
105
+ if (this.type === tt._if) node.expression = this.goalIf();
106
+ else node.expression = this.type === tt.braceR ? this.jsx_parseEmptyExpression() : this.parseExpression();
107
+ this.expect(tt.braceR);
108
+ return this.finishNode(node, 'JSXExpressionContainer');
109
+ }
110
+
111
+ // if (a) X else if (b) Y else Z -> (a) ? (X) : (b) ? (Y) : (Z)
112
+ goalIf() {
113
+ const node = this.startNode();
114
+ edits.push({ at: this.start, del: 2, ins: '' });
115
+ this.next();
116
+ this.parseParenExpression();
117
+ edits.push({ at: this.lastTokEnd, del: 0, ins: ' ? (' });
118
+ this.parseMaybeAssign();
119
+ const end = this.lastTokEnd;
120
+ if (this.type === tt._else) {
121
+ edits.push({ at: end, del: 0, ins: ')' });
122
+ edits.push({ at: this.start, del: 4, ins: ':' });
123
+ this.next();
124
+ if (this.type === tt._if) this.goalIf();
125
+ else {
126
+ edits.push({ at: this.start, del: 0, ins: '(' });
127
+ this.parseMaybeAssign();
128
+ edits.push({ at: this.lastTokEnd, del: 0, ins: ')' });
129
+ }
130
+ } else edits.push({ at: end, del: 0, ins: ') : null' });
131
+ return this.finishNode(node, 'GoalIf');
132
+ }
133
+ }
134
+
135
+ try {
136
+ GoalParser.parse(source, { ecmaVersion: 'latest', sourceType: 'module', allowHashBang: true });
137
+ } catch (e) {
138
+ if (e instanceof GoalError) throw e;
139
+ fail(e.pos, e.message.replace(/ \(\d+:\d+\)$/, ''));
140
+ }
141
+
142
+ edits.sort((a, b) => a.at - b.at);
143
+ let code = '';
144
+ let last = 0;
145
+ for (const e of edits) {
146
+ code += source.slice(last, e.at) + e.ins;
147
+ last = e.at + e.del;
148
+ }
149
+ code += source.slice(last);
150
+
151
+ const map = (pos) => {
152
+ let shift = 0;
153
+ for (const e of edits) {
154
+ const at = e.at + shift;
155
+ if (pos < at) break;
156
+ if (pos < at + e.ins.length) return e.at;
157
+ shift += e.ins.length - e.del;
158
+ }
159
+ return pos - shift;
160
+ };
161
+ return { code, routes, serverFns, map };
162
+ }