@a10k/iridium-dev-server 0.0.0-stage → 0.0.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/LICENSE +21 -0
- package/Readme.md +239 -0
- package/index.js +15 -0
- package/lib/config.js +28 -0
- package/lib/define-module.js +129 -0
- package/lib/live.js +87 -0
- package/lib/mcp-stdio.js +78 -0
- package/lib/mcp.js +312 -0
- package/lib/notebooks.js +137 -0
- package/lib/server.js +295 -0
- package/lib/viewer.js +210 -0
- package/package.json +44 -4
- package/skill/SKILL.md +92 -0
- package/README.md +0 -3
package/lib/mcp.js
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
// MCP server: lets an assistant work on Iridium notebooks in the user's open
|
|
2
|
+
// browser tab. The dev server is only a relay (see live.js): every tool is a
|
|
3
|
+
// command the tab carries out on its own notebook, as if the user had, and
|
|
4
|
+
// reads come from the tab. The file changes only when the tab saves.
|
|
5
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import { notebookName, readNotebook } from './notebooks.js';
|
|
8
|
+
|
|
9
|
+
export const INSTRUCTIONS = `Iridium notebooks are reactive Observable notebooks that run in the user's browser. Use these tools whenever the user asks for an Iridium notebook, an Observable notebook, or an interactive notebook, chart, or data exploration they want to see live.
|
|
10
|
+
|
|
11
|
+
The tools work on the notebook open in the user's browser tab, as if the user were doing it: create_notebook or open_notebook opens a tab; then add_cell/add_cells, edit_cell, run_cell, delete_cell and move_cell change it in that tab, read_notebook reads its cells and outputs, evaluate inspects values without adding cells, screenshot_cells shows you cells' rendered output as images (check charts and layout with it rather than driving a browser), and save_notebook saves it as the tab's Save (Cmd+S) does. Every edit returns the cells' live output once they have run (value, rendered text, or error), plus any other cells that are now failing, so check results and fix errors before moving on. The user may edit in the tab too: re-read before editing cells you didn't just write (brief: true lists cells compactly, ids reads only some).
|
|
12
|
+
|
|
13
|
+
Edits are unsaved until saved, like the user's own edits (unsaved_changes in results). Save only when the user asks you to. Address cells by id or by the name they define (cell: "data"). For small changes to a long cell, edit_cell with replace: [{old, new}] patches its code instead of resending it. To open a notebook in a particular browser, pass browser (e.g. "Google Chrome") to create_notebook or open_notebook.
|
|
14
|
+
|
|
15
|
+
Cells are Observable JavaScript: \`name = expression\`, \`name = { ...; return value; }\` blocks, \`viewof x = Inputs.range([0, 10])\`, \`mutable x = 0\`, generators (yield), \`import {chart} from "@d3/bar-chart"\` from observablehq.com, \`md\\\`...\\\`\` and \`html\\\`...\\\`\` for text and markup. Cells react to each other by name in any order; each named cell is defined once. Plain JavaScript cells also work (several statements, \`const\` declarations shared with other cells, \`import {x} from "npm:pkg"\`, \`display(value)\`). Built-ins include d3, Plot, Inputs, htl, _ (lodash), md, html, svg, tex, dot, mermaid, DuckDBClient, FileAttachment, width, now, invalidation, Generators, require. Prefer Plot for charts and Inputs for controls, and use \`width\` for responsive sizes.`;
|
|
16
|
+
|
|
17
|
+
const text = (value) => ({
|
|
18
|
+
content: [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }],
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
const failure = (message) => ({ content: [{ type: 'text', text: message }], isError: true });
|
|
22
|
+
|
|
23
|
+
// The name a cell defines (`name = …`, `viewof name = …`, `mutable name = …`),
|
|
24
|
+
// after any leading comments; undefined for anonymous cells.
|
|
25
|
+
const definedName = (source) =>
|
|
26
|
+
String(source ?? '')
|
|
27
|
+
.replace(/^(\s|\/\/[^\n]*\n|\/\*[\s\S]*?\*\/)*/, '')
|
|
28
|
+
.match(/^(?:(?:viewof|mutable)\s+)?([A-Za-z_$][\w$]*)\s*=(?![=>])/)?.[1];
|
|
29
|
+
|
|
30
|
+
const firstLine = (source) => {
|
|
31
|
+
const line = String(source ?? '').replace(/^(\s|\/\/[^\n]*\n)*/, '').split('\n')[0];
|
|
32
|
+
return line.length > 80 ? `${line.slice(0, 79)}…` : line;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export const createMcpServer = ({ live, urlFor, fileFor = () => undefined, createNotebook, openBrowser, listNotebooks, version = '1.0.0' }) => {
|
|
36
|
+
const server = new McpServer({ name: 'iridium', version }, { instructions: INSTRUCTIONS });
|
|
37
|
+
|
|
38
|
+
const wait = z.number().int().min(0).max(60000).optional()
|
|
39
|
+
.describe('How long to wait for the cells to finish running, in ms (default 8000).');
|
|
40
|
+
const notebookArg = z.string().describe('Notebook name (letters, digits and "-"), e.g. "sales-dashboard".');
|
|
41
|
+
const browserArg = z.string().optional()
|
|
42
|
+
.describe('Open it in this browser application (e.g. "Google Chrome", "Safari") instead of the default one.');
|
|
43
|
+
|
|
44
|
+
const requireNotebook = (raw) => {
|
|
45
|
+
const name = notebookName(raw);
|
|
46
|
+
if (!fileFor(name) && !live.clients(name)) throw new Error(`No notebook named "${name}". Use list_notebooks or create_notebook.`);
|
|
47
|
+
return name;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
// A cell by id, or by the name it defines (cell: "data" or "viewof x").
|
|
51
|
+
const cellArgs = {
|
|
52
|
+
id: z.number().int().optional().describe('The cell\'s id.'),
|
|
53
|
+
cell: z.string().optional().describe('Or the name the cell defines, e.g. "data" or "viewof region".'),
|
|
54
|
+
};
|
|
55
|
+
const tabCells = async (name) => (await live.request(name, 'cells')).cells;
|
|
56
|
+
const resolveCell = async (name, { id, cell }) => {
|
|
57
|
+
const cells = await tabCells(name);
|
|
58
|
+
let found;
|
|
59
|
+
if (id !== undefined) found = cells.find((c) => c.id === id);
|
|
60
|
+
else if (cell) {
|
|
61
|
+
const wanted = cell.replace(/^(viewof|mutable)\s+/, '');
|
|
62
|
+
found = cells.find((c) => definedName(c.sourceCode) === wanted);
|
|
63
|
+
} else throw new Error('Give the cell\'s id or the name it defines (cell).');
|
|
64
|
+
if (!found) throw new Error(`No cell ${id ?? `defining "${cell}"`} in ${name}. Use read_notebook with brief: true to list the cells.`);
|
|
65
|
+
return found;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
// Opens the notebook in the browser unless a tab already shows it, and waits
|
|
69
|
+
// briefly for that tab to connect.
|
|
70
|
+
const ensureTab = async (name, open, browser) => {
|
|
71
|
+
if (live.clients(name) || !open) return live.clients(name) > 0;
|
|
72
|
+
openBrowser(urlFor(name), browser);
|
|
73
|
+
for (let i = 0; i < 60 && !live.clients(name); i++) await new Promise((r) => setTimeout(r, 250));
|
|
74
|
+
return live.clients(name) > 0;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// The tab's state of `ids` after an edit, and any other failing cells.
|
|
78
|
+
const outcome = async (name, ids, waitMs, extra = {}) => {
|
|
79
|
+
const result = { notebook: name, url: urlFor(name), ...extra };
|
|
80
|
+
const edited = ids?.length ? await live.describe(name, ids, waitMs ?? 8000) : null;
|
|
81
|
+
const all = await live.describe(name, undefined, edited ? 0 : (waitMs ?? 8000));
|
|
82
|
+
result.unsaved_changes = all.unsaved;
|
|
83
|
+
// The caller just wrote the edited cells' code: don't send it back. An
|
|
84
|
+
// empty ids list (delete_cell) reports no cells, only other failing ones.
|
|
85
|
+
result.cells = edited ? edited.cells.map(({ source, ...cell }) => cell) : ids ? [] : all.cells;
|
|
86
|
+
const failing = all.cells.filter((cell) => !ids?.includes(cell.id) && ['error', 'rejected'].includes(cell.status));
|
|
87
|
+
if (failing.length) result.other_failing_cells = failing.map(({ id, source, status, error }) => ({ id, status, error, source: source.slice(0, 120) }));
|
|
88
|
+
return result;
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const tool = (name, description, inputSchema, handler) =>
|
|
92
|
+
server.registerTool(name, { description, inputSchema }, async (args) => {
|
|
93
|
+
try {
|
|
94
|
+
return text(await handler(args));
|
|
95
|
+
} catch (error) {
|
|
96
|
+
return failure(error.message);
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
const placement = {
|
|
101
|
+
after: z.number().int().optional().describe('Insert after the cell with this id.'),
|
|
102
|
+
before: z.number().int().optional().describe('Insert before the cell with this id.'),
|
|
103
|
+
index: z.number().int().min(0).optional().describe('Insert at this position (0 = top). Default: the end.'),
|
|
104
|
+
};
|
|
105
|
+
const cellSpec = z.object({
|
|
106
|
+
source: z.string().describe('The cell code.'),
|
|
107
|
+
pinned: z.boolean().optional().describe('Show the code editor (default true). Unpin prose and finished outputs.'),
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
tool('list_notebooks', 'List the Iridium notebooks, with their URLs, files and how many browser tabs show each.', {}, async () =>
|
|
111
|
+
listNotebooks().map((name) => ({ name, url: urlFor(name), file: fileFor(name), open_tabs: live.clients(name) })),
|
|
112
|
+
);
|
|
113
|
+
|
|
114
|
+
tool(
|
|
115
|
+
'create_notebook',
|
|
116
|
+
'Create a new, empty notebook file, open it in the user\'s browser, and add initial cells there (unsaved until saved). Returns the cells\' ids and live outputs.',
|
|
117
|
+
{
|
|
118
|
+
name: notebookArg,
|
|
119
|
+
title: z.string().optional().describe('Display title (default: the name).'),
|
|
120
|
+
cells: z.array(cellSpec).optional().describe('Initial cells, top to bottom.'),
|
|
121
|
+
browser: browserArg,
|
|
122
|
+
wait_ms: wait,
|
|
123
|
+
},
|
|
124
|
+
async ({ name: raw, title, cells = [], browser, wait_ms }) => {
|
|
125
|
+
const name = notebookName(raw);
|
|
126
|
+
if (fileFor(name)) throw new Error(`A notebook named "${name}" already exists. Use open_notebook, or choose another name.`);
|
|
127
|
+
createNotebook(name, title);
|
|
128
|
+
if (!(await ensureTab(name, true, browser))) {
|
|
129
|
+
return { notebook: name, url: urlFor(name), file: fileFor(name), created: true, note: 'Created, but no tab connected: open the url, then add the cells.' };
|
|
130
|
+
}
|
|
131
|
+
if (!cells.length) return outcome(name, undefined, wait_ms, { created: true, file: fileFor(name) });
|
|
132
|
+
const { ids } = await live.request(name, 'insert', { cells });
|
|
133
|
+
return outcome(name, ids, wait_ms, { created: true, file: fileFor(name), ids });
|
|
134
|
+
},
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
tool(
|
|
138
|
+
'open_notebook',
|
|
139
|
+
'Open a notebook in the user\'s browser (unless a tab already shows it) and return its cells with live outputs.',
|
|
140
|
+
{ name: notebookArg, browser: browserArg, wait_ms: wait },
|
|
141
|
+
async ({ name: raw, browser, wait_ms }) => {
|
|
142
|
+
const name = requireNotebook(raw);
|
|
143
|
+
if (!(await ensureTab(name, true, browser))) throw new Error(`Opened ${urlFor(name)}, but no tab connected yet. Try again in a moment.`);
|
|
144
|
+
return outcome(name, undefined, wait_ms, { file: fileFor(name) });
|
|
145
|
+
},
|
|
146
|
+
);
|
|
147
|
+
|
|
148
|
+
tool(
|
|
149
|
+
'read_notebook',
|
|
150
|
+
'Read the open notebook\'s cells (id, source, pinned) with each cell\'s live status and output (value, rendered text, error, exports). brief: true lists every cell in one line (id, name, status, first line of code); ids reads only those cells. Without an open tab, returns the saved file\'s code.',
|
|
151
|
+
{
|
|
152
|
+
notebook: notebookArg,
|
|
153
|
+
ids: z.array(z.number().int()).optional().describe('Only these cells.'),
|
|
154
|
+
brief: z.boolean().optional().describe('One short line per cell instead of full code and output.'),
|
|
155
|
+
wait_ms: wait,
|
|
156
|
+
},
|
|
157
|
+
async ({ notebook, ids, brief = false, wait_ms }) => {
|
|
158
|
+
const name = requireNotebook(notebook);
|
|
159
|
+
const base = { notebook: name, url: urlFor(name), file: fileFor(name) };
|
|
160
|
+
if (!live.clients(name)) {
|
|
161
|
+
const saved = (fileFor(name) ? readNotebook(fileFor(name)) : []).filter((cell) => !ids || ids.includes(cell.id));
|
|
162
|
+
return { ...base, note: 'No tab shows this notebook: this is the saved file, without outputs. Call open_notebook to work on it.', cells: saved.map(({ id, pin, sourceCode }) => (brief ? { id, name: definedName(sourceCode), pinned: !!pin, code: firstLine(sourceCode) } : { id, pinned: !!pin, source: sourceCode })) };
|
|
163
|
+
}
|
|
164
|
+
const { cells, unsaved } = await live.describe(name, ids, wait_ms ?? 3000);
|
|
165
|
+
if (!brief) return { ...base, unsaved_changes: unsaved, cells };
|
|
166
|
+
return {
|
|
167
|
+
...base,
|
|
168
|
+
unsaved_changes: unsaved,
|
|
169
|
+
cells: cells.map(({ id, pinned, status, source, error }) => {
|
|
170
|
+
const line = { id, name: definedName(source), pinned, status, code: firstLine(source) };
|
|
171
|
+
if (error) line.error = String(error).slice(0, 200);
|
|
172
|
+
return Object.fromEntries(Object.entries(line).filter(([, value]) => value !== undefined));
|
|
173
|
+
}),
|
|
174
|
+
};
|
|
175
|
+
},
|
|
176
|
+
);
|
|
177
|
+
|
|
178
|
+
tool(
|
|
179
|
+
'add_cell',
|
|
180
|
+
'Add a cell to the open notebook (at the end, or after/before a cell, or at an index); it runs. Returns its id and live output.',
|
|
181
|
+
{ notebook: notebookArg, source: z.string().describe('The cell code.'), pinned: z.boolean().optional().describe('Show the code editor (default true).'), ...placement, wait_ms: wait },
|
|
182
|
+
async ({ notebook, source, pinned = true, wait_ms, ...where }) => {
|
|
183
|
+
const name = requireNotebook(notebook);
|
|
184
|
+
const { ids } = await live.request(name, 'insert', { cells: [{ source, pinned }], ...where });
|
|
185
|
+
return outcome(name, ids, wait_ms, { id: ids[0] });
|
|
186
|
+
},
|
|
187
|
+
);
|
|
188
|
+
|
|
189
|
+
tool(
|
|
190
|
+
'add_cells',
|
|
191
|
+
'Add several cells in order to the open notebook (at the end, or after/before a cell, or at an index). Returns their ids and live outputs.',
|
|
192
|
+
{ notebook: notebookArg, cells: z.array(cellSpec).min(1), ...placement, wait_ms: wait },
|
|
193
|
+
async ({ notebook, cells, wait_ms, ...where }) => {
|
|
194
|
+
const name = requireNotebook(notebook);
|
|
195
|
+
const { ids } = await live.request(name, 'insert', { cells, ...where });
|
|
196
|
+
return outcome(name, ids, wait_ms, { ids });
|
|
197
|
+
},
|
|
198
|
+
);
|
|
199
|
+
|
|
200
|
+
tool(
|
|
201
|
+
'edit_cell',
|
|
202
|
+
'Change a cell in the open notebook (by id, or by the name it defines) and run it: replace its code (source), patch it (replace: [{old, new}], each old text found exactly once, applied in order; cheaper than resending a long cell), and/or pin it. Returns its live output and any cells now failing.',
|
|
203
|
+
{
|
|
204
|
+
notebook: notebookArg,
|
|
205
|
+
...cellArgs,
|
|
206
|
+
source: z.string().optional().describe('The cell\'s new code.'),
|
|
207
|
+
replace: z.array(z.object({ old: z.string().min(1), new: z.string() })).optional()
|
|
208
|
+
.describe('Patches to the current code: each `old` text must appear exactly once.'),
|
|
209
|
+
pinned: z.boolean().optional(),
|
|
210
|
+
wait_ms: wait,
|
|
211
|
+
},
|
|
212
|
+
async ({ notebook, source, replace, pinned, wait_ms, ...which }) => {
|
|
213
|
+
const name = requireNotebook(notebook);
|
|
214
|
+
if (source !== undefined && replace) throw new Error('Give either source or replace, not both.');
|
|
215
|
+
const cell = await resolveCell(name, which);
|
|
216
|
+
if (replace) {
|
|
217
|
+
source = cell.sourceCode;
|
|
218
|
+
for (const { old, new: text } of replace) {
|
|
219
|
+
const count = source.split(old).length - 1;
|
|
220
|
+
if (count !== 1) throw new Error(`replace: ${count ? `${count} matches` : 'no match'} in cell ${cell.id} for ${JSON.stringify(old.slice(0, 80))}; nothing changed. Include more surrounding text, or read the cell (read_notebook with ids).`);
|
|
221
|
+
source = source.replace(old, () => text);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
await live.request(name, 'update', { id: cell.id, sourceCode: source, pin: pinned });
|
|
225
|
+
return outcome(name, [cell.id], wait_ms, { id: cell.id });
|
|
226
|
+
},
|
|
227
|
+
);
|
|
228
|
+
|
|
229
|
+
tool('delete_cell', 'Delete a cell from the open notebook (by id, or by the name it defines). Returns any cells now failing (e.g. ones that used its value).', { notebook: notebookArg, ...cellArgs, wait_ms: wait }, async ({ notebook, wait_ms, ...which }) => {
|
|
230
|
+
const name = requireNotebook(notebook);
|
|
231
|
+
const { id } = await resolveCell(name, which);
|
|
232
|
+
await live.request(name, 'remove', { id });
|
|
233
|
+
return outcome(name, [], wait_ms, { deleted: id });
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
tool(
|
|
237
|
+
'move_cell',
|
|
238
|
+
'Move a cell in the open notebook (after/before another cell, or to an index). Order only affects layout: cells react by name.',
|
|
239
|
+
{ notebook: notebookArg, ...cellArgs, ...placement },
|
|
240
|
+
async ({ notebook, id: rawId, cell, ...where }) => {
|
|
241
|
+
const name = requireNotebook(notebook);
|
|
242
|
+
const { id } = await resolveCell(name, { id: rawId, cell });
|
|
243
|
+
return { notebook: name, ...(await live.request(name, 'move', { id, ...where })) };
|
|
244
|
+
},
|
|
245
|
+
);
|
|
246
|
+
|
|
247
|
+
tool('run_cell', 'Run a cell in the open notebook again without changing it (e.g. to refetch data or replay an animation).', { notebook: notebookArg, ...cellArgs, wait_ms: wait }, async ({ notebook, wait_ms, ...which }) => {
|
|
248
|
+
const name = requireNotebook(notebook);
|
|
249
|
+
const { id } = await resolveCell(name, which);
|
|
250
|
+
await live.request(name, 'run', { id });
|
|
251
|
+
return outcome(name, [id], wait_ms, { id });
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
// Images, not text: registered without the text wrapper.
|
|
255
|
+
server.registerTool(
|
|
256
|
+
'screenshot_cells',
|
|
257
|
+
{
|
|
258
|
+
description: 'Screenshot cells of the open notebook as PNG images, exactly as the user\'s tab shows them (charts, layout, styling, input values, unsaved edits). The tab uses Chrome\'s tab capture: the first time, it asks the user to allow it (they click Allow, then share the tab), so the first call can wait for them. Up to 6 cells per call.',
|
|
259
|
+
inputSchema: {
|
|
260
|
+
notebook: notebookArg,
|
|
261
|
+
ids: z.array(z.number().int()).optional().describe('Cells by id.'),
|
|
262
|
+
cells: z.array(z.string()).optional().describe('Or by the names they define, e.g. ["calendar", "chart"].'),
|
|
263
|
+
include_code: z.boolean().optional().describe('Include the code editor of pinned cells (default: the output only).'),
|
|
264
|
+
scale: z.number().min(0.5).max(3).optional().describe('Image pixels per CSS pixel (default 1; 2 for retina detail).'),
|
|
265
|
+
},
|
|
266
|
+
},
|
|
267
|
+
async ({ notebook, ids = [], cells: names = [], include_code = false, scale = 1 }) => {
|
|
268
|
+
try {
|
|
269
|
+
const name = requireNotebook(notebook);
|
|
270
|
+
const wanted = [...ids];
|
|
271
|
+
for (const cell of names) wanted.push((await resolveCell(name, { cell })).id);
|
|
272
|
+
if (!wanted.length) throw new Error('Give ids or cells to screenshot.');
|
|
273
|
+
if (wanted.length > 6) throw new Error('Up to 6 cells per call.');
|
|
274
|
+
await live.describe(name, wanted, 8000); // let them finish running
|
|
275
|
+
// Allow two minutes: the first capture waits for the user to allow it.
|
|
276
|
+
const { shots } = await live.request(name, 'screenshot', { ids: wanted, includeCode: include_code, scale }, 120000);
|
|
277
|
+
const summary = shots.map(({ id, width: w, height: h, error }) => (error ? { id, error } : { id, width: w, height: h }));
|
|
278
|
+
return {
|
|
279
|
+
content: [
|
|
280
|
+
{ type: 'text', text: JSON.stringify({ notebook: name, shots: summary }, null, 2) },
|
|
281
|
+
...shots.filter((shot) => shot.png).map((shot) => ({ type: 'image', data: shot.png, mimeType: 'image/png' })),
|
|
282
|
+
],
|
|
283
|
+
};
|
|
284
|
+
} catch (error) {
|
|
285
|
+
return failure(error.message);
|
|
286
|
+
}
|
|
287
|
+
},
|
|
288
|
+
);
|
|
289
|
+
|
|
290
|
+
tool(
|
|
291
|
+
'save_notebook',
|
|
292
|
+
'Save the open notebook to its file, exactly as the tab\'s Save (Cmd+S) does. Only when the user asks to save.',
|
|
293
|
+
{ notebook: notebookArg },
|
|
294
|
+
async ({ notebook }) => {
|
|
295
|
+
const name = requireNotebook(notebook);
|
|
296
|
+
const { unsaved } = await live.request(name, 'save');
|
|
297
|
+
return { notebook: name, file: fileFor(name), saved: true, unsaved_changes: unsaved };
|
|
298
|
+
},
|
|
299
|
+
);
|
|
300
|
+
|
|
301
|
+
tool(
|
|
302
|
+
'evaluate',
|
|
303
|
+
'Evaluate an expression (or cell code) against the open notebook\'s live values without adding a cell, e.g. "data.length" or "Object.keys(data[0])".',
|
|
304
|
+
{ notebook: notebookArg, expression: z.string(), timeout_ms: z.number().int().min(100).max(60000).optional() },
|
|
305
|
+
async ({ notebook, expression, timeout_ms = 10000 }) => {
|
|
306
|
+
const name = requireNotebook(notebook);
|
|
307
|
+
return live.request(name, 'evaluate', { source: expression, timeout: timeout_ms }, timeout_ms + 5000);
|
|
308
|
+
},
|
|
309
|
+
);
|
|
310
|
+
|
|
311
|
+
return server;
|
|
312
|
+
};
|
package/lib/notebooks.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// Notebook files: Observable Notebook Kit's HTML format (`<name>.html`, the
|
|
2
|
+
// format Observable Desktop edits), with legacy `<name>.ojs` files read for
|
|
3
|
+
// compatibility and converted to .html on their next save.
|
|
4
|
+
import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { JSDOM } from 'jsdom';
|
|
7
|
+
import { tokTypes as tt } from 'acorn';
|
|
8
|
+
import { CellParser } from '@observablehq/parser';
|
|
9
|
+
import { deserialize, serialize, toNotebook, transpile } from '@observablehq/notebook-kit';
|
|
10
|
+
|
|
11
|
+
const { window } = new JSDOM('');
|
|
12
|
+
|
|
13
|
+
// Notebook names come from URLs and request bodies: keep only the first path
|
|
14
|
+
// segment and letters/digits, so a name can never reach outside the folder.
|
|
15
|
+
export const notebookName = (raw) =>
|
|
16
|
+
String(raw ?? '')
|
|
17
|
+
.replace(/^\/+/, '')
|
|
18
|
+
.replace(/\/.*$/, '')
|
|
19
|
+
.replace(/[^a-zA-Z0-9]/g, '-') || 'index';
|
|
20
|
+
|
|
21
|
+
export const listNotebooks = (dir) => [
|
|
22
|
+
...new Set(
|
|
23
|
+
readdirSync(dir)
|
|
24
|
+
.filter((file) => /\.(html|ojs)$/.test(file) && isNotebookFile(join(dir, file)))
|
|
25
|
+
.map((file) => file.replace(/\.(html|ojs)$/, '')),
|
|
26
|
+
),
|
|
27
|
+
];
|
|
28
|
+
|
|
29
|
+
// An .html file in the notebooks folder is a notebook only if it has <notebook>.
|
|
30
|
+
const isNotebookFile = (path) =>
|
|
31
|
+
path.endsWith('.ojs') || /<notebook[\s>]/.test(readFileSync(path, 'utf8'));
|
|
32
|
+
|
|
33
|
+
export const notebookPath = (dir, name) => {
|
|
34
|
+
const html = join(dir, `${name}.html`);
|
|
35
|
+
if (existsSync(html) && isNotebookFile(html)) return html;
|
|
36
|
+
const ojs = join(dir, `${name}.ojs`);
|
|
37
|
+
return existsSync(ojs) ? ojs : null;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
// --- Cell types -------------------------------------------------------------
|
|
41
|
+
|
|
42
|
+
// Same rule as Iridium (src/compile.js): Observable JavaScript first, plain
|
|
43
|
+
// JavaScript if it is not valid Observable JavaScript; npm:/jsr: imports are
|
|
44
|
+
// plain JavaScript. Cells that compile as neither are kept as Observable JS.
|
|
45
|
+
const PACKAGE_IMPORT = /\bfrom\s*(["'])(npm|jsr):/;
|
|
46
|
+
export const cellMode = (source) => {
|
|
47
|
+
const compiles = (mode) => {
|
|
48
|
+
try {
|
|
49
|
+
transpile({ id: 1, value: source, mode });
|
|
50
|
+
return true;
|
|
51
|
+
} catch {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
if (PACKAGE_IMPORT.test(source) && compiles('js')) return 'js';
|
|
56
|
+
if (compiles('ojs')) return 'ojs';
|
|
57
|
+
if (compiles('js')) return 'js';
|
|
58
|
+
return 'ojs';
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
// Template cells from Observable Desktop (Markdown, HTML, TeX, Graphviz) run
|
|
62
|
+
// in Iridium as the equivalent tagged template, and are saved back in their
|
|
63
|
+
// original mode while they keep that shape.
|
|
64
|
+
const TEMPLATE_TAGS = { md: 'md', html: 'html', tex: 'tex', dot: 'dot' };
|
|
65
|
+
const toTemplate = (tag, value) => `${tag}\`${value.replace(/`/g, '\\`')}\``;
|
|
66
|
+
const fromTemplate = (tag, source) => {
|
|
67
|
+
const match = source.match(new RegExp(`^${tag}\`([\\s\\S]*)\`$`));
|
|
68
|
+
return match && !/(^|[^\\])`/.test(match[1]) ? match[1].replace(/\\`/g, '`') : null;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
// --- Reading ------------------------------------------------------------------
|
|
72
|
+
|
|
73
|
+
// Iridium's cell shape: { id, pin, sourceCode }, plus `mode` for cells that
|
|
74
|
+
// came from another Kit mode, so they can be saved back unchanged.
|
|
75
|
+
export const readNotebook = (path) =>
|
|
76
|
+
path.endsWith('.ojs') ? readOjs(readFileSync(path, 'utf8')) : readHtml(readFileSync(path, 'utf8'));
|
|
77
|
+
|
|
78
|
+
export const readNotebookMeta = (path) => {
|
|
79
|
+
if (!path?.endsWith('.html')) return {};
|
|
80
|
+
const { title, theme, readOnly } = deserialize(readFileSync(path, 'utf8'), {
|
|
81
|
+
parser: new window.DOMParser(),
|
|
82
|
+
});
|
|
83
|
+
return { title, theme, readOnly };
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const readHtml = (html) =>
|
|
87
|
+
deserialize(html, { parser: new window.DOMParser() }).cells.map(({ id, value, mode, pinned }) => {
|
|
88
|
+
if (mode === 'ojs' || mode === 'js') return { id, pin: pinned, sourceCode: value };
|
|
89
|
+
const tag = TEMPLATE_TAGS[mode];
|
|
90
|
+
// Other modes (SQL, Python, TypeScript, …) can't run in Iridium; keep them
|
|
91
|
+
// as they are so saving doesn't lose them.
|
|
92
|
+
return { id, pin: pinned, mode, sourceCode: tag ? toTemplate(tag, value) : value };
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
// Legacy .ojs: Observable JavaScript cells separated by `;`, pinned cells
|
|
96
|
+
// marked with a leading /*PIN*/ comment. @observablehq/parser 6 dropped
|
|
97
|
+
// parseModule, so split the file with a CellParser that reads cells until EOF.
|
|
98
|
+
class ModuleParser extends CellParser {
|
|
99
|
+
parseTopLevel(node) {
|
|
100
|
+
node.cells = [];
|
|
101
|
+
while (this.type !== tt.eof) node.cells.push(this.parseCell(this.startNode()));
|
|
102
|
+
this.next();
|
|
103
|
+
return this.finishNode(node, 'Program');
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const readOjs = (source) => {
|
|
108
|
+
const ends = ModuleParser.parse(source).cells.map((cell) => cell.end);
|
|
109
|
+
return ends.map((end, i) => {
|
|
110
|
+
const text = source.slice(i ? ends[i - 1] : 0, end).replace(/^\n+/, '');
|
|
111
|
+
return {
|
|
112
|
+
id: i + 1,
|
|
113
|
+
pin: text.startsWith('/*PIN*/'),
|
|
114
|
+
sourceCode: text.replace(/^\/\*PIN\*\/\n*/, '').replace(/;$/, ''),
|
|
115
|
+
};
|
|
116
|
+
});
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
// --- Writing ------------------------------------------------------------------
|
|
120
|
+
|
|
121
|
+
const toKitCell = ({ id, pin, sourceCode, mode }, index) => {
|
|
122
|
+
const value = String(sourceCode ?? '');
|
|
123
|
+
const cell = { id: Number(id) > 0 ? Number(id) : index + 1, pinned: !!pin };
|
|
124
|
+
const tag = TEMPLATE_TAGS[mode];
|
|
125
|
+
if (tag) {
|
|
126
|
+
const inner = fromTemplate(tag, value);
|
|
127
|
+
if (inner != null) return { ...cell, mode, value: inner };
|
|
128
|
+
} else if (mode && mode !== 'ojs' && mode !== 'js') {
|
|
129
|
+
return { ...cell, mode, value }; // unsupported mode: saved back unchanged
|
|
130
|
+
}
|
|
131
|
+
return { ...cell, mode: cellMode(value), value };
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
export const writeNotebook = (path, cells, meta = {}) => {
|
|
135
|
+
const notebook = toNotebook({ ...meta, cells: cells.map(toKitCell) });
|
|
136
|
+
writeFileSync(path, serialize(notebook, { document: window.document }));
|
|
137
|
+
};
|