@crossworks/content-core 0.300.143 → 0.400.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crossworks/content-core",
3
- "version": "0.300.143",
3
+ "version": "0.400.0",
4
4
  "description": "Browser-safe content logic — markdown, blocks, pages, tables, formulas — shared by the server and any client. Zero server deps by design: nothing here may reach @mantle/db, node-only APIs, or the network (the jackdaw-repo-split P0 boundary).",
5
5
  "type": "module",
6
6
  "exports": {
@@ -8,8 +8,10 @@
8
8
  "./block-diff": "./src/block-diff.ts",
9
9
  "./block-ids": "./src/block-ids.ts",
10
10
  "./block-list": "./src/block-list.ts",
11
+ "./canvas": "./src/canvas.ts",
11
12
  "./contacts-format": "./src/contacts-format.ts",
12
13
  "./doc-to-markdown": "./src/doc-to-markdown.ts",
14
+ "./drift-spec": "./src/drift-spec.ts",
13
15
  "./formula-dimensions": "./src/formula-dimensions.ts",
14
16
  "./formula-eval": "./src/formula-eval.ts",
15
17
  "./formula-seed": "./src/formula-seed.ts",
@@ -34,7 +36,7 @@
34
36
  "./tree": "./src/tree.ts"
35
37
  },
36
38
  "dependencies": {
37
- "@mantle/client-types": "npm:@crossworks/client-types@0.300.143",
39
+ "@mantle/client-types": "npm:@crossworks/client-types@0.400.0",
38
40
  "marked": "^18.1.0",
39
41
  "mathjs": "15.2.0"
40
42
  },
@@ -0,0 +1,154 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ CANVAS_DEFAULT_SIZE,
4
+ canvasImports,
5
+ canvasLoadProblems,
6
+ canvasText,
7
+ decodeHtmlEntities,
8
+ parseCanvasHead,
9
+ parseCanvasSize,
10
+ } from './canvas';
11
+
12
+ const CANVAS = `<!doctype html>
13
+ <html>
14
+ <head>
15
+ <title>Unit 3 feed section, P&amp;ID</title>
16
+ <meta name="description" content="Pumps P-301A/B to exchanger E-302." />
17
+ <meta name="canvas:size" content="1920x1080" />
18
+ <meta name="canvas:theme" content="fixed" />
19
+ <meta name="canvas:poster-at" content="2.5s" />
20
+ <style>.x { color: red }</style>
21
+ </head>
22
+ <body>
23
+ <!-- a comment the index must not read -->
24
+ <h1>Feed <b>pumps</b></h1><p>Flow&nbsp;rate 12&#x2009;m3/h</p>
25
+ <script type="module">
26
+ import * as d3 from 'd3';
27
+ import { animate } from "motion";
28
+ import 'alpinejs';
29
+ const m = await import('three');
30
+ const secret = 'never indexed';
31
+ </script>
32
+ <script src="/canvas-runtime/plotly/plotly.min.js"></script>
33
+ <script>import notAModule from 'classic';</script>
34
+ </body>
35
+ </html>`;
36
+
37
+ describe('parseCanvasHead', () => {
38
+ it('reads the head contract', () => {
39
+ expect(parseCanvasHead(CANVAS)).toEqual({
40
+ title: 'Unit 3 feed section, P&ID',
41
+ description: 'Pumps P-301A/B to exchanger E-302.',
42
+ size: { w: 1920, h: 1080 },
43
+ theme: 'fixed',
44
+ posterAt: 2.5,
45
+ });
46
+ });
47
+
48
+ it('defaults what the head leaves out', () => {
49
+ expect(parseCanvasHead('<html><body>hi</body></html>')).toEqual({
50
+ title: '',
51
+ description: '',
52
+ size: { ...CANVAS_DEFAULT_SIZE },
53
+ theme: 'follow',
54
+ posterAt: null,
55
+ });
56
+ });
57
+
58
+ it('reads attributes in any order and quote style', () => {
59
+ const head = parseCanvasHead(
60
+ "<head><meta content='fill' name=canvas:size><title> A </title></head>",
61
+ );
62
+ expect(head.size).toBe('fill');
63
+ expect(head.title).toBe('A');
64
+ });
65
+ });
66
+
67
+ describe('parseCanvasSize', () => {
68
+ it('takes WxH within bounds, or fill', () => {
69
+ expect(parseCanvasSize('1600x900')).toEqual({ w: 1600, h: 900 });
70
+ expect(parseCanvasSize(' FILL ')).toBe('fill');
71
+ expect(parseCanvasSize('50x50')).toBeNull();
72
+ expect(parseCanvasSize('9000x900')).toBeNull();
73
+ expect(parseCanvasSize('wide')).toBeNull();
74
+ expect(parseCanvasSize(null)).toBeNull();
75
+ });
76
+ });
77
+
78
+ describe('canvasText', () => {
79
+ it('is the title, description and visible text, never script, style or comments', () => {
80
+ const text = canvasText(CANVAS);
81
+ expect(text).toContain('Unit 3 feed section, P&ID');
82
+ expect(text).toContain('Pumps P-301A/B');
83
+ expect(text).toContain('Feed pumps');
84
+ expect(text).toContain('Flow rate 12');
85
+ expect(text).not.toContain('never indexed');
86
+ expect(text).not.toContain('color: red');
87
+ expect(text).not.toContain('comment');
88
+ });
89
+
90
+ it('is deterministic, so an unchanged canvas changes nothing the index reads', () => {
91
+ expect(canvasText(CANVAS)).toBe(canvasText(CANVAS));
92
+ expect(canvasText(CANVAS.replace('red', 'blue'))).toBe(canvasText(CANVAS));
93
+ });
94
+ });
95
+
96
+ describe('canvasImports', () => {
97
+ it('lists module imports and script sources, not a classic script', () => {
98
+ expect(canvasImports(CANVAS)).toEqual({
99
+ modules: ['d3', 'motion', 'alpinejs', 'three'],
100
+ scripts: ['/canvas-runtime/plotly/plotly.min.js'],
101
+ });
102
+ });
103
+ });
104
+
105
+ describe('decodeHtmlEntities', () => {
106
+ it('decodes named and numeric references and leaves unknown ones', () => {
107
+ expect(decodeHtmlEntities('a &lt;b&gt; &#65;&#x42; &unknown;')).toBe('a <b> AB &unknown;');
108
+ });
109
+ });
110
+
111
+ describe('linear on hostile input (the canvas audit)', () => {
112
+ const quick = (f: () => unknown) => {
113
+ const t = performance.now();
114
+ f();
115
+ return performance.now() - t;
116
+ };
117
+
118
+ it('many unclosed hidden tags, many unclosed heads, titles and scripts', () => {
119
+ const cases = [
120
+ '<style '.repeat(150_000),
121
+ '<head '.repeat(150_000),
122
+ '<title>'.repeat(150_000),
123
+ '<body '.repeat(150_000),
124
+ '<script type="module">import '.repeat(30_000),
125
+ '<script type="module">' + 'import '.repeat(100_000) + ' '.repeat(100_000),
126
+ ];
127
+ for (const html of cases) {
128
+ expect(quick(() => canvasText(html))).toBeLessThan(1000);
129
+ expect(quick(() => canvasImports(html))).toBeLessThan(1000);
130
+ }
131
+ });
132
+ });
133
+
134
+ describe('canvasLoadProblems', () => {
135
+ const MODULES = ['d3', 'motion', 'echarts'];
136
+ it('passes the vendored set, inline data and the runtime paths', () => {
137
+ const ok = `<html><head><link rel="stylesheet" href="/canvas-runtime/reveal/reveal.css"></head>
138
+ <body><img src="data:image/png;base64,AA"><script src="/canvas-runtime/plotly/plotly.min.js"></script>
139
+ <script type="module">import * as d3 from 'd3'; import { animate } from 'motion';</script></body></html>`;
140
+ expect(canvasLoadProblems(ok, MODULES)).toEqual([]);
141
+ });
142
+
143
+ it('names an unknown library, a CDN and an outside file, with the fix', () => {
144
+ const bad = `<html><body><script src="https://cdn.example.test/x.js"></script>
145
+ <img src="/api/files/1"><script type="module">import gsap from 'gsap'; import x from 'https://esm.example.test/y';</script></body></html>`;
146
+ const p = canvasLoadProblems(bad, MODULES);
147
+ expect(p).toHaveLength(4);
148
+ expect(p.join('\n')).toMatch(
149
+ /'gsap': not in the canvas library set\. Use one of: d3, motion, echarts/,
150
+ );
151
+ expect(p.join('\n')).toMatch(/no network/);
152
+ expect(p.join('\n')).toMatch(/only files under \/canvas-runtime\//);
153
+ });
154
+ });
package/src/canvas.ts ADDED
@@ -0,0 +1,368 @@
1
+ /**
2
+ * Present canvases (docs/proposals/canvas-files.md section 4.2): one
3
+ * self-contained HTML document per item. This module reads a canvas WITHOUT
4
+ * running it: the head contract (title, description, design size, theme),
5
+ * the visible text search and the extractor index, and the library imports.
6
+ *
7
+ * Pure and dependency free (no DOM, no parser package), so the brain, the
8
+ * tools and the client read a canvas the same way. It is a reader for
9
+ * well-formed agent-written HTML, not a sanitiser: nothing here makes a
10
+ * canvas safe to run. The sandboxed frame does that (section 5.2).
11
+ */
12
+
13
+ /** The largest canvas source the brain stores (section 4.1). */
14
+ export const CANVAS_MAX_BYTES = 1_000_000;
15
+
16
+ /** The design size a fixed canvas is drawn at when its head names none. */
17
+ export const CANVAS_DEFAULT_SIZE = { w: 1600, h: 900 } as const;
18
+
19
+ /** How the frame fits a canvas: a fixed design size scaled to the space with
20
+ * letterboxing, or the whole viewport (`canvas:size="fill"`). */
21
+ export type CanvasSize = { w: number; h: number } | 'fill';
22
+
23
+ export type CanvasHead = {
24
+ /** `<title>`, or '' when the head has none. */
25
+ title: string;
26
+ /** `<meta name="description">`, or ''. */
27
+ description: string;
28
+ size: CanvasSize;
29
+ /** 'fixed' pins the light palette (`canvas:theme="fixed"`); 'follow' takes
30
+ * the owner's theme. */
31
+ theme: 'follow' | 'fixed';
32
+ /** When to take the poster of an animation, in seconds, or null. */
33
+ posterAt: number | null;
34
+ };
35
+
36
+ const NAMED_ENTITIES: Record<string, string> = {
37
+ amp: '&',
38
+ lt: '<',
39
+ gt: '>',
40
+ quot: '"',
41
+ apos: "'",
42
+ nbsp: ' ',
43
+ ndash: '-',
44
+ mdash: '-',
45
+ hellip: '...',
46
+ copy: '(c)',
47
+ deg: '°',
48
+ };
49
+
50
+ /** Decode the character references agent HTML commonly holds. */
51
+ export function decodeHtmlEntities(text: string): string {
52
+ return text.replace(/&(#x[0-9a-f]{1,8}|#[0-9]{1,8}|[a-z]{1,32});/gi, (whole, ref: string) => {
53
+ if (ref[0] === '#') {
54
+ const code =
55
+ ref[1] === 'x' || ref[1] === 'X' ? parseInt(ref.slice(2), 16) : parseInt(ref.slice(1), 10);
56
+ return Number.isFinite(code) && code > 0 && code <= 0x10ffff
57
+ ? String.fromCodePoint(code)
58
+ : whole;
59
+ }
60
+ return NAMED_ENTITIES[ref.toLowerCase()] ?? whole;
61
+ });
62
+ }
63
+
64
+ /** The value of an attribute in one tag's source, or null. */
65
+ function attrOf(tag: string, name: string): string | null {
66
+ const re = new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i');
67
+ const m = re.exec(tag);
68
+ if (!m) return null;
69
+ return decodeHtmlEntities(m[1] ?? m[2] ?? m[3] ?? '');
70
+ }
71
+
72
+ /** Every `<meta name=... content=...>` of the document, by lower-case name. */
73
+ function metaTags(html: string): Map<string, string> {
74
+ const out = new Map<string, string>();
75
+ for (const m of html.matchAll(/<meta\b[^>]*>/gi)) {
76
+ const name = attrOf(m[0], 'name');
77
+ const content = attrOf(m[0], 'content');
78
+ if (name && content !== null && !out.has(name.toLowerCase())) {
79
+ out.set(name.toLowerCase(), content.trim());
80
+ }
81
+ }
82
+ return out;
83
+ }
84
+
85
+ /** `1600x900` → { w, h } within sane bounds, `fill` → 'fill', else null. */
86
+ export function parseCanvasSize(value: string | null | undefined): CanvasSize | null {
87
+ const v = (value ?? '').trim().toLowerCase();
88
+ if (v === 'fill') return 'fill';
89
+ const m = /^(\d{2,5})\s*x\s*(\d{2,5})$/.exec(v);
90
+ if (!m) return null;
91
+ const w = Number(m[1]);
92
+ const h = Number(m[2]);
93
+ if (w < 100 || h < 100 || w > 8000 || h > 8000) return null;
94
+ return { w, h };
95
+ }
96
+
97
+ /** `2.5s`, `2500ms` or `2.5` → seconds, within 0..60, else null. */
98
+ function parseSeconds(value: string | undefined): number | null {
99
+ const m = /^(\d+(?:\.\d+)?)\s*(ms|s)?$/i.exec((value ?? '').trim());
100
+ if (!m) return null;
101
+ const n = Number(m[1]) / (m[2]?.toLowerCase() === 'ms' ? 1000 : 1);
102
+ return n >= 0 && n <= 60 ? n : null;
103
+ }
104
+
105
+ // Every reader below is a linear scan (indexOf, and regexes bounded to one
106
+ // tag or a short window), never a backtracking regex over the document: a
107
+ // canvas is written by an agent that may be steered, and a save, a search
108
+ // index or a frame load must not be held up by a document built to make a
109
+ // regex run for minutes (the canvas audit, 2026-10-24).
110
+
111
+ /** The tags whose content is never visible text. */
112
+ const HIDDEN_TAGS = new Set(['script', 'style', 'noscript', 'template']);
113
+
114
+ /** The tag name at `<` (lower case), or null. Reads at most 40 characters. */
115
+ function tagNameAt(html: string, lt: number): string | null {
116
+ const m = /^<([a-zA-Z][\w:-]*)/.exec(html.slice(lt, lt + 40));
117
+ return m ? m[1]!.toLowerCase() : null;
118
+ }
119
+
120
+ /** The index just past the `>` that closes `</name ...>` from `from`, or
121
+ * the end of the text when there is none. `lower` is the text in lower case. */
122
+ function pastClose(lower: string, name: string, from: number): number {
123
+ const close = lower.indexOf(`</${name}`, from);
124
+ if (close < 0) return lower.length;
125
+ const gt = lower.indexOf('>', close);
126
+ return gt < 0 ? lower.length : gt + 1;
127
+ }
128
+
129
+ /** Comments, scripts, styles and other non-visible blocks removed. */
130
+ function withoutHiddenBlocks(html: string): string {
131
+ const lower = html.toLowerCase();
132
+ let out = '';
133
+ let i = 0;
134
+ while (i < html.length) {
135
+ const lt = html.indexOf('<', i);
136
+ if (lt < 0) {
137
+ out += html.slice(i);
138
+ break;
139
+ }
140
+ out += html.slice(i, lt);
141
+ if (html.startsWith('<!--', lt)) {
142
+ const end = html.indexOf('-->', lt + 4);
143
+ out += ' ';
144
+ i = end < 0 ? html.length : end + 3;
145
+ continue;
146
+ }
147
+ const name = tagNameAt(html, lt);
148
+ if (name && HIDDEN_TAGS.has(name)) {
149
+ out += ' ';
150
+ i = pastClose(lower, name, lt + 1 + name.length);
151
+ continue;
152
+ }
153
+ out += '<';
154
+ i = lt + 1;
155
+ }
156
+ return out;
157
+ }
158
+
159
+ /** Every `<...>` replaced by a space, in one pass. (`/<[^>]+>/g` reads to
160
+ * the end of the text from each `<` that has no `>` after it.) */
161
+ function withoutTags(html: string): string {
162
+ let out = '';
163
+ let i = 0;
164
+ while (i < html.length) {
165
+ const lt = html.indexOf('<', i);
166
+ if (lt < 0) {
167
+ out += html.slice(i);
168
+ break;
169
+ }
170
+ out += html.slice(i, lt);
171
+ const gt = html.indexOf('>', lt + 1);
172
+ if (gt < 0) {
173
+ out += html.slice(lt);
174
+ break;
175
+ }
176
+ out += ' ';
177
+ i = gt + 1;
178
+ }
179
+ return out;
180
+ }
181
+
182
+ function collapse(text: string): string {
183
+ return text.replace(/\s+/g, ' ').trim();
184
+ }
185
+
186
+ /** The most of the document the head is looked for in. */
187
+ const HEAD_SCAN_MAX = 64_000;
188
+
189
+ /** The document's head (from `<head` to `</head>`, else the first
190
+ * HEAD_SCAN_MAX characters). */
191
+ function headOf(html: string): string {
192
+ const window = html.slice(0, HEAD_SCAN_MAX);
193
+ const lower = window.toLowerCase();
194
+ const open = lower.indexOf('<head');
195
+ if (open < 0) return window;
196
+ const close = lower.indexOf('</head', open);
197
+ return window.slice(open, close < 0 ? window.length : close);
198
+ }
199
+
200
+ /** The text inside the head's `<title>`, or ''. */
201
+ function titleOf(head: string): string {
202
+ const lower = head.toLowerCase();
203
+ const open = lower.indexOf('<title');
204
+ if (open < 0) return '';
205
+ const gt = lower.indexOf('>', open);
206
+ if (gt < 0) return '';
207
+ const close = lower.indexOf('</title', gt);
208
+ return head.slice(gt + 1, close < 0 ? Math.min(head.length, gt + 1 + 400) : close);
209
+ }
210
+
211
+ /** Read a canvas's head contract (section 4.2). Missing parts take their
212
+ * defaults: no title is '', no size is the default design size. */
213
+ export function parseCanvasHead(html: string): CanvasHead {
214
+ const head = headOf(html);
215
+ const metas = metaTags(head);
216
+ return {
217
+ title: collapse(decodeHtmlEntities(titleOf(head))).slice(0, 200),
218
+ description: collapse(metas.get('description') ?? '').slice(0, 500),
219
+ size: parseCanvasSize(metas.get('canvas:size')) ?? { ...CANVAS_DEFAULT_SIZE },
220
+ theme: metas.get('canvas:theme')?.toLowerCase() === 'fixed' ? 'fixed' : 'follow',
221
+ posterAt: parseSeconds(metas.get('canvas:poster-at')),
222
+ };
223
+ }
224
+
225
+ /** The most text a canvas contributes to search and the extractor. */
226
+ export const CANVAS_TEXT_MAX = 20_000;
227
+
228
+ /** The document's body (after `<body ...>`, up to the last `</body`), else
229
+ * the whole document. */
230
+ function bodyOf(html: string): string {
231
+ const lower = html.toLowerCase();
232
+ const open = lower.indexOf('<body');
233
+ if (open < 0) return html;
234
+ const gt = lower.indexOf('>', open);
235
+ if (gt < 0) return html;
236
+ const close = lower.lastIndexOf('</body');
237
+ return html.slice(gt + 1, close > gt ? close : html.length);
238
+ }
239
+
240
+ /**
241
+ * The canvas's derived text (section 4.3): title, description, then the
242
+ * visible text of the body, with scripts, styles and comments removed.
243
+ * Deterministic, so an unchanged canvas yields the same text and a save that
244
+ * only moves a colour changes nothing the index reads.
245
+ */
246
+ export function canvasText(html: string): string {
247
+ const { title, description } = parseCanvasHead(html);
248
+ const visible = collapse(
249
+ decodeHtmlEntities(
250
+ // Tags become spaces so words in adjacent cells never fuse.
251
+ withoutTags(withoutHiddenBlocks(bodyOf(html))),
252
+ ),
253
+ );
254
+ return [title, description, visible]
255
+ .filter((s) => s.length > 0)
256
+ .join('\n')
257
+ .slice(0, CANVAS_TEXT_MAX);
258
+ }
259
+
260
+ /** How far after `import` or `export` a specifier is looked for. */
261
+ const IMPORT_WINDOW = 400;
262
+
263
+ /** The specifiers one module script imports, each statement read within a
264
+ * short window after its keyword. */
265
+ function moduleSpecifiers(code: string): string[] {
266
+ const out: string[] = [];
267
+ const keyword = /\b(import|export)\b/g;
268
+ let k: RegExpExecArray | null;
269
+ while ((k = keyword.exec(code))) {
270
+ const window = code.slice(k.index, k.index + IMPORT_WINDOW);
271
+ const m =
272
+ k[1] === 'import'
273
+ ? (/^import\s*\(\s*["']([^"'\n]+)["']\s*\)/.exec(window) ??
274
+ /^import\s*["']([^"'\n]+)["']/.exec(window) ??
275
+ /^import\b[^"';]*?\bfrom\s*["']([^"'\n]+)["']/.exec(window))
276
+ : /^export\b[^"';]*?\bfrom\s*["']([^"'\n]+)["']/.exec(window);
277
+ if (m) out.push(m[1]!);
278
+ }
279
+ return out;
280
+ }
281
+
282
+ /**
283
+ * The module specifiers a canvas imports (`import x from 'd3'`,
284
+ * `import 'motion'`, `import('three')`), and the classic script sources it
285
+ * loads, deduplicated in order. The save step records the library names
286
+ * (meta.libs); a later phase refuses a name outside the vendored set.
287
+ */
288
+ export function canvasImports(html: string): { modules: string[]; scripts: string[] } {
289
+ const modules: string[] = [];
290
+ const scripts: string[] = [];
291
+ const lower = html.toLowerCase();
292
+ let i = 0;
293
+ while (i < html.length) {
294
+ const open = lower.indexOf('<script', i);
295
+ if (open < 0) break;
296
+ const gt = lower.indexOf('>', open);
297
+ if (gt < 0) break;
298
+ const attrs = `<script ${html.slice(open + 7, gt)}>`;
299
+ const close = lower.indexOf('</script', gt);
300
+ const code = html.slice(gt + 1, close < 0 ? html.length : close);
301
+ i = close < 0 ? html.length : close + 8;
302
+ const src = attrOf(attrs, 'src');
303
+ if (src) {
304
+ if (!scripts.includes(src)) scripts.push(src);
305
+ continue;
306
+ }
307
+ if ((attrOf(attrs, 'type') ?? '').toLowerCase() !== 'module') continue;
308
+ for (const spec of moduleSpecifiers(code)) if (!modules.includes(spec)) modules.push(spec);
309
+ }
310
+ return { modules, scripts };
311
+ }
312
+
313
+ /** The path classic scripts and stylesheets of the vendored set sit under. */
314
+ export const CANVAS_RUNTIME_PREFIX = '/canvas-runtime/';
315
+
316
+ /** `src` and `href` values of the document's tags, in order (bounded scan). */
317
+ function urlAttributes(html: string): string[] {
318
+ const out: string[] = [];
319
+ for (const m of html.matchAll(
320
+ /<(?:script|link|img|source|audio|video|iframe|embed|object)\b[^>]{0,2000}>/gi,
321
+ )) {
322
+ for (const name of ['src', 'href', 'data', 'poster']) {
323
+ const v = attrOf(m[0], name);
324
+ if (v !== null) out.push(v.trim());
325
+ }
326
+ }
327
+ return out;
328
+ }
329
+
330
+ /**
331
+ * What would make a canvas fail in its frame, found before it is saved
332
+ * (section 6.2): a module the vendored set does not have, a classic script
333
+ * or stylesheet outside `/canvas-runtime/` and `/share-runtime/`, or any URL
334
+ * to another host (the frame refuses the network, so it would only ever be
335
+ * blank). `modules` is the import map's specifiers. Each problem names the
336
+ * fix; the caller refuses the save with the list.
337
+ */
338
+ export function canvasLoadProblems(html: string, modules: readonly string[]): string[] {
339
+ const problems: string[] = [];
340
+ const known = new Set(modules);
341
+ const { modules: imported } = canvasImports(html);
342
+ for (const spec of imported) {
343
+ if (known.has(spec)) continue;
344
+ if (/^(https?:)?\/\//i.test(spec)) {
345
+ problems.push(
346
+ `import '${spec}': the frame has no network. Import a library by its bare name instead: ${modules.join(', ')}.`,
347
+ );
348
+ } else {
349
+ problems.push(
350
+ `import '${spec}': not in the canvas library set. Use one of: ${modules.join(', ')}; or plain SVG and JS.`,
351
+ );
352
+ }
353
+ }
354
+ for (const url of urlAttributes(html)) {
355
+ if (!url || url.startsWith('#') || /^(data|blob):/i.test(url)) continue;
356
+ if (/^(https?:)?\/\//i.test(url)) {
357
+ problems.push(
358
+ `'${url.slice(0, 120)}': the frame has no network, so nothing loads from another host. Inline it (a data: URL, inline SVG) or use the vendored set.`,
359
+ );
360
+ continue;
361
+ }
362
+ if (url.startsWith(CANVAS_RUNTIME_PREFIX) || url.startsWith('/share-runtime/')) continue;
363
+ problems.push(
364
+ `'${url.slice(0, 120)}': only files under ${CANVAS_RUNTIME_PREFIX} (for example ${CANVAS_RUNTIME_PREFIX}plotly/plotly.min.js) load in a canvas. Inline anything else.`,
365
+ );
366
+ }
367
+ return [...new Set(problems)];
368
+ }
@@ -116,6 +116,17 @@ describe('docToMarkdown — round-trip stability', () => {
116
116
  );
117
117
  });
118
118
 
119
+ it('an embedded Present canvas: an image node with presentId, back to present:', () => {
120
+ const md = 'Before\n\n![Pump curve](present:3f1c2b4a-0000-4000-8000-000000000001)\n\nAfter';
121
+ roundTrips(md);
122
+ const img = (markdownToDoc(md) as N).content!.find((n) => n.type === 'image')!;
123
+ expect(img.attrs).toMatchObject({
124
+ src: null,
125
+ alt: 'Pump curve',
126
+ presentId: '3f1c2b4a-0000-4000-8000-000000000001',
127
+ });
128
+ });
129
+
119
130
  it('an inline media:/page: link inside prose stays a plain link (block forms are standalone lines)', () => {
120
131
  roundTrips('see [spec.pdf](media:f-2) inline here');
121
132
  const doc = markdownToDoc('see [spec.pdf](media:f-2) inline here') as N;
@@ -106,6 +106,8 @@ function imageToMd(node: PMNode): string {
106
106
  const nodeId = s(node.attrs?.nodeId);
107
107
  const drawId = s(node.attrs?.drawId);
108
108
  if (drawId) return `![${alt}](draw:${drawId})`;
109
+ const presentId = s(node.attrs?.presentId);
110
+ if (presentId) return `![${alt}](present:${presentId})`;
109
111
  return `![${alt}](${nodeId ? `media:${nodeId}` : s(node.attrs?.src)})`;
110
112
  }
111
113
 
@@ -0,0 +1,83 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { FRESH_APPEARANCE } from '@mantle/client-types/fresh-appearance';
3
+ import {
4
+ DRIFT_SPEC_DEFAULTS,
5
+ DRIFT_SPEC_MAX,
6
+ decodeDriftSpec,
7
+ encodeDriftSpec,
8
+ randomDriftSpec,
9
+ type DriftSpec,
10
+ } from './drift-spec';
11
+
12
+ const V2: DriftSpec = {
13
+ ...DRIFT_SPEC_DEFAULTS,
14
+ seed: 123456,
15
+ style: 'marble',
16
+ pal: 'chart',
17
+ tone: 'lighter',
18
+ speed: 3.5,
19
+ angle: -45,
20
+ };
21
+
22
+ describe('the Drift spec codec', () => {
23
+ it('decodes a Neat v1 spec as silk, keeping seed, tone and speed', () => {
24
+ const spec = decodeDriftSpec('{"v":1,"seed":7,"tone":"darker","speed":4}');
25
+ expect(spec).toEqual({
26
+ ...DRIFT_SPEC_DEFAULTS,
27
+ seed: 7,
28
+ tone: 'darker',
29
+ speed: 4,
30
+ style: 'silk',
31
+ });
32
+ });
33
+
34
+ it('decodes the fresh-install default (still v1)', () => {
35
+ expect(decodeDriftSpec(FRESH_APPEARANCE.neatBackground)?.style).toBe('silk');
36
+ });
37
+
38
+ it('round-trips v2 through its canonical encoding', () => {
39
+ const wire = encodeDriftSpec(V2);
40
+ expect(decodeDriftSpec(wire)).toEqual(V2);
41
+ expect(encodeDriftSpec(decodeDriftSpec(wire)!)).toBe(wire);
42
+ expect(JSON.parse(wire).v).toBe(2);
43
+ });
44
+
45
+ it('encodes v1 input as v2', () => {
46
+ const spec = decodeDriftSpec('{"v":1,"seed":7,"tone":"auto","speed":2}')!;
47
+ expect(JSON.parse(encodeDriftSpec(spec))).toMatchObject({ v: 2, style: 'silk', seed: 7 });
48
+ });
49
+
50
+ it('keeps the largest spec under the storage cap', () => {
51
+ const big = randomDriftSpec({ ...V2, seed: 0xffffffff, scale: 0.33, str: 0.33, angle: -179 });
52
+ expect(encodeDriftSpec({ ...big, seed: 0xffffffff }).length).toBeLessThan(DRIFT_SPEC_MAX);
53
+ });
54
+
55
+ it('reads garbage as off (null), never a throw', () => {
56
+ for (const bad of [
57
+ undefined,
58
+ null,
59
+ 42,
60
+ '',
61
+ ' ',
62
+ 'not json',
63
+ '[]',
64
+ 'null',
65
+ '{"v":2}',
66
+ '{"v":3,"seed":1}',
67
+ '{"v":2,"seed":-1}',
68
+ '{"v":2,"seed":1.5}',
69
+ '{"v":1,"seed":1,"tone":"neon","speed":2}',
70
+ '{"v":1,"seed":1,"tone":"auto","speed":-1}',
71
+ 'x'.repeat(DRIFT_SPEC_MAX + 1),
72
+ ]) {
73
+ expect(decodeDriftSpec(bad)).toBeNull();
74
+ }
75
+ });
76
+
77
+ it('clamps out-of-range numbers and unknown enums to the defaults', () => {
78
+ const spec = decodeDriftSpec(
79
+ '{"v":2,"seed":1,"speed":99,"style":"plasma","str":5,"angle":720}',
80
+ );
81
+ expect(spec).toMatchObject({ speed: 6, style: 'mesh', str: 1, angle: 180 });
82
+ });
83
+ });
@@ -0,0 +1,165 @@
1
+ /**
2
+ * The stored form of the animated background (Drift), and the ONE codec for
3
+ * it. The brain validates with it (projectNeatBackground), the /s reader and
4
+ * the owner app decode with it (@mantle/share-ui/drift re-exports it), so a
5
+ * spec the brain keeps is exactly a spec every renderer paints.
6
+ *
7
+ * It lives here, not in share-ui, because the brain's read projections are in
8
+ * this package and share-ui depends on it, never the other way round. Pure
9
+ * data and zero DOM: the engine and the theme maths stay in share-ui.
10
+ *
11
+ * Version 2 of the Neat spec. v1 (`{v:1, seed, tone, speed}`, everything a
12
+ * brain stored before Drift, and the fresh-install default) still decodes,
13
+ * upgraded to the silk style, the closest look. Encoding is always v2.
14
+ *
15
+ * Kept compact (short keys, fixed order) so the canonical encoding of the
16
+ * largest valid spec stays well under the 200-char storage cap, and equal
17
+ * specs compare equal as strings.
18
+ */
19
+
20
+ /** Push the wash below the page surface ('darker'), above it ('lighter'), or
21
+ * follow the mode: dark mode darkens, light mode lightens ('auto'). */
22
+ export type DriftTone = 'auto' | 'darker' | 'lighter';
23
+
24
+ /** Which tokens feed the palette: the three brand roles, or the five chart
25
+ * colours (more hues, more variety, still per-theme). */
26
+ export type DriftPaletteSource = 'brand' | 'chart';
27
+
28
+ /**
29
+ * The shape family. Each is its own fragment shader in the engine.
30
+ *
31
+ * - `mesh` soft colour fields drifting past each other. The calmest; the
32
+ * safest behind dense content.
33
+ * - `silk` a lit, folded sheet: the Neat look, with real specular depth.
34
+ * - `aurora` curtains of light with a hard foot and a long soft tail.
35
+ * - `dunes` stacked horizon layers, each casting a soft shadow on the one
36
+ * behind it. Rotate it for diagonal or vertical strata.
37
+ * - `marble` recursive domain warp: liquid, smoke, agate.
38
+ */
39
+ export type DriftStyle = 'mesh' | 'silk' | 'aurora' | 'dunes' | 'marble';
40
+
41
+ export const DRIFT_STYLES: readonly DriftStyle[] = ['mesh', 'silk', 'aurora', 'dunes', 'marble'];
42
+ export const DRIFT_TONES: readonly DriftTone[] = ['auto', 'darker', 'lighter'];
43
+ export const DRIFT_PALETTES: readonly DriftPaletteSource[] = ['brand', 'chart'];
44
+
45
+ export type DriftSpec = {
46
+ v: 2;
47
+ seed: number;
48
+ tone: DriftTone;
49
+ /** 0 (still) to {@link DRIFT_SPEED_MAX}, the same range as the Neat spec. */
50
+ speed: number;
51
+ style: DriftStyle;
52
+ pal: DriftPaletteSource;
53
+ /** How far the colours stray from the page surface, 0 to 1. */
54
+ str: number;
55
+ scale: number;
56
+ warp: number;
57
+ soft: number;
58
+ light: number;
59
+ grain: number;
60
+ angle: number;
61
+ };
62
+
63
+ export const DRIFT_SPEED_MAX = 6;
64
+ /** Storage cap, shared with the brain's PUT route and read projection. */
65
+ export const DRIFT_SPEC_MAX = 200;
66
+
67
+ export const DRIFT_SPEC_DEFAULTS: Omit<DriftSpec, 'seed'> = {
68
+ v: 2,
69
+ tone: 'auto',
70
+ speed: 2,
71
+ style: 'mesh',
72
+ pal: 'brand',
73
+ str: 0.55,
74
+ scale: 1,
75
+ warp: 0.5,
76
+ soft: 0.6,
77
+ light: 0.5,
78
+ grain: 0.12,
79
+ angle: 0,
80
+ };
81
+
82
+ const round2 = (n: number) => Math.round(n * 100) / 100;
83
+
84
+ const num = (v: unknown, lo: number, hi: number, fallback: number) =>
85
+ typeof v === 'number' && Number.isFinite(v) ? round2(Math.min(hi, Math.max(lo, v))) : fallback;
86
+
87
+ const oneOf = <T extends string>(list: readonly T[], v: unknown, fallback: T): T =>
88
+ (list as readonly unknown[]).includes(v) ? (v as T) : fallback;
89
+
90
+ function normalize(o: Partial<DriftSpec> & { seed: number }): DriftSpec {
91
+ const d = DRIFT_SPEC_DEFAULTS;
92
+ return {
93
+ v: 2,
94
+ seed: o.seed >>> 0,
95
+ tone: oneOf(DRIFT_TONES, o.tone, d.tone),
96
+ speed: num(o.speed, 0, DRIFT_SPEED_MAX, d.speed),
97
+ style: oneOf(DRIFT_STYLES, o.style, d.style),
98
+ pal: oneOf(DRIFT_PALETTES, o.pal, d.pal),
99
+ str: num(o.str, 0, 1, d.str),
100
+ scale: num(o.scale, 0.25, 4, d.scale),
101
+ warp: num(o.warp, 0, 1, d.warp),
102
+ soft: num(o.soft, 0, 1, d.soft),
103
+ light: num(o.light, 0, 1, d.light),
104
+ grain: num(o.grain, 0, 1, d.grain),
105
+ angle: Math.round(num(o.angle, -180, 180, d.angle)),
106
+ };
107
+ }
108
+
109
+ /** Canonical wire encoding: always v2, fixed key order, rounded numbers. */
110
+ export function encodeDriftSpec(spec: DriftSpec): string {
111
+ const s = normalize(spec);
112
+ return JSON.stringify({
113
+ v: 2,
114
+ seed: s.seed,
115
+ tone: s.tone,
116
+ speed: s.speed,
117
+ style: s.style,
118
+ pal: s.pal,
119
+ str: s.str,
120
+ scale: s.scale,
121
+ warp: s.warp,
122
+ soft: s.soft,
123
+ light: s.light,
124
+ grain: s.grain,
125
+ angle: s.angle,
126
+ });
127
+ }
128
+
129
+ /**
130
+ * Parse and shape-check a stored value. Garbage reads as null (off), never a
131
+ * throw. Accepts v2, and v1 (the Neat spec) upgraded to the silk style.
132
+ * Out-of-range numbers clamp rather than reject, so a spec saved by a newer
133
+ * client with a wider range still paints; an unknown version is off.
134
+ */
135
+ export function decodeDriftSpec(raw: unknown): DriftSpec | null {
136
+ if (typeof raw !== 'string') return null;
137
+ const t = raw.trim();
138
+ if (t.length === 0 || t.length > DRIFT_SPEC_MAX) return null;
139
+ let parsed: unknown;
140
+ try {
141
+ parsed = JSON.parse(t);
142
+ } catch {
143
+ return null;
144
+ }
145
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
146
+ const o = parsed as Record<string, unknown>;
147
+ if (typeof o.seed !== 'number' || !Number.isInteger(o.seed) || o.seed < 0 || o.seed > 0xffffffff)
148
+ return null;
149
+ if (o.v === 1) {
150
+ if (!(DRIFT_TONES as readonly unknown[]).includes(o.tone)) return null;
151
+ if (typeof o.speed !== 'number' || !Number.isFinite(o.speed) || o.speed < 0) return null;
152
+ return normalize({ seed: o.seed, tone: o.tone as DriftTone, speed: o.speed, style: 'silk' });
153
+ }
154
+ if (o.v !== 2) return null;
155
+ return normalize(o as Partial<DriftSpec> & { seed: number });
156
+ }
157
+
158
+ /** A fresh seed over the given look (the generator's "Generate"). */
159
+ export function randomDriftSpec(prev?: Partial<DriftSpec>): DriftSpec {
160
+ return normalize({
161
+ ...DRIFT_SPEC_DEFAULTS,
162
+ ...prev,
163
+ seed: Math.floor(Math.random() * 0xffffffff),
164
+ });
165
+ }
@@ -12,6 +12,8 @@ import {
12
12
  mediaFileId,
13
13
  stripInlineMediaImages,
14
14
  drawNodeId,
15
+ presentNodeId,
16
+ presentPosterSrc,
15
17
  } from './markdown-refs';
16
18
 
17
19
  describe('mediaFileId', () => {
@@ -119,6 +121,19 @@ describe('markdownRefs', () => {
119
121
  });
120
122
  });
121
123
 
124
+ describe('present: references', () => {
125
+ it('extracts an embedded canvas as a present-typed ref, and builds its snapshot path', () => {
126
+ const refs = markdownRefs('![Deck](present:c-1) ![b](draw:d1)');
127
+ expect(refs).toEqual([
128
+ { scheme: 'present', id: 'c-1', nodeType: 'present' },
129
+ { scheme: 'draw', id: 'd1', nodeType: 'draw' },
130
+ ]);
131
+ expect(presentNodeId('present:c-1')).toBe('c-1');
132
+ expect(presentNodeId('draw:c-1')).toBeNull();
133
+ expect(presentPosterSrc('a/../b?x')).toBe('/api/presents/a%2F..%2Fb%3Fx/poster');
134
+ });
135
+ });
136
+
122
137
  describe('draw: references', () => {
123
138
  it('extracts an embedded drawing as a draw-typed ref', () => {
124
139
  const refs = markdownRefs('Here is the plan:\n\n![Architecture](draw:abc-123)\n');
@@ -8,6 +8,7 @@
8
8
  * [Folder index](folder:<id>) a live list of a folder's pages (`folder:here`
9
9
  * for the page's own folder)
10
10
  * ![alt](draw:<draw-id>) an embedded drawing
11
+ * ![Title](present:<id>) an embedded Present canvas, as its snapshot
11
12
  * [Label](mention:<ref>:<id>) a mention chip
12
13
  *
13
14
  * Kept here, alone, with **no dependencies**, because two converters read these
@@ -43,6 +44,23 @@ export const FOLDER_HERE = 'here';
43
44
  * snapshot, so editing the drawing updates every page that embeds it. */
44
45
  export const DRAW_HREF = /^draw:([^\s]+)$/;
45
46
 
47
+ /** `present:<present-id>`, a Present canvas embedded as its snapshot (the
48
+ * poster its latest look drew). A LIVE reference like `draw:`: the page
49
+ * shows the canvas's current poster, and a reader who may read the canvas
50
+ * opens the canvas itself from it. */
51
+ export const PRESENT_HREF = /^present:([^\s]+)$/;
52
+
53
+ /** The canvas id behind a `present:` href, or null for any other href. */
54
+ export function presentNodeId(href: string | undefined | null): string | null {
55
+ return PRESENT_HREF.exec(href ?? '')?.[1] ?? null;
56
+ }
57
+
58
+ /** The scope-gated serve path for a canvas's snapshot, the one place it is
59
+ * spelled out for markdown conversion (encoded, as drawRawSrc). */
60
+ export function presentPosterSrc(nodeId: string): string {
61
+ return `/api/presents/${encodeURIComponent(nodeId)}/poster`;
62
+ }
63
+
46
64
  /** The draw node id behind a `draw:` href, or null for any other href. */
47
65
  export function drawNodeId(href: string | undefined | null): string | null {
48
66
  return DRAW_HREF.exec(href ?? '')?.[1] ?? null;
@@ -97,6 +115,7 @@ const SCHEME_NODE_TYPE = {
97
115
  media: 'file',
98
116
  page: 'page',
99
117
  draw: 'draw',
118
+ present: 'present',
100
119
  folder: 'branch',
101
120
  } as const;
102
121
 
@@ -104,7 +123,7 @@ const SCHEME_NODE_TYPE = {
104
123
  * the id it points at, and the node type that scheme requires (unset ⇒ any
105
124
  * node). `nodeType` is what makes a wrong-type reference reportable. */
106
125
  export type MarkdownRef = {
107
- scheme: 'media' | 'page' | 'mention' | 'draw' | 'folder';
126
+ scheme: 'media' | 'page' | 'mention' | 'draw' | 'present' | 'folder';
108
127
  id: string;
109
128
  nodeType?: (typeof SCHEME_NODE_TYPE)[keyof typeof SCHEME_NODE_TYPE];
110
129
  };
@@ -136,6 +155,10 @@ export function markdownRefs(source: string | undefined | null): MarkdownRef[] {
136
155
  if (page?.[1]) ref = { scheme: 'page', id: page[1], nodeType: SCHEME_NODE_TYPE.page };
137
156
  const draw = DRAW_HREF.exec(href);
138
157
  if (draw?.[1]) ref = { scheme: 'draw', id: draw[1], nodeType: SCHEME_NODE_TYPE.draw };
158
+ const present = PRESENT_HREF.exec(href);
159
+ if (present?.[1]) {
160
+ ref = { scheme: 'present', id: present[1], nodeType: SCHEME_NODE_TYPE.present };
161
+ }
139
162
  // A Folder index names a folder row; `folder:here` names none.
140
163
  const folder = FOLDER_HREF.exec(href);
141
164
  if (folder?.[1] && folder[1] !== FOLDER_HERE) {
@@ -35,6 +35,7 @@ import {
35
35
  MEDIA_HREF,
36
36
  PAGE_HREF,
37
37
  DRAW_HREF,
38
+ PRESENT_HREF,
38
39
  FOLDER_HREF,
39
40
  FOLDER_HERE,
40
41
  } from './markdown-refs';
@@ -269,15 +270,19 @@ function paragraphAndImages(tokens: Tok[] | undefined): PMNode[] {
269
270
  // ![alt](draw:<drawId>) → an embedded drawing, which is still an IMAGE
270
271
  // node (block-level picture with alt text) — only the bytes come from a
271
272
  // drawing's committed snapshot instead of an uploaded file, so the whole
272
- // image pipeline carries it. Anything else is a plain URL image.
273
+ // image pipeline carries it. ![Title](present:<id>) is a canvas's
274
+ // snapshot, the same way. Anything else is a plain URL image.
273
275
  const media = MEDIA_HREF.exec(t.href ?? '');
274
276
  const draw = DRAW_HREF.exec(t.href ?? '');
277
+ const present = PRESENT_HREF.exec(t.href ?? '');
275
278
  out.push(
276
279
  media
277
280
  ? { type: 'image', attrs: { src: null, alt: t.text ?? null, nodeId: media[1]! } }
278
281
  : draw
279
282
  ? { type: 'image', attrs: { src: null, alt: t.text ?? null, drawId: draw[1]! } }
280
- : { type: 'image', attrs: { src: t.href ?? '', alt: t.text ?? null } },
283
+ : present
284
+ ? { type: 'image', attrs: { src: null, alt: t.text ?? null, presentId: present[1]! } }
285
+ : { type: 'image', attrs: { src: t.href ?? '', alt: t.text ?? null } },
281
286
  );
282
287
  } else {
283
288
  buf.push(t);
@@ -79,8 +79,18 @@ describe('readNeatBackground', () => {
79
79
  expect(readNeatBackground(mine)).toBe(mine);
80
80
  });
81
81
 
82
- it('reads garbage as off, never as the default', () => {
82
+ it('keeps a Drift v2 spec, unchanged', () => {
83
+ const v2 =
84
+ '{"v":2,"seed":9,"tone":"auto","speed":2,"style":"aurora","pal":"chart","str":0.4,"scale":1,"warp":0.5,"soft":0.6,"light":0.5,"grain":0.12,"angle":30}';
85
+ expect(readNeatBackground(v2)).toBe(v2);
86
+ });
87
+
88
+ it('reads garbage and unknown versions as off, never as the default', () => {
83
89
  expect(readNeatBackground('{"v":2}')).toBeUndefined();
90
+ expect(readNeatBackground('{"v":3,"seed":1}')).toBeUndefined();
91
+ expect(readNeatBackground('{"v":1,"seed":1,"tone":"neon","speed":2}')).toBeUndefined();
92
+ expect(readNeatBackground('not json')).toBeUndefined();
93
+ expect(readNeatBackground('x'.repeat(201))).toBeUndefined();
84
94
  expect(readNeatBackground(42)).toBeUndefined();
85
95
  });
86
96
  });
@@ -33,6 +33,7 @@ import {
33
33
  type ThinkingEffort,
34
34
  } from './thinking-tiers';
35
35
  import { FRESH_APPEARANCE } from '@mantle/client-types/fresh-appearance';
36
+ import { DRIFT_SPEC_MAX, decodeDriftSpec } from './drift-spec';
36
37
  import {
37
38
  APP_OPENS_MAX,
38
39
  APP_PINS_MAX,
@@ -281,31 +282,24 @@ export function projectBackgrounds(raw: unknown): string | undefined {
281
282
  }
282
283
 
283
284
  /**
284
- * Project a stored `neatBackground` — the whole-surface animated gradient's
285
- * spec, compact JSON `{v:1, seed, tone, speed}`.
285
+ * Project a stored `neatBackground`: the whole-surface animated background's
286
+ * spec (Drift). The key keeps its first name; the value is compact JSON, v2
287
+ * (`{v:2, seed, tone, speed, style, ...}`) or a Neat-era v1
288
+ * (`{v:1, seed, tone, speed}`), which still paints, as silk.
286
289
  *
287
- * Shape-checked only, the projectBackgrounds contract: colours and the full
288
- * shader parameter derivation live in the web layer
289
- * (@mantle/web-ui/neat-background), and the client decodes defensively again
290
- * on read, so a value that survives storage still never reaches WebGL
291
- * unvalidated. The cap is a storage guard — a canonical spec is ~60 chars.
290
+ * Validated by the ONE codec every renderer decodes with
291
+ * (@mantle/content-core/drift-spec), and passed through UNCHANGED when it
292
+ * decodes: a v1 stays v1 on disk and on the wire. An unknown version or
293
+ * garbage reads as unset (off), never a crash. Colours and the shader
294
+ * parameters live in the renderer, which decodes again on read. The cap is a
295
+ * storage guard.
292
296
  */
293
- export const NEAT_BACKGROUND_MAX = 200;
297
+ export const NEAT_BACKGROUND_MAX = DRIFT_SPEC_MAX;
294
298
 
295
299
  export function projectNeatBackground(raw: unknown): string | undefined {
296
300
  if (typeof raw !== 'string') return undefined;
297
301
  const t = raw.trim();
298
- if (!t || t.length > NEAT_BACKGROUND_MAX) return undefined;
299
- try {
300
- const o = JSON.parse(t) as Record<string, unknown>;
301
- if (!o || typeof o !== 'object' || o.v !== 1) return undefined;
302
- if (typeof o.seed !== 'number' || !Number.isInteger(o.seed) || o.seed < 0) return undefined;
303
- if (o.tone !== 'auto' && o.tone !== 'darker' && o.tone !== 'lighter') return undefined;
304
- if (typeof o.speed !== 'number' || !Number.isFinite(o.speed) || o.speed < 0) return undefined;
305
- return t;
306
- } catch {
307
- return undefined;
308
- }
302
+ return decodeDriftSpec(t) ? t : undefined;
309
303
  }
310
304
 
311
305
  /** Project a stored `defaultMode` — the brain's default light/dark mode for