@1agh/maude 0.22.0 → 0.23.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.
Files changed (60) hide show
  1. package/cli/commands/design-link.test.mjs +53 -1
  2. package/cli/commands/hub.test.mjs +10 -9
  3. package/cli/lib/design-link.mjs +154 -7
  4. package/cli/lib/hubs-config.mjs +42 -4
  5. package/package.json +9 -9
  6. package/plugins/design/dev-server/bin/check-runtime-bundles.sh +125 -0
  7. package/plugins/design/dev-server/bin/runtime-health.sh +47 -6
  8. package/plugins/design/dev-server/build.ts +87 -7
  9. package/plugins/design/dev-server/canvas-comment-mount.tsx +384 -0
  10. package/plugins/design/dev-server/canvas-lib.tsx +22 -6
  11. package/plugins/design/dev-server/canvas-shell.tsx +25 -226
  12. package/plugins/design/dev-server/client/app.jsx +37 -15
  13. package/plugins/design/dev-server/collab/awareness-bridge.ts +77 -0
  14. package/plugins/design/dev-server/collab/registry.ts +51 -0
  15. package/plugins/design/dev-server/config.schema.json +20 -0
  16. package/plugins/design/dev-server/context.ts +7 -0
  17. package/plugins/design/dev-server/dist/client.bundle.js +21 -12
  18. package/plugins/design/dev-server/dist/comment-mount.js +1801 -0
  19. package/plugins/design/dev-server/dist/runtime/.min-sizes.json +16 -0
  20. package/plugins/design/dev-server/dist/runtime/lib0_decoding.js +2 -6
  21. package/plugins/design/dev-server/dist/runtime/lib0_encoding.js +2 -6
  22. package/plugins/design/dev-server/dist/runtime/motion.js +4787 -8
  23. package/plugins/design/dev-server/dist/runtime/motion_react.js +9654 -7
  24. package/plugins/design/dev-server/dist/runtime/pixi-js.js +5865 -5469
  25. package/plugins/design/dev-server/dist/runtime/react-dom.js +4 -22
  26. package/plugins/design/dev-server/dist/runtime/react-dom_client.js +5 -23
  27. package/plugins/design/dev-server/dist/runtime/react.js +4 -22
  28. package/plugins/design/dev-server/dist/runtime/react_jsx-dev-runtime.js +4 -22
  29. package/plugins/design/dev-server/dist/runtime/react_jsx-runtime.js +4 -22
  30. package/plugins/design/dev-server/dist/runtime/y-protocols_awareness.js +2 -6
  31. package/plugins/design/dev-server/dist/runtime/y-protocols_sync.js +2 -6
  32. package/plugins/design/dev-server/dist/runtime/yjs.js +2 -6
  33. package/plugins/design/dev-server/dom-selection.ts +156 -0
  34. package/plugins/design/dev-server/hmr-broadcast.ts +51 -20
  35. package/plugins/design/dev-server/input-router.tsx +99 -61
  36. package/plugins/design/dev-server/server.ts +18 -0
  37. package/plugins/design/dev-server/sync/agent.ts +323 -0
  38. package/plugins/design/dev-server/sync/atomic-write.ts +103 -0
  39. package/plugins/design/dev-server/sync/codec.ts +169 -0
  40. package/plugins/design/dev-server/sync/echo-guard.ts +108 -0
  41. package/plugins/design/dev-server/sync/fs-mirror.ts +160 -0
  42. package/plugins/design/dev-server/sync/hubs-config.ts +87 -0
  43. package/plugins/design/dev-server/sync/index.ts +474 -0
  44. package/plugins/design/dev-server/test/collab-awareness-bridge.test.ts +223 -0
  45. package/plugins/design/dev-server/test/comment-mount.test.ts +87 -0
  46. package/plugins/design/dev-server/test/hmr-classify.test.ts +70 -0
  47. package/plugins/design/dev-server/test/sync-agent.test.ts +278 -0
  48. package/plugins/design/dev-server/test/sync-atomic-write.test.ts +63 -0
  49. package/plugins/design/dev-server/test/sync-codec.test.ts +165 -0
  50. package/plugins/design/dev-server/test/sync-echo-guard.test.ts +96 -0
  51. package/plugins/design/dev-server/test/sync-fs-mirror.test.ts +182 -0
  52. package/plugins/design/dev-server/test/sync-hardening.test.ts +520 -0
  53. package/plugins/design/dev-server/test/sync-hubs-config.test.ts +130 -0
  54. package/plugins/design/dev-server/test/sync-runtime.test.ts +285 -0
  55. package/plugins/design/dev-server/test/use-collab.test.ts +0 -0
  56. package/plugins/design/dev-server/use-collab.tsx +157 -13
  57. package/plugins/design/dev-server/use-selection-set.tsx +12 -0
  58. package/plugins/design/dev-server/use-tool-mode.tsx +12 -0
  59. package/plugins/design/templates/_shell.html +15 -5
  60. package/plugins/design/templates/design-system-inspiration/SUB-AGENT-PROMPTS.md +1 -0
@@ -0,0 +1,87 @@
1
+ // comment-mount — shell-owned comment layer. Covers provider dedup (the
2
+ // Maybe* wrappers consume an outer instance instead of double-mounting) and
3
+ // the bundle scope-guard (react/react-dom externalized to the importmap so the
4
+ // comment layer shares the canvas's single React singleton).
5
+
6
+ import { describe, expect, test } from 'bun:test';
7
+ import { join } from 'node:path';
8
+
9
+ import { createElement } from 'react';
10
+ import { renderToStaticMarkup } from 'react-dom/server';
11
+
12
+ import {
13
+ MaybeSelectionSetProvider,
14
+ SelectionSetProvider,
15
+ useSelectionSetOptional,
16
+ } from '../use-selection-set.tsx';
17
+ import { MaybeToolProvider, ToolProvider, useToolMode } from '../use-tool-mode.tsx';
18
+
19
+ describe('comment-mount / MaybeToolProvider dedup', () => {
20
+ function ToolReader() {
21
+ const { tool } = useToolMode();
22
+ return createElement('span', { 'data-tool': tool });
23
+ }
24
+
25
+ test('consumes an OUTER ToolProvider instead of double-mounting', () => {
26
+ // Outer provider seeds tool='comment'. If MaybeToolProvider mounted a
27
+ // fresh provider, the reader would see the default 'move' instead.
28
+ const html = renderToStaticMarkup(
29
+ createElement(
30
+ ToolProvider,
31
+ { initial: 'comment' },
32
+ createElement(MaybeToolProvider, null, createElement(ToolReader))
33
+ )
34
+ );
35
+ expect(html).toContain('data-tool="comment"');
36
+ });
37
+
38
+ test('mounts its OWN ToolProvider when none exists above', () => {
39
+ const html = renderToStaticMarkup(
40
+ createElement(MaybeToolProvider, null, createElement(ToolReader))
41
+ );
42
+ expect(html).toContain('data-tool="move"');
43
+ });
44
+ });
45
+
46
+ describe('comment-mount / MaybeSelectionSetProvider dedup', () => {
47
+ function SelReader() {
48
+ const ctx = useSelectionSetOptional();
49
+ // Tag identity so we can assert a single context instance is shared.
50
+ return createElement('span', { 'data-has-ctx': ctx ? 'yes' : 'no' });
51
+ }
52
+
53
+ test('provides a SelectionSet when none exists above', () => {
54
+ const html = renderToStaticMarkup(
55
+ createElement(MaybeSelectionSetProvider, null, createElement(SelReader))
56
+ );
57
+ expect(html).toContain('data-has-ctx="yes"');
58
+ });
59
+
60
+ test('does not throw when nested inside an existing SelectionSetProvider', () => {
61
+ expect(() =>
62
+ renderToStaticMarkup(
63
+ createElement(
64
+ SelectionSetProvider,
65
+ { postTarget: null },
66
+ createElement(MaybeSelectionSetProvider, null, createElement(SelReader))
67
+ )
68
+ )
69
+ ).not.toThrow();
70
+ });
71
+ });
72
+
73
+ describe('comment-mount / bundle scope-guard', () => {
74
+ test('dist/comment-mount.js externalizes react + exports mountCanvas', async () => {
75
+ const here = join(import.meta.dir, '..');
76
+ const bundle = Bun.file(join(here, 'dist', 'comment-mount.js'));
77
+ expect(await bundle.exists()).toBe(true);
78
+ const src = await bundle.text();
79
+ // mountCanvas is the public entry the shell calls.
80
+ expect(src.includes('mountCanvas')).toBe(true);
81
+ // React must be a BARE import (resolved by _shell.html's importmap), not
82
+ // inlined — a second React instance would break hooks ("invalid hook
83
+ // call") across the canvas module and the comment layer.
84
+ expect(/import[^;]*["']react-dom\/client["']/.test(src)).toBe(true);
85
+ expect(/import[^;]*["']react["']/.test(src)).toBe(true);
86
+ });
87
+ });
@@ -0,0 +1,70 @@
1
+ // Unit test for hmr-broadcast.ts classifyChange().
2
+ //
3
+ // The load-bearing case: a canvas/specimen sibling stylesheet (e.g. motion.css
4
+ // next to motion.tsx) is INLINED into the built module — there is no <link> for
5
+ // the iframe css-swap to target, so it must route to a module reload keyed on
6
+ // the sibling .tsx. Link-mounted CSS (tokens / _components / _layout — no
7
+ // sibling .tsx) keeps the fast css swap. Regression guard for the silent-drop
8
+ // bug (see .ai/logs/rca/hmr-inlined-css-dropped.md).
9
+
10
+ import { describe, expect, test } from 'bun:test';
11
+
12
+ import { classifyChange } from '../hmr-broadcast.ts';
13
+
14
+ describe('classifyChange', () => {
15
+ const noSibling = () => false;
16
+ const hasSibling = () => true;
17
+
18
+ test('sibling-tsx CSS → module reload keyed on the .tsx', () => {
19
+ const msg = classifyChange(
20
+ 'system/x/preview/motion.css',
21
+ (cssRel) => cssRel === 'system/x/preview/motion.css'
22
+ );
23
+ expect(msg?.mode).toBe('module');
24
+ expect(msg?.file).toBe('system/x/preview/motion.tsx');
25
+ expect(msg?.scope).toBe('canvas');
26
+ });
27
+
28
+ test('link-mounted partial CSS (no sibling .tsx) → css swap', () => {
29
+ expect(classifyChange('system/x/preview/_components.css', noSibling)?.mode).toBe('css');
30
+ expect(classifyChange('system/x/preview/_layout.css', noSibling)?.mode).toBe('css');
31
+ expect(classifyChange('system/x/colors_and_type.css', noSibling)?.mode).toBe('css');
32
+ });
33
+
34
+ test('css mode echoes the changed file path', () => {
35
+ const msg = classifyChange('system/x/colors_and_type.css', noSibling);
36
+ expect(msg?.mode).toBe('css');
37
+ expect(msg?.file).toBe('system/x/colors_and_type.css');
38
+ });
39
+
40
+ test('_lib/** → hard reload (no file)', () => {
41
+ const msg = classifyChange('_lib/canvas-lib.tsx', hasSibling);
42
+ expect(msg?.mode).toBe('hard');
43
+ expect(msg?.scope).toBe('lib');
44
+ expect(msg?.file).toBeUndefined();
45
+ });
46
+
47
+ test('.tsx / .jsx / .ts / .js → module reload', () => {
48
+ for (const f of ['ui/Foo.tsx', 'ui/Foo.jsx', 'ui/Foo.ts', 'ui/Foo.js']) {
49
+ expect(classifyChange(f, noSibling)?.mode).toBe('module');
50
+ expect(classifyChange(f, noSibling)?.file).toBe(f);
51
+ }
52
+ });
53
+
54
+ test('.meta.json → meta (not treated as a .json no-op)', () => {
55
+ const msg = classifyChange('ui/Foo.meta.json', noSibling);
56
+ expect(msg?.mode).toBe('meta');
57
+ expect(msg?.file).toBe('ui/Foo.meta.json');
58
+ });
59
+
60
+ test('unrelated extensions → null', () => {
61
+ expect(classifyChange('ui/notes.md', noSibling)).toBeNull();
62
+ expect(classifyChange('assets/logo.svg', noSibling)).toBeNull();
63
+ });
64
+
65
+ test('backslash paths are normalised before classification', () => {
66
+ const msg = classifyChange('system\\x\\preview\\motion.css', () => true);
67
+ expect(msg?.mode).toBe('module');
68
+ expect(msg?.file).toBe('system/x/preview/motion.tsx');
69
+ });
70
+ });
@@ -0,0 +1,278 @@
1
+ // Sync-agent integration tests — Phase 9 Task 4.
2
+ //
3
+ // Uses an in-memory pair of Y.Docs cross-linked via Y.applyUpdate as a stand-in
4
+ // for HocuspocusProvider's transport. The agent under test owns docB; docA
5
+ // represents "another peer talking to the hub". Updates flow:
6
+ //
7
+ // docA → encode → applyUpdate(docB) → agent observes → write to disk
8
+ // disk → onRead → applyFromFs → applyHtmlToDoc(docB) → encode → docA
9
+ //
10
+ // This lets us validate the whole bidi loop, echo prevention, and the
11
+ // 100-event stress scenario from the plan without booting a real hub.
12
+
13
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
14
+ import { tmpdir } from 'node:os';
15
+ import { join } from 'node:path';
16
+
17
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
18
+ import * as Y from 'yjs';
19
+
20
+ import { type CanvasSyncAgent, createCanvasSyncAgent } from '../sync/agent.ts';
21
+ import { Y_SYNC_TYPES, applyHtmlToDoc, htmlFromDoc } from '../sync/codec.ts';
22
+ import { createEchoGuard, hashBytes } from '../sync/echo-guard.ts';
23
+ import { createFsReader } from '../sync/fs-mirror.ts';
24
+
25
+ let dir: string;
26
+ let agent: CanvasSyncAgent;
27
+ let docA: Y.Doc;
28
+ let docB: Y.Doc;
29
+
30
+ function paths() {
31
+ return {
32
+ html: join(dir, 'screen.html'),
33
+ comments: join(dir, '_comments', 'screen.json'),
34
+ annotations: join(dir, 'screen.annotations.svg'),
35
+ };
36
+ }
37
+
38
+ beforeEach(() => {
39
+ dir = mkdtempSync(join(tmpdir(), 'sync-agent-'));
40
+ docA = new Y.Doc();
41
+ docB = new Y.Doc();
42
+ // Mirror docA→docB and docB→docA, ignoring transient origin objects from
43
+ // the transport itself (we use a symbol).
44
+ const TRANSPORT = Symbol('transport');
45
+ docA.on('update', (update: Uint8Array, origin: unknown) => {
46
+ if (origin === TRANSPORT) return;
47
+ Y.applyUpdate(docB, update, TRANSPORT);
48
+ });
49
+ docB.on('update', (update: Uint8Array, origin: unknown) => {
50
+ if (origin === TRANSPORT) return;
51
+ Y.applyUpdate(docA, update, TRANSPORT);
52
+ });
53
+ });
54
+
55
+ afterEach(() => {
56
+ agent?.stop();
57
+ rmSync(dir, { recursive: true, force: true });
58
+ });
59
+
60
+ function makeAgent(extra: { adopt?: boolean; flushMs?: number } = {}): CanvasSyncAgent {
61
+ const a = createCanvasSyncAgent({
62
+ slug: 'screen',
63
+ doc: docB,
64
+ paths: paths(),
65
+ echoGuard: createEchoGuard(),
66
+ flushMs: 0, // synchronous flush; the agent uses queueMicrotask
67
+ ...extra,
68
+ });
69
+ a.start();
70
+ return a;
71
+ }
72
+
73
+ describe('CanvasSyncAgent — hub → disk (Flow B)', () => {
74
+ test('writes HTML to disk when other peer mutates the doc', async () => {
75
+ agent = makeAgent();
76
+ // Other peer types into docA — propagates to docB via the in-memory
77
+ // transport, which our agent observes.
78
+ applyHtmlToDoc(docA, '<button>v1</button>');
79
+ await agent.flush();
80
+
81
+ expect(readFileSync(paths().html, 'utf8')).toBe('<button>v1</button>');
82
+ });
83
+
84
+ test('debounces multiple rapid peer edits into one disk write', async () => {
85
+ agent = makeAgent({ flushMs: 30 });
86
+ for (let i = 0; i < 10; i++) {
87
+ applyHtmlToDoc(docA, `<button>v${i}</button>`);
88
+ }
89
+ await new Promise((res) => setTimeout(res, 80));
90
+
91
+ expect(readFileSync(paths().html, 'utf8')).toBe('<button>v9</button>');
92
+ });
93
+
94
+ test('writes comments JSON when Y.Array changes', async () => {
95
+ agent = makeAgent();
96
+ docA.transact(() => {
97
+ docA.getArray('comments').push([{ id: 'c1', body: 'hello' }]);
98
+ });
99
+ await agent.flush();
100
+
101
+ const written = JSON.parse(readFileSync(paths().comments, 'utf8'));
102
+ expect(written).toEqual([{ id: 'c1', body: 'hello' }]);
103
+ });
104
+
105
+ test('writes annotations SVG when Y.Map.svg changes', async () => {
106
+ agent = makeAgent();
107
+ docA.transact(() => {
108
+ docA.getMap('annotations').set('svg', '<svg>annot</svg>');
109
+ });
110
+ await agent.flush();
111
+
112
+ expect(readFileSync(paths().annotations, 'utf8')).toBe('<svg>annot</svg>');
113
+ });
114
+ });
115
+
116
+ describe('CanvasSyncAgent — disk → hub (Flow A)', () => {
117
+ test('applies disk HTML to doc when applyFromFs is called', () => {
118
+ agent = makeAgent();
119
+ const bytes = new TextEncoder().encode('<div>local-edit</div>');
120
+ const changed = agent.applyFromFs({
121
+ path: paths().html,
122
+ bytes,
123
+ hash: hashBytes(bytes),
124
+ });
125
+ expect(changed).toBe(true);
126
+ expect(htmlFromDoc(docA)).toBe('<div>local-edit</div>');
127
+ });
128
+
129
+ test('parses + applies comments JSON from disk', () => {
130
+ agent = makeAgent();
131
+ const snap = [{ id: 'c2' }];
132
+ const str = `${JSON.stringify(snap, null, 2)}\n`;
133
+ const bytes = new TextEncoder().encode(str);
134
+ agent.applyFromFs({ path: paths().comments, bytes, hash: hashBytes(bytes) });
135
+ expect(docA.getArray('comments').toArray()).toEqual(snap);
136
+ });
137
+
138
+ test('applies annotations SVG from disk', () => {
139
+ agent = makeAgent();
140
+ const bytes = new TextEncoder().encode('<svg>x</svg>');
141
+ agent.applyFromFs({ path: paths().annotations, bytes, hash: hashBytes(bytes) });
142
+ expect(docA.getMap<string>('annotations').get('svg')).toBe('<svg>x</svg>');
143
+ });
144
+
145
+ test('drops the fs-watch echo of its own atomic write', async () => {
146
+ agent = makeAgent();
147
+ // Peer edits → agent writes to disk → echo guard recorded.
148
+ applyHtmlToDoc(docA, '<button>hi</button>');
149
+ await agent.flush();
150
+
151
+ // Simulate the fs.watch firing for the path we just wrote.
152
+ const bytes = readFileSync(paths().html);
153
+ const u8 = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
154
+ const changed = agent.applyFromFs({
155
+ path: paths().html,
156
+ bytes: u8,
157
+ hash: hashBytes(u8),
158
+ });
159
+
160
+ expect(changed).toBe(false);
161
+ });
162
+ });
163
+
164
+ describe('CanvasSyncAgent — cold start reconciliation', () => {
165
+ test('hub-wins (default): overwrites disk when doc differs', async () => {
166
+ // Local disk has stale content.
167
+ writeFileSync(paths().html, '<old>');
168
+ // Hub state arrives via docA (propagated to docB before reconcile runs).
169
+ applyHtmlToDoc(docA, '<new>');
170
+
171
+ agent = makeAgent();
172
+ await agent.reconcile();
173
+
174
+ expect(readFileSync(paths().html, 'utf8')).toBe('<new>');
175
+ });
176
+
177
+ test('adopt mode: pushes local disk state up to the doc', async () => {
178
+ writeFileSync(paths().html, '<button>local</button>');
179
+ // Hub has stale content.
180
+ applyHtmlToDoc(docA, '<old-hub>');
181
+
182
+ agent = makeAgent({ adopt: true });
183
+ await agent.reconcile();
184
+
185
+ expect(htmlFromDoc(docA)).toBe('<button>local</button>');
186
+ expect(htmlFromDoc(docB)).toBe('<button>local</button>');
187
+ });
188
+
189
+ test('adopt mode is one-shot — second reconcile is hub-wins', async () => {
190
+ writeFileSync(paths().html, '<button>local-v1</button>');
191
+ agent = makeAgent({ adopt: true });
192
+ await agent.reconcile();
193
+
194
+ // Hub changes the value.
195
+ applyHtmlToDoc(docA, '<button>hub-v2</button>');
196
+
197
+ // Disk reverts to a stale local-only state.
198
+ writeFileSync(paths().html, '<button>local-v3</button>');
199
+ await agent.reconcile();
200
+
201
+ // Hub state won this time.
202
+ expect(htmlFromDoc(docB)).toBe('<button>hub-v2</button>');
203
+ });
204
+
205
+ test('identical disk + doc states: no disk write', async () => {
206
+ writeFileSync(paths().html, '<button>same</button>');
207
+ applyHtmlToDoc(docA, '<button>same</button>');
208
+
209
+ agent = makeAgent();
210
+ let writes = 0;
211
+ const customAgent = createCanvasSyncAgent({
212
+ slug: 'screen',
213
+ doc: docB,
214
+ paths: paths(),
215
+ echoGuard: createEchoGuard(),
216
+ flushMs: 0,
217
+ writer: () => {
218
+ writes++;
219
+ },
220
+ });
221
+ customAgent.start();
222
+ await customAgent.reconcile();
223
+ customAgent.stop();
224
+
225
+ expect(writes).toBe(0);
226
+ });
227
+ });
228
+
229
+ describe('CanvasSyncAgent — stress: 100 rapid disk writes converge with no echo loop', () => {
230
+ test('100-event scenario from plan validate', async () => {
231
+ // Wire up fs-mirror against the temp dir so this looks like the production
232
+ // flow: file writes → fs.watch → fs-mirror debounce → agent.applyFromFs.
233
+ agent = makeAgent({ flushMs: 20 });
234
+
235
+ const reader = createFsReader({
236
+ rootDir: dir,
237
+ quietMs: 15,
238
+ accept: (p) => p.endsWith('.html'),
239
+ onRead: async (evt) => {
240
+ agent.applyFromFs({
241
+ path: join(dir, evt.path),
242
+ bytes: evt.bytes,
243
+ hash: evt.hash,
244
+ });
245
+ },
246
+ });
247
+
248
+ // Track how many times the doc transitioned — should be bounded, no echo
249
+ // loop multiplying it.
250
+ let docUpdates = 0;
251
+ docB.on('update', () => {
252
+ docUpdates++;
253
+ });
254
+
255
+ for (let i = 0; i < 100; i++) {
256
+ writeFileSync(paths().html, `<button>${i}</button>`);
257
+ reader.notify('screen.html');
258
+ }
259
+
260
+ // Let everything settle: reader quiet (15ms), agent flush (20ms) + slack.
261
+ await new Promise((res) => setTimeout(res, 200));
262
+ await reader.flush();
263
+ await agent.flush();
264
+ reader.stop();
265
+
266
+ // Doc + disk + peer all converge on the last write.
267
+ const last = '<button>99</button>';
268
+ expect(htmlFromDoc(docB)).toBe(last);
269
+ expect(htmlFromDoc(docA)).toBe(last);
270
+ expect(readFileSync(paths().html, 'utf8')).toBe(last);
271
+
272
+ // Update count must be bounded — strictly < 100 transitions (debounce did
273
+ // its job) AND < 200 (no echo loop running 2x amplification).
274
+ expect(docUpdates).toBeLessThan(200);
275
+ // Also: it should be > 0 — we DID see real syncs.
276
+ expect(docUpdates).toBeGreaterThan(0);
277
+ });
278
+ });
@@ -0,0 +1,63 @@
1
+ // Atomic-write unit tests — Phase 9 Task 4.
2
+
3
+ import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+
7
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
8
+
9
+ import { atomicWrite } from '../sync/atomic-write.ts';
10
+
11
+ let dir: string;
12
+
13
+ beforeEach(() => {
14
+ dir = mkdtempSync(join(tmpdir(), 'atomic-write-'));
15
+ });
16
+
17
+ afterEach(() => {
18
+ rmSync(dir, { recursive: true, force: true });
19
+ });
20
+
21
+ describe('atomicWrite', () => {
22
+ test('writes UTF-8 string to a new path', () => {
23
+ const p = join(dir, 'a.html');
24
+ atomicWrite(p, '<button>hi</button>');
25
+ expect(readFileSync(p, 'utf8')).toBe('<button>hi</button>');
26
+ });
27
+
28
+ test('writes Uint8Array bytes verbatim', () => {
29
+ const p = join(dir, 'b.html');
30
+ const bytes = new TextEncoder().encode('<div>x</div>');
31
+ atomicWrite(p, bytes);
32
+ expect(readFileSync(p, 'utf8')).toBe('<div>x</div>');
33
+ });
34
+
35
+ test('overwrites existing files atomically (no partial-write window)', () => {
36
+ const p = join(dir, 'c.html');
37
+ writeFileSync(p, 'old');
38
+ atomicWrite(p, 'new');
39
+ expect(readFileSync(p, 'utf8')).toBe('new');
40
+ });
41
+
42
+ test('cleans up the .tmp sidecar after a successful write', () => {
43
+ const p = join(dir, 'd.html');
44
+ atomicWrite(p, 'final');
45
+ const leftovers = readdirSync(dir).filter((f) => f.startsWith('d.html.tmp.'));
46
+ expect(leftovers).toEqual([]);
47
+ });
48
+
49
+ test('rapid sequential writes converge on the last value', () => {
50
+ const p = join(dir, 'e.html');
51
+ for (let i = 0; i < 50; i++) {
52
+ atomicWrite(p, `v${i}`);
53
+ }
54
+ expect(readFileSync(p, 'utf8')).toBe('v49');
55
+ const leftovers = readdirSync(dir).filter((f) => f.startsWith('e.html.tmp.'));
56
+ expect(leftovers).toEqual([]);
57
+ });
58
+
59
+ test('returns the path it wrote', () => {
60
+ const p = join(dir, 'f.html');
61
+ expect(atomicWrite(p, 'x')).toBe(p);
62
+ });
63
+ });
@@ -0,0 +1,165 @@
1
+ // Codec unit tests — Phase 9 Task 4.
2
+ //
3
+ // Verify Y.Doc <-> disk round-trips for the three classes of files the sync
4
+ // agent shuttles: HTML body, comments JSON, annotations SVG.
5
+
6
+ import { describe, expect, test } from 'bun:test';
7
+ import * as Y from 'yjs';
8
+
9
+ import { Y_TYPES } from '../collab/persistence.ts';
10
+ import {
11
+ Y_SYNC_TYPES,
12
+ annotationsFromDoc,
13
+ applyAnnotationsToDoc,
14
+ applyCommentsToDoc,
15
+ applyHtmlToDoc,
16
+ commentsFromDoc,
17
+ htmlFromDoc,
18
+ } from '../sync/codec.ts';
19
+
20
+ describe('HTML codec', () => {
21
+ test('htmlFromDoc returns empty string for a fresh doc', () => {
22
+ const doc = new Y.Doc();
23
+ expect(htmlFromDoc(doc)).toBe('');
24
+ });
25
+
26
+ test('applyHtmlToDoc → htmlFromDoc round-trip', () => {
27
+ const doc = new Y.Doc();
28
+ applyHtmlToDoc(doc, '<button>hello</button>');
29
+ expect(htmlFromDoc(doc)).toBe('<button>hello</button>');
30
+ });
31
+
32
+ test('applyHtmlToDoc with identical content is a no-op', () => {
33
+ const doc = new Y.Doc();
34
+ applyHtmlToDoc(doc, '<button>hi</button>');
35
+ let updates = 0;
36
+ doc.on('update', () => {
37
+ updates++;
38
+ });
39
+ const changed = applyHtmlToDoc(doc, '<button>hi</button>');
40
+ expect(changed).toBe(false);
41
+ expect(updates).toBe(0);
42
+ });
43
+
44
+ test('applyHtmlToDoc emits a minimal op via common prefix + suffix', () => {
45
+ const doc = new Y.Doc();
46
+ applyHtmlToDoc(doc, '<button class="cta">Click</button>');
47
+
48
+ // Yjs requires `event.changes.delta` to be read inside the observer.
49
+ let inserts = '';
50
+ let deletes = 0;
51
+ const yText = doc.getText(Y_SYNC_TYPES.html);
52
+ yText.observe((evt) => {
53
+ for (const d of evt.changes.delta) {
54
+ if (typeof d.insert === 'string') inserts += d.insert;
55
+ if (typeof d.delete === 'number') deletes += d.delete;
56
+ }
57
+ });
58
+
59
+ applyHtmlToDoc(doc, '<button class="cta">Tap</button>');
60
+ expect(htmlFromDoc(doc)).toBe('<button class="cta">Tap</button>');
61
+
62
+ // The change is "Click" → "Tap". With shared prefix
63
+ // `<button class="cta">` and shared suffix `</button>`, the delta should
64
+ // only touch the middle.
65
+ expect(inserts).toBe('Tap');
66
+ expect(deletes).toBe('Click'.length);
67
+ });
68
+
69
+ test('applyHtmlToDoc handles complete replace (no shared prefix)', () => {
70
+ const doc = new Y.Doc();
71
+ applyHtmlToDoc(doc, 'aaaa');
72
+ applyHtmlToDoc(doc, 'bbbb');
73
+ expect(htmlFromDoc(doc)).toBe('bbbb');
74
+ });
75
+
76
+ test('applyHtmlToDoc tags transaction with origin', () => {
77
+ const doc = new Y.Doc();
78
+ applyHtmlToDoc(doc, 'seed');
79
+
80
+ let observedOrigin: unknown = 'unset';
81
+ doc.on('update', (_update: Uint8Array, origin: unknown) => {
82
+ observedOrigin = origin;
83
+ });
84
+
85
+ const myOrigin = { id: 'sync-agent' };
86
+ applyHtmlToDoc(doc, 'changed', myOrigin);
87
+ expect(observedOrigin).toBe(myOrigin);
88
+ });
89
+ });
90
+
91
+ describe('Comments codec', () => {
92
+ test('commentsFromDoc returns empty array for a fresh doc', () => {
93
+ expect(commentsFromDoc(new Y.Doc())).toEqual([]);
94
+ });
95
+
96
+ test('applyCommentsToDoc → commentsFromDoc round-trip', () => {
97
+ const doc = new Y.Doc();
98
+ const snap = [{ id: 'c1', body: 'hi' }];
99
+ applyCommentsToDoc(doc, snap);
100
+ expect(commentsFromDoc(doc)).toEqual(snap);
101
+ });
102
+
103
+ test('applyCommentsToDoc with identical content is a no-op', () => {
104
+ const doc = new Y.Doc();
105
+ applyCommentsToDoc(doc, [{ id: 'c1' }]);
106
+ let updates = 0;
107
+ doc.on('update', () => {
108
+ updates++;
109
+ });
110
+ const changed = applyCommentsToDoc(doc, [{ id: 'c1' }]);
111
+ expect(changed).toBe(false);
112
+ expect(updates).toBe(0);
113
+ });
114
+
115
+ test('applyCommentsToDoc replaces existing entries on disk-wins update', () => {
116
+ const doc = new Y.Doc();
117
+ applyCommentsToDoc(doc, [{ id: 'c1' }, { id: 'c2' }]);
118
+ applyCommentsToDoc(doc, [{ id: 'c3' }]);
119
+ expect(commentsFromDoc(doc)).toEqual([{ id: 'c3' }]);
120
+ });
121
+
122
+ test('comments share Y_TYPES.comments name with Phase 6 persistence', () => {
123
+ const doc = new Y.Doc();
124
+ applyCommentsToDoc(doc, [{ id: 'c1' }]);
125
+ // The Phase 6 persistence layer reads from this name directly.
126
+ expect(doc.getArray(Y_TYPES.comments).toArray()).toEqual([{ id: 'c1' }]);
127
+ });
128
+ });
129
+
130
+ describe('Annotations codec', () => {
131
+ test('annotationsFromDoc returns null for a fresh doc', () => {
132
+ expect(annotationsFromDoc(new Y.Doc())).toBeNull();
133
+ });
134
+
135
+ test('applyAnnotationsToDoc → annotationsFromDoc round-trip', () => {
136
+ const doc = new Y.Doc();
137
+ applyAnnotationsToDoc(doc, '<svg></svg>');
138
+ expect(annotationsFromDoc(doc)).toBe('<svg></svg>');
139
+ });
140
+
141
+ test('applyAnnotationsToDoc with null clears the entry', () => {
142
+ const doc = new Y.Doc();
143
+ applyAnnotationsToDoc(doc, '<svg></svg>');
144
+ applyAnnotationsToDoc(doc, null);
145
+ expect(annotationsFromDoc(doc)).toBeNull();
146
+ });
147
+
148
+ test('applyAnnotationsToDoc with identical content is a no-op', () => {
149
+ const doc = new Y.Doc();
150
+ applyAnnotationsToDoc(doc, '<svg></svg>');
151
+ let updates = 0;
152
+ doc.on('update', () => {
153
+ updates++;
154
+ });
155
+ const changed = applyAnnotationsToDoc(doc, '<svg></svg>');
156
+ expect(changed).toBe(false);
157
+ expect(updates).toBe(0);
158
+ });
159
+
160
+ test('annotations share Y_TYPES.annotations name with Phase 5 persistence', () => {
161
+ const doc = new Y.Doc();
162
+ applyAnnotationsToDoc(doc, '<svg>x</svg>');
163
+ expect(doc.getMap<string>(Y_TYPES.annotations).get('svg')).toBe('<svg>x</svg>');
164
+ });
165
+ });