@lightblues/jig 0.0.11 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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;
@@ -0,0 +1,79 @@
1
+ const TAG = /^[A-Za-z][\w-]{0,31}$/;
2
+ const text = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
3
+ const attr = (s) => text(s).replace(/"/g, '&quot;').replace(/[\r\n\t]/g, ' ');
4
+ function value(v, max) {
5
+ let json;
6
+ try {
7
+ json = JSON.stringify(v) ?? 'null';
8
+ }
9
+ catch {
10
+ json = '"(not JSON)"';
11
+ }
12
+ return text(json.length > max ? `${json.slice(0, max)}… (${json.length} chars, cut)` : json);
13
+ }
14
+ function when(at) {
15
+ if (at === undefined)
16
+ return undefined;
17
+ const d = at instanceof Date ? at : new Date(at);
18
+ return Number.isNaN(d.getTime()) ? String(at) : d.toISOString();
19
+ }
20
+ function attrs(a) {
21
+ return Object.entries(a).filter(([, v]) => v !== undefined && v !== '').map(([k, v]) => ` ${k}="${attr(v)}"`).join('');
22
+ }
23
+ function block(s, max) {
24
+ const lines = [` <surface${attrs({ id: s.surface, kind: s.kind, title: s.title })}>`];
25
+ if (s.state && Object.keys(s.state).length)
26
+ lines.push(` <state>${value(s.state, max)}</state>`);
27
+ if (s.now && Object.keys(s.now).length)
28
+ lines.push(` <now>${value(s.now, max)}</now>`);
29
+ const last = new Map();
30
+ const time = (e) => (e.at === undefined ? -Infinity : new Date(e.at).getTime() || -Infinity);
31
+ for (const e of s.events ?? []) {
32
+ const seen = last.get(e.name);
33
+ if (!seen || time(e) >= time(seen))
34
+ last.set(e.name, e);
35
+ }
36
+ for (const e of [...last.values()].sort((a, b) => time(b) - time(a)))
37
+ lines.push(` <last${attrs({ event: e.name, at: when(e.at) })}>${value(e.data, max)}</last>`);
38
+ lines.push(' </surface>');
39
+ return lines.join('\n');
40
+ }
41
+ /**
42
+ * The text an agent gets on its next run, or `''` when there is nothing to say. Values are JSON, escaped for XML-ish
43
+ * text; the model reads them, nothing parses them back.
44
+ */
45
+ export function surfacesContext(surfaces, options = {}) {
46
+ const maxChars = options.maxChars ?? 8_000;
47
+ const maxSurfaces = options.maxSurfaces ?? 8;
48
+ const max = options.maxValueChars ?? 2_000;
49
+ const tag = options.tag && TAG.test(options.tag) ? options.tag : 'surfaces';
50
+ if (!surfaces.length)
51
+ return '';
52
+ const open = `<${tag}>`;
53
+ const close = `</${tag}>`;
54
+ const kept = [];
55
+ let size = open.length + close.length + 2;
56
+ let omitted = 0;
57
+ for (const s of surfaces) {
58
+ if (kept.length >= maxSurfaces) {
59
+ omitted++;
60
+ continue;
61
+ }
62
+ const b = block(s, max);
63
+ // Room for the omitted line, whatever follows.
64
+ if (size + b.length + 1 + 40 > maxChars) {
65
+ omitted++;
66
+ continue;
67
+ }
68
+ kept.push(b);
69
+ size += b.length + 1;
70
+ }
71
+ if (omitted)
72
+ kept.push(` <omitted surfaces="${omitted}"/>`);
73
+ return [open, ...kept, close].join('\n');
74
+ }
75
+ /** The same as an AG-UI `Context` entry (`RunAgentInput.context[]`), or null when empty. */
76
+ export function surfacesContextEntry(surfaces, options = {}) {
77
+ const v = surfacesContext(surfaces, options);
78
+ return v ? { description: options.description ?? 'Interactive surfaces the reader has in view: their saved state, live values and last events', value: v } : null;
79
+ }
@@ -0,0 +1,50 @@
1
+ import type { CanvasState, ThemeKind } from './protocol.ts';
2
+ /**
3
+ * Who reads the page. `owner`: the reader asked for it (intake, assay, baton console, kiln). `multi`: an app with
4
+ * several users (lemma authored pages; later private chats behind a click). `multi` has no popups and loads images
5
+ * only from the host's own media origin.
6
+ */
7
+ export type CanvasProfile = 'owner' | 'multi';
8
+ /**
9
+ * The iframe `sandbox` per profile. Never `allow-same-origin` (the frame keeps an opaque origin: no cookies, storage
10
+ * or host API), never forms, modals or top navigation. Owner pages may open links in a new tab.
11
+ */
12
+ export declare const CANVAS_SANDBOX: Record<CanvasProfile, string>;
13
+ export interface CanvasDocumentOptions {
14
+ profile: CanvasProfile;
15
+ /** Absolute http(s) URL of the built runtime (`buildRuntime`), served by the host. Its query string is ignored by the CSP. */
16
+ runtimeUrl: string;
17
+ /** The host's media origin (`https://media.example.com`): the only place a `multi` page loads images from. */
18
+ mediaOrigin?: string;
19
+ /** Extra stylesheet and font URLs (absolute http(s)), such as KaTeX's CSS for the kit's `<Math>`. */
20
+ styleUrls?: readonly string[];
21
+ theme: ThemeKind;
22
+ /** The surface's saved values, so the first render already shows them. */
23
+ state?: CanvasState;
24
+ surface?: string;
25
+ title?: string;
26
+ /** The page background before the runtime paints, to avoid a white flash in dark mode. */
27
+ background?: string;
28
+ }
29
+ /** An absolute http(s) URL as a CSP source (origin + path, no query or fragment); throws on anything else. */
30
+ export declare function cspSource(url: string, what: string): string;
31
+ /** An origin (`https://host[:port]`, no path); throws on anything else. */
32
+ export declare function cspOrigin(origin: string, what: string): string;
33
+ /**
34
+ * The Content-Security-Policy of a canvas document. No network (`connect-src 'none'`), no frames, forms or `<base>`,
35
+ * no `eval`; scripts only from the runtime URL and the inline boot script. Images: `data:`, `blob:` and the media
36
+ * origin, plus any `https:` image for `owner` (a page can leak its state in an image URL; the owner is its only reader).
37
+ */
38
+ export declare function canvasCsp(options: Pick<CanvasDocumentOptions, 'profile' | 'runtimeUrl' | 'mediaOrigin' | 'styleUrls'>): string;
39
+ /** Inline `<script>` text cannot hold `</script` or `<!--`; both have equivalent escaped spellings in JS. */
40
+ export declare function scriptSafe(code: string): string;
41
+ export declare function escapeHtml(text: string): string;
42
+ /**
43
+ * The `srcdoc` of a canvas: a relay document (CSP, then the nested page frame, then the relay script) whose inner
44
+ * frame holds the page: the CSP first, then the runtime by URL, then the compiled body inline. The runtime
45
+ * (`window.__jigCanvas.run`) mounts it, posts `ready`, and takes the host's `init`. Put it in an iframe with
46
+ * `sandbox={CANVAS_SANDBOX[profile]}` (`CanvasFrame` does).
47
+ */
48
+ export declare function canvasDocument(compiled: string, options: CanvasDocumentOptions): string;
49
+ /** The inner page alone (what runs the canvas). `canvasDocument` wraps it in the relay; use that. */
50
+ export declare function canvasPage(compiled: string, options: CanvasDocumentOptions): string;
@@ -0,0 +1,128 @@
1
+ /**
2
+ * The iframe `sandbox` per profile. Never `allow-same-origin` (the frame keeps an opaque origin: no cookies, storage
3
+ * or host API), never forms, modals or top navigation. Owner pages may open links in a new tab.
4
+ */
5
+ export const CANVAS_SANDBOX = {
6
+ owner: 'allow-scripts allow-popups allow-popups-to-escape-sandbox',
7
+ multi: 'allow-scripts',
8
+ };
9
+ const CSS_COLOR = /^(#[0-9a-f]{3,8}|[a-z]+|(rgb|hsl)a?\([\d\s.,%/]+\))$/i;
10
+ /** An absolute http(s) URL as a CSP source (origin + path, no query or fragment); throws on anything else. */
11
+ export function cspSource(url, what) {
12
+ let u;
13
+ try {
14
+ u = new URL(url);
15
+ }
16
+ catch {
17
+ throw new TypeError(`${what} must be an absolute http(s) URL: ${JSON.stringify(url)}`);
18
+ }
19
+ if (u.protocol !== 'https:' && u.protocol !== 'http:')
20
+ throw new TypeError(`${what} must be http(s): ${JSON.stringify(url)}`);
21
+ if (u.username || u.password)
22
+ throw new TypeError(`${what} must not carry credentials`);
23
+ const source = u.origin + u.pathname;
24
+ if (/[\s;,'"]/.test(source))
25
+ throw new TypeError(`${what} has a character a CSP cannot hold: ${JSON.stringify(url)}`);
26
+ return source;
27
+ }
28
+ /** An origin (`https://host[:port]`, no path); throws on anything else. */
29
+ export function cspOrigin(origin, what) {
30
+ const source = cspSource(origin, what);
31
+ const u = new URL(source);
32
+ if (u.pathname !== '/' || origin.replace(/\/$/, '') !== u.origin)
33
+ throw new TypeError(`${what} must be an origin without a path: ${JSON.stringify(origin)}`);
34
+ return u.origin;
35
+ }
36
+ /**
37
+ * The Content-Security-Policy of a canvas document. No network (`connect-src 'none'`), no frames, forms or `<base>`,
38
+ * no `eval`; scripts only from the runtime URL and the inline boot script. Images: `data:`, `blob:` and the media
39
+ * origin, plus any `https:` image for `owner` (a page can leak its state in an image URL; the owner is its only reader).
40
+ */
41
+ export function canvasCsp(options) {
42
+ const runtime = cspSource(options.runtimeUrl, 'runtimeUrl');
43
+ const media = options.mediaOrigin ? ` ${cspOrigin(options.mediaOrigin, 'mediaOrigin')}` : '';
44
+ const styles = (options.styleUrls ?? []).map((u) => ` ${cspSource(u, 'styleUrls')}`).join('');
45
+ const images = `data: blob:${media}${options.profile === 'owner' ? ' https:' : ''}`;
46
+ if (options.profile !== 'owner' && options.profile !== 'multi')
47
+ throw new TypeError(`unknown profile ${JSON.stringify(options.profile)}`);
48
+ return [
49
+ "default-src 'none'",
50
+ `script-src ${runtime} 'unsafe-inline'`,
51
+ `style-src 'unsafe-inline'${styles}`,
52
+ `font-src data:${styles}`,
53
+ `img-src ${images}`,
54
+ `media-src ${images}`,
55
+ "connect-src 'none'",
56
+ "frame-src 'none'",
57
+ "worker-src 'none'",
58
+ "object-src 'none'",
59
+ "form-action 'none'",
60
+ "base-uri 'none'",
61
+ ].join('; ');
62
+ }
63
+ /** Inline `<script>` text cannot hold `</script` or `<!--`; both have equivalent escaped spellings in JS. */
64
+ export function scriptSafe(code) {
65
+ return code.replace(/<\/(script)/gi, '<\\/$1').replace(/<!--/g, '<\\!--');
66
+ }
67
+ /** JSON that is safe inside an inline script. */
68
+ function scriptJson(value) {
69
+ return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
70
+ }
71
+ export function escapeHtml(text) {
72
+ return text.replace(/[&<>"']/g, (ch) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[ch]);
73
+ }
74
+ /**
75
+ * The relay: the outer document of a canvas. It holds the canvas page in a nested sandboxed frame and passes messages
76
+ * between it and the host, unchanged. Why a second frame: a sandboxed page may still navigate itself, and CSP cannot
77
+ * forbid that, so `location.href = "https://x/?" + state` would send its state off the device. A frame's navigation is
78
+ * checked against its *parent's* `frame-src`; the relay's is `'none'`, so the browser blocks it (and a second `load`
79
+ * of the inner frame tells the host the page tried; the relay removes it). The relay carries the same CSP as the page,
80
+ * because a srcdoc page inherits its parent's policy as well as its own.
81
+ */
82
+ const RELAY = `(function(){var f=document.getElementById('c'),p=window.parent,n=0,T='jig-canvas';
83
+ addEventListener('message',function(e){var d=e.data;if(e.source===p){f.contentWindow&&f.contentWindow.postMessage(d,'*');return}
84
+ if(e.source!==f.contentWindow||!d||d.type!==T)return;
85
+ if(d.op==='size'&&typeof d.height==='number'&&d.height>=0)f.style.height=Math.min(Math.ceil(d.height),20000)+'px';p.postMessage(d,'*')});
86
+ f.addEventListener('load',function(){if(++n>1){f.remove();p.postMessage({type:T,v:1,op:'navigated'},'*')}})})()`;
87
+ /**
88
+ * The `srcdoc` of a canvas: a relay document (CSP, then the nested page frame, then the relay script) whose inner
89
+ * frame holds the page: the CSP first, then the runtime by URL, then the compiled body inline. The runtime
90
+ * (`window.__jigCanvas.run`) mounts it, posts `ready`, and takes the host's `init`. Put it in an iframe with
91
+ * `sandbox={CANVAS_SANDBOX[profile]}` (`CanvasFrame` does).
92
+ */
93
+ export function canvasDocument(compiled, options) {
94
+ const csp = canvasCsp(options);
95
+ const inner = canvasPage(compiled, options);
96
+ const sandbox = CANVAS_SANDBOX[options.profile];
97
+ const background = pageBackground(options);
98
+ return [
99
+ `<!doctype html><html><head><meta charset="utf-8">`,
100
+ `<meta http-equiv="Content-Security-Policy" content="${escapeHtml(csp)}"><meta name="referrer" content="no-referrer">`,
101
+ `<style>html,body{margin:0;background:${background}}iframe{display:block;width:100%;height:0;border:0}</style></head><body>`,
102
+ `<iframe id="c" sandbox="${sandbox}" referrerpolicy="no-referrer" title="${escapeHtml(options.title ?? 'canvas')}" srcdoc="${escapeHtml(inner)}"></iframe>`,
103
+ `<script>${RELAY}</script></body></html>`,
104
+ ].join('');
105
+ }
106
+ function pageBackground(options) {
107
+ return options.background && CSS_COLOR.test(options.background) ? options.background : options.theme === 'dark' ? '#111' : '#fff';
108
+ }
109
+ /** The inner page alone (what runs the canvas). `canvasDocument` wraps it in the relay; use that. */
110
+ export function canvasPage(compiled, options) {
111
+ if (typeof compiled !== 'string')
112
+ throw new TypeError('compiled must be the string compileCanvas returned');
113
+ const csp = canvasCsp(options);
114
+ const runtime = new URL(options.runtimeUrl).href;
115
+ const theme = options.theme === 'dark' ? 'dark' : 'light';
116
+ const boot = scriptJson({ theme, state: options.state ?? {}, surface: options.surface ?? '' });
117
+ const styles = (options.styleUrls ?? []).map((u) => `<link rel="stylesheet" href="${escapeHtml(new URL(u).href)}">`).join('');
118
+ return [
119
+ `<!doctype html><html data-theme="${theme}"><head><meta charset="utf-8">`,
120
+ `<meta http-equiv="Content-Security-Policy" content="${escapeHtml(csp)}">`,
121
+ `<meta name="referrer" content="no-referrer"><meta name="viewport" content="width=device-width,initial-scale=1">`,
122
+ `<title>${escapeHtml(options.title ?? 'canvas')}</title>${styles}`,
123
+ `<style>html{color-scheme:${theme}}body{margin:0;background:${pageBackground(options)}}</style></head><body><div id="root"></div>`,
124
+ `<script src="${escapeHtml(runtime)}"></script>`,
125
+ `<script>window.__jigCanvas.run(function (require, exports, module, __h, __Fragment) {\n${scriptSafe(compiled)}\n}, ${boot})</script>`,
126
+ `</body></html>`,
127
+ ].join('');
128
+ }
@@ -0,0 +1,65 @@
1
+ import { type CSSProperties, type ReactNode } from 'react';
2
+ import { type RateLimit } from './bridge.ts';
3
+ import { type CanvasProfile } from './document.ts';
4
+ import type { CanvasAction, CanvasState, ThemeKind } from './protocol.ts';
5
+ export { CANVAS_SANDBOX, canvasDocument, canvasCsp, type CanvasProfile, type CanvasDocumentOptions } from './document.ts';
6
+ export { HostBridge, createPageBridge, type HostBridgeOptions, type RateLimit } from './bridge.ts';
7
+ export * from './protocol.ts';
8
+ /** How long the page has from mounting to its first `size` before the host shows "not responding". */
9
+ export declare const FIRST_SIZE_BUDGET_MS = 5000;
10
+ /** Live frames per page by default. */
11
+ export declare const MAX_LIVE_FRAMES = 3;
12
+ export type CanvasFrameStatus = 'idle' | 'loading' | 'live' | 'paused' | 'not-responding' | 'render-error' | 'navigated' | 'compile-error';
13
+ export interface CanvasFrameProps {
14
+ /** The compiled body (`compileCanvas`). `null` or `compileError` shows the source instead. */
15
+ src: string | null | undefined;
16
+ /** The TSX the model wrote: shown when it did not compile, did not respond, or on "source". */
17
+ source?: string;
18
+ /** The compile error, when `src` is missing because of one. */
19
+ compileError?: string;
20
+ /** The host's id for this surface. */
21
+ surface: string;
22
+ profile: CanvasProfile;
23
+ /** URL of the built runtime (`buildRuntime`), on the host's origin or its static origin. Relative is resolved against the page. */
24
+ runtimeUrl: string;
25
+ /** Where a `multi` page may load images from. */
26
+ mediaOrigin?: string;
27
+ /** Extra stylesheets (KaTeX CSS for `<Math>`). */
28
+ styleUrls?: readonly string[];
29
+ /** The state the host holds now. A new object replaces the page's values (another device, or the agent). */
30
+ state?: CanvasState;
31
+ theme?: ThemeKind;
32
+ /** Debounced: every key the page changed since the last call, latest value each. */
33
+ onState?: (set: CanvasState) => void;
34
+ onEvent?: (name: string, data: unknown) => void;
35
+ /** Only during a click in the frame. The host checks the action against its own list. */
36
+ onAction?: (action: CanvasAction) => void;
37
+ onStatus?: (status: CanvasFrameStatus, detail?: string) => void;
38
+ /** Each page message dropped (invalid, over a limit, rate-limited, an action without a click), with the reason. */
39
+ onReject?: (reason: string, data: unknown) => void;
40
+ /** Event names allowed; default the first 20 the page uses. */
41
+ events?: readonly string[];
42
+ /**
43
+ * When the frame starts: `visible` (scrolled into view, the default), `click` (a "Show" button first; use it for
44
+ * model output in multi-user apps) or `eager`.
45
+ */
46
+ load?: 'visible' | 'click' | 'eager';
47
+ title?: string;
48
+ background?: string;
49
+ className?: string;
50
+ style?: CSSProperties;
51
+ /** Height before the page reports its own. Default 120. */
52
+ minHeight?: number;
53
+ /** Height cap. Default 4,000 (the page scrolls inside past it). */
54
+ maxHeight?: number;
55
+ debounceMs?: number;
56
+ rate?: RateLimit;
57
+ eventRate?: RateLimit;
58
+ budgetMs?: number;
59
+ /** Overrides the page-wide limit of live frames (`MAX_LIVE_FRAMES`). */
60
+ maxLive?: number;
61
+ }
62
+ /** Frames live now (for tests and host dashboards). */
63
+ export declare function liveFrameCount(): number;
64
+ /** A model-written canvas in a sandboxed iframe. */
65
+ export declare function CanvasFrame(props: CanvasFrameProps): ReactNode;