import assert from 'assert'; import * as fs from 'fs/promises'; import * as os from 'os'; import path from 'path'; import { assignNodeIds, stripNodeIds, applyChangeList, parseChangeList, deduplicateInlineScripts, normalizedIndexOf, transformPage, ChangeList, TransformPageArgs, } from '../src/service/transformPage'; import { Builder, BuilderResult, ContextSection } from '../src/builders/types'; // --------------------------------------------------------------------------- // assignNodeIds // --------------------------------------------------------------------------- describe('assignNodeIds', () => { it('assigns sequential data-nid to every element', () => { const html = '

Hello

'; const { html: result, nodeCount } = assignNodeIds(html); assert.ok(result.includes('data-nid="0"')); assert.ok(nodeCount > 0); // Every tag should have an id — count occurrences const ids = result.match(/data-nid="/g); assert.strictEqual(ids?.length, nodeCount); }); it('returns nodeCount matching the number of tags', () => { const html = '
AB
'; const { nodeCount } = assignNodeIds(html); // cheerio wraps in ... so count includes those assert.ok(nodeCount >= 4); // html, head, body, div, span, span = 6 }); it('assigns data-nid to script and style elements', () => { const html = ''; const { html: result, nodeCount } = assignNodeIds(html); // All 6 elements should have ids: html, head, style, script(inline), body, script(src) const ids = result.match(/data-nid="/g); assert.strictEqual(ids?.length, nodeCount); assert.strictEqual(nodeCount, 6); // Verify the style and script tags specifically got ids assert.ok(result.match(/]+data-nid="/), 'style element should have data-nid'); assert.ok(result.match(/]+data-nid="/), 'script element should have data-nid'); }); }); // --------------------------------------------------------------------------- // stripNodeIds // --------------------------------------------------------------------------- describe('stripNodeIds', () => { it('removes all data-nid attributes', () => { const html = '

Hi

'; const result = stripNodeIds(html); assert.ok(!result.includes('data-nid')); assert.ok(result.includes('

Hi

')); }); }); // --------------------------------------------------------------------------- // assignNodeIds -> stripNodeIds roundtrip // --------------------------------------------------------------------------- describe('assignNodeIds -> stripNodeIds roundtrip', () => { it('produces HTML without data-nid attributes', () => { const original = '

Hello

'; const { html: annotated } = assignNodeIds(original); assert.ok(annotated.includes('data-nid')); const stripped = stripNodeIds(annotated); assert.ok(!stripped.includes('data-nid')); assert.ok(stripped.includes('

Hello

')); }); }); // --------------------------------------------------------------------------- // applyChangeList // --------------------------------------------------------------------------- describe('applyChangeList', () => { // Helper: wrap content in a minimal annotated structure const annotated = '' + '

Old text

' + ''; it('applies "update" — replaces innerHTML', () => { const changes: ChangeList = [ { op: 'update', nodeId: '11', html: 'New text' }, ]; const result = applyChangeList(annotated, changes); assert.ok(result.includes('

New text

')); }); it('applies "replace" — replaces outerHTML', () => { const changes: ChangeList = [ { op: 'replace', nodeId: '11', html: 'Replaced' }, ]; const result = applyChangeList(annotated, changes); assert.ok(result.includes('Replaced')); assert.ok(!result.includes('data-nid="11"')); }); it('applies "delete" — removes element', () => { const changes: ChangeList = [ { op: 'delete', nodeId: '11' }, ]; const result = applyChangeList(annotated, changes); assert.ok(!result.includes('data-nid="11"')); assert.ok(!result.includes('Old text')); }); it('applies "insert" with position "append"', () => { const changes: ChangeList = [ { op: 'insert', parentId: '10', position: 'append', html: 'Appended' }, ]; const result = applyChangeList(annotated, changes); assert.ok(result.includes('Appended')); }); it('applies "insert" with position "prepend"', () => { const changes: ChangeList = [ { op: 'insert', parentId: '10', position: 'prepend', html: 'Prepended' }, ]; const result = applyChangeList(annotated, changes); // Prepended element should appear before the

const prependIdx = result.indexOf('Prepended'); const pIdx = result.indexOf('

'); assert.ok(prependIdx < pIdx); }); it('applies "insert" with position "before"', () => { const changes: ChangeList = [ { op: 'insert', parentId: '11', position: 'before', html: 'Before' }, ]; const result = applyChangeList(annotated, changes); const beforeIdx = result.indexOf('Before'); const pIdx = result.indexOf('

'); assert.ok(beforeIdx < pIdx); }); it('applies "insert" with position "after"', () => { const changes: ChangeList = [ { op: 'insert', parentId: '11', position: 'after', html: 'After' }, ]; const result = applyChangeList(annotated, changes); const afterIdx = result.indexOf('After'); const pIdx = result.indexOf('

'); assert.ok(afterIdx > pIdx); }); it('warns but does not throw on missing node for update/replace/delete', () => { const changes: ChangeList = [ { op: 'update', nodeId: '999', html: 'Ghost' }, ]; // Should not throw const result = applyChangeList(annotated, changes); assert.ok(!result.includes('Ghost')); }); it('warns but does not throw on missing parent for insert', () => { const changes: ChangeList = [ { op: 'insert', parentId: '999', position: 'append', html: 'Fail' }, ]; // Should not throw — warns and skips const result = applyChangeList(annotated, changes); assert.ok(!result.includes('Fail')); assert.ok(result.includes('Old text')); // original content preserved }); it('applies "style-element" — sets style attribute on unlocked element', () => { const changes: ChangeList = [ { op: 'style-element', nodeId: '11', style: 'color: red; font-size: 16px' }, ]; const result = applyChangeList(annotated, changes); assert.ok(result.includes('style="color: red; font-size: 16px"')); assert.ok(result.includes('data-nid="11"')); }); it('skips "style-element" on a data-locked element', () => { const lockedHtml = '' + '

Locked text

' + ''; const changes: ChangeList = [ { op: 'style-element', nodeId: '11', style: 'color: red' }, ]; const result = applyChangeList(lockedHtml, changes); assert.ok(!result.includes('style="color: red"')); }); it('warns but does not throw on missing node for style-element', () => { const changes: ChangeList = [ { op: 'style-element', nodeId: '999', style: 'color: red' }, ]; const result = applyChangeList(annotated, changes); assert.ok(!result.includes('color: red')); }); it('allows delete of unlocked child inside a data-locked parent', () => { const lockedParentHtml = '' + '
' + '

Child message

' + '

Another child

' + '
'; const changes: ChangeList = [ { op: 'delete', nodeId: '11' }, ]; const result = applyChangeList(lockedParentHtml, changes); assert.ok(!result.includes('Child message')); assert.ok(result.includes('Another child')); }); it('blocks delete of element that itself has data-locked', () => { const lockedHtml = '' + '

Locked

' + ''; const changes: ChangeList = [ { op: 'delete', nodeId: '11' }, ]; const result = applyChangeList(lockedHtml, changes); assert.ok(result.includes('Locked')); }); it('allows replace of unlocked child inside a data-locked parent', () => { const lockedParentHtml = '' + '
' + '

Old child

' + '
'; const changes: ChangeList = [ { op: 'replace', nodeId: '11', html: 'New child' }, ]; const result = applyChangeList(lockedParentHtml, changes); assert.ok(result.includes('New child')); assert.ok(!result.includes('Old child')); }); it('warns but does not throw on missing node for replace', () => { const changes: ChangeList = [ { op: 'replace', nodeId: '999', html: 'Ghost' }, ]; const result = applyChangeList(annotated, changes); assert.ok(!result.includes('Ghost')); }); it('skips replace on a data-locked element', () => { const lockedHtml = '' + '

Locked

' + ''; const changes: ChangeList = [ { op: 'replace', nodeId: '11', html: 'Replaced' }, ]; const result = applyChangeList(lockedHtml, changes); assert.ok(result.includes('Locked')); assert.ok(!result.includes('Replaced')); }); it('warns but does not throw on missing node for delete', () => { const changes: ChangeList = [ { op: 'delete', nodeId: '999' }, ]; const result = applyChangeList(annotated, changes); // Should not throw, original content preserved assert.ok(result.includes('Old text')); }); it('warns but does not throw on unknown insert position', () => { const changes = [ { op: 'insert', parentId: '10', position: 'sideways', html: 'Oops' }, ] as unknown as ChangeList; // Should not throw — warns and skips const result = applyChangeList(annotated, changes); assert.ok(!result.includes('Oops')); assert.ok(result.includes('Old text')); // original content preserved }); it('throws on unknown op', () => { const changes = [{ op: 'explode', nodeId: '10' }] as unknown as ChangeList; assert.throws(() => applyChangeList(annotated, changes), /Unknown change op/); }); }); // --------------------------------------------------------------------------- // parseChangeList // --------------------------------------------------------------------------- describe('parseChangeList', () => { it('parses raw JSON array', () => { const input = '[{"op":"update","nodeId":"1","html":"Hi"}]'; const result = parseChangeList(input); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].op, 'update'); }); it('parses markdown-fenced JSON', () => { const input = '```json\n[{"op":"delete","nodeId":"2"}]\n```'; const result = parseChangeList(input); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].op, 'delete'); }); it('extracts JSON array embedded in text', () => { const input = 'Here are the changes:\n[{"op":"delete","nodeId":"3"}]\nDone.'; const result = parseChangeList(input); assert.strictEqual(result.length, 1); }); it('throws on invalid JSON', () => { assert.throws(() => parseChangeList('not json at all'), /Failed to parse/); }); it('throws on non-array JSON', () => { assert.throws(() => parseChangeList('{"op":"update"}'), /Failed to parse/); }); }); // --------------------------------------------------------------------------- // injectError — REMOVED (iframe model: errors reported via shell postMessage) // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // deduplicateInlineScripts // --------------------------------------------------------------------------- describe('deduplicateInlineScripts', () => { it('removes the first of two exact-duplicate inline scripts', () => { const script = `let count = 0;\nlet name = "test";\nfunction init() {}\nfunction render() {}`; const html = ``; const result = deduplicateInlineScripts(html); // Should keep exactly one script const matches = result.match(/`; const result = deduplicateInlineScripts(html); const matches = result.match(/`; const result = deduplicateInlineScripts(html); const matches = result.match(/`; const result = deduplicateInlineScripts(html); // Both should be preserved — the id-script is exempt from dedup assert.ok(result.includes('id="app"')); const scriptTags = result.match(/`; const result = deduplicateInlineScripts(html); const matches = result.match(/`; const result = deduplicateInlineScripts(html); const matches = result.match(/`; const result = deduplicateInlineScripts(html); const matches = result.match(/`; const result = deduplicateInlineScripts(html); const matches = result.match(/id="app"/g); assert.strictEqual(matches?.length, 1); assert.ok(result.includes('let x = 2')); assert.ok(!result.includes('let x = 1')); }); it('keeps only the last of three scripts with the same id', () => { const html = ``; const result = deduplicateInlineScripts(html); const matches = result.match(/id="logic"/g); assert.strictEqual(matches?.length, 1); assert.ok(result.includes('let v = 3')); assert.ok(!result.includes('let v = 1')); assert.ok(!result.includes('let v = 2')); }); it('preserves scripts with different ids', () => { const html = ``; const result = deduplicateInlineScripts(html); assert.ok(result.includes('id="alpha"')); assert.ok(result.includes('id="beta"')); assert.ok(result.includes('let a = 1')); assert.ok(result.includes('let b = 2')); }); it('never removes scripts with system ids even if duplicated', () => { const systemIds = ['page-info', 'page-helpers', 'page-script', 'error']; for (const sysId of systemIds) { const html = ``; const result = deduplicateInlineScripts(html); const matches = result.match(new RegExp(`id="${sysId}"`, 'g')); assert.strictEqual(matches?.length, 2, `Expected 2 scripts with id="${sysId}" to be preserved`); } }); }); // --------------------------------------------------------------------------- // normalizedIndexOf // --------------------------------------------------------------------------- describe('normalizedIndexOf', () => { it('returns null when needle is not found', () => { assert.strictEqual(normalizedIndexOf('hello world', 'xyz'), null); }); it('finds exact match and returns correct positions', () => { const result = normalizedIndexOf('let x = 1;', 'x = 1'); assert.ok(result !== null); assert.strictEqual(result.start, 4); assert.strictEqual(result.end, 9); }); it('matches despite whitespace differences', () => { const haystack = 'let x =\n 1;'; const needle = 'x = 1;'; const result = normalizedIndexOf(haystack, needle); assert.ok(result !== null); // Should span from 'x' to end of ';' const matched = haystack.slice(result.start, result.end); assert.ok(matched.includes('x')); assert.ok(matched.includes('1;')); }); it('handles newlines vs spaces', () => { const haystack = 'function foo() {\n return 1;\n}'; const needle = 'foo() { return 1; }'; const result = normalizedIndexOf(haystack, needle); assert.ok(result !== null); }); }); // --------------------------------------------------------------------------- // applyChangeList — search-replace / search-insert ops // --------------------------------------------------------------------------- describe('applyChangeList — search-replace / search-insert ops', () => { const scriptHtml = '' + '' + ''; it('search-replace replaces exact text match', () => { const changes: ChangeList = [ { op: 'search-replace', nodeId: '5', search: 'let b = 2;', replace: 'let b = 20;' }, ]; const result = applyChangeList(scriptHtml, changes); assert.ok(result.includes('let b = 20;')); assert.ok(!result.includes('let b = 2;')); assert.ok(result.includes('let a = 1;')); assert.ok(result.includes('let c = 3;')); }); it('search-replace with empty replace deletes text', () => { const changes: ChangeList = [ { op: 'search-replace', nodeId: '5', search: 'let c = 3;\n', replace: '' }, ]; const result = applyChangeList(scriptHtml, changes); assert.ok(!result.includes('let c = 3;')); assert.ok(result.includes('let b = 2;')); assert.ok(result.includes('let d = 4;')); }); it('search-replace falls back to normalized match', () => { // Script has single spaces, search has different whitespace const html = '' + '' + ''; const changes: ChangeList = [ { op: 'search-replace', nodeId: '5', search: 'function foo() { return 1; }', replace: 'function foo() { return 2; }' }, ]; const result = applyChangeList(html, changes); assert.ok(result.includes('return 2;')); }); it('search-replace warns on no match found', () => { const changes: ChangeList = [ { op: 'search-replace', nodeId: '5', search: 'nonexistent text', replace: 'replacement' }, ]; // Should not throw const result = applyChangeList(scriptHtml, changes); // Original content preserved assert.ok(result.includes('let a = 1;')); assert.ok(!result.includes('replacement')); }); it('search-replace works on style blocks', () => { const styleHtml = ''; const changes: ChangeList = [ { op: 'search-replace', nodeId: '3', search: '.b { color: blue; }', replace: '.b { color: purple; }' }, ]; const result = applyChangeList(styleHtml, changes); assert.ok(result.includes('.b { color: purple; }')); assert.ok(!result.includes('color: blue')); }); it('search-insert inserts after matched text', () => { const changes: ChangeList = [ { op: 'search-insert', nodeId: '5', after: 'let b = 2;', content: '\nlet inserted = true;' }, ]; const result = applyChangeList(scriptHtml, changes); assert.ok(result.includes('let inserted = true;')); const idxB = result.indexOf('let b = 2;'); const idxInserted = result.indexOf('let inserted = true;'); const idxC = result.indexOf('let c = 3;'); assert.ok(idxB < idxInserted); assert.ok(idxInserted < idxC); }); it('search-insert warns on no match found', () => { const changes: ChangeList = [ { op: 'search-insert', nodeId: '5', after: 'nonexistent text', content: '\nnew stuff' }, ]; const result = applyChangeList(scriptHtml, changes); assert.ok(result.includes('let a = 1;')); assert.ok(!result.includes('new stuff')); }); it('warns but does not throw on missing node for search ops', () => { const ops: ChangeList = [ { op: 'search-replace', nodeId: '999', search: 'x', replace: 'y' }, { op: 'search-insert', nodeId: '999', after: 'x', content: 'y' }, ]; for (const change of ops) { const result = applyChangeList(scriptHtml, [change]); assert.ok(result.includes('let a = 1;')); } }); }); // --------------------------------------------------------------------------- // transformPage (integration with stub Builder) // --------------------------------------------------------------------------- describe('transformPage', () => { // Minimal page with a viewer-panel and thoughts div const testPage = `

SynthOS: Welcome!

Hello world

`; /** Extract the data-nid for an element identified by a CSS-style attribute (e.g. id="content") from annotated HTML. */ function findNodeId(annotatedHtml: string, idAttr: string): string { // Match a tag that contains both data-nid="X" and the target id, in either order const pattern1 = new RegExp(`data-nid="(\\d+)"[^>]*${idAttr}`); const pattern2 = new RegExp(`${idAttr}[^>]*data-nid="(\\d+)"`); const m = annotatedHtml.match(pattern1) || annotatedHtml.match(pattern2); return m ? m[1] : '99999'; } /** Create a stub builder that calls the given handler to produce a BuilderResult. */ function makeBuilder(handler: (currentPage: ContextSection, additionalSections: ContextSection[], userMessage: string, newBuild: boolean) => Promise): Builder { return { run: handler }; } function makeArgs(builder: Builder, pageState?: string): TransformPageArgs { return { builder, additionalSections: [], pageState: pageState ?? testPage, message: 'Change the content', }; } it('happy path — applies valid change list and returns transformed HTML', async () => { const builder = makeBuilder(async (currentPage) => { const nodeId = findNodeId(currentPage.content, 'id="content"'); return { kind: 'transforms', changes: [{ op: 'update', nodeId, html: 'Updated content' }], }; }); const result = await transformPage(makeArgs(builder)); assert.strictEqual(result.completed, true); assert.ok(result.value); assert.ok(result.value.html.includes('Updated content')); assert.strictEqual(result.value.changeCount, 1); // Should not contain data-nid attributes assert.ok(!result.value.html.includes('data-nid')); }); it('returns errorText when builder returns error (shell displays it)', async () => { const builder = makeBuilder(async () => ({ kind: 'error', error: new Error('API quota exceeded'), })); const result = await transformPage(makeArgs(builder)); assert.strictEqual(result.completed, true); assert.ok(result.value); assert.strictEqual(result.value.errorText, 'API quota exceeded'); assert.ok(!result.value.html.includes('id="error"'), 'error should not be injected into HTML'); assert.strictEqual(result.value.changeCount, -1); }); it('returns replyText when builder returns reply (shell displays it)', async () => { const builder = makeBuilder(async () => ({ kind: 'reply', text: 'I cannot help with that.', })); const result = await transformPage({ ...makeArgs(builder), productName: 'SynthOS', }); assert.strictEqual(result.completed, true); assert.ok(result.value); assert.strictEqual(result.value.replyText, 'I cannot help with that.'); assert.ok(!result.value.html.includes('User:'), 'chat messages should not be injected into HTML'); assert.strictEqual(result.value.changeCount, -1); }); it('handles missing nodes gracefully (no repair pass)', async () => { const builder = makeBuilder(async (currentPage) => { const contentNodeId = findNodeId(currentPage.content, 'id="content"'); return { kind: 'transforms', changes: [ { op: 'update', nodeId: contentNodeId, html: 'First pass change' }, { op: 'update', nodeId: '9999', html: 'Ghost node' }, // will be skipped ], }; }); const result = await transformPage(makeArgs(builder)); assert.strictEqual(result.completed, true); assert.ok(result.value); assert.ok(result.value.html.includes('First pass change')); // changeCount counts all ops, including skipped ones assert.strictEqual(result.value.changeCount, 2); }); it('exercises replace, delete, insert, and style-element ops through pipeline', async () => { const builder = makeBuilder(async (currentPage) => { const contentNodeId = findNodeId(currentPage.content, 'id="content"'); const viewerNodeId = findNodeId(currentPage.content, 'class="viewer-panel"'); return { kind: 'transforms', changes: [ { op: 'replace', nodeId: contentNodeId, html: '

Replaced

' }, { op: 'insert', parentId: viewerNodeId, position: 'append', html: 'Appended' }, { op: 'style-element', nodeId: viewerNodeId, style: 'background: blue' }, ], }; }); const result = await transformPage(makeArgs(builder)); assert.strictEqual(result.completed, true); assert.ok(result.value); assert.ok(result.value.html.includes('Replaced')); assert.ok(result.value.html.includes('Appended')); assert.ok(result.value.html.includes('background: blue')); assert.strictEqual(result.value.changeCount, 3); }); it('skips replace on locked element', async () => { const lockedPage = `

SynthOS: Welcome!

Locked content

`; const builder = makeBuilder(async (currentPage) => { const contentNodeId = findNodeId(currentPage.content, 'id="content"'); return { kind: 'transforms', changes: [{ op: 'replace', nodeId: contentNodeId, html: '

Should fail

' }], }; }); const result = await transformPage(makeArgs(builder, lockedPage)); assert.strictEqual(result.completed, true); assert.ok(result.value!.html.includes('Locked content')); }); it('skips delete on locked element', async () => { const lockedPage = `

SynthOS: Welcome!

Locked

`; const builder = makeBuilder(async (currentPage) => { const contentNodeId = findNodeId(currentPage.content, 'id="content"'); return { kind: 'transforms', changes: [{ op: 'delete', nodeId: contentNodeId }], }; }); const result = await transformPage(makeArgs(builder, lockedPage)); assert.strictEqual(result.completed, true); assert.ok(result.value!.html.includes('Locked')); }); it('skips style-element on locked element', async () => { const lockedPage = `

SynthOS: Welcome!

Styled

`; const builder = makeBuilder(async (currentPage) => { const contentNodeId = findNodeId(currentPage.content, 'id="content"'); return { kind: 'transforms', changes: [{ op: 'style-element', nodeId: contentNodeId, style: 'color: red' }], }; }); const result = await transformPage(makeArgs(builder, lockedPage)); assert.strictEqual(result.completed, true); assert.ok(!result.value!.html.includes('color: red')); }); it('catches exceptions from builder and returns errorText (shell displays it)', async () => { const builder = makeBuilder(async () => { throw new Error('Unexpected builder crash'); }); const result = await transformPage(makeArgs(builder)); assert.strictEqual(result.completed, true); assert.ok(result.value); assert.strictEqual(result.value.errorText, 'Unexpected builder crash'); assert.ok(!result.value.html.includes('id="error"'), 'error should not be injected into HTML'); assert.strictEqual(result.value.changeCount, -1); }); it('detects newBuild when isBuilder is true and only one chat message', async () => { let capturedNewBuild: boolean | undefined; const builder = makeBuilder(async (_cp, _as, _msg, newBuild) => { capturedNewBuild = newBuild; return { kind: 'transforms', changes: [] }; }); await transformPage({ ...makeArgs(builder), isBuilder: true, }); assert.strictEqual(capturedNewBuild, true); }); it('detects existing build when multiple chat messages present', async () => { const multiMessagePage = `

SynthOS: Welcome!

User: Build me a todo app

SynthOS: Here you go!

Content

`; let capturedNewBuild: boolean | undefined; const builder = makeBuilder(async (_cp, _as, _msg, newBuild) => { capturedNewBuild = newBuild; return { kind: 'transforms', changes: [] }; }); await transformPage({ ...makeArgs(builder, multiMessagePage), isBuilder: true, }); assert.strictEqual(capturedNewBuild, false); }); it('applies search-replace through full pipeline', async () => { const pageWithScript = `

SynthOS: Welcome!

Hello

`; const builder = makeBuilder(async (currentPage) => { // The current page should NOT have line numbers assert.ok(!currentPage.content.includes('01:'), 'currentPage should not contain line numbers'); // Find the script node id const scriptNodeId = findNodeId(currentPage.content, 'id="page-script"'); return { kind: 'transforms', changes: [ { op: 'search-replace', nodeId: scriptNodeId, search: 'let count = 0;', replace: 'let count = 42;' }, ], }; }); const result = await transformPage(makeArgs(builder, pageWithScript)); assert.strictEqual(result.completed, true); assert.ok(result.value); // Edit should be applied assert.ok(result.value.html.includes('let count = 42;')); // Node ids should be stripped assert.ok(!result.value.html.includes('data-nid')); assert.strictEqual(result.value.changeCount, 1); }); });