@open-spreadsheet/core 0.2.0 → 0.4.0

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/server.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
+ import { assetPath, assetsDir, listAssets, MIME, readAsset, readChartStyles, readFavorites, renameAsset, renderChart, saveImage, setFavorite, SHARED, trashAsset, writeChartStyles, writeNote } from './assets.js';
4
5
  import { currentFile, hashOf, ID, listWorkbooks, OpsError, readWorkbook, trashWorkbook, workbookFile, writeWorkbook } from './ops.js';
5
6
 
6
7
  const CORE = path.dirname(fileURLToPath(import.meta.url));
@@ -49,7 +50,12 @@ export function initWorkspace(dir) {
49
50
  )}\n`,
50
51
  );
51
52
  writeFileSync(path.join(root, 'open-spreadsheet.config.json'), '{}\n');
52
- writeFileSync(path.join(root, '.gitignore'), 'node_modules\n.DS_Store\n# workbooks moved to the trash from the viewer or an agent\nsheets/.trash\n');
53
+ mkdirSync(path.join(root, 'assets'), { recursive: true });
54
+ writeFileSync(
55
+ path.join(root, 'assets', 'README.md'),
56
+ '# Shared notes\n\nMarkdown notes here are context for every workbook in this workspace: what the numbers mean, where they come from, conventions to keep. Agents read them before they work. Images here are shared too.\n',
57
+ );
58
+ writeFileSync(path.join(root, '.gitignore'), 'node_modules\n.DS_Store\n# workbooks moved to the trash from the viewer or an agent\nsheets/.trash\n**/assets/.trash\n# your own picks, such as favourite notes\n.open-spreadsheet/\n');
53
59
  const agents = readFileSync(path.join(CORE, 'templates', 'AGENTS.md'), 'utf8');
54
60
  writeFileSync(path.join(root, 'AGENTS.md'), agents);
55
61
  writeFileSync(path.join(root, 'CLAUDE.md'), agents);
@@ -114,7 +120,21 @@ function allowedWrite(req) {
114
120
  }
115
121
  }
116
122
 
117
- const STATUS = { bad_id: 400, bad_data: 400, bad_json: 422, not_found: 404, exists: 409, conflict: 412 };
123
+ const STATUS = { bad_id: 400, bad_data: 400, bad_json: 422, not_found: 404, exists: 409, conflict: 412, bad_name: 400, bad_range: 400, bad_type: 400, no_sheet: 404, too_big: 413, bad_style: 400 };
124
+
125
+ /** A request body as bytes, for image uploads; refused past `max`. */
126
+ const readBytes = (req, max = 15_000_000) =>
127
+ new Promise((resolve, reject) => {
128
+ const parts = [];
129
+ let size = 0;
130
+ req.on('data', (c) => {
131
+ size += c.length;
132
+ if (size > max) reject(new OpsError('too_big', 'An image is at most 15 MB.'));
133
+ else parts.push(c);
134
+ });
135
+ req.on('end', () => resolve(Buffer.concat(parts)));
136
+ req.on('error', reject);
137
+ });
118
138
 
119
139
  function apiPlugin(root) {
120
140
  // Bodies this server just wrote, so its own write does not come back as an outside change.
@@ -123,6 +143,14 @@ function apiPlugin(root) {
123
143
  name: 'open-spreadsheet:api',
124
144
  configureServer(server) {
125
145
  server.watcher.add(path.join(root, 'sheets'));
146
+ server.watcher.add(path.join(root, 'assets'));
147
+ // An asset written or removed (by an agent, apply-notes, the CLI): the Assets panel reloads its list.
148
+ const assetEvent = (file) => {
149
+ const rel = path.relative(root, file).split(path.sep);
150
+ const scope = rel[0] === 'assets' && rel.length === 2 ? SHARED : rel[0] === 'sheets' && rel[2] === 'assets' && rel.length === 4 ? rel[1] : null;
151
+ if (scope) server.ws.send({ type: 'custom', event: 'open-spreadsheet:assets', data: { scope } });
152
+ };
153
+ for (const ev of ['add', 'change', 'unlink']) server.watcher.on(ev, assetEvent);
126
154
  server.watcher.on('change', (file) => {
127
155
  const m = /sheets[\\/]([^\\/]+)[\\/]workbook\.json$/.exec(file);
128
156
  if (!m) return;
@@ -179,13 +207,64 @@ function apiPlugin(root) {
179
207
  const { id, title, data, from } = JSON.parse(await readBody(req));
180
208
  if (!ID.test(id ?? '')) return json(res, 400, { error: 'Use lowercase letters, numbers and dashes.' });
181
209
  if (existsSync(workbookFile(root, id))) return json(res, 409, { error: 'That name is taken.' });
210
+ const fromAssets = from !== undefined && ID.test(from) ? assetsDir(root, from) : null;
182
211
  let book = blankWorkbook(title || id);
183
212
  if (from !== undefined) book = { ...readWorkbook(root, from).data, ...(title ? { title } : {}) };
184
213
  else if (data !== undefined) book = { ...data, title: title || data.title || id };
185
214
  const { text } = await writeWorkbook(root, id, book, { create: true });
186
215
  ownWrites.set(id, text);
216
+ if (fromAssets && existsSync(fromAssets)) cpSync(fromAssets, assetsDir(root, id), { recursive: true, filter: (f) => !f.includes(`${path.sep}.trash`) });
187
217
  return json(res, 201, { id });
188
218
  }
219
+ if (url.pathname === '/__api/chart-styles') {
220
+ if (req.method === 'GET') return json(res, 200, await readChartStyles(root));
221
+ if (!allowedWrite(req)) return json(res, 403, { error: 'forbidden' });
222
+ if (req.method === 'PUT') return json(res, 200, await writeChartStyles(root, JSON.parse(await readBody(req))));
223
+ }
224
+ if (url.pathname === '/__api/favorites') {
225
+ if (req.method === 'GET') return json(res, 200, { favorites: readFavorites(root) });
226
+ if (!allowedWrite(req)) return json(res, 403, { error: 'forbidden' });
227
+ if (req.method === 'PUT') {
228
+ const b = JSON.parse(await readBody(req));
229
+ return json(res, 200, { favorites: setFavorite(root, b.scope, b.name, Boolean(b.on)) });
230
+ }
231
+ }
232
+ // ---------- assets ----------
233
+ if (url.pathname.startsWith('/__api/assets')) {
234
+ const scope = url.searchParams.get('scope') ?? '';
235
+ const name = url.searchParams.get('name') ?? '';
236
+ if (url.pathname === '/__api/assets' && req.method === 'GET') return json(res, 200, { scope, assets: listAssets(root, scope) });
237
+ if (url.pathname === '/__api/assets/file' && req.method === 'GET') {
238
+ const body = readAsset(root, scope, name);
239
+ const ext = name.split('.').pop().toLowerCase();
240
+ res.writeHead(200, {
241
+ 'content-type': MIME[ext] ?? 'application/octet-stream',
242
+ // An SVG or note from the folder is shown, never run: no scripts, no requests, its own origin.
243
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox",
244
+ 'x-content-type-options': 'nosniff',
245
+ 'cache-control': 'no-store',
246
+ ...(url.searchParams.has('download') ? { 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}` } : {}),
247
+ });
248
+ return res.end(body);
249
+ }
250
+ if (!allowedWrite(req)) return json(res, 403, { error: 'forbidden' });
251
+ if (url.pathname === '/__api/assets/note' && req.method === 'PUT') {
252
+ const b = JSON.parse(await readBody(req));
253
+ return json(res, 200, writeNote(root, b.scope, b.name, b.text));
254
+ }
255
+ if (url.pathname === '/__api/assets/upload' && req.method === 'POST') {
256
+ assetPath(root, scope, name);
257
+ return json(res, 201, saveImage(root, scope, name, await readBytes(req), { replace: url.searchParams.get('replace') === '1' }));
258
+ }
259
+ if (url.pathname === '/__api/assets/chart' && req.method === 'POST') {
260
+ const b = JSON.parse(await readBody(req));
261
+ return json(res, 201, await renderChart(root, b.workbook, b));
262
+ }
263
+ if (url.pathname === '/__api/assets/rename' && req.method === 'POST') return json(res, 200, renameAsset(root, scope, name, url.searchParams.get('to') ?? ''));
264
+ if (url.pathname === '/__api/assets' && req.method === 'DELETE') return json(res, 200, trashAsset(root, scope, name));
265
+ return json(res, 404, { error: 'not found' });
266
+ }
267
+
189
268
  const m = /^\/__api\/workbooks\/([^/]+)$/.exec(url.pathname);
190
269
  if (m && ID.test(m[1])) {
191
270
  const id = m[1];
@@ -14,8 +14,10 @@ People leave notes on cells in the editor (right-click → Add note, or ⇧F2).
14
14
  1. **Find them.** With the MCP server, call `list_notes` (all workbooks, or one). Otherwise read the `notes` of every sheet in `sheets/*/workbook.json`.
15
15
  2. **Sort them.** A note that asks for something ("make this a percentage", "add a total under this column", "this should use the March numbers") is a request. A note that only explains ("source: 2025 annual report") is documentation: leave it.
16
16
  3. **Do each request** on the cell the note is on and whatever it names — cells, formulas, styles, formats, layout — following the `sheet-authoring` skill. Keep totals as formulas.
17
+ - **A note asking for a chart or a picture** ("make a bar chart of this", "chart sales by month") gets an image in the workbook's Assets, never a chart on the grid: call `render_chart` with the range the note is about (its data, header row and first column included) and a title from the note. If the request sits in a note, put the chart in it with `![title](file.svg)` (the path from the note). Say the file name in your report.
18
+ - **A note to remember** ("these figures are in thousands", "source: 2025 report") can go into a Markdown note in Assets with `write_note`, then the cell note is done.
17
19
  4. **Remove each note you carried out** (`set_note` with empty `text`, or delete the key from `notes`). If a request is unclear or impossible, leave the note and say why.
18
20
  5. **Check.** Run `open-spreadsheet check` (or the `check` tool) and fix what it reports.
19
- 6. **Report** which notes you applied, which you left and why.
21
+ 6. **Report** which notes you applied, which you left and why, and any chart images or notes you saved in Assets.
20
22
 
21
23
  The editor reloads as you write, so the person sees each change and the note disappear.
@@ -35,7 +35,7 @@ Each workbook is `sheets/<id>/workbook.json`. The grid editor at `pnpm dev` relo
35
35
  | `hiddenRows` / `hiddenCols` | Rows (1-based numbers) and columns (letters) hidden by hand |
36
36
  | `names` (top level, beside `sheets`) | Defined names: `{ "Sales": "Orders!$F$2:$F$200" }`, used in formulas as `=SUM(Sales)`; each points at a cell or range with its sheet |
37
37
  | `protected` | Ranges a person locked, `["A1:D1", "F2"]`. The editor and MCP refuse to change them; never edit or remove them yourself — ask the person |
38
- | `charts` | Charts over the grid: `[{ "id": "sales", "type": "bar", "range": "A1:C13", "title": "Sales by month", "x": 520, "y": 0, "w": 440, "h": 270 }]` — `type` is `bar`, `line` or `pie`; the range's first column holds the categories and its first row the series names; `x`/`y`/`w`/`h` are px at 100% zoom from the sheet's top-left |
38
+ | `charts` | Not used for new work: charts are images in Assets (below). An older workbook may still have charts here; the editor offers to move them |
39
39
  | `color` | The sheet tab's colour |
40
40
  | `notes` | A1 address → a note left on the cell (see the `apply-notes` skill) |
41
41
  | `conditional` | Conditional formats, later ones win: `{ "range": "D2:D50", "type": "gt", "value": 10000, "style": { "bg": "#ffc7ce", "color": "#9c0006" } }`; types `gt lt ge le eq ne` (value), `between` (value, value2), `contains` (text), `duplicate`, `colorScale` (`colors`: 2 or 3 hex, low → high), `dataBar` (`color`), `top` (`rank`, optional `percent`, `bottom`), `average` (optional `below`, `equal`), `iconSet` (`set` as Excel names it — `3Arrows`, `3TrafficLights1`, `4Rating`, `5Arrows`…; optional `thresholds` in percent, `reverse`). All of them go to and from .xlsx |
@@ -74,3 +74,13 @@ Math and trigonometry (SUM, SUMIF(S), SUMPRODUCT, SUBTOTAL, ROUND/ROUNDUP/ROUNDD
74
74
 
75
75
  1. Run `open-spreadsheet check` (or the MCP `check` tool). It lists formulas that show `#NAME?`, `#REF!`, `#CIRC!`, `#VALUE!` and malformed entries.
76
76
  2. Read the result back with the MCP `read_range` tool, or open the workbook in the viewer.
77
+
78
+ ## Assets: chart images and notes
79
+
80
+ Each workbook has an assets folder, `sheets/<id>/assets/`, and the workspace has a shared one, `assets/`. They hold:
81
+
82
+ - **Chart images.** Charts are never placed on the grid. Draw one from a range with the MCP `render_chart` tool (`workbook`, `sheet`, `range`, `type`, `title`); it saves an SVG in the workbook's assets, the same picture the editor makes, and the editor redraws it whenever the numbers change. The range's first column holds the categories and its first row the series names. Types: `bar` (columns), `barH` (horizontal bars, for long names or rankings), `stacked` (a total and its parts), `line` (a trend), `area` (a trend with its volume), `pie` / `doughnut` (shares; the doughnut shows the total), `scatter` (two numbers against each other; the first column is x), `combo` (the first series as columns, the rest as lines on a right-hand axis — amounts with a rate). Charts take a **style** (`style`: a built-in one — `default`, `ocean`, `warm`, `pastel`, `mono`, `night` — or the workspace's own); leave it out and the chart follows the workspace default. `list_chart_styles` shows them; `save_chart_style` adds a house style (e.g. from brand colours) to `assets/chart-styles.json`.
83
+ - **Notes (`.md`).** What people know about the numbers: sources, meanings, rules to keep. **Read the notes before you change a workbook** (`list_assets` then `read_asset`, or the files themselves), for that workbook and for `shared`. Write what you found or decided with `write_note` when it will help next time.
84
+
85
+ Without MCP, read and write the files directly. Never put an image or note anywhere else, and never name one with a folder in it.
86
+
@@ -45,6 +45,7 @@ npx open-spreadsheet export <id> --range A1:F200 --out data.csv # computed val
45
45
  - Sizes are pixels: `cols` by letter, `rows` by 1-based row number.
46
46
  - **Defined names** sit at the top level: `"names": { "Sales": "Orders!$F$2:$F$200" }`, then `=SUM(Sales)`.
47
47
  - **Conditional formats, dropdown lists and filters** live beside the cells too (`conditional`, `validation`, `filter`); see the `sheet-authoring` skill.
48
+ - **Assets** sit beside each workbook in `sheets/<id>/assets/` (and shared in `assets/`): chart images and Markdown notes. **Read a workbook's notes and the shared ones before you change it** — they say what the numbers mean and what to keep. Charts are never on the grid: make one with the MCP `render_chart` tool (an SVG in Assets), in the workspace's chart style unless asked for another (`list_chart_styles`). Keep what you learn with `write_note`. A note shows an asset with a Markdown image by its path from the note: `![Sales](sales.svg)` beside it, `../../../assets/x.svg` for a shared one.
48
49
  - **Protected ranges** (`"protected": ["A1:D1"]` on a sheet) are cells a person locked. Do not change them, by MCP or by editing the JSON; if a task needs them changed, ask the person to unprotect them in the editor.
49
50
  - **Notes** are comments people leave on cells, often requests for you. "Apply the notes" means: do what each asks, then remove it (the `apply-notes` skill).
50
51