@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.
- package/README.md +1 -0
- package/dist/agent-chat/markdown.d.ts +4 -0
- package/dist/agent-chat/markdown.js +223 -15
- package/dist/agent-chat/react.d.ts +7 -1
- package/dist/agent-chat/react.js +98 -9
- package/dist/canvas/bridge.d.ts +110 -0
- package/dist/canvas/bridge.js +255 -0
- package/dist/canvas/build.d.ts +25 -0
- package/dist/canvas/build.js +54 -0
- package/dist/canvas/compile.d.ts +29 -0
- package/dist/canvas/compile.js +218 -0
- package/dist/canvas/context.d.ts +43 -0
- package/dist/canvas/context.js +79 -0
- package/dist/canvas/document.d.ts +50 -0
- package/dist/canvas/document.js +128 -0
- package/dist/canvas/frame.d.ts +65 -0
- package/dist/canvas/frame.js +197 -0
- package/dist/canvas/names.d.ts +1 -0
- package/dist/canvas/names.js +6 -0
- package/dist/canvas/protocol.d.ts +93 -0
- package/dist/canvas/protocol.js +152 -0
- package/dist/canvas/runtime.d.ts +25 -0
- package/dist/canvas/runtime.js +110 -0
- package/dist/canvas/server.d.ts +5 -0
- package/dist/canvas/server.js +8 -0
- package/dist/canvas/state.d.ts +31 -0
- package/dist/canvas/state.js +72 -0
- package/dist/canvas/store.d.ts +39 -0
- package/dist/canvas/store.js +82 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +30 -1
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// The canvas state protocol (J008, `.ea/docs/canvas.md`): one set of messages for tier A (in-page, provider callbacks)
|
|
2
|
+
// and tier B (sandboxed iframe, postMessage). This module is pure: no React, no DOM, no Node built-in, so the server,
|
|
3
|
+
// the host frame and the in-frame runtime all validate with the same code.
|
|
4
|
+
/** `type` of every bridged message. */
|
|
5
|
+
export const FRAME_MESSAGE_TYPE = 'jig-canvas';
|
|
6
|
+
/** Protocol version; a message with another `v` is dropped. */
|
|
7
|
+
export const FRAME_MESSAGE_VERSION = 1;
|
|
8
|
+
/** Limits (v2 §2). A message over a limit is dropped, never truncated. */
|
|
9
|
+
export const LIMITS = {
|
|
10
|
+
/** Longest state key. */
|
|
11
|
+
key: 200,
|
|
12
|
+
/** A surface's whole state, as JSON characters. */
|
|
13
|
+
state: 20_000,
|
|
14
|
+
/** One event's `data`, as JSON characters. */
|
|
15
|
+
eventData: 2_000,
|
|
16
|
+
/** One action, as JSON characters. */
|
|
17
|
+
action: 4_000,
|
|
18
|
+
/** Distinct event names a tier-B surface may use. */
|
|
19
|
+
eventNames: 20,
|
|
20
|
+
/** Tallest frame, in CSS pixels; a larger `size` is clamped. */
|
|
21
|
+
height: 20_000,
|
|
22
|
+
/** Deepest JSON nesting accepted in a value. */
|
|
23
|
+
depth: 32,
|
|
24
|
+
/** Longest render-error message kept. */
|
|
25
|
+
error: 2_000,
|
|
26
|
+
};
|
|
27
|
+
export const EVENT_NAME = /^[A-Za-z][\w.:-]{0,63}$/;
|
|
28
|
+
const ACTION_TYPE = /^[A-Za-z][\w.:-]{0,63}$/;
|
|
29
|
+
/** Wrap a message for `postMessage`. */
|
|
30
|
+
export function frameMessage(message) {
|
|
31
|
+
return { type: FRAME_MESSAGE_TYPE, v: FRAME_MESSAGE_VERSION, ...message };
|
|
32
|
+
}
|
|
33
|
+
function isPlainObject(value) {
|
|
34
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
35
|
+
return false;
|
|
36
|
+
const proto = Object.getPrototypeOf(value);
|
|
37
|
+
return proto === Object.prototype || proto === null;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Plain JSON within `depth`: objects with the plain prototype, arrays, strings, finite numbers, booleans, null.
|
|
41
|
+
* `postMessage` clones Maps, Dates, typed arrays and cycles; none of those is state.
|
|
42
|
+
*/
|
|
43
|
+
export function isJson(value, depth = LIMITS.depth) {
|
|
44
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean')
|
|
45
|
+
return true;
|
|
46
|
+
if (typeof value === 'number')
|
|
47
|
+
return Number.isFinite(value);
|
|
48
|
+
if (depth <= 0)
|
|
49
|
+
return false;
|
|
50
|
+
if (Array.isArray(value)) {
|
|
51
|
+
if (Object.getPrototypeOf(value) !== Array.prototype)
|
|
52
|
+
return false;
|
|
53
|
+
for (let i = 0; i < value.length; i++)
|
|
54
|
+
if (!(i in value) || !isJson(value[i], depth - 1))
|
|
55
|
+
return false;
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
if (!isPlainObject(value))
|
|
59
|
+
return false;
|
|
60
|
+
for (const key of Object.keys(value))
|
|
61
|
+
if (!isJson(value[key], depth - 1))
|
|
62
|
+
return false;
|
|
63
|
+
return Object.getOwnPropertySymbols(value).length === 0;
|
|
64
|
+
}
|
|
65
|
+
/** JSON length of a value already checked by `isJson`. */
|
|
66
|
+
export function jsonSize(value) {
|
|
67
|
+
return JSON.stringify(value)?.length ?? 0;
|
|
68
|
+
}
|
|
69
|
+
function envelope(data) {
|
|
70
|
+
if (!isPlainObject(data))
|
|
71
|
+
return null;
|
|
72
|
+
if (data.type !== FRAME_MESSAGE_TYPE || data.v !== FRAME_MESSAGE_VERSION || typeof data.op !== 'string')
|
|
73
|
+
return null;
|
|
74
|
+
return data;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* A page → host message, validated, or null. Unknown ops, wrong types, oversized values, non-JSON values, keys over
|
|
78
|
+
* 200 chars and bad event or action names are all null. Checking `event.source` is the caller's job (`CanvasFrame`).
|
|
79
|
+
*/
|
|
80
|
+
export function parseFrameMessage(data) {
|
|
81
|
+
const m = envelope(data);
|
|
82
|
+
if (!m)
|
|
83
|
+
return null;
|
|
84
|
+
switch (m.op) {
|
|
85
|
+
case 'ready':
|
|
86
|
+
return { op: 'ready' };
|
|
87
|
+
case 'navigated':
|
|
88
|
+
return { op: 'navigated' };
|
|
89
|
+
case 'state': {
|
|
90
|
+
const { key, value, seq } = m;
|
|
91
|
+
if (typeof key !== 'string' || !key || key.length > LIMITS.key)
|
|
92
|
+
return null;
|
|
93
|
+
if (!('value' in m) || !isJson(value) || jsonSize(value) > LIMITS.state)
|
|
94
|
+
return null;
|
|
95
|
+
if (typeof seq !== 'number' || !Number.isSafeInteger(seq) || seq < 1)
|
|
96
|
+
return null;
|
|
97
|
+
return { op: 'state', key, value, seq };
|
|
98
|
+
}
|
|
99
|
+
case 'event': {
|
|
100
|
+
const { name, data: payload = null } = m;
|
|
101
|
+
if (typeof name !== 'string' || !EVENT_NAME.test(name))
|
|
102
|
+
return null;
|
|
103
|
+
if (!isJson(payload) || jsonSize(payload) > LIMITS.eventData)
|
|
104
|
+
return null;
|
|
105
|
+
return { op: 'event', name, data: payload };
|
|
106
|
+
}
|
|
107
|
+
case 'action': {
|
|
108
|
+
const { action } = m;
|
|
109
|
+
if (!isPlainObject(action) || typeof action.type !== 'string' || !ACTION_TYPE.test(action.type))
|
|
110
|
+
return null;
|
|
111
|
+
if (!isJson(action) || jsonSize(action) > LIMITS.action)
|
|
112
|
+
return null;
|
|
113
|
+
return { op: 'action', action: action };
|
|
114
|
+
}
|
|
115
|
+
case 'size': {
|
|
116
|
+
const { height } = m;
|
|
117
|
+
if (typeof height !== 'number' || !Number.isFinite(height) || height < 0)
|
|
118
|
+
return null;
|
|
119
|
+
return { op: 'size', height: Math.min(Math.ceil(height), LIMITS.height) };
|
|
120
|
+
}
|
|
121
|
+
case 'error': {
|
|
122
|
+
const { message } = m;
|
|
123
|
+
if (typeof message !== 'string')
|
|
124
|
+
return null;
|
|
125
|
+
return { op: 'error', message: message.slice(0, LIMITS.error) };
|
|
126
|
+
}
|
|
127
|
+
default:
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
const isTheme = (v) => v === 'light' || v === 'dark';
|
|
132
|
+
const isAck = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
|
|
133
|
+
/** A host → page message, validated, or null. The runtime also checks `event.source === window.parent`. */
|
|
134
|
+
export function parseHostMessage(data) {
|
|
135
|
+
const m = envelope(data);
|
|
136
|
+
if (!m)
|
|
137
|
+
return null;
|
|
138
|
+
switch (m.op) {
|
|
139
|
+
case 'init':
|
|
140
|
+
if (!isPlainObject(m.state) || !isJson(m.state) || !isTheme(m.theme) || !isAck(m.ack))
|
|
141
|
+
return null;
|
|
142
|
+
return { op: 'init', state: m.state, theme: m.theme, ack: m.ack };
|
|
143
|
+
case 'state':
|
|
144
|
+
if (!isPlainObject(m.values) || !isJson(m.values) || !isAck(m.ack))
|
|
145
|
+
return null;
|
|
146
|
+
return { op: 'state', values: m.values, ack: m.ack };
|
|
147
|
+
case 'theme':
|
|
148
|
+
return isTheme(m.kind) ? { op: 'theme', kind: m.kind } : null;
|
|
149
|
+
default:
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { createElement as h, Fragment, type ComponentType, type ReactNode } from 'react';
|
|
2
|
+
import type { ThemeKind } from './protocol.ts';
|
|
3
|
+
/** The compiled canvas: a CommonJS body with JSX as `__h` / `__Fragment` (`compileCanvas`). */
|
|
4
|
+
export type CanvasFactory = (require: (name: string) => unknown, exports: Record<string, unknown>, module: {
|
|
5
|
+
exports: Record<string, unknown>;
|
|
6
|
+
}, __h: typeof h, __Fragment: typeof Fragment) => void;
|
|
7
|
+
export interface CanvasRuntimeOptions {
|
|
8
|
+
/** The kit module: every name a canvas may import. The state hooks and React's hooks are added unless the kit has its own. */
|
|
9
|
+
kit: Record<string, unknown>;
|
|
10
|
+
/** Module names that resolve to the kit. Default `jig/canvas`, `cursor/canvas`. Keep in step with `compileCanvas`. */
|
|
11
|
+
modules?: readonly string[];
|
|
12
|
+
/** Wraps the canvas: the kit's theme provider and page shell. Gets the theme kind. */
|
|
13
|
+
Root?: ComponentType<{
|
|
14
|
+
theme: ThemeKind;
|
|
15
|
+
children?: ReactNode;
|
|
16
|
+
}>;
|
|
17
|
+
/** What a render error shows inside the frame. */
|
|
18
|
+
ErrorView?: ComponentType<{
|
|
19
|
+
error: unknown;
|
|
20
|
+
}>;
|
|
21
|
+
}
|
|
22
|
+
/** Load the compiled body against the kit and return its default export. Throws what the body throws. */
|
|
23
|
+
export declare function loadCanvas(factory: CanvasFactory, kit: Record<string, unknown>, modules: readonly string[]): ComponentType;
|
|
24
|
+
/** Install `window.__jigCanvas.run`. Call once in the runtime entry. */
|
|
25
|
+
export declare function startCanvasRuntime(options: CanvasRuntimeOptions): void;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// `@lightblues/jig/canvas/runtime`: the browser runtime inside the sandboxed frame: `buildRuntime` bundles this with React, react-dom and a kit into
|
|
2
|
+
// `runtime.js`. The document (`canvasDocument`) loads it and calls `window.__jigCanvas.run(factory, boot)`.
|
|
3
|
+
import { Component, createElement as h, Fragment, useEffect } from 'react';
|
|
4
|
+
import * as React from 'react';
|
|
5
|
+
import { createRoot } from 'react-dom/client';
|
|
6
|
+
import { createPageBridge } from "./bridge.js";
|
|
7
|
+
import { CanvasStateProvider, useCanvasAction, useCanvasEvent, useCanvasState, useCanvasSurface, useCanvasTheme } from "./state.js";
|
|
8
|
+
function errorText(error) {
|
|
9
|
+
return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
10
|
+
}
|
|
11
|
+
function DefaultError({ error }) {
|
|
12
|
+
return h('pre', { role: 'alert', style: { margin: 0, padding: '12px 14px', whiteSpace: 'pre-wrap', overflowWrap: 'anywhere', font: '12px/18px ui-monospace,monospace', color: '#b42318' } }, errorText(error));
|
|
13
|
+
}
|
|
14
|
+
/** Load the compiled body against the kit and return its default export. Throws what the body throws. */
|
|
15
|
+
export function loadCanvas(factory, kit, modules) {
|
|
16
|
+
const allowed = new Set(modules);
|
|
17
|
+
const module = { exports: {} };
|
|
18
|
+
const require = (name) => {
|
|
19
|
+
if (allowed.has(name))
|
|
20
|
+
return kit;
|
|
21
|
+
throw new Error(`canvas may import only ${[...allowed].join(' or ')}; found ${JSON.stringify(name)}`);
|
|
22
|
+
};
|
|
23
|
+
factory(require, module.exports, module, h, Fragment);
|
|
24
|
+
const value = module.exports.default;
|
|
25
|
+
if (typeof value !== 'function' && !(value && typeof value === 'object' && '$$typeof' in value))
|
|
26
|
+
throw new Error('canvas must `export default` a component');
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
/** Install `window.__jigCanvas.run`. Call once in the runtime entry. */
|
|
30
|
+
export function startCanvasRuntime(options) {
|
|
31
|
+
const kit = {
|
|
32
|
+
useState: React.useState, useEffect: React.useEffect, useMemo: React.useMemo, useRef: React.useRef, useCallback: React.useCallback, Fragment,
|
|
33
|
+
useCanvasState, useCanvasEvent, useCanvasAction, useCanvasTheme, useCanvasSurface,
|
|
34
|
+
...options.kit,
|
|
35
|
+
};
|
|
36
|
+
const modules = options.modules ?? ['jig/canvas', 'cursor/canvas'];
|
|
37
|
+
const ErrorView = options.ErrorView ?? DefaultError;
|
|
38
|
+
const Root = options.Root ?? (({ children }) => h(Fragment, null, children));
|
|
39
|
+
function run(factory, boot) {
|
|
40
|
+
const parent = window.parent;
|
|
41
|
+
const bridge = createPageBridge({ post: (m) => parent.postMessage(m, '*'), init: { state: boot.state ?? {}, theme: boot.theme }, surface: boot.surface });
|
|
42
|
+
// Only the host (the parent window) may talk to the page; a sibling frame or a popup is ignored.
|
|
43
|
+
window.addEventListener('message', (event) => {
|
|
44
|
+
if (event.source !== parent)
|
|
45
|
+
return;
|
|
46
|
+
bridge.receive(event.data);
|
|
47
|
+
});
|
|
48
|
+
window.addEventListener('pagehide', () => bridge.flush());
|
|
49
|
+
bridge.ready();
|
|
50
|
+
let reported = false;
|
|
51
|
+
const report = (error) => {
|
|
52
|
+
if (reported)
|
|
53
|
+
return;
|
|
54
|
+
reported = true;
|
|
55
|
+
bridge.error(errorText(error));
|
|
56
|
+
};
|
|
57
|
+
window.addEventListener('error', (event) => report(event.error ?? event.message));
|
|
58
|
+
window.addEventListener('unhandledrejection', (event) => report(event.reason));
|
|
59
|
+
class Boundary extends Component {
|
|
60
|
+
state = { error: null };
|
|
61
|
+
static getDerivedStateFromError(error) {
|
|
62
|
+
return { error };
|
|
63
|
+
}
|
|
64
|
+
componentDidCatch(error, _info) {
|
|
65
|
+
report(error);
|
|
66
|
+
}
|
|
67
|
+
render() {
|
|
68
|
+
return this.state.error == null ? this.props.children : h(ErrorView, { error: this.state.error });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
let body = null;
|
|
72
|
+
let loadError = null;
|
|
73
|
+
try {
|
|
74
|
+
body = loadCanvas(factory, kit, modules);
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
loadError = err;
|
|
78
|
+
report(err);
|
|
79
|
+
}
|
|
80
|
+
// Height: the document's, after each layout change, but only once the canvas has committed. A page busy in its
|
|
81
|
+
// first render never sends a size, so the host's "not responding" budget catches it.
|
|
82
|
+
let committed = false;
|
|
83
|
+
let last = -1;
|
|
84
|
+
const measure = () => {
|
|
85
|
+
if (!committed)
|
|
86
|
+
return;
|
|
87
|
+
const height = Math.ceil(document.body.scrollHeight);
|
|
88
|
+
if (height !== last) {
|
|
89
|
+
last = height;
|
|
90
|
+
bridge.size(height);
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
new ResizeObserver(measure).observe(document.body);
|
|
94
|
+
const Themed = () => {
|
|
95
|
+
const theme = useCanvasTheme();
|
|
96
|
+
useEffect(() => {
|
|
97
|
+
committed = true;
|
|
98
|
+
measure();
|
|
99
|
+
}, []);
|
|
100
|
+
useEffect(() => {
|
|
101
|
+
document.documentElement.dataset.theme = theme;
|
|
102
|
+
document.documentElement.style.colorScheme = theme;
|
|
103
|
+
}, [theme]);
|
|
104
|
+
return h(Root, { theme }, h(Boundary, null, loadError != null || !body ? h(ErrorView, { error: loadError }) : h(body)));
|
|
105
|
+
};
|
|
106
|
+
const root = document.getElementById('root') ?? document.body.appendChild(document.createElement('div'));
|
|
107
|
+
createRoot(root).render(h(CanvasStateProvider, { store: bridge.store }, h(Themed)));
|
|
108
|
+
}
|
|
109
|
+
window.__jigCanvas = { run };
|
|
110
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { compileCanvas, canvasTitle, CanvasCompileError, CANVAS_MODULES, CANVAS_MAX_BYTES, type CompileCanvasOptions } from './compile.ts';
|
|
2
|
+
export { canvasDocument, canvasCsp, CANVAS_SANDBOX, scriptSafe, type CanvasDocumentOptions, type CanvasProfile } from './document.ts';
|
|
3
|
+
export { surfacesContext, surfacesContextEntry, type SurfaceView, type SurfaceEvent, type SurfacesContextOptions } from './context.ts';
|
|
4
|
+
export { RUNTIME_NAMES } from './names.ts';
|
|
5
|
+
export * from './protocol.ts';
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// `@lightblues/jig/canvas/server`: compile a canvas at write time, build its sandboxed document, validate what a frame
|
|
2
|
+
// posts, and render surfaces for the agent's context. Its only import is `sucrase` (an optional peer, for
|
|
3
|
+
// `compileCanvas`); everything else is pure and runs in a browser too.
|
|
4
|
+
export { compileCanvas, canvasTitle, CanvasCompileError, CANVAS_MODULES, CANVAS_MAX_BYTES } from "./compile.js";
|
|
5
|
+
export { canvasDocument, canvasCsp, CANVAS_SANDBOX, scriptSafe } from "./document.js";
|
|
6
|
+
export { surfacesContext, surfacesContextEntry } from "./context.js";
|
|
7
|
+
export { RUNTIME_NAMES } from "./names.js";
|
|
8
|
+
export * from "./protocol.js";
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type ReactNode } from 'react';
|
|
2
|
+
import { CanvasStore, type CanvasStoreOptions } from './store.ts';
|
|
3
|
+
import type { CanvasAction, CanvasState, ThemeKind } from './protocol.ts';
|
|
4
|
+
export { CanvasStore, type CanvasStoreOptions } from './store.ts';
|
|
5
|
+
export { LIMITS, type CanvasAction, type CanvasState, type ThemeKind } from './protocol.ts';
|
|
6
|
+
export interface CanvasStateProviderProps extends CanvasStoreOptions {
|
|
7
|
+
/** A store made elsewhere (the frame runtime); its callbacks are its own and the props' are ignored. Without it the provider makes one per `surface`. */
|
|
8
|
+
store?: CanvasStore;
|
|
9
|
+
/**
|
|
10
|
+
* The host's values for this surface. When this object changes (another device or the agent changed the state), the
|
|
11
|
+
* page's values are replaced; nothing is sent back. Leave it unset to keep `initial` only.
|
|
12
|
+
*/
|
|
13
|
+
values?: CanvasState;
|
|
14
|
+
children?: ReactNode;
|
|
15
|
+
}
|
|
16
|
+
/** One surface's state. Several providers on one page keep separate state. */
|
|
17
|
+
export declare function CanvasStateProvider(props: CanvasStateProviderProps): ReactNode;
|
|
18
|
+
export type SetCanvasState<T> = (action: T | ((prev: T) => T)) => void;
|
|
19
|
+
/**
|
|
20
|
+
* `useState` whose value the host keeps per surface (and the agent can read). Outside a provider it is a plain
|
|
21
|
+
* `useState`. Values must be JSON; a write over a limit is dropped (`LIMITS`).
|
|
22
|
+
*/
|
|
23
|
+
export declare function useCanvasState<T>(key: string, defaultValue: T): [T, SetCanvasState<T>];
|
|
24
|
+
/** `(name, data) => void`: an append-only event the host stores and the agent reads (a guess, a result). */
|
|
25
|
+
export declare function useCanvasEvent(): (name: string, data?: unknown) => void;
|
|
26
|
+
/** A stable `dispatch` for buttons. The host decides what each action does, and acts only during a click. */
|
|
27
|
+
export declare function useCanvasAction(): (action: CanvasAction) => void;
|
|
28
|
+
/** The host's theme kind (`light` / `dark`); `light` outside a provider. */
|
|
29
|
+
export declare function useCanvasTheme(): ThemeKind;
|
|
30
|
+
/** The surface id of the nearest provider, `''` outside one. */
|
|
31
|
+
export declare function useCanvasSurface(): string;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// `@lightblues/jig/canvas/state`: React bindings of the canvas store: `CanvasStateProvider` and the hooks canvases and kit components call. The same
|
|
2
|
+
// hooks work in-page (tier A: the provider's callbacks go to the host) and in the frame (tier B: the runtime's
|
|
3
|
+
// provider holds a store bridged over postMessage). Cursor's names are kept: `useCanvasState`, `useCanvasAction`.
|
|
4
|
+
import { createContext, createElement, useCallback, useContext, useEffect, useRef, useState, useSyncExternalStore } from 'react';
|
|
5
|
+
import { CanvasStore } from "./store.js";
|
|
6
|
+
export { CanvasStore } from "./store.js";
|
|
7
|
+
export { LIMITS } from "./protocol.js";
|
|
8
|
+
const StoreContext = createContext(null);
|
|
9
|
+
/** One surface's state. Several providers on one page keep separate state. */
|
|
10
|
+
export function CanvasStateProvider(props) {
|
|
11
|
+
const { store: given, surface, initial, values, theme, children } = props;
|
|
12
|
+
const made = useRef(null);
|
|
13
|
+
if (!given && (!made.current || made.current.surface !== (surface ?? '')))
|
|
14
|
+
made.current = new CanvasStore({ surface, initial: values ?? initial, theme });
|
|
15
|
+
const store = given ?? made.current;
|
|
16
|
+
// The latest callbacks, without making a new store. A given store keeps its own (the frame runtime's bridge).
|
|
17
|
+
if (!given)
|
|
18
|
+
store.options = { ...store.options, onState: props.onState, onEvent: props.onEvent, onAction: props.onAction, onDrop: props.onDrop };
|
|
19
|
+
const first = useRef(true);
|
|
20
|
+
useEffect(() => {
|
|
21
|
+
if (first.current)
|
|
22
|
+
return void (first.current = false);
|
|
23
|
+
if (values)
|
|
24
|
+
store.replace(values);
|
|
25
|
+
}, [store, values]);
|
|
26
|
+
useEffect(() => {
|
|
27
|
+
if (theme)
|
|
28
|
+
store.setTheme(theme);
|
|
29
|
+
}, [store, theme]);
|
|
30
|
+
return createElement(StoreContext.Provider, { value: store }, children);
|
|
31
|
+
}
|
|
32
|
+
const noSubscribe = () => () => { };
|
|
33
|
+
/**
|
|
34
|
+
* `useState` whose value the host keeps per surface (and the agent can read). Outside a provider it is a plain
|
|
35
|
+
* `useState`. Values must be JSON; a write over a limit is dropped (`LIMITS`).
|
|
36
|
+
*/
|
|
37
|
+
export function useCanvasState(key, defaultValue) {
|
|
38
|
+
const store = useContext(StoreContext);
|
|
39
|
+
const fallback = useRef(defaultValue);
|
|
40
|
+
const [local, setLocal] = useState(defaultValue);
|
|
41
|
+
const read = () => store?.get(key);
|
|
42
|
+
const stored = useSyncExternalStore(store ? store.subscribe : noSubscribe, read, read);
|
|
43
|
+
const value = store ? (store.has(key) ? stored : fallback.current) : local;
|
|
44
|
+
const set = useCallback((action) => {
|
|
45
|
+
if (!store)
|
|
46
|
+
return setLocal(action);
|
|
47
|
+
const prev = (store.has(key) ? store.get(key) : fallback.current);
|
|
48
|
+
const next = typeof action === 'function' ? action(prev) : action;
|
|
49
|
+
store.set(key, next);
|
|
50
|
+
}, [store, key]);
|
|
51
|
+
return [value, set];
|
|
52
|
+
}
|
|
53
|
+
/** `(name, data) => void`: an append-only event the host stores and the agent reads (a guess, a result). */
|
|
54
|
+
export function useCanvasEvent() {
|
|
55
|
+
const store = useContext(StoreContext);
|
|
56
|
+
return useCallback((name, data = null) => void store?.event(name, data), [store]);
|
|
57
|
+
}
|
|
58
|
+
/** A stable `dispatch` for buttons. The host decides what each action does, and acts only during a click. */
|
|
59
|
+
export function useCanvasAction() {
|
|
60
|
+
const store = useContext(StoreContext);
|
|
61
|
+
return useCallback((action) => void store?.action(action), [store]);
|
|
62
|
+
}
|
|
63
|
+
/** The host's theme kind (`light` / `dark`); `light` outside a provider. */
|
|
64
|
+
export function useCanvasTheme() {
|
|
65
|
+
const store = useContext(StoreContext);
|
|
66
|
+
const read = () => store?.theme ?? 'light';
|
|
67
|
+
return useSyncExternalStore(store ? store.subscribe : noSubscribe, read, read);
|
|
68
|
+
}
|
|
69
|
+
/** The surface id of the nearest provider, `''` outside one. */
|
|
70
|
+
export function useCanvasSurface() {
|
|
71
|
+
return useContext(StoreContext)?.surface ?? '';
|
|
72
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { type CanvasAction, type CanvasState, type ThemeKind } from './protocol.ts';
|
|
2
|
+
export interface CanvasStoreOptions {
|
|
3
|
+
/** The host's id for this surface (`"lemma:econ/fig-growth"`, `"artifact:<id>"`, `"msg:<id>/<n>"`). */
|
|
4
|
+
surface?: string;
|
|
5
|
+
/** Saved values. */
|
|
6
|
+
initial?: CanvasState;
|
|
7
|
+
theme?: ThemeKind;
|
|
8
|
+
/** A `useCanvasState` write: latest wins, the host debounces and stores it. */
|
|
9
|
+
onState?: (key: string, value: unknown) => void;
|
|
10
|
+
/** A `useCanvasEvent` call: append-only, sent at once. */
|
|
11
|
+
onEvent?: (name: string, data: unknown) => void;
|
|
12
|
+
/** A `useCanvasAction` dispatch: the host decides, during a click only. */
|
|
13
|
+
onAction?: (action: CanvasAction) => void;
|
|
14
|
+
/** A write, event or action dropped by the store's checks (the same limits as the frame bridge). */
|
|
15
|
+
onDrop?: (reason: string) => void;
|
|
16
|
+
}
|
|
17
|
+
export declare class CanvasStore {
|
|
18
|
+
readonly surface: string;
|
|
19
|
+
private values;
|
|
20
|
+
private kind;
|
|
21
|
+
private readonly listeners;
|
|
22
|
+
/** Callbacks; the provider swaps them for the latest props. */
|
|
23
|
+
options: CanvasStoreOptions;
|
|
24
|
+
constructor(options?: CanvasStoreOptions);
|
|
25
|
+
get snapshot(): CanvasState;
|
|
26
|
+
get theme(): ThemeKind;
|
|
27
|
+
has(key: string): boolean;
|
|
28
|
+
get(key: string): unknown;
|
|
29
|
+
/** A write from the page: kept, shown, and passed to `onState`. False when a limit drops it. */
|
|
30
|
+
set(key: string, value: unknown): boolean;
|
|
31
|
+
/** Values from the host (another device or the agent changed them): shown, not sent back. */
|
|
32
|
+
replace(values: CanvasState): void;
|
|
33
|
+
setTheme(kind: ThemeKind): void;
|
|
34
|
+
event(name: string, data?: unknown): boolean;
|
|
35
|
+
action(action: CanvasAction): boolean;
|
|
36
|
+
subscribe: (listener: () => void) => (() => void);
|
|
37
|
+
private notify;
|
|
38
|
+
private drop;
|
|
39
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// The in-page state store behind the canvas hooks: one per surface. Pure (no React, no DOM): the React provider wraps
|
|
2
|
+
// it for tier A, and the frame runtime connects it to postMessage for tier B.
|
|
3
|
+
import { EVENT_NAME, isJson, jsonSize, LIMITS } from "./protocol.js";
|
|
4
|
+
export class CanvasStore {
|
|
5
|
+
surface;
|
|
6
|
+
values;
|
|
7
|
+
kind;
|
|
8
|
+
listeners = new Set();
|
|
9
|
+
/** Callbacks; the provider swaps them for the latest props. */
|
|
10
|
+
options;
|
|
11
|
+
constructor(options = {}) {
|
|
12
|
+
this.options = options;
|
|
13
|
+
this.surface = options.surface ?? '';
|
|
14
|
+
this.values = { ...(options.initial ?? {}) };
|
|
15
|
+
this.kind = options.theme ?? 'light';
|
|
16
|
+
}
|
|
17
|
+
get snapshot() {
|
|
18
|
+
return this.values;
|
|
19
|
+
}
|
|
20
|
+
get theme() {
|
|
21
|
+
return this.kind;
|
|
22
|
+
}
|
|
23
|
+
has(key) {
|
|
24
|
+
return Object.hasOwn(this.values, key);
|
|
25
|
+
}
|
|
26
|
+
get(key) {
|
|
27
|
+
return this.has(key) ? this.values[key] : undefined;
|
|
28
|
+
}
|
|
29
|
+
/** A write from the page: kept, shown, and passed to `onState`. False when a limit drops it. */
|
|
30
|
+
set(key, value) {
|
|
31
|
+
if (typeof key !== 'string' || !key || key.length > LIMITS.key)
|
|
32
|
+
return this.drop('state: bad key');
|
|
33
|
+
if (!isJson(value))
|
|
34
|
+
return this.drop(`state ${key}: not JSON`);
|
|
35
|
+
const next = { ...this.values, [key]: value };
|
|
36
|
+
if (jsonSize(next) > LIMITS.state)
|
|
37
|
+
return this.drop(`state ${key}: surface state over ${LIMITS.state} chars`);
|
|
38
|
+
if (this.has(key) && Object.is(this.values[key], value))
|
|
39
|
+
return true;
|
|
40
|
+
this.values = next;
|
|
41
|
+
this.notify();
|
|
42
|
+
this.options.onState?.(key, value);
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
/** Values from the host (another device or the agent changed them): shown, not sent back. */
|
|
46
|
+
replace(values) {
|
|
47
|
+
this.values = { ...values };
|
|
48
|
+
this.notify();
|
|
49
|
+
}
|
|
50
|
+
setTheme(kind) {
|
|
51
|
+
if (kind === this.kind)
|
|
52
|
+
return;
|
|
53
|
+
this.kind = kind;
|
|
54
|
+
this.notify();
|
|
55
|
+
}
|
|
56
|
+
event(name, data = null) {
|
|
57
|
+
if (typeof name !== 'string' || !EVENT_NAME.test(name))
|
|
58
|
+
return this.drop(`event: bad name`);
|
|
59
|
+
if (!isJson(data) || jsonSize(data) > LIMITS.eventData)
|
|
60
|
+
return this.drop(`event ${name}: data not JSON or over ${LIMITS.eventData} chars`);
|
|
61
|
+
this.options.onEvent?.(name, data);
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
action(action) {
|
|
65
|
+
if (!action || typeof action !== 'object' || typeof action.type !== 'string' || !isJson(action) || jsonSize(action) > LIMITS.action)
|
|
66
|
+
return this.drop('action: not a JSON object with a type');
|
|
67
|
+
this.options.onAction?.(action);
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
subscribe = (listener) => {
|
|
71
|
+
this.listeners.add(listener);
|
|
72
|
+
return () => this.listeners.delete(listener);
|
|
73
|
+
};
|
|
74
|
+
notify() {
|
|
75
|
+
for (const listener of [...this.listeners])
|
|
76
|
+
listener();
|
|
77
|
+
}
|
|
78
|
+
drop(reason) {
|
|
79
|
+
this.options.onDrop?.(reason);
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const parts: readonly ["agent-paseo", "agent-pi", "agent-chat", "markdown"];
|
|
1
|
+
export declare const parts: readonly ["agent-paseo", "agent-pi", "agent-chat", "markdown", "canvas"];
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @lightblues/jig: reusable parts for my apps. Each part is its own subpath export; this root only names the parts.
|
|
2
|
-
export const parts = ['agent-paseo', 'agent-pi', 'agent-chat', 'markdown'];
|
|
2
|
+
export const parts = ['agent-paseo', 'agent-pi', 'agent-chat', 'markdown', 'canvas'];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lightblues/jig",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Reusable parts for my apps: agent runtimes (Paseo, pi) that speak AG-UI, a thin thread-following client, one markdown renderer, and more as they prove reusable.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -48,6 +48,26 @@
|
|
|
48
48
|
"types": "./dist/markdown/react.d.ts",
|
|
49
49
|
"default": "./dist/markdown/react.js"
|
|
50
50
|
},
|
|
51
|
+
"./canvas/server": {
|
|
52
|
+
"types": "./dist/canvas/server.d.ts",
|
|
53
|
+
"default": "./dist/canvas/server.js"
|
|
54
|
+
},
|
|
55
|
+
"./canvas/state": {
|
|
56
|
+
"types": "./dist/canvas/state.d.ts",
|
|
57
|
+
"default": "./dist/canvas/state.js"
|
|
58
|
+
},
|
|
59
|
+
"./canvas/frame": {
|
|
60
|
+
"types": "./dist/canvas/frame.d.ts",
|
|
61
|
+
"default": "./dist/canvas/frame.js"
|
|
62
|
+
},
|
|
63
|
+
"./canvas/runtime": {
|
|
64
|
+
"types": "./dist/canvas/runtime.d.ts",
|
|
65
|
+
"default": "./dist/canvas/runtime.js"
|
|
66
|
+
},
|
|
67
|
+
"./canvas/build": {
|
|
68
|
+
"types": "./dist/canvas/build.d.ts",
|
|
69
|
+
"default": "./dist/canvas/build.js"
|
|
70
|
+
},
|
|
51
71
|
"./package.json": "./package.json"
|
|
52
72
|
},
|
|
53
73
|
"scripts": {
|
|
@@ -82,6 +102,7 @@
|
|
|
82
102
|
"react": "19.3.1",
|
|
83
103
|
"react-dom": "19.3.1",
|
|
84
104
|
"react-test-renderer": "19.3.1",
|
|
105
|
+
"sucrase": "3.35.1",
|
|
85
106
|
"typescript": "^5.9.0",
|
|
86
107
|
"yaml": "2.9.0",
|
|
87
108
|
"zod": "4.6.7"
|
|
@@ -92,6 +113,7 @@
|
|
|
92
113
|
"@earendil-works/pi-ai": "~1.4.0",
|
|
93
114
|
"@earendil-works/pi-coding-agent": "~1.4.0",
|
|
94
115
|
"@getpaseo/client": "0.16.1 || 0.17.4",
|
|
116
|
+
"esbuild": ">=0.25",
|
|
95
117
|
"highlight.js": "^11.0.0",
|
|
96
118
|
"katex": ">=0.16.21",
|
|
97
119
|
"markdown-it": "^15.0.0",
|
|
@@ -100,6 +122,7 @@
|
|
|
100
122
|
"mermaid": "^12.0.0",
|
|
101
123
|
"react": ">=18",
|
|
102
124
|
"react-dom": ">=18",
|
|
125
|
+
"sucrase": "~3.35.0",
|
|
103
126
|
"yaml": "^2.0.0"
|
|
104
127
|
},
|
|
105
128
|
"peerDependenciesMeta": {
|
|
@@ -118,6 +141,9 @@
|
|
|
118
141
|
"@getpaseo/client": {
|
|
119
142
|
"optional": true
|
|
120
143
|
},
|
|
144
|
+
"esbuild": {
|
|
145
|
+
"optional": true
|
|
146
|
+
},
|
|
121
147
|
"highlight.js": {
|
|
122
148
|
"optional": true
|
|
123
149
|
},
|
|
@@ -142,6 +168,9 @@
|
|
|
142
168
|
"react-dom": {
|
|
143
169
|
"optional": true
|
|
144
170
|
},
|
|
171
|
+
"sucrase": {
|
|
172
|
+
"optional": true
|
|
173
|
+
},
|
|
145
174
|
"yaml": {
|
|
146
175
|
"optional": true
|
|
147
176
|
}
|