@lightblues/jig 0.1.0 → 0.1.2

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,255 @@
1
+ // Both ends of the tier-B message bridge, without DOM or React: `CanvasFrame` and the frame runtime wire these to
2
+ // `postMessage`, and the tests drive them through forced interleavings.
3
+ import { CanvasStore } from "./store.js";
4
+ import { frameMessage, jsonSize, LIMITS, parseFrameMessage, parseHostMessage, } from "./protocol.js";
5
+ /** Events a page may make before the host's `init`; later ones are dropped. */
6
+ const HELD_EVENTS = 20;
7
+ /**
8
+ * The page side. State writes are coalesced: within `flushMs` only the latest value per key is posted, so a slider
9
+ * dragged at 60 fps sends at most one message per key per window and stays under the host's rate limit. An event or
10
+ * action posts the waiting writes first, so the host sees them in the page's order. Nothing is posted but `ready`
11
+ * until the host's `init` arrives: writes and (up to 20) events made before it are kept and posted then, in order;
12
+ * actions made before it are dropped.
13
+ *
14
+ * Each posted write carries a `seq`; a host `state`/`init` carries `ack`, the last `seq` the host had when it sent it.
15
+ * Writes newer than `ack` (posted, or still waiting) stay on top of the host's values instead of flickering back.
16
+ */
17
+ export function createPageBridge(options) {
18
+ const { post } = options;
19
+ const setTimer = options.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
20
+ let seq = 0;
21
+ let timer = null;
22
+ // Writes wait for `init`: before it the host would drop them, and the page would show a value nobody stored.
23
+ let initialized = false;
24
+ const outbox = new Map();
25
+ const held = [];
26
+ const unacked = new Map();
27
+ const flush = () => {
28
+ timer = null;
29
+ if (!initialized)
30
+ return;
31
+ for (const [key, value] of outbox) {
32
+ seq += 1;
33
+ unacked.set(key, { value, seq });
34
+ post(frameMessage({ op: 'state', key, value, seq }));
35
+ }
36
+ outbox.clear();
37
+ };
38
+ const store = new CanvasStore({
39
+ surface: options.surface,
40
+ initial: options.init.state,
41
+ theme: options.init.theme,
42
+ onState: (key, value) => {
43
+ outbox.delete(key);
44
+ outbox.set(key, value);
45
+ if (timer === null)
46
+ timer = setTimer(flush, options.flushMs ?? 50);
47
+ },
48
+ onEvent: (name, data) => {
49
+ if (!initialized)
50
+ return void (held.length < HELD_EVENTS && held.push({ name, data }));
51
+ flush();
52
+ post(frameMessage({ op: 'event', name, data }));
53
+ },
54
+ onAction: (action) => {
55
+ // An action before init is dropped, not held: posted later it could arrive during an unrelated click.
56
+ if (!initialized)
57
+ return;
58
+ flush();
59
+ post(frameMessage({ op: 'action', action }));
60
+ },
61
+ });
62
+ const replace = (values, ack) => {
63
+ for (const [key, w] of unacked)
64
+ if (w.seq <= ack)
65
+ unacked.delete(key);
66
+ const next = { ...values };
67
+ for (const [key, w] of unacked)
68
+ next[key] = w.value;
69
+ for (const [key, value] of outbox)
70
+ next[key] = value;
71
+ store.replace(next);
72
+ };
73
+ return {
74
+ store,
75
+ receive(data) {
76
+ const m = parseHostMessage(data);
77
+ if (!m)
78
+ return;
79
+ if (m.op === 'theme')
80
+ store.setTheme(m.kind);
81
+ else if (m.op === 'init') {
82
+ store.setTheme(m.theme);
83
+ replace(m.state, m.ack);
84
+ if (!initialized) {
85
+ initialized = true;
86
+ flush();
87
+ for (const e of held.splice(0))
88
+ post(frameMessage({ op: 'event', name: e.name, data: e.data }));
89
+ }
90
+ }
91
+ else
92
+ replace(m.values, m.ack);
93
+ },
94
+ ready: () => post(frameMessage({ op: 'ready' })),
95
+ size: (height) => post(frameMessage({ op: 'size', height })),
96
+ error: (message) => post(frameMessage({ op: 'error', message: String(message).slice(0, LIMITS.error) })),
97
+ flush,
98
+ };
99
+ }
100
+ class Bucket {
101
+ tokens;
102
+ at;
103
+ limit;
104
+ now;
105
+ constructor(limit, now) {
106
+ this.limit = limit;
107
+ this.now = now;
108
+ this.tokens = limit.burst;
109
+ this.at = now();
110
+ }
111
+ take() {
112
+ const t = this.now();
113
+ this.tokens = Math.min(this.limit.burst, this.tokens + ((t - this.at) / 1000) * this.limit.perSecond);
114
+ this.at = t;
115
+ if (this.tokens < 1)
116
+ return false;
117
+ this.tokens -= 1;
118
+ return true;
119
+ }
120
+ }
121
+ /** The host side: validates, rate-limits, debounces and answers. One per live frame. */
122
+ export class HostBridge {
123
+ o;
124
+ state;
125
+ theme;
126
+ pending = {};
127
+ lastSeq = 0;
128
+ timer = null;
129
+ isReady = false;
130
+ disposed = false;
131
+ names = new Set();
132
+ rate;
133
+ eventRate;
134
+ setTimer;
135
+ clearTimer;
136
+ constructor(options) {
137
+ this.o = options;
138
+ this.state = options.state;
139
+ this.theme = options.theme;
140
+ const now = options.now ?? (() => Date.now());
141
+ this.rate = new Bucket(options.rate ?? { burst: 100, perSecond: 50 }, now);
142
+ this.eventRate = new Bucket(options.eventRate ?? { burst: 20, perSecond: 1 }, now);
143
+ this.setTimer = options.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
144
+ this.clearTimer = options.clearTimer ?? ((t) => clearTimeout(t));
145
+ }
146
+ /** Swap callbacks for the latest props (state and theme go through `setState` / `setTheme`). */
147
+ update(options) {
148
+ this.o = { ...this.o, ...options };
149
+ }
150
+ get ready() {
151
+ return this.isReady;
152
+ }
153
+ /** What the page should show now: the host's state with the page's not-yet-passed-on writes on top. */
154
+ current() {
155
+ return { ...this.state, ...this.pending };
156
+ }
157
+ receive(data) {
158
+ if (this.disposed)
159
+ return;
160
+ if (!this.rate.take())
161
+ return this.reject('rate limit', data);
162
+ const m = parseFrameMessage(data);
163
+ if (!m)
164
+ return this.reject('invalid message', data);
165
+ if (m.op === 'navigated') {
166
+ this.dispose();
167
+ this.o.onNavigated?.();
168
+ return;
169
+ }
170
+ if (m.op === 'ready') {
171
+ if (this.isReady)
172
+ return this.reject('ready twice', data);
173
+ this.isReady = true;
174
+ this.o.post(frameMessage({ op: 'init', state: this.current(), theme: this.theme, ack: this.lastSeq }));
175
+ this.o.onReady?.();
176
+ return;
177
+ }
178
+ if (!this.isReady)
179
+ return this.reject('before ready', data);
180
+ this.handle(m, data);
181
+ }
182
+ handle(m, data) {
183
+ switch (m.op) {
184
+ case 'state': {
185
+ this.lastSeq = Math.max(this.lastSeq, m.seq);
186
+ if (jsonSize({ ...this.current(), [m.key]: m.value }) > LIMITS.state)
187
+ return this.reject(`state over ${LIMITS.state} chars`, data);
188
+ this.pending[m.key] = m.value;
189
+ if (this.timer !== null)
190
+ this.clearTimer(this.timer);
191
+ this.timer = this.setTimer(() => this.flush(), this.o.debounceMs ?? 800);
192
+ return;
193
+ }
194
+ case 'event': {
195
+ const allowed = this.o.events;
196
+ if (allowed ? !allowed.includes(m.name) : !this.names.has(m.name) && this.names.size >= LIMITS.eventNames)
197
+ return this.reject(`event name ${m.name} not allowed`, data);
198
+ if (!this.eventRate.take())
199
+ return this.reject('event rate limit', data);
200
+ this.names.add(m.name);
201
+ this.o.onEvent?.(m.name, m.data);
202
+ return;
203
+ }
204
+ case 'action':
205
+ if (!(this.o.userActive?.() ?? false))
206
+ return this.reject('action without user activation', data);
207
+ this.o.onAction?.(m.action);
208
+ return;
209
+ case 'size':
210
+ this.o.onSize?.(m.height);
211
+ return;
212
+ case 'error':
213
+ this.o.onError?.(m.message);
214
+ return;
215
+ }
216
+ }
217
+ /** The host's state changed (the agent, another device, or its own save): replace the page's values. */
218
+ setState(values) {
219
+ // A host that passes a new but equal object on each render does not make the page re-render.
220
+ if (values === this.state || JSON.stringify(values) === JSON.stringify(this.state))
221
+ return;
222
+ this.state = values;
223
+ if (this.isReady && !this.disposed)
224
+ this.o.post(frameMessage({ op: 'state', values: this.current(), ack: this.lastSeq }));
225
+ }
226
+ setTheme(kind) {
227
+ if (kind === this.theme)
228
+ return;
229
+ this.theme = kind;
230
+ if (this.isReady && !this.disposed)
231
+ this.o.post(frameMessage({ op: 'theme', kind }));
232
+ }
233
+ /** Pass on waiting state writes now. */
234
+ flush() {
235
+ if (this.timer !== null)
236
+ this.clearTimer(this.timer);
237
+ this.timer = null;
238
+ const set = this.pending;
239
+ if (!Object.keys(set).length)
240
+ return;
241
+ this.pending = {};
242
+ this.state = { ...this.state, ...set };
243
+ this.o.onState?.(set);
244
+ }
245
+ /** Flush and stop: later messages are ignored and nothing more is posted. */
246
+ dispose() {
247
+ if (this.disposed)
248
+ return;
249
+ this.flush();
250
+ this.disposed = true;
251
+ }
252
+ reject(reason, data) {
253
+ this.o.onReject?.(reason, data);
254
+ }
255
+ }
@@ -0,0 +1,25 @@
1
+ export interface BuildRuntimeOptions {
2
+ /** Absolute path of the kit module: every name it exports is importable from a canvas. */
3
+ kit: string;
4
+ /** A component the kit exports that wraps every canvas (theme provider, page shell); gets `{ theme }`. */
5
+ root?: string;
6
+ /** A component the kit exports that shows a render error; gets `{ error }`. */
7
+ errorView?: string;
8
+ /** Module names that resolve to the kit. Default `jig/canvas`, `cursor/canvas`. */
9
+ modules?: readonly string[];
10
+ /** Write here as well as returning the code. */
11
+ outFile?: string;
12
+ /** Default true. */
13
+ minify?: boolean;
14
+ /** Default `['es2020']`. */
15
+ target?: string[];
16
+ }
17
+ export interface BuiltRuntime {
18
+ code: string;
19
+ /** sha256 of the code, 12 hex chars, for the `?v=` of the runtime URL. */
20
+ hash: string;
21
+ bytes: number;
22
+ /** What a canvas may import: the kit's exports and the runtime's hooks. Pass to `compileCanvas({ exports })`. */
23
+ exports: string[];
24
+ }
25
+ export declare function buildRuntime(options: BuildRuntimeOptions): Promise<BuiltRuntime>;
@@ -0,0 +1,54 @@
1
+ // `@lightblues/jig/canvas/build`: bundle a kit with React and the frame runtime into the `runtime.js` a canvas document
2
+ // loads. Node only, run from a host's build script; esbuild is an optional peer.
3
+ import { createHash } from 'node:crypto';
4
+ import { mkdir, writeFile } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { RUNTIME_NAMES } from "./names.js";
8
+ /** The runtime module next to this file, `.ts` in the source tree and `.js` in `dist/`. */
9
+ function sibling(name) {
10
+ const self = fileURLToPath(import.meta.url);
11
+ return path.join(path.dirname(self), `${name}${path.extname(self)}`);
12
+ }
13
+ /** The kit's export names, from an esbuild metafile of the kit alone. */
14
+ async function kitExports(esbuild, kit) {
15
+ const r = await esbuild.build({ entryPoints: [kit], bundle: true, write: false, format: 'esm', platform: 'browser', metafile: true, logLevel: 'silent', packages: 'external', outdir: '/tmp/jig-kit-exports' });
16
+ const out = Object.values(r.metafile.outputs).find((o) => o.entryPoint);
17
+ return out ? [...out.exports].filter((n) => n !== 'default') : [];
18
+ }
19
+ export async function buildRuntime(options) {
20
+ const esbuild = (await import('esbuild'));
21
+ const kit = path.resolve(options.kit);
22
+ const names = await kitExports(esbuild, kit);
23
+ for (const n of [options.root, options.errorView])
24
+ if (n && !names.includes(n))
25
+ throw new Error(`the kit ${kit} does not export ${n}`);
26
+ const entry = [
27
+ `import * as kit from ${JSON.stringify(kit)};`,
28
+ `import { startCanvasRuntime } from ${JSON.stringify(sibling('runtime'))};`,
29
+ `startCanvasRuntime({ kit, modules: ${JSON.stringify(options.modules ?? null)} ?? undefined, Root: ${options.root ? `kit[${JSON.stringify(options.root)}]` : 'undefined'}, ErrorView: ${options.errorView ? `kit[${JSON.stringify(options.errorView)}]` : 'undefined'} });`,
30
+ ].join('\n');
31
+ const r = await esbuild.build({
32
+ stdin: { contents: entry, resolveDir: path.dirname(kit), sourcefile: 'jig-canvas-runtime-entry.js', loader: 'js' },
33
+ bundle: true,
34
+ write: false,
35
+ minify: options.minify ?? true,
36
+ format: 'iife',
37
+ platform: 'browser',
38
+ target: options.target ?? ['es2020'],
39
+ define: { 'process.env.NODE_ENV': '"production"' },
40
+ legalComments: 'none',
41
+ logLevel: 'silent',
42
+ });
43
+ const code = r.outputFiles[0].text;
44
+ if (options.outFile) {
45
+ await mkdir(path.dirname(options.outFile), { recursive: true });
46
+ await writeFile(options.outFile, code);
47
+ }
48
+ return {
49
+ code,
50
+ hash: createHash('sha256').update(code).digest('hex').slice(0, 12),
51
+ bytes: Buffer.byteLength(code),
52
+ exports: [...new Set([...RUNTIME_NAMES, ...names])].sort(),
53
+ };
54
+ }
@@ -0,0 +1,29 @@
1
+ /** Module names a canvas may import from by default: Cursor's, so a Cursor canvas ports, and jig's. */
2
+ export declare const CANVAS_MODULES: readonly ["jig/canvas", "cursor/canvas"];
3
+ /** Default source cap: 100 KB of UTF-8 (v2 §4). */
4
+ export declare const CANVAS_MAX_BYTES = 100000;
5
+ export interface CompileCanvasOptions {
6
+ /** Module names allowed in `import { … } from "<name>"`. Default `CANVAS_MODULES`; a host adds its alias (`intake/canvas`). */
7
+ modules?: readonly string[];
8
+ /** Names the kit exports. Without it, any name is accepted (a missing one is `undefined` at render). */
9
+ exports?: readonly string[];
10
+ /** Source cap in UTF-8 bytes. Default 100 KB. */
11
+ maxBytes?: number;
12
+ }
13
+ /** A compile failure: `message` names the line and shows it, ready to return to the model as a tool error. */
14
+ export declare class CanvasCompileError extends Error {
15
+ name: string;
16
+ /** The source line, when the problem has one. */
17
+ readonly line?: number;
18
+ constructor(message: string, line?: number);
19
+ }
20
+ /**
21
+ * Compile canvas TSX to the body the runtime runs as `(require, exports, module, __h, __Fragment)`. Throws a
22
+ * `CanvasCompileError` when the source is over the cap, does not parse, imports anything but named imports from an
23
+ * allowed module, uses `require`, dynamic `import()` or `import.meta`, re-exports, or has no `export default`.
24
+ */
25
+ export declare function compileCanvas(source: string, options?: CompileCanvasOptions): string;
26
+ /** The line and one either side, numbered, each cut to 200 chars. */
27
+ export declare function excerpt(source: string, line: number): string;
28
+ /** The text of the first `<H1>` in the source, as a title fallback. */
29
+ export declare function canvasTitle(source: string): string;
@@ -0,0 +1,218 @@
1
+ // Compile a canvas (one TSX file against the kit) on the server, at write time. Checks run on sucrase's own tokens,
2
+ // not on regexes over the text, so a string, comment or JSX text that looks like an import is not one, and an import
3
+ // written oddly is still seen.
4
+ import { transform } from 'sucrase';
5
+ import { parse } from 'sucrase/dist/parser/index.js';
6
+ import { TokenType as tt } from 'sucrase/dist/parser/tokenizer/types.js';
7
+ /** Module names a canvas may import from by default: Cursor's, so a Cursor canvas ports, and jig's. */
8
+ export const CANVAS_MODULES = ['jig/canvas', 'cursor/canvas'];
9
+ /** Default source cap: 100 KB of UTF-8 (v2 §4). */
10
+ export const CANVAS_MAX_BYTES = 100_000;
11
+ // The parser's token types are internal to sucrase; fail loudly if a sucrase release renames one, rather than let a
12
+ // check compare against `undefined` and pass everything.
13
+ for (const name of ['name', 'string', 'braceL', 'braceR', 'braceBarL', 'braceBarR', 'dollarBraceL', 'parenL', 'parenR', 'comma', 'colon', 'dot', 'questionDot', 'star', '_break', '_default', '_with', '_export', '_import']) {
14
+ if (typeof tt[name] !== 'number')
15
+ throw new Error(`sucrase's parser has no token type ${name}; jig/canvas/server needs sucrase ~3.35`);
16
+ }
17
+ /** Names the compiled body uses; a canvas may not declare or call them. */
18
+ const RESERVED = new Set(['require', 'module', 'exports', '__h', '__Fragment']);
19
+ /** A compile failure: `message` names the line and shows it, ready to return to the model as a tool error. */
20
+ export class CanvasCompileError extends Error {
21
+ name = 'CanvasCompileError';
22
+ /** The source line, when the problem has one. */
23
+ line;
24
+ constructor(message, line) {
25
+ super(message);
26
+ this.line = line;
27
+ }
28
+ }
29
+ /**
30
+ * Compile canvas TSX to the body the runtime runs as `(require, exports, module, __h, __Fragment)`. Throws a
31
+ * `CanvasCompileError` when the source is over the cap, does not parse, imports anything but named imports from an
32
+ * allowed module, uses `require`, dynamic `import()` or `import.meta`, re-exports, or has no `export default`.
33
+ */
34
+ export function compileCanvas(source, options = {}) {
35
+ if (typeof source !== 'string')
36
+ throw new CanvasCompileError('canvas source must be a string');
37
+ const max = options.maxBytes ?? CANVAS_MAX_BYTES;
38
+ const bytes = new TextEncoder().encode(source).length;
39
+ if (bytes > max)
40
+ throw new CanvasCompileError(`canvas is ${bytes} bytes; the limit is ${max}`);
41
+ const modules = new Set(options.modules ?? CANVAS_MODULES);
42
+ const known = options.exports ? new Set(options.exports) : null;
43
+ const shown = [...modules].map((m) => JSON.stringify(m)).join(' or ');
44
+ let tokens;
45
+ try {
46
+ tokens = parse(source, true, true, false).tokens;
47
+ }
48
+ catch (err) {
49
+ throw syntaxError(source, err);
50
+ }
51
+ const fail = (index, message) => {
52
+ const line = lineAt(source, tokens[index]?.start ?? 0);
53
+ throw new CanvasCompileError(`line ${line}: ${message}\n${excerpt(source, line)}`, line);
54
+ };
55
+ const text = (i) => source.slice(tokens[i].start, tokens[i].end);
56
+ const stringValue = (i) => {
57
+ try {
58
+ return JSON.parse(text(i).replace(/^'|'$/g, '"'));
59
+ }
60
+ catch {
61
+ return text(i).slice(1, -1);
62
+ }
63
+ };
64
+ let hasDefault = false;
65
+ let depth = 0;
66
+ for (let i = 0; i < tokens.length; i++) {
67
+ const t = tokens[i];
68
+ if (t.type === tt.braceL || t.type === tt.dollarBraceL || t.type === tt.braceBarL)
69
+ depth++;
70
+ else if (t.type === tt.braceR || t.type === tt.braceBarR)
71
+ depth--;
72
+ else if (t.type === tt.name && text(i) === 'import')
73
+ fail(i, 'a canvas may not use `import.meta`');
74
+ else if (t.type === tt.name && RESERVED.has(text(i))) {
75
+ if (!isProperty(tokens, i))
76
+ fail(i, `a canvas may not use \`${text(i)}\`; import from ${shown}`);
77
+ }
78
+ else if (t.type === tt._import) {
79
+ const next = tokens[i + 1];
80
+ if (next?.type === tt.parenL)
81
+ fail(i, 'a canvas may not use dynamic `import()`');
82
+ if (next?.type === tt.dot)
83
+ fail(i, 'a canvas may not use `import.meta`');
84
+ if (depth !== 0)
85
+ fail(i, 'imports belong at the top of the file');
86
+ i = checkImport(i);
87
+ }
88
+ else if (t.type === tt._export) {
89
+ const next = tokens[i + 1];
90
+ if (next?.type === tt._default)
91
+ hasDefault = true;
92
+ else if (next?.type === tt.star)
93
+ fail(i, 'a canvas may not re-export a module');
94
+ else if (next?.type === tt.braceL) {
95
+ let j = i + 1;
96
+ while (j < tokens.length && tokens[j].type !== tt.braceR) {
97
+ if (tokens[j].type === tt._default || (tokens[j].type === tt.name && text(j) === 'default'))
98
+ hasDefault = true;
99
+ j++;
100
+ }
101
+ if (tokens[j + 1]?.type === tt.name && text(j + 1) === 'from')
102
+ fail(i, 'a canvas may not re-export a module');
103
+ }
104
+ }
105
+ }
106
+ if (!hasDefault)
107
+ throw new CanvasCompileError('canvas must `export default` a component');
108
+ /** `import` at `i`: only `import { a, b as c, type D } from "<allowed>"` or `import type …`. Returns the last index. */
109
+ function checkImport(i) {
110
+ let j = i + 1;
111
+ const isType = tokens[j]?.type === tt.name && text(j) === 'type' && tokens[j + 1]?.type !== tt.comma && !(tokens[j + 1]?.type === tt.name && text(j + 1) === 'from');
112
+ if (isType)
113
+ j++;
114
+ if (tokens[j]?.type === tt.string) {
115
+ fail(i, `a canvas may not import a module for its side effects (${text(j)})`);
116
+ }
117
+ if (tokens[j]?.type !== tt.braceL) {
118
+ fail(i, `use named imports only: \`import { Stack, Text } from ${JSON.stringify([...modules][0])}\` (no default or namespace import)`);
119
+ }
120
+ const names = []; // value imports, checked against `exports`
121
+ j++;
122
+ while (j < tokens.length && tokens[j].type !== tt.braceR) {
123
+ const tok = tokens[j];
124
+ if (tok.type === tt.comma) {
125
+ j++;
126
+ continue;
127
+ }
128
+ // `type X`, `X`, `X as Y`, `type X as Y`; the imported name is the first name that is not `type`.
129
+ let k = j;
130
+ let typeOnly = false;
131
+ if (tokens[k]?.type === tt.name && text(k) === 'type' && (tokens[k + 1]?.type === tt.name || tokens[k + 1]?.type === tt._default || tokens[k + 1]?.type === tt.string || tokens[k + 1]?.type >= tt._break)) {
132
+ k++;
133
+ typeOnly = true;
134
+ }
135
+ const imported = tokens[k];
136
+ if (imported.type === tt._default || (imported.type === tt.name && text(k) === 'default'))
137
+ fail(i, 'the kit has no default export; import components by name');
138
+ if (imported.type === tt.string || /^['"]/.test(text(k)))
139
+ fail(i, 'string import names are not allowed');
140
+ if (imported.type !== tt.name && !(imported.type >= tt._break))
141
+ fail(i, `unexpected ${text(k)} in an import`);
142
+ if (!typeOnly)
143
+ names.push({ name: text(k), at: k });
144
+ j = k + 1;
145
+ if (tokens[j]?.type === tt.name && text(j) === 'as')
146
+ j += 2;
147
+ }
148
+ j++;
149
+ if (!(tokens[j]?.type === tt.name && text(j) === 'from') || tokens[j + 1]?.type !== tt.string)
150
+ fail(i, 'malformed import');
151
+ const from = stringValue(j + 1);
152
+ if (!modules.has(from))
153
+ fail(i, `a canvas may import only from ${shown}; found ${JSON.stringify(from)}`);
154
+ if (!isType && known)
155
+ for (const n of names)
156
+ if (!known.has(n.name))
157
+ fail(i, `${JSON.stringify(from)} does not export ${n.name}`);
158
+ if (tokens[j + 2]?.type === tt._with || (tokens[j + 2]?.type === tt.name && text(j + 2) === 'assert'))
159
+ fail(i, 'import attributes are not allowed');
160
+ return j + 1;
161
+ }
162
+ let code;
163
+ try {
164
+ code = transform(source, {
165
+ transforms: ['typescript', 'jsx', 'imports'],
166
+ jsxPragma: '__h',
167
+ jsxFragmentPragma: '__Fragment',
168
+ production: true,
169
+ filePath: 'canvas.tsx',
170
+ }).code;
171
+ }
172
+ catch (err) {
173
+ throw syntaxError(source, err);
174
+ }
175
+ // Belt and braces: in the transformed body, every `require` is a call with an allowed literal name.
176
+ const out = parse(code, false, false, false).tokens;
177
+ for (let i = 0; i < out.length; i++) {
178
+ const t = out[i];
179
+ if (t.type !== tt.name || code.slice(t.start, t.end) !== 'require' || isProperty(out, i))
180
+ continue;
181
+ const arg = out[i + 2];
182
+ const name = arg?.type === tt.string ? code.slice(arg.start + 1, arg.end - 1) : undefined;
183
+ if (out[i + 1]?.type !== tt.parenL || name === undefined || !modules.has(name) || out[i + 3]?.type !== tt.parenR) {
184
+ throw new CanvasCompileError(`the compiled canvas uses require(${arg ? code.slice(arg.start, arg.end) : ''}); only ${shown} are allowed`);
185
+ }
186
+ }
187
+ if (!/\bexports\.\s*default\s*=/.test(code))
188
+ throw new CanvasCompileError('canvas must `export default` a component');
189
+ return code;
190
+ }
191
+ /** `x.require` and `{ require: 1 }` name a property, not the binding. (`{ require }` shorthand is the binding.) */
192
+ function isProperty(tokens, i) {
193
+ const prev = tokens[i - 1];
194
+ const next = tokens[i + 1];
195
+ return prev?.type === tt.dot || prev?.type === tt.questionDot || (next?.type === tt.colon && (prev?.type === tt.braceL || prev?.type === tt.comma));
196
+ }
197
+ function syntaxError(source, err) {
198
+ const loc = err.loc;
199
+ const message = String(err?.message ?? err).replace(/^Error transforming canvas\.tsx: /, '');
200
+ return new CanvasCompileError(`canvas does not compile: ${message}${loc ? `\n${excerpt(source, loc.line)}` : ''}`, loc?.line);
201
+ }
202
+ function lineAt(source, index) {
203
+ let line = 1;
204
+ for (let i = 0; i < index && i < source.length; i++)
205
+ if (source.charCodeAt(i) === 10)
206
+ line++;
207
+ return line;
208
+ }
209
+ /** The line and one either side, numbered, each cut to 200 chars. */
210
+ export function excerpt(source, line) {
211
+ const lines = source.split('\n');
212
+ const from = Math.max(1, line - 1);
213
+ return lines.slice(from - 1, line + 1).map((t, i) => `${String(from + i).padStart(4)} | ${t.length > 200 ? `${t.slice(0, 200)}…` : t}`).join('\n');
214
+ }
215
+ /** The text of the first `<H1>` in the source, as a title fallback. */
216
+ export function canvasTitle(source) {
217
+ return /<H1(?:\s[^>]*)?>([^<{]+)<\/H1>/.exec(source)?.[1]?.trim() ?? '';
218
+ }
@@ -0,0 +1,43 @@
1
+ import type { CanvasState } from './protocol.ts';
2
+ export interface SurfaceEvent {
3
+ name: string;
4
+ data: unknown;
5
+ /** When it happened: ISO text or a Date. */
6
+ at?: string | Date;
7
+ }
8
+ export interface SurfaceView {
9
+ /** The surface id (`"artifact:<id>"`, `"lemma:econ/fig-growth"`). */
10
+ surface: string;
11
+ /** What it is, for the agent: a title, a figure caption. */
12
+ title?: string;
13
+ /** A host-chosen kind attribute (`canvas`, `figure`, `table`). */
14
+ kind?: string;
15
+ /** The stored state. */
16
+ state?: CanvasState;
17
+ /** What the page shows now, if it differs from what is stored (live values the page sent with the ask). */
18
+ now?: CanvasState;
19
+ /** Events, any order; the last one of each name is kept, newest first. */
20
+ events?: readonly SurfaceEvent[];
21
+ }
22
+ export interface SurfacesContextOptions {
23
+ /** Cap of the whole text. Default 8,000 chars. Surfaces past it are counted in `<omitted>`, never cut midway. */
24
+ maxChars?: number;
25
+ /** At most this many surfaces (lemma: 8). Default 8. */
26
+ maxSurfaces?: number;
27
+ /** One JSON value longer than this is cut with a note. Default 2,000 chars. */
28
+ maxValueChars?: number;
29
+ /** The outer tag. Default `surfaces`. */
30
+ tag?: string;
31
+ }
32
+ /**
33
+ * The text an agent gets on its next run, or `''` when there is nothing to say. Values are JSON, escaped for XML-ish
34
+ * text; the model reads them, nothing parses them back.
35
+ */
36
+ export declare function surfacesContext(surfaces: readonly SurfaceView[], options?: SurfacesContextOptions): string;
37
+ /** The same as an AG-UI `Context` entry (`RunAgentInput.context[]`), or null when empty. */
38
+ export declare function surfacesContextEntry(surfaces: readonly SurfaceView[], options?: SurfacesContextOptions & {
39
+ description?: string;
40
+ }): {
41
+ description: string;
42
+ value: string;
43
+ } | null;