Files
logic-puzzle/scripts/test_web_narration.mjs
T
2026-11-14 08:55:48 +01:00

85 lines
5.4 KiB
JavaScript

// Exercise the real HTML audio bridge under Chromium's strict gesture policy.
import {spawn} from 'node:child_process';
import {createServer} from 'node:http';
import {mkdtemp, readFile, rm} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {join} from 'node:path';
import assert from 'node:assert/strict';
const root = process.cwd();
const chrome = process.env.CHROME_BIN || '/home/ubuntu/.cache/ms-playwright/chromium-1248/chrome-linux64/chrome';
const sleep = ms => new Promise(r => setTimeout(r, ms));
const server = createServer(async (req,res) => {
try {
if (req.url === '/') { res.setHeader('Content-Type','text/html'); res.end('<!doctype html><button id="tap">Tap</button><script src="/narration.js"></script>'); return; }
const path = req.url === '/narration.js' ? join(root,'web/narration.js') : join(root,'build/web',decodeURIComponent(req.url.slice(1)));
const data = await readFile(path);
res.setHeader('Content-Type', path.endsWith('.js') ? 'text/javascript' : 'audio/mpeg');
res.setHeader('Accept-Ranges','bytes');
const range = req.headers.range?.match(/bytes=(\d+)-(\d*)/);
if (range) {
const start=Number(range[1]), end=range[2] ? Math.min(Number(range[2]),data.length-1) : data.length-1;
res.writeHead(206, {'Content-Range': `bytes ${start}-${end}/${data.length}`, 'Content-Length': end-start+1});
res.end(data.subarray(start,end+1));
} else { res.setHeader('Content-Length',data.length); res.end(data); }
} catch (_) { res.writeHead(404); res.end(); }
});
await new Promise(r => server.listen(0,'127.0.0.1',r));
const port=server.address().port;
const debugServer=createServer();
await new Promise(r => debugServer.listen(0,'127.0.0.1',r));
const debugPort=debugServer.address().port;
await new Promise(r => debugServer.close(r));
const profile=await mkdtemp(join(tmpdir(),'lumen-chrome-'));
const browser=spawn(chrome,['--headless=new','--no-sandbox','--disable-dev-shm-usage','--disable-gpu',
'--autoplay-policy=user-gesture-required','--remote-allow-origins=*',`--remote-debugging-port=${debugPort}`,
`--user-data-dir=${profile}`,'about:blank'],{stdio:'ignore'});
let ws;
try {
let target;
for (let i=0;i<100;i++) {
try {
const result=await fetch(`http://127.0.0.1:${debugPort}/json/new?${encodeURIComponent(`http://127.0.0.1:${port}/`)}`,{method:'PUT'});
if (result.ok) {target=await result.json();break;}
} catch (_) {}
await sleep(100);
}
assert.ok(target,'Chromium failed to start');
ws=new WebSocket(target.webSocketDebuggerUrl);
await new Promise((resolve,reject)=>{ws.onopen=resolve;ws.onerror=reject;});
let id=0; const pending=new Map();
ws.onmessage=event=>{const message=JSON.parse(event.data);if(message.id&&pending.has(message.id)){const p=pending.get(message.id);pending.delete(message.id);message.error?p.reject(Error(message.error.message)):p.resolve(message.result);}};
const cdp=(method,params={})=>new Promise((resolve,reject)=>{const n=++id;pending.set(n,{resolve,reject});ws.send(JSON.stringify({id:n,method,params}));});
const evaluate=async expression=>{const out=await cdp('Runtime.evaluate',{expression,awaitPromise:true,returnByValue:true});if(out.exceptionDetails)throw Error(out.exceptionDetails.text+': '+JSON.stringify(out.exceptionDetails.exception));return out.result.value;};
await cdp('Page.enable');
for(let i=0;i<100;i++){if(await evaluate("document.readyState === 'complete' && !!window.lumenNarration"))break;await sleep(100);}
const first=`http://127.0.0.1:${port}/assets/assets/postcards/audio/washing-line.mp3`;
const second=`http://127.0.0.1:${port}/assets/assets/postcards/audio/bakery-door.mp3`;
await evaluate('window.a=lumenNarration.create(()=>{});window.b=lumenNarration.create(()=>{});');
const blocked=await evaluate(`lumenNarration.play(a,${JSON.stringify(first)},1,true).then(()=>false,()=>true)`);
assert.equal(blocked,true,'Chromium must enforce gesture policy in this test');
await cdp('Input.dispatchMouseEvent',{type:'mousePressed',x:20,y:20,button:'left',clickCount:1});
await cdp('Input.dispatchMouseEvent',{type:'mouseReleased',x:20,y:20,button:'left',clickCount:1});
await sleep(3000);
await evaluate(`lumenNarration.play(a,${JSON.stringify(first)},1,true)`);
await sleep(1200);
assert.equal(await evaluate('lumenNarration.playing(a)'),true,'first reading did not play');
assert.ok(await evaluate('lumenNarration.position(a)')>300,'first reading did not advance');
await evaluate('lumenNarration.stop(a)');
await sleep(100);
await evaluate(`lumenNarration.play(a,${JSON.stringify(second)},1,true)`);
await sleep(1200);
assert.equal(await evaluate('lumenNarration.playing(a)'),true,'next reading did not autoplay');
assert.ok(await evaluate('lumenNarration.position(a)')>300,'next reading did not advance');
await evaluate('lumenNarration.pause(a)');
assert.equal(await evaluate('lumenNarration.playing(a)'),false,'pause did not stop playback');
await evaluate(`lumenNarration.play(b,${JSON.stringify(first)},1,true)`);
await sleep(500);
assert.equal(await evaluate('lumenNarration.playing(b)'),true,'second narrator was not unlocked');
await evaluate('lumenNarration.dispose(a);lumenNarration.dispose(b)');
console.log('PASS: blocked before gesture; after one tap, both narrators play, advance, change tracks and pause.');
} finally {
ws?.close(); browser.kill('SIGTERM'); server.close();
await sleep(500); await rm(profile,{recursive:true,force:true,maxRetries:5,retryDelay:100});
}