diff options
Diffstat (limited to 'test')
| -rw-r--r-- | test/output.zig | 6 | ||||
| -rw-r--r-- | test/panes.zig | 4 | ||||
| -rw-r--r-- | test/pdf.zig | 50 | ||||
| -rw-r--r-- | test/pdf_sections_bench.zig | 2 | ||||
| -rw-r--r-- | test/web-snapshots/README.md | 7 | ||||
| -rw-r--r-- | test/web-snapshots/touch-fixture.zig | 58 | ||||
| -rw-r--r-- | test/web-snapshots/touch.dump | bin | 96576 -> 0 bytes | |||
| -rw-r--r-- | test/web-snapshots/touch.mjs | 302 | ||||
| -rw-r--r-- | test/web_driver_test.mjs | 134 | ||||
| -rw-r--r-- | test/web_harness.mjs | 190 | ||||
| -rw-r--r-- | test/web_snapshot.mjs | 550 |
11 files changed, 26 insertions, 1277 deletions
diff --git a/test/output.zig b/test/output.zig index 3d92e867..eb4da9b3 100644 --- a/test/output.zig +++ b/test/output.zig @@ -493,7 +493,6 @@ fn configFixture(tmp: *std.testing.TmpDir, content: ?[]const u8, buf: *[4096]u8) } test "Config opens the startup file, and a second Config goes back to its pane" { - if (comptime !pardes.hosted) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [4096]u8 = undefined; @@ -521,7 +520,6 @@ test "Config opens the startup file, and a second Config goes back to its pane" } test "Config with no startup file opens a pane of its name, and Save makes its directory" { - if (comptime !pardes.hosted) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [4096]u8 = undefined; @@ -573,7 +571,6 @@ test "EffectCode lists readable virtual sources used by this backend" { .tui => "/virtual/src/tui/panel_compositor.zig", .gui => "/virtual/shaders/ui.vert.glsl", .macos => "/virtual/src/macos/Sources/ScenePostprocessor.swift", - .web => unreachable, }; try std.testing.expect(std.mem.indexOf(u8, out.content, backend_source) != null); var paths = std.mem.tokenizeScalar(u8, out.content, '\n'); @@ -759,7 +756,6 @@ test "LookNext/LookPrev skips formatted context and selects comment match locati } test "LookNext/LookPrev selects one output location per row and opens nothing" { - if (platform == .web) return; var cwd_buf: [4096]u8 = undefined; var path_buf: [4096]u8 = undefined; const paths = try projectPaths(&cwd_buf, &path_buf); @@ -794,7 +790,6 @@ test "LookNext/LookPrev selects one output location per row and opens nothing" { } test "LookPrev exactly reverses LookNext across output panes and the ring seam" { - if (platform == .web) return; var cwd_buf: [4096]u8 = undefined; var path_buf: [4096]u8 = undefined; const paths = try projectPaths(&cwd_buf, &path_buf); @@ -985,7 +980,6 @@ test "Look ignores slash-only comment markers while retaining root and real path for ([_][]const u8{ "(//),", "///!" }) |marker| try std.testing.expectEqual(@as(?look.Span, null), look.wordSpan(null, marker, ".", &realbuf)); try std.testing.expectEqual(@as(?look.Span, null), look.lineSpan(null, " // ordinary comment", ".", &realbuf)); - if (platform == .web) return; try std.testing.expect(look.resolve(null, "/", ".", &realbuf) == .dir); try std.testing.expect(look.wordSpan(null, "/", ".", &realbuf) != null); var pathbuf: [4096]u8 = undefined; diff --git a/test/panes.zig b/test/panes.zig index 6decd43d..9e4886fb 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -2579,7 +2579,6 @@ const TerminalTests = struct { } test "fresh-shell greeting waits for OSC 133 B input phase" { - if (pardes.platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); defer p.deinit(); const pane = p.panes[0].?; @@ -2614,7 +2613,6 @@ const TerminalTests = struct { } test "the greeting is dropped, never typed later, once something ran or was typed first" { - if (pardes.platform == .web) return; for ([_][]const u8{ // A command ran before the first prompt was seen at rest. "\x1b]133;A;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07\x1b]133;C;aid=pardes\x07out\r\n\x1b]133;D;0;aid=pardes\x07\x1b]133;A;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07", @@ -2638,7 +2636,6 @@ const TerminalTests = struct { } test "fresh-shell commands preserve order and wait for OSC 133 B" { - if (pardes.platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); while (p.nextEffect()) |_| {} // the host has not acknowledged spawn yet @@ -2677,7 +2674,6 @@ const TerminalTests = struct { } test "unmarked fresh shells omit the automatic greeting" { - if (pardes.platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{}); defer p.deinit(); const pane = p.panes[0].?; diff --git a/test/pdf.zig b/test/pdf.zig index 053e45dc..460a5734 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -94,7 +94,7 @@ const PdfLinkTests = struct { } test "PDF links activate embedded URLs and blank internal annotations" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const p = try init(tmp); @@ -112,7 +112,7 @@ const PdfLinkTests = struct { } test "PDF links offer distinct visible destinations and do not duplicate the same URL" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const p = try init(tmp); @@ -152,7 +152,7 @@ const PdfLinkTests = struct { } test "PDF links hover clears on leave page and reload while right drag chooses Look text" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const p = try init(tmp); @@ -201,7 +201,7 @@ test { } test "PDF mounted bytes own their source after the caller frees it" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const source = try pardes.filesystem.readFile(gpa, "docs/design.pdf"); var document = pdf_impl.Document.openBytes(source) catch |err| { @@ -224,7 +224,7 @@ test "PDF mounted bytes own their source after the caller frees it" { } test "explicit OS PDF opens and reloads keep their namespace path" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -264,7 +264,7 @@ test "PDF feature gates keep argv and builtin behavior coherent" { try std.testing.expectEqualStrings("tz", config.leader_path.get(maybe_fit.?).?); try std.testing.expectEqualStrings("ti", config.leader_path.get(maybe_tint.?).?); try std.testing.expectEqualStrings("ts", config.leader_path.get(maybe_sections.?).?); - } else if (platform != .web) { + } else { const p = try Pardes.init(std.testing.allocator, .{ .file = "docs/design.pdf", .cols = 80, @@ -279,7 +279,7 @@ test "PDF feature gates keep argv and builtin behavior coherent" { } test "PdfSections Look follows the exact owning PDF, not an equal path" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -340,7 +340,7 @@ test "SDL PDF raster policy is materially denser than Kitty" { } test "watched PDF reload replaces MuPDF state and preserves the reading view" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); @@ -482,7 +482,7 @@ test "watched PDF reload replaces MuPDF state and preserves the reading view" { } test "PDF reload does not re-center an already revealed matching search" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const fixture = try pardes.filesystem.readFile(gpa, "docs/design.pdf"); defer gpa.free(fixture); @@ -538,7 +538,7 @@ test "PDF reload does not re-center an already revealed matching search" { } test "MuPDF pane renders, navigates, searches, and round-trips its page" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ @@ -881,7 +881,7 @@ test "MuPDF pane renders, navigates, searches, and round-trips its page" { } test "a fling's banded pages show the reader exactly what whole pages would" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; // The contract fast scrolling is allowed to change: HOW pixels are carried // (a strip of a page instead of the page) but never WHICH pixels arrive. So @@ -976,7 +976,7 @@ fn expectNearRows(expected: []const u8, got: []const u8) !void { } test "a tall page is drawn at the display's resolution, in bands that are the whole page's rows" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; // The page is fifteen A4 heights tall. Squeezed whole into the raster // budget it was a third as wide as the pane and blown up, blurred; it is @@ -1145,7 +1145,7 @@ fn copySourceRect( } test "Escape cancels PDF chrome in place, then leaves the pane; Shift-Escape leaves at once" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ @@ -1226,7 +1226,7 @@ test "Escape cancels PDF chrome in place, then leaves the pane; Shift-Escape lea } test "PDF continuous strip renders every intersecting short page" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ @@ -1281,7 +1281,7 @@ test "PDF continuous strip renders every intersecting short page" { } test "PDF tint resolves a theme's null page colors to its chrome" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const p = try Pardes.init(std.testing.allocator, .{ .file = "docs/design.pdf", @@ -1301,7 +1301,7 @@ test "PDF tint resolves a theme's null page colors to its chrome" { } test "PDF tint and tinted theme changes rebuild every visible raster only" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ @@ -1441,7 +1441,7 @@ test "PDF tint and tinted theme changes rebuild every visible raster only" { } test "PDF resize preserves page-relative document position" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ @@ -1487,7 +1487,7 @@ test "PDF resize preserves page-relative document position" { } test "PDF pane geometry change preserves its page-relative position" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ @@ -1544,7 +1544,7 @@ test "PDF pane geometry change preserves its page-relative position" { } test "PDF n/N addresses and reveals distinct MuPDF hits on one page" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ @@ -1644,7 +1644,7 @@ test "PDF n/N addresses and reveals distinct MuPDF hits on one page" { } test "PDF native mouse selection, Look, and highlights share page geometry" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ @@ -2001,7 +2001,7 @@ test "PDF native mouse selection, Look, and highlights share page geometry" { } test "Esc back into a PDF keeps the offset within its page" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -2043,7 +2043,7 @@ test "Esc back into a PDF keeps the offset within its page" { } test "PDF Back and Forward clear selections and land on recorded pages" { - if (!pdf_enabled or platform == .web) return error.SkipZigTest; + if (!pdf_enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .file = "docs/design.pdf", .cols = 80, .rows = 28 }); defer p.deinit(); p.native_images = true; @@ -2070,7 +2070,7 @@ test "PDF Back and Forward clear selections and land on recorded pages" { } test "a PDF's fit and tint, and Collapse, read in its ctl and come back from a Dump" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -2121,7 +2121,7 @@ fn stripAtPlace(p: *Pardes, pane: *pardes.Pane, page: usize, fraction: f64) !f64 } test "a PDF's jumps: Back after a far jump returns to the exact offset, two places on one page are two entries" { - if (!pdf_enabled or platform == .web) return error.SkipZigTest; + if (!pdf_enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .file = jumpPdf(), .cols = 80, .rows = 28 }); defer p.deinit(); p.native_images = true; @@ -2156,7 +2156,7 @@ test "a PDF's jumps: Back after a far jump returns to the exact offset, two plac } test "a PDF's jumps: JumpScope file keeps to the PDF, and a closed PDF reopens at its place" { - if (!pdf_enabled or platform == .web) return error.SkipZigTest; + if (!pdf_enabled) return error.SkipZigTest; // Recent keeps a file by the path it was opened as: a real one here, // as a Look opens one. var cwd_buf: [4096]u8 = undefined; diff --git a/test/pdf_sections_bench.zig b/test/pdf_sections_bench.zig index 4ab4b5c4..30b89e09 100644 --- a/test/pdf_sections_bench.zig +++ b/test/pdf_sections_bench.zig @@ -432,7 +432,7 @@ fn summarize( } /// A host benchmark compiler barrier. MuPDF benchmarks are build-and-run -/// steps, so they never target the freestanding web backend; an empty volatile +/// steps, so they run on a native backend only; an empty volatile /// asm with only the abstract memory clobber is valid on every native backend /// Zig can run here and costs no machine instruction. inline fn compilerBarrier() void { diff --git a/test/web-snapshots/README.md b/test/web-snapshots/README.md deleted file mode 100644 index 999e8fad..00000000 --- a/test/web-snapshots/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Browser interaction tests - -`zig build web-snap` loads `touch.dump` (`python3 -B tools/web_fixture.py <pardes> test/web-snapshots/touch.dump` makes it: a native session on `touch-fixture.zig` at 100x30, theme helix, Verbose off) and runs `touch.mjs` in Chromium. -The fixed source fixture exercises complete keyword styles, touch Look through -the self filesystem, separator resizing, and scrolling without another Look. -Assertions locate current pane geometry; no live project source or author paths -are captured in goldens. diff --git a/test/web-snapshots/touch-fixture.zig b/test/web-snapshots/touch-fixture.zig deleted file mode 100644 index b1d5d81e..00000000 --- a/test/web-snapshots/touch-fixture.zig +++ /dev/null @@ -1,58 +0,0 @@ -pub fn choose(value: u32) []const u8 { - if (value == 42) return "touch fixture"; - return "/virtual/pane/1/body"; -} - -pub const rows = [_]u32{ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 16, - 17, - 18, - 19, - 20, - 21, - 22, - 23, - 24, - 25, - 26, - 27, - 28, - 29, - 30, - 31, - 32, - 33, - 34, - 35, - 36, - 37, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 46, - 47, - 48, - 49, - 50, -};
\ No newline at end of file diff --git a/test/web-snapshots/touch.dump b/test/web-snapshots/touch.dump Binary files differdeleted file mode 100644 index bcc58352..00000000 --- a/test/web-snapshots/touch.dump +++ /dev/null diff --git a/test/web-snapshots/touch.mjs b/test/web-snapshots/touch.mjs deleted file mode 100644 index 6ced7a29..00000000 --- a/test/web-snapshots/touch.mjs +++ /dev/null @@ -1,302 +0,0 @@ -import assert from "node:assert/strict"; - -function tags(frame) { - // This fixture has workspace and column bars in its first two rows; a - // pane's tag text starts after the two-cell marker gutter. - return frame.styleRows.flatMap((cells, y) => y > 1 && /^\s{2}\S/.test(frame.lines[y]) && cells.some((cell) => cell[2] & 128) ? [y] : []); -} - -function pane(frame, name) { - const rows = tags(frame); - const top = rows.find((row) => frame.lines[row].includes(name)); - assert.notEqual(top, undefined, `missing pane ${name}`); - const bottom = rows.find((row) => row > top) ?? frame.rows; - return { top, bottom, lines: frame.lines.slice(top + 1, bottom) }; -} - -// helix's keyword and string/number colours (src/themes/helix.zig). -const KW = 0xd776f9, STR = 0xf3cd7a; - -function styled(frame) { - const source = pane(frame, "touch-fixture.zig"); - for (const [line, word, fg, bold] of [ - ["pub fn choose", "fn", KW, false], - ["pub fn choose", "choose", 0xbdbdbd, false], - ["if (value", "if", KW, false], - ["if (value", "42", STR, false], - ["if (value", '"touch fixture"', STR, false], - ]) { - const row = source.lines.findIndex((text) => text.includes(line)); - assert(row >= 0, `missing source line ${line}`); - const col = source.lines[row].indexOf(word); - for (let x = col; x < col + word.length; x++) { - const style = frame.styleRows[source.top + 1 + row][x]; - assert.equal(style[0], fg, `${word} cell ${x - col} foreground`); - assert.equal(Boolean(style[2] & 1), bold, `${word} cell ${x - col} bold`); - } - } - for (const [row, line] of source.lines.entries()) { - const number = /\b(\d+),/.exec(line); - if (!number) continue; - for (let x = number.index; x < number.index + number[1].length; x++) { - assert.equal(frame.styleRows[source.top + 1 + row][x][0], STR, `row ${row} number foreground`); - } - } -} - -export default async function ({ grid, touch, wait, stable, delay, evaluate, mouse }) { - await stable(100, 5000); - const compactGeometry = await evaluate(`(() => { - const root = document.createElement("div"); - root.className = "pardes"; - root.style.cssText = "position:fixed;left:0;top:0;width:20px;height:40px"; - document.body.append(root); - const memory = new WebAssembly.Memory({initial:1}); - const bytes = new Uint8Array(memory.buffer), data = new DataView(memory.buffer); - for (const [base,count] of [[0,4],[1024,10]]) for(let i=0;i<count;i++) { - const off=base+i*20; bytes[off]=65+i; bytes[off+18]=1; - data.setUint32(off+8,0xffffff,true); data.setUint32(off+12,0x123456,true); - if(base && i<2) data.setUint16(off+16,128,true); - } - const values=[3,2,1,0,0,2,2,42,0,2,1,1]; - const wasm={memory,pardes_gui_tagline_font_percent:()=>50,pardes_frame:()=>4, - pardes_pointer_shape:()=>0,pardes_frame_cols:()=>2,pardes_frame_rows:()=>2, - pardes_frame_ptr:()=>0,pardes_cursor_x:()=>65535,pardes_cursor_y:()=>65535,pardes_cursor_bar:()=>0, - pardes_body_layer_limit:()=>1,pardes_body_layer_value:(_,field)=>values[field],pardes_body_layer_cells:()=>1024}; - const renderer=new pardes.runtime.renderer.constructor(root,wasm); - Object.assign(renderer,{cellWidth:10,cellHeight:20,taglineWidth:5,taglineHeight:10}); - renderer.render(); - const layer=renderer.layerRoot.firstChild, rect=layer.getBoundingClientRect(); - const bands=[...layer.children].slice(0,3).map(node=>{ - const box=node.getBoundingClientRect();return [box.y-rect.y,box.height]; - }); - const cursor=layer.querySelector('.is-cursor'); - renderer.render(); - const result={bands,height:rect.height,clipped:getComputedStyle(layer).overflow, - cursor:cursor?.textContent,cached:renderer.layerRoot.firstChild===layer}; - values[0]=5;values[2]=3;values[6]=4;values[11]=0;values[12]=1;values[13]=1; - renderer.render(); - const borders=()=>[...renderer.layerRoot.querySelectorAll('[data-context-border]')].map(node=>parseFloat(node.style.top)); - result.gapBorders=borders(); - const withGap=renderer.layerRoot.firstChild; - values[12]=0; - renderer.render(); - result.closedGapBorders=borders(); - result.borderChangeInvalidates=renderer.layerRoot.firstChild!==withGap; - // The 13 fields of a tag layer: a one-line tag, its caret on line 0. - const tagValues=[2,2,0,42,1,0,1,1,1,1,0x334455,1,0]; - wasm.pardes_tag_layer_limit=()=>1; - wasm.pardes_tag_layer_value=(_,field)=>tagValues[field]; - wasm.pardes_tag_layer_cells=()=>1024; - wasm.pardes_tagline_band_offset=()=>2560; - renderer.render(); - const tag=renderer.tagRoot.firstChild; - result.tag={left:parseFloat(tag.style.left),top:parseFloat(tag.style.top),width:parseFloat(tag.style.width), - text:tag.textContent,cursor:tag.querySelector('.is-cursor')?.textContent, - gripVisible:renderer.cells[0].style.visibility,covered:renderer.cells[1].style.visibility, - background:tag.style.backgroundColor}; - renderer.render(); - result.tag.cached=renderer.tagRoot.firstChild===tag; - tagValues[10]=0x556677; - renderer.render(); - result.tag.bgInvalidates=renderer.tagRoot.firstChild!==tag; - wasm.pardes_tag_text_inset=()=>3; - tagValues[1]=1;tagValues[4]=3;tagValues[5]=0; - bytes[0]=32;data.setUint32(8,0x778899,true); - renderer.render(); - const columnGrip=renderer.tagRoot.querySelector('[data-tag-grip]'); - const marks=node=>[...node.children].map(mark=>[parseFloat(mark.style.left),parseFloat(mark.style.top),parseFloat(mark.style.width)]); - result.columnMarks=columnGrip ? marks(columnGrip) : []; - tagValues[1]=2;tagValues[5]=1;bytes[40]=32;data.setUint32(48,0x778899,true); - renderer.render(); - result.paneMarks=marks(renderer.tagRoot.querySelector('[data-tag-grip]')); - const inkCenter=canvas=>{ - const pixels=canvas.getContext('2d').getImageData(0,0,canvas.width,canvas.height).data; - let minX=canvas.width,minY=canvas.height,maxX=-1,maxY=-1; - for(let y=0;y<canvas.height;y++) for(let x=0;x<canvas.width;x++) if(pixels[(y*canvas.width+x)*4+3]>8) { - minX=Math.min(minX,x);maxX=Math.max(maxX,x);minY=Math.min(minY,y);maxY=Math.max(maxY,y); - } - return {x:(minX+maxX+1-canvas.width)/2,y:(minY+maxY+1-canvas.height)/2,visible:maxX>=0}; - }; - Object.assign(renderer,{cellWidth:20,cellHeight:40,taglineWidth:10,taglineHeight:28}); - renderer.cells[2].style.font='18px serif'; - renderer.resetGripMetrics(); - result.modeGlyphs=[]; - for(const glyph of ['^','$']) { - bytes[40]=glyph.charCodeAt(0); - renderer.render(); - const canvas=renderer.tagRoot.querySelector('canvas[data-tag-grip]'); - const center=inkCenter(canvas),size=renderer.gripMetrics.size; - renderer.render(); - result.modeGlyphs.push({...center,suppressed:renderer.cells[2].textContent===' ', - reused:renderer.tagRoot.querySelector('canvas[data-tag-grip]')===canvas, - measuredOnce:renderer.gripMetrics.size===size}); - } - const glyphCell=renderer.cells[2]; - glyphCell.style.font='italic 24px serif'; - renderer.resetGripMetrics(); - const italic=renderer.drawGripGlyph(glyphCell,{text:'j',attrs:2},40,40); - result.italic=inkCenter(italic); - const saved=renderer.gripMetrics.values().next().value; - renderer.drawGripGlyph(glyphCell,{text:'j',attrs:2},40,40); - result.italic.cached=renderer.gripMetrics.size===1 && renderer.gripMetrics.values().next().value===saved; - document.fonts.dispatchEvent(new Event('loadingdone')); - result.fontInvalidation=renderer.gripMetrics.size===0 && renderer.gripFonts.size===0 && renderer.tagNodes.size===0; - glyphCell.style.font='italic 30px serif'; - renderer.drawGripGlyph(glyphCell,{text:'j',attrs:2},40,40); - result.fontRemeasured=renderer.gripMetrics.values().next().value!==saved && [...renderer.gripFonts.values()][0].includes('30px'); - root.remove();return result; - })()`); - assert.deepEqual(compactGeometry.bands, [[0,10],[10,20],[30,20]], "compact headers release real height to additional body rows"); - assert.equal(compactGeometry.height,40); - assert.equal(compactGeometry.clipped,"hidden"); - assert.equal(compactGeometry.cursor,"E"); - assert(compactGeometry.cached,"unchanged compact layers reuse their DOM nodes"); - assert.deepEqual(compactGeometry.gapBorders,[20,30],"source gaps and final header have separators, consecutive headers do not"); - assert.deepEqual(compactGeometry.closedGapBorders,[30]); - assert(compactGeometry.borderChangeInvalidates,"separator changes invalidate an otherwise unchanged layer"); - - assert.deepEqual(compactGeometry.tag, {left:10,top:10,width:10,text:"AB",cursor:"B", - gripVisible:"",covered:"hidden",background:"rgb(51, 68, 85)",cached:true,bgInvalidates:true}, - "tag text uses its own columns after a fixed body-width grip, with cursor and cached base background"); - - assert.deepEqual(compactGeometry.columnMarks,[],"column handles have no mark"); - assert.deepEqual(compactGeometry.paneMarks,[[7,33,6],[7,36,6]],"pane handles keep their physical mark geometry"); - - for (const glyph of [...compactGeometry.modeGlyphs,compactGeometry.italic]) { - assert(glyph.visible,"mode indicator has visible rasterized ink"); - assert(Math.abs(glyph.x)<=1 && Math.abs(glyph.y)<=1,`ink center offset ${glyph.x},${glyph.y}`); - } - for (const glyph of compactGeometry.modeGlyphs) assert(glyph.suppressed && glyph.reused && glyph.measuredOnce,"mode ink is drawn once and cached"); - assert(compactGeometry.italic.cached,"asymmetric italic glyph reuses cached ink bounds"); - assert(compactGeometry.fontInvalidation && compactGeometry.fontRemeasured,"font loading clears cached faces and bounds before remeasurement"); - - let frame = await grid(); - assert.equal(tags(frame).length, 1); - styled(frame); - const link = "/virtual/pane/1/body"; - const row = frame.lines.findIndex((text) => text.includes(link)); - const col = frame.lines[row].indexOf(link) + 5; - let finger = await touch("down", 1, col, row, null); - finger = await touch("move", 1, col + 0.2, row + 0.1, finger); - await touch("up", 1, col + 0.2, row + 0.1, finger); - await wait(async () => tags(await grid()).length === 2, 5000, "Look opening the reflected body"); - await stable(100, 5000); - frame = await grid(); - styled(frame); - const reflected = pane(frame, link); - assert(reflected.lines.some((text) => text.includes("pub fn choose"))); - const original = pane(frame, "touch-fixture.zig"); - const sharedRows = Math.min(reflected.lines.length, original.lines.length); - assert(sharedRows >= 6); - assert.deepEqual(reflected.lines.slice(0, sharedRows), original.lines.slice(0, sharedRows), "Look must read the source pane body"); - - const center = Math.floor(frame.cols / 2); - // No rule between panes: the lower one's grip, its tag's gutter, moves it. - const separator = Math.max(original.top, reflected.top); - const distance = original.top < reflected.top ? 4 : -4; - finger = await touch("down", 2, 0, separator, null); - for (let step = 1; step <= 8; step++) { - finger = await touch("move", 2, 0, separator + distance * step / 8, finger); - await delay(20); - } - await touch("up", 2, 0, separator + distance, finger); - await stable(100, 5000); - frame = await grid(); - assert.equal(tags(frame).length, 2); - const resized = pane(frame, "touch-fixture.zig"); - assert(resized.lines.length >= original.lines.length + 3, "separator drag must resize, not scroll the body"); - assert.equal(resized.lines[0], original.lines[0], "resizing must preserve the source viewport"); - styled(frame); - - const beforeScroll = resized.lines[0]; - const reflectedBeforeScroll = pane(frame, link).lines; - const from = resized.bottom - 3; - const to = Math.max(resized.top + 2, from - 7); - finger = await touch("down", 3, center, from, null); - for (let step = 1; step <= 12; step++) { - finger = await touch("move", 3, center, from + (to - from) * step / 12, finger); - await delay(20); - } - await touch("up", 3, center, to, finger); - await stable(100, 5000); - frame = await grid(); - assert.equal(tags(frame).length, 2, "scroll must not also Look"); - const scrolled = pane(frame, "touch-fixture.zig"); - assert.equal(scrolled.top, resized.top, "body scrolling must not resize"); - assert.notEqual(scrolled.lines[0], beforeScroll, "source must scroll"); - assert(Number(scrolled.lines[0].trim().split(/\s+/)[0]) > 1, "scroll advances source line numbers"); - assert.deepEqual(pane(frame, link).lines, reflectedBeforeScroll, "scrolling the source must leave its neighbor alone"); - - const sourceRow = scrolled.top + 2; - const reflectedRow = pane(frame, link).top + 2; - const point = await evaluate(`(() => { - const runtime = pardes.runtime; - const root = runtime.root; - const wasm = runtime.wasm; - const events = []; - const canceled = []; - const pointerDownCanceled = []; - const click = (row) => { - wasm.pardes_mouse(0, 0, 10, row, 0); - wasm.pardes_mouse(0, 1, 10, row, 0); - wasm.pardes_tick(); - runtime.renderer.render(); - }; - click(${sourceRow}); - click(${reflectedRow}); - runtime.wasm = { ...wasm, pardes_mouse: (...args) => { - events.push(args.slice(0, 2)); - wasm.pardes_mouse(...args); - }, pardes_mouse_pixel: (...args) => { - events.push(args.slice(0, 2)); - wasm.pardes_mouse_pixel(...args); - } }; - const observe = (event) => { - if (event.type === "pointerdown") pointerDownCanceled.push(event.defaultPrevented); - else if (event.button === 3 || event.button === 4) canceled.push(event.defaultPrevented); - }; - for (const type of ["pointerdown", "mousedown", "auxclick"]) root.addEventListener(type, observe); - pardes.thumbTest = { wasm, observe, events, canceled, pointerDownCanceled }; - return runtime.cellPoint(10, ${sourceRow}); - })()`); - const thumb = async (button, held = false) => { - const mask = button === "back" ? 8 : 16; - await mouse({ type: "mousePressed", button, buttons: mask | Number(held), ...point, clickCount: 1 }); - await mouse({ type: "mouseReleased", button, buttons: Number(held), ...point, clickCount: 1 }); - await stable(100, 5000); - return (await grid()).cursorY; - }; - try { - const backRow = await thumb("back"); - const forwardRow = await thumb("forward"); - assert(backRow > scrolled.top && backRow < scrolled.bottom, "Back returns to the source pane"); - const reflectedAfter = pane(await grid(), link); - assert(forwardRow > reflectedAfter.top && forwardRow < reflectedAfter.bottom, "Forward returns to the reflected pane"); - - await mouse({ type: "mousePressed", button: "left", buttons: 1, ...point, clickCount: 1 }); - await evaluate("pardes.thumbTest.heldPointer = pardes.runtime.pointer"); - await thumb("back", true); - await thumb("forward", true); - const navigation = await evaluate(`({ - events: pardes.thumbTest.events, - canceled: pardes.thumbTest.canceled, - pointerDownCanceled: pardes.thumbTest.pointerDownCanceled, - keptPointer: pardes.thumbTest.heldPointer !== null && pardes.runtime.pointer === pardes.thumbTest.heldPointer, - })`); - const presses = navigation.events.filter((event) => event[1] === 0 && (event[0] === 8 || event[0] === 9)); - assert.deepEqual(presses, [[8, 0], [9, 0], [8, 0], [9, 0]], "each physical thumb press navigates once"); - assert(!navigation.events.some((event) => event[0] === 1 || (event[0] === 0 && event[1] === 3)), "thumb buttons must not become selection drags or middle clicks"); - assert(navigation.canceled.length >= 4 && navigation.canceled.every(Boolean), "thumb mouse and auxclick events must cancel browser defaults"); - assert(navigation.pointerDownCanceled.every((value) => !value), "mouse pointerdown must permit subsequent mousedown events"); - assert(navigation.keptPointer, "thumb navigation must retain the held selection pointer"); - } finally { - await mouse({ type: "mouseReleased", button: "left", buttons: 0, ...point, clickCount: 1 }); - await evaluate(`(() => { - for (const type of ["pointerdown", "mousedown", "auxclick"]) - pardes.runtime.root.removeEventListener(type, pardes.thumbTest.observe); - pardes.runtime.wasm = pardes.thumbTest.wasm; - delete pardes.thumbTest; - })()`); - } -} diff --git a/test/web_driver_test.mjs b/test/web_driver_test.mjs deleted file mode 100644 index 5484d763..00000000 --- a/test/web_driver_test.mjs +++ /dev/null @@ -1,134 +0,0 @@ -import assert from "node:assert/strict"; -import { spawn } from "node:child_process"; -import { once } from "node:events"; -import net from "node:net"; -import test from "node:test"; -import { Cdp, stopChrome } from "./web_snapshot.mjs"; - -class Socket extends EventTarget { - readyState = WebSocket.OPEN; - sent = []; - closes = 0; - - send(data) { - this.sent.push(JSON.parse(data)); - } - - reply(data) { - this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify(data) })); - } - - close() { - this.readyState = WebSocket.CLOSED; - this.closes += 1; - this.dispatchEvent(new Event("close")); - } -} - -test("CDP replies clear deadlines and preserve protocol errors", { timeout: 2_000 }, async () => { - const socket = new Socket(); - const client = new Cdp(socket, [], 20); - try { - const reply = client.send("Runtime.enable"); - socket.reply({ id: socket.sent[0].id, result: { enabled: true } }); - assert.deepEqual(await reply, { enabled: true }); - const error = assert.rejects(client.send("Runtime.bad"), /Runtime.bad: unknown method/); - socket.reply({ id: socket.sent[1].id, error: { message: "unknown method" } }); - await error; - await new Promise((resolve) => setTimeout(resolve, 40)); - assert.equal(client.pending.size, 0); - assert.equal(client.error, null); - assert.equal(socket.closes, 0); - } finally { - client.close(); - } -}); - -test("CDP timeout rejects all pending and future commands", { timeout: 2_000 }, async () => { - const socket = new Socket(); - const client = new Cdp(socket, [], 20); - await Promise.all([ - assert.rejects(client.send("Runtime.evaluate"), /Runtime.evaluate timed out/), - assert.rejects(client.send("Page.enable"), /Runtime.evaluate timed out/), - ]); - await assert.rejects(client.send("Log.enable"), /Runtime.evaluate timed out/); - assert.equal(client.pending.size, 0); - assert.equal(socket.closes, 1); - assert.equal(socket.sent.length, 2); -}); - -for (const event of ["close", "error"]) { - test(`CDP ${event} immediately rejects pending commands`, { timeout: 2_000 }, async () => { - const socket = new Socket(); - const client = new Cdp(socket, [], 10_000); - const pending = Promise.all([ - assert.rejects(client.send("Runtime.evaluate"), /DevTools connection/), - assert.rejects(client.send("Page.enable"), /DevTools connection/), - ]); - socket.dispatchEvent(new Event(event)); - await pending; - assert.equal(client.pending.size, 0); - assert.equal(socket.closes, 1); - }); -} - -test("CDP rejects malformed replies and synchronous send failures", { timeout: 2_000 }, async () => { - const socket = new Socket(); - const client = new Cdp(socket, []); - const pending = assert.rejects(client.send("Runtime.evaluate"), /invalid DevTools message/); - socket.dispatchEvent(new MessageEvent("message", { data: "not json" })); - await pending; - assert.equal(client.pending.size, 0); - assert.equal(socket.closes, 1); - - const broken = new Socket(); - broken.send = () => { throw new Error("broken transport"); }; - const failed = new Cdp(broken, []); - await assert.rejects(failed.send("Page.enable"), /send DevTools command Page.enable/); - assert.equal(failed.pending.size, 0); - assert.equal(broken.closes, 1); -}); - -test("closing CDP cancels commands once", { timeout: 2_000 }, async () => { - const socket = new Socket(); - const client = new Cdp(socket, []); - const pending = assert.rejects(client.send("Runtime.evaluate"), /DevTools client closed/); - client.close(); - client.close(); - await pending; - assert.equal(client.pending.size, 0); - assert.equal(socket.closes, 1); -}); - -test("CDP closes a stalled connection after its deadline", { timeout: 2_000 }, async (t) => { - const sockets = new Set(); - const server = net.createServer((socket) => { - sockets.add(socket); - socket.resume(); - socket.on("close", () => sockets.delete(socket)); - }); - t.after(async () => { - const closed = new Promise((resolve) => server.close(resolve)); - for (const socket of sockets) socket.destroy(); - await closed; - }); - server.listen(0, "127.0.0.1"); - await once(server, "listening"); - await assert.rejects(Cdp.connect(`ws://127.0.0.1:${server.address().port}`, [], 40), /connection timed out/); - const deadline = Date.now() + 1_000; - while (sockets.size && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 5)); - assert.equal(sockets.size, 0, "timed-out connection must close its TCP socket"); -}); - -test("Chrome cleanup escalates and reaps a process ignoring SIGTERM", { timeout: 2_000 }, async (t) => { - const child = spawn(process.execPath, ["--input-type=module", "-e", ` - process.on("SIGTERM", () => {}); - setInterval(() => {}, 1000); - console.log("ready"); - `], { stdio: ["ignore", "pipe", "ignore"] }); - t.after(() => stopChrome(child, 10)); - await once(child.stdout, "data"); - await stopChrome(child, 20); - assert.equal(child.signalCode, "SIGKILL"); - await stopChrome(child, 20); -}); diff --git a/test/web_harness.mjs b/test/web_harness.mjs deleted file mode 100644 index 7fd58b86..00000000 --- a/test/web_harness.mjs +++ /dev/null @@ -1,190 +0,0 @@ -#!/usr/bin/env node -// Dependency-free JS harness: instantiate the real freestanding core in Node, -// then render its packed frame through app.mjs against a deliberately tiny DOM -// double. Chrome is reserved for the separate browser/e2e snapshot harness. - -import assert from "node:assert/strict"; -import fs from "node:fs/promises"; -import path from "node:path"; -import { pathToFileURL } from "node:url"; - -if (process.argv.length !== 3) { - console.error("usage: node test/web_harness.mjs <zig-out/web>"); - process.exit(2); -} - -async function main() { - const webDir = path.resolve(process.argv[2]); - const wasmBytes = await fs.readFile(path.join(webDir, "pardes.wasm")); - const module = await WebAssembly.compile(wasmBytes); - const { DomRenderer, browserHost } = await import(pathToFileURL(path.join(webDir, "app.mjs"))); - assert.deepEqual( - [...new Set(WebAssembly.Module.imports(module).map((entry) => entry.module))], - ["pardes"], - "the freestanding core must import nothing but the page's own host", - ); - - // The page's real import object, with every call recorded: the browser host - // is only what a page can actually do, and a replay must ask it for nothing. - const host = browserHost(); - const asked = []; - for (const [name, fn] of Object.entries(host.imports.pardes)) { - host.imports.pardes[name] = (...args) => { - asked.push(name); - return fn(...args); - }; - } - const { exports: wasm } = await WebAssembly.instantiate(module, host.imports); - host.wasm = wasm; - - for (const name of [ - "memory", "pardes_init", "pardes_frame", "pardes_frame_ptr", "pardes_key", - "pardes_mouse", "pardes_pointer_leave", "pardes_pointer_shape", "pardes_gui_tagline_font_percent", - "pardes_paste", "pardes_tick", - "pardes_should_quit", "pardes_deinit", - ]) assert.ok(wasm[name], `missing wasm export ${name}`); - - assert.equal(wasm.pardes_init(80, 24), 0, `wasm init error ${wasm.pardes_last_error()}`); - assert.equal(wasm.pardes_frame(), 0, "a frame exists only once the core has presented one"); - wasm.pardes_tick(); - assert.equal(wasm.pardes_frame(), 80 * 24); - assert.ok(wasm.pardes_frame_ptr() > 0); - - const document = new FakeDocument(); - const root = document.createElement("main"); - root.ownerDocument = document; - const renderer = new DomRenderer(root, wasm); - const draw = () => { - wasm.pardes_tick(); - return renderer.render(); - }; - const first = renderer.render(); - assert.equal(root.style.cursor, "text"); - renderer.wasm = { ...wasm, pardes_pointer_shape: () => 1 }; - renderer.render(); - assert.equal(root.style.cursor, "pointer", "link hover should display the hand pointer"); - renderer.wasm = wasm; - renderer.render(); - assert.equal(root.style.cursor, "text", "leaving a link should restore the text pointer"); - - assert.equal(first.cols, 80); - assert.equal(first.rows, 24); - assert.equal(root.children.length, 24); - assert.equal(root.children[0].children.length, 80); - assert.ok(first.cells.some((cell) => cell.text !== " "), "dump rendered an empty frame"); - assert.ok(root.walk().every((node) => node.tagName !== "CANVAS"), "renderer created a canvas"); - const taglineIndex = first.cells.findIndex((cell) => cell.attrs & (1 << 7)); - const bodyIndex = first.cells.findIndex((cell) => !(cell.attrs & (1 << 7)) && cell.text !== " "); - assert.ok(taglineIndex >= 0, "frame ABI did not mark a tagline font role"); - assert.ok(bodyIndex >= 0, "fixture has no body glyph to compare with tagline"); - assert.ok(renderer.cells[taglineIndex].classList.names.has("is-tagline"), "DOM tagline class was not applied"); - assert.ok(!renderer.cells[bodyIndex].classList.names.has("is-tagline"), "DOM inferred tagline role for body text"); - assert.equal( - root.style["--pardes-tagline-font-size"], - `${wasm.pardes_gui_tagline_font_percent()}%`, - "DOM did not use the build-time tagline percentage", - ); - - const firstCell = renderer.cells[0]; - const second = draw(); - assert.equal(renderer.cells[0], firstCell, "stable frames should reuse DOM nodes"); - assert.equal(second.cells.length, 80 * 24); - - // The embedded dump is test/web-snapshots/touch.dump.zon, a fixed source - // fixture (no live project paths). Over-scroll first (the core clamps at row - // zero) so the Look below always lands on the fixture's own first rows. - for (let tick = 0; tick < 128; tick += 1) wasm.pardes_mouse(3, 0, 5, 3, 0); - const listingTop = draw(); - const topLines = Array.from({ length: listingTop.rows }, (_, row) => - listingTop.cells.slice(row * listingTop.cols, (row + 1) * listingTop.cols).map((cell) => cell.text).join("")); - assert.ok( - topLines.some((text) => /^\s*1 pub fn choose/.test(text)), - "fixture source did not scroll to its first row", - ); - const link = "/virtual/pane/1/body"; - const linkRow = topLines.findIndex((text) => text.includes(link)); - assert.ok(linkRow >= 0, "fixture has no Look target"); - const linkCol = topLines[linkRow].indexOf(link) + 5; - wasm.pardes_mouse(2, 0, linkCol, linkRow, 0); - wasm.pardes_mouse(2, 1, linkCol, linkRow, 0); - const looked = draw(); - const lookedText = looked.cells.map((cell) => cell.text).join(""); - assert.ok( - lookedText.includes(`${link} `) && lookedText.split("pub fn choose").length - 1 >= 2, - "right-click LOOK did not open the reflected source body", - ); - const sourceRows = Array.from({ length: looked.rows }, (_, row) => - looked.cells.slice(row * looked.cols, (row + 1) * looked.cols)); - const codeRows = sourceRows.filter((row) => row.map((cell) => cell.text).join("").match(/^\s*\d+\s/)); - const codeColors = new Set(codeRows.flatMap((row) => row.slice(5).map((cell) => `${cell.fg}:${cell.attrs & 1}`))); - assert.ok(codeColors.size >= 3, "Tree-sitter did not apply distinct syntax styles to the fixture"); - assert.deepEqual(asked, [], "a plain replay asked the page for host IO"); - - wasm.pardes_resize(41, 13); - const resized = draw(); - assert.equal(resized.cols, 41); - assert.equal(resized.rows, 13); - assert.equal(root.children.length, 13); - assert.equal(root.children[0].children.length, 41); - - wasm.pardes_deinit(); - console.error("web harness ok: freestanding wasm + Tree-sitter + packed DOM renderer"); -} - -class FakeDocument { - constructor() { - this.body = new FakeElement("body", this); - } - - createElement(tagName) { - return new FakeElement(tagName, this); - } -} - -class FakeElement { - constructor(tagName, ownerDocument) { - this.tagName = tagName.toUpperCase(); - this.ownerDocument = ownerDocument; - this.children = []; - this.attributes = new Map(); - this.dataset = {}; - this.style = new FakeStyle(); - this.classList = new FakeClassList(this); - this.className = ""; - this.textContent = ""; - } - - setAttribute(name, value) { - this.attributes.set(name, String(value)); - } - - replaceChildren(...children) { - this.children = children; - } - - *walk() { - yield this; - for (const child of this.children) yield* child.walk(); - } -} - -class FakeStyle { - setProperty(name, value) { - this[name] = value; - } -} - -class FakeClassList { - constructor(element) { - this.element = element; - this.names = new Set(); - } - - toggle(name, force) { - if (force) this.names.add(name); - else this.names.delete(name); - this.element.className = [...this.names].join(" "); - } -} - -await main(); diff --git a/test/web_snapshot.mjs b/test/web_snapshot.mjs deleted file mode 100644 index 61467c4d..00000000 --- a/test/web_snapshot.mjs +++ /dev/null @@ -1,550 +0,0 @@ -#!/usr/bin/env node -// Native touch events through Chromium's DevTools protocol, without npm. -// PARDES_CHROME overrides the Chromium executable. -import childProcess from "node:child_process"; -import fs from "node:fs"; -import fsp from "node:fs/promises"; -import http from "node:http"; -import net from "node:net"; -import os from "node:os"; -import path from "node:path"; -import { fileURLToPath, pathToFileURL } from "node:url"; - -const VIEWPORT = { width: 1120, height: 720 }; -let scriptPath; -let server; -let chrome; -let client; -let userDataDir; -let chromeStderr = ""; -const browserLog = []; - -async function main() { - const args = process.argv.slice(2); - const update = args.includes("--update"); - const positional = args.filter((arg) => arg !== "--update"); - if (positional.length !== 2) { - console.error("usage: node test/web_snapshot.mjs <zig-out/web> <test.mjs|script.snap> [--update]"); - process.exitCode = 2; - return; - } - const webDir = path.resolve(positional[0]); - scriptPath = path.resolve(positional[1]); - const scenarioModule = scriptPath.endsWith(".mjs"); - const goldenPath = scriptPath.replace(/\.snap$/, ".golden"); - try { - if (!scenarioModule && goldenPath === scriptPath) throw new Error(`not a test module or .snap path: ${scriptPath}`); - if (scenarioModule && update) throw new Error("semantic browser tests have no golden to update"); - const served = await serveDirectory(webDir); - server = served.server; - const debugPort = await unusedPort(); - const chromePath = await findChrome(); - userDataDir = await fsp.mkdtemp(path.join(os.tmpdir(), "pardes-web-snap-")); - chrome = childProcess.spawn(chromePath, [ - "--headless=new", - "--no-sandbox", - "--disable-dev-shm-usage", - "--enable-unsafe-swiftshader", - "--use-angle=swiftshader", - "--no-first-run", - "--no-default-browser-check", - `--remote-debugging-address=127.0.0.1`, - `--remote-debugging-port=${debugPort}`, - `--user-data-dir=${userDataDir}`, - "about:blank", - ], { stdio: ["ignore", "ignore", "pipe"] }); - chrome.on("error", (error) => { chromeStderr += `\n${error.message}`; }); - chrome.stderr.setEncoding("utf8"); - chrome.stderr.on("data", (chunk) => { - chromeStderr = (chromeStderr + chunk).slice(-16_384); - }); - - await waitForDevTools(debugPort, chrome); - const targetResponse = await fetch( - `http://127.0.0.1:${debugPort}/json/new?${encodeURIComponent(`http://127.0.0.1:${served.port}/index.html`)}`, - { method: "PUT", signal: AbortSignal.timeout(10_000) }, - ); - if (!targetResponse.ok) throw new Error(`create Chrome target: HTTP ${targetResponse.status}`); - const target = await targetResponse.json(); - client = await Cdp.connect(target.webSocketDebuggerUrl, browserLog); - await client.send("Runtime.enable"); - await client.send("Page.enable"); - await client.send("Log.enable"); - await client.send("Emulation.setDeviceMetricsOverride", { - ...VIEWPORT, - screenWidth: VIEWPORT.width, - screenHeight: VIEWPORT.height, - deviceScaleFactor: 1, - mobile: false, - }); - await client.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 1 }); - await waitForRuntime(20_000); - - if (scenarioModule) { - const scenario = await import(pathToFileURL(scriptPath)); - await scenario.default({ grid, touch: dispatchTouch, wait: waitUntil, stable: waitStable, delay, evaluate, - mouse: (event) => client.send("Input.dispatchMouseEvent", event) }); - console.error(`web test ok: ${path.relative(process.cwd(), scriptPath)}`); - return; - } - const output = await runScript(await fsp.readFile(scriptPath, "utf8")); - if (update) { - await fsp.writeFile(goldenPath, output); - console.error(`updated ${path.relative(process.cwd(), goldenPath)}`); - } else { - const golden = await fsp.readFile(goldenPath, "utf8").catch(() => null); - if (golden === null) throw new Error(`missing ${goldenPath}; run with --update`); - if (golden !== output) { - const actualPath = goldenPath.replace(/\.golden$/, ".actual"); - await fsp.writeFile(actualPath, output); - throw new Error(`snapshot mismatch; actual written to ${actualPath}`); - } - console.error(`web snapshot ok: ${path.relative(process.cwd(), scriptPath)}`); - } - } catch (error) { - console.error(error?.stack ?? error); - if (scenarioModule && client) { - const frame = await grid().catch(() => null); - if (frame) console.error(formatSnapshot("failure", frame)); - } - if (browserLog.length) console.error(`browser log:\n${browserLog.join("\n")}`); - if (chromeStderr.trim()) console.error(`chromium stderr (tail):\n${chromeStderr.trim()}`); - process.exitCode = 1; - } finally { - client?.close(); - if (chrome) await stopChrome(chrome); - if (server) { - const closed = new Promise((resolve) => server.close(resolve)); - server.closeAllConnections(); - await closed; - } - if (userDataDir) await fsp.rm(userDataDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); - } -} - -async function runScript(source) { - let output = ""; - let activeTouch = null; - const lines = source.split("\n"); - for (let index = 0; index < lines.length; index += 1) { - const line = lines[index].trim(); - if (!line || line.startsWith("#")) continue; - const tokens = line.split(/\s+/); - const command = tokens.shift(); - try { - if (command === "wait") { - const timeout = integer(tokens.shift(), "wait timeout"); - const needle = tokens.join(" "); - if (!needle) throw new Error("wait needs text"); - await waitUntil(async () => (await grid()).text.includes(needle), timeout, `screen containing ${JSON.stringify(needle)}`); - } else if (command === "stable") { - const quiet = integer(tokens.shift(), "stable quiet time"); - const timeout = integer(tokens.shift(), "stable timeout"); - await waitStable(quiet, timeout); - } else if (command === "snap") { - const label = tokens.join(" "); - if (!label) throw new Error("snap needs a label"); - output += formatSnapshot(label, await grid()); - } else if (command === "snapstyle") { - const label = tokens.join(" "); - if (!label) throw new Error("snapstyle needs a label"); - output += formatStyleSnapshot(label, await grid()); - } else if (command === "touch") { - const phase = tokens.shift(); - const id = integer(tokens.shift(), "touch id"); - const col = number(tokens.shift(), "touch col"); - const row = number(tokens.shift(), "touch row"); - if (tokens.length || !["down", "move", "up"].includes(phase)) throw new Error("bad touch command"); - activeTouch = await dispatchTouch(phase, id, col, row, activeTouch); - await delay(40); - } else if (command === "swipe") { - const id = integer(tokens.shift(), "swipe id"); - const x0 = number(tokens.shift(), "swipe start col"); - const y0 = number(tokens.shift(), "swipe start row"); - const x1 = number(tokens.shift(), "swipe end col"); - const y1 = number(tokens.shift(), "swipe end row"); - const steps = integer(tokens.shift(), "swipe steps"); - if (tokens.length || steps < 1) throw new Error("bad swipe command"); - activeTouch = await dispatchTouch("down", id, x0, y0, activeTouch); - for (let step = 1; step <= steps; step += 1) { - const t = step / steps; - activeTouch = await dispatchTouch("move", id, x0 + (x1 - x0) * t, y0 + (y1 - y0) * t, activeTouch); - await delay(20); - } - activeTouch = await dispatchTouch("up", id, x1, y1, activeTouch); - await delay(80); - } else { - throw new Error(`unknown command ${command}`); - } - } catch (error) { - const screen = await grid().catch(() => null); - const detail = screen ? `\ncurrent screen:\n${screen.lines.map((row) => `|${row}`).join("\n")}` : ""; - throw new Error(`${path.basename(scriptPath)}:${index + 1}: ${line}\n${error.message}${detail}`, { cause: error }); - } - } - if (activeTouch) throw new Error("script ended with a finger still down"); - return output; -} - -async function dispatchTouch(phase, id, col, row, active) { - const point = await evaluate(`pardes.test.cellPoint(${JSON.stringify(col)}, ${JSON.stringify(row)})`); - const touch = { x: point.x, y: point.y, id, radiusX: 1, radiusY: 1, force: 1 }; - if (phase === "down") { - if (active) throw new Error("only one finger is supported by this web test"); - await client.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [touch] }); - return touch; - } - if (!active || active.id !== id) throw new Error(`finger ${id} is not down`); - if (phase === "move") { - await client.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: [touch] }); - return touch; - } - // Chrome's touchEnd carries no points; a final move gives SDL the scripted - // release coordinate before the lift. - await client.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: [touch] }); - await client.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); - return null; -} - -async function grid() { - return evaluate(`(() => { - const frame = pardes.test.grid(); - const { cols, rows, cursorX, cursorY } = frame; - const lines = []; - const styleRows = []; - for (let y = 0; y < rows; y++) { - let line = ""; - const styles = []; - for (let x = 0; x < cols; x++) { - const cell = frame.cells[y * cols + x]; - line += cell.text || " "; - styles.push([cell.fg, cell.bg, cell.attrs]); - } - lines.push(line.replace(/ +$/, "")); - styleRows.push(styles); - } - return { - cols, rows, lines, styleRows, - cursorX, cursorY, - text: lines.join("\\n"), - }; - })()`); -} - -function formatSnapshot(label, state) { - const cursorX = state.cursorX < 0 ? 0 : state.cursorX; - const cursorY = state.cursorY < 0 ? 0 : state.cursorY; - let out = `== snap ${label} grid=${state.cols}x${state.rows} cursor=${cursorX},${cursorY}\n`; - for (const line of state.lines) out += `|${line}\n`; - return out; -} - -function formatStyleSnapshot(label, state) { - let out = `== style ${label}\n`; - for (let y = 0; y < state.rows; y++) { - const styles = state.styleRows[y]; - out += `|${y}:`; - let runStart = 0; - let runKey = styleKey(styles[0]); - for (let x = 1; x <= state.cols; x++) { - const key = x === state.cols ? null : styleKey(styles[x]); - if (key === runKey) continue; - out += ` ${runStart}-${x - 1} ${runKey}`; - runStart = x; - runKey = key; - } - out += "\n"; - } - return out; -} - -function styleKey([fg, bg, attrs]) { - return `${colorKey(fg)},${colorKey(bg)},${attrsKey(attrs)}`; -} - -function colorKey(color) { - if (color === 0x01000000) return "d"; - if ((color & 0xff000000) === 0x02000000) return `p${color & 0xff}`; - return `#${(color & 0xffffff).toString(16).padStart(6, "0")}`; -} - -function attrsKey(attrs) { - let out = ""; - if (attrs & (1 << 0)) out += "b"; - if (attrs & (1 << 1)) out += "f"; - if (attrs & (1 << 2)) out += "i"; - if (attrs & (1 << 3)) out += "k"; - if (attrs & (1 << 4)) out += "r"; - if (attrs & (1 << 5)) out += "v"; - if (attrs & (1 << 6)) out += "x"; - out += ["", "u", "U", "~", ".", "-"][(attrs >> 8) & 0x7] ?? "?"; - return out; -} - -async function waitStable(quiet, timeout) { - const deadline = Date.now() + timeout; - let previous = JSON.stringify(await grid()); - while (Date.now() < deadline) { - await delay(Math.min(quiet, deadline - Date.now())); - const current = JSON.stringify(await grid()); - if (current === previous && Date.now() <= deadline) return; - previous = current; - } - throw new Error(`screen did not stabilize within ${timeout}ms`); -} - -async function waitForRuntime(timeout) { - await waitUntil(async () => { - try { - return await evaluate(`(() => { - const app = globalThis.pardes; - if (!app?.test?.grid()?.cols || document.querySelector("canvas")) return false; - const want = app.runtime.gridSize(); - const frame = app.test.grid(); - const tagline = document.querySelector(".pardes-cell.is-tagline"); - const body = document.querySelector(".pardes-cell:not(.is-tagline)"); - if (!tagline || !body) return false; - const tagRect = tagline.getBoundingClientRect(); - const bodyRect = body.getBoundingClientRect(); - return frame.cols === want.cols && frame.rows === want.rows && - document.querySelectorAll(".pardes-row").length === want.rows && - tagRect.width === bodyRect.width && tagRect.height === bodyRect.height && - parseFloat(getComputedStyle(tagline).fontSize) < parseFloat(getComputedStyle(body).fontSize); - })()`); - } catch (error) { - if (client.error) throw error; - return false; - } - }, timeout, "Pardes web runtime"); -} - -async function waitUntil(predicate, timeout, description) { - const deadline = Date.now() + timeout; - while (Date.now() < deadline) { - if (await predicate()) return; - if (chrome && (chrome.exitCode !== null || chrome.signalCode !== null)) - throw new Error(`Chromium exited with ${chrome.exitCode ?? chrome.signalCode}`); - await delay(50); - } - throw new Error(`timed out waiting for ${description}`); -} - -async function evaluate(expression) { - const response = await client.send("Runtime.evaluate", { - expression, - returnByValue: true, - awaitPromise: true, - }); - if (response.exceptionDetails) throw new Error(response.exceptionDetails.text); - return response.result.value; -} - -export class Cdp { - static async connect(url, log, timeout = 10_000) { - const socket = new WebSocket(url); - const client = new Cdp(socket, log, timeout); - try { - await new Promise((resolve, reject) => { - const finish = (error) => { - clearTimeout(timer); - socket.removeEventListener("open", opened); - socket.removeEventListener("close", failed); - socket.removeEventListener("error", failed); - if (error) reject(error); else resolve(); - }; - const opened = () => finish(); - const failed = () => finish(client.error ?? new Error(`connect DevTools websocket ${url}`)); - const timer = setTimeout(() => finish(new Error(`DevTools connection timed out after ${timeout}ms`)), timeout); - socket.addEventListener("open", opened, { once: true }); - socket.addEventListener("close", failed, { once: true }); - socket.addEventListener("error", failed, { once: true }); - }); - return client; - } catch (error) { - client.close(); - throw error; - } - } - - constructor(socket, log, timeout = 10_000) { - this.socket = socket; - this.timeout = timeout; - this.nextId = 1; - this.pending = new Map(); - this.error = null; - socket.addEventListener("close", (event) => this.fail(new Error(`DevTools connection closed (${event.code ?? "unknown"})`))); - socket.addEventListener("error", () => this.fail(new Error("DevTools connection error"))); - socket.addEventListener("message", (event) => { - if (this.error) return; - try { - const message = JSON.parse(event.data); - if (message.id) { - const pending = this.pending.get(message.id); - if (!pending) return; - this.pending.delete(message.id); - clearTimeout(pending.timer); - if (message.error) pending.reject(new Error(`${pending.method}: ${message.error.message}`)); - else pending.resolve(message.result ?? {}); - return; - } - if (message.method === "Runtime.exceptionThrown") - log.push(`exception: ${message.params.exceptionDetails.text}`); - else if (message.method === "Runtime.consoleAPICalled") - log.push(`console ${message.params.type}: ${message.params.args.map((arg) => arg.value ?? arg.description).join(" ")}`); - else if (message.method === "Log.entryAdded") - log.push(`${message.params.entry.level}: ${message.params.entry.text}`); - } catch (error) { - this.fail(new Error("invalid DevTools message", { cause: error })); - } - }); - } - - send(method, params = {}) { - if (this.error) return Promise.reject(this.error); - if (this.socket.readyState !== WebSocket.OPEN) { - this.fail(new Error("DevTools connection is not open")); - return Promise.reject(this.error); - } - const id = this.nextId++; - return new Promise((resolve, reject) => { - const timer = setTimeout(() => this.fail(new Error(`${method} timed out after ${this.timeout}ms`)), this.timeout); - this.pending.set(id, { resolve, reject, method, timer }); - try { - this.socket.send(JSON.stringify({ id, method, params })); - } catch (error) { - this.fail(new Error(`send DevTools command ${method}`, { cause: error })); - } - }); - } - - fail(error) { - if (this.error) return; - this.error = error; - for (const pending of this.pending.values()) { - clearTimeout(pending.timer); - pending.reject(error); - } - this.pending.clear(); - this.socket.close(); - } - - close() { - this.fail(new Error("DevTools client closed")); - } -} - -export async function stopChrome(child, timeout = 2_000) { - if (!child.pid || child.exitCode !== null || child.signalCode !== null) return; - await new Promise((resolve) => { - const timer = setTimeout(() => child.kill("SIGKILL"), timeout); - child.once("exit", () => { - clearTimeout(timer); - resolve(); - }); - child.kill("SIGTERM"); - }); -} - -async function serveDirectory(root) { - const canonicalRoot = await fsp.realpath(root); - const server = http.createServer(async (request, response) => { - try { - const url = new URL(request.url, "http://localhost"); - const relative = decodeURIComponent(url.pathname === "/" ? "/index.html" : url.pathname); - const filename = path.resolve(canonicalRoot, `.${relative}`); - if (filename !== canonicalRoot && !filename.startsWith(`${canonicalRoot}${path.sep}`)) { - response.writeHead(403).end(); - return; - } - const contents = await fsp.readFile(filename); - const contentType = filename.endsWith(".wasm") ? "application/wasm" - : filename.endsWith(".js") || filename.endsWith(".mjs") ? "text/javascript; charset=utf-8" - : filename.endsWith(".css") ? "text/css; charset=utf-8" - : filename.endsWith(".ttf") ? "font/ttf" - : "text/html; charset=utf-8"; - response.writeHead(200, { "content-type": contentType, "cache-control": "no-store" }); - response.end(contents); - } catch { - response.writeHead(404).end(); - } - }); - await new Promise((resolve, reject) => { - server.once("error", reject); - server.listen(0, "127.0.0.1", resolve); - }); - return { server, port: server.address().port }; -} - -async function unusedPort() { - const probe = net.createServer(); - await new Promise((resolve, reject) => { - probe.once("error", reject); - probe.listen(0, "127.0.0.1", resolve); - }); - const port = probe.address().port; - await new Promise((resolve) => probe.close(resolve)); - return port; -} - -async function waitForDevTools(port, child) { - const deadline = Date.now() + 10_000; - while (Date.now() < deadline) { - if (!child.pid || child.exitCode !== null || child.signalCode !== null) - throw new Error(`Chromium exited with ${child.exitCode ?? child.signalCode}`); - try { - const response = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(500) }); - if (response.ok) return; - } catch {} - await delay(50); - } - throw new Error("Chromium DevTools endpoint did not start"); -} - -async function findChrome() { - const candidates = []; - if (process.env.PARDES_CHROME) candidates.push(process.env.PARDES_CHROME); - for (const command of ["chromium", "chromium-browser", "google-chrome", "google-chrome-stable"]) { - const found = childProcess.spawnSync("which", [command], { encoding: "utf8" }); - if (found.status === 0 && found.stdout.trim()) candidates.push(found.stdout.trim()); - } - // macOS installs a browser as an application BUNDLE, whose executable is - // buried inside it and never on PATH, so the lookup above finds nothing on - // a Mac that has Chrome sitting in /Applications. - if (process.platform === "darwin") - for (const app of ["Google Chrome", "Chromium", "Google Chrome Canary"]) - candidates.push(`/Applications/${app}.app/Contents/MacOS/${app}`); - const cache = process.env.PLAYWRIGHT_BROWSERS_PATH || path.join(os.homedir(), ".cache", "ms-playwright"); - for (const entry of await fsp.readdir(cache).catch(() => [])) { - if (entry.startsWith("chromium-")) { - candidates.push(path.join(cache, entry, "chrome-linux64", "chrome")); - candidates.push(path.join(cache, entry, "chrome-linux", "chrome")); - } else if (entry.startsWith("chromium_headless_shell-")) { - candidates.push(path.join(cache, entry, "chrome-headless-shell-linux64", "chrome-headless-shell")); - } - } - for (const candidate of candidates) { - try { - await fsp.access(candidate, fs.constants.X_OK); - return candidate; - } catch {} - } - throw new Error("no Chromium found; set PARDES_CHROME=/path/to/chrome"); -} - -function integer(value, label) { - const parsed = Number.parseInt(value, 10); - if (!Number.isSafeInteger(parsed) || String(parsed) !== value) throw new Error(`bad ${label}: ${value}`); - return parsed; -} - -function number(value, label) { - const parsed = Number(value); - if (!Number.isFinite(parsed)) throw new Error(`bad ${label}: ${value}`); - return parsed; -} - -function delay(ms) { - return new Promise((resolve) => setTimeout(resolve, ms)); -} - -if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main(); |
