// Real-time CDP smoke test: virtual-time screenshots finish before Wasm // compilation on a worker. No credentials or production workspace are used. import {spawn} from 'node:child_process'; import {writeFile} from 'node:fs/promises'; import {setTimeout as delay} from 'node:timers/promises'; const [url, profile, screenshot, width = '1440', height = '1000'] = process.argv.slice(2); const browser = spawn('chromium', ['--headless', '--no-sandbox', '--disable-gpu', '--disable-background-networking', '--no-proxy-server', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank']); process.on('SIGTERM', () => { browser.kill(); process.exit(1); }); let socket; try { const endpoint = await new Promise((resolve, reject) => { let log = ''; browser.stderr.on('data', chunk => { log += chunk; const match = log.match(/DevTools listening on (ws:\/\/[^\s]+)/); if (match) resolve(match[1]); }); browser.on('error', reject); browser.on('exit', code => reject(new Error(`Browser exited ${code}: ${log}`))); }); socket = new WebSocket(endpoint); await new Promise((resolve, reject) => { socket.onopen = resolve; socket.onerror = reject; }); let id = 0; const pending = new Map(); socket.onmessage = event => { const message = JSON.parse(event.data), pair = pending.get(message.id); if (pair) { pending.delete(message.id); message.error ? pair.reject(new Error(JSON.stringify(message.error))) : pair.resolve(message.result); } }; const send = (method, params = {}, sessionId) => new Promise((resolve, reject) => { pending.set(++id, {resolve, reject}); socket.send(JSON.stringify({id, method, params, sessionId})); }); const {targetId} = await send('Target.createTarget', {url: 'about:blank'}); const {sessionId} = await send('Target.attachToTarget', {targetId, flatten: true}); const call = (method, params) => send(method, params, sessionId); await call('Page.enable'); await call('Emulation.setDeviceMetricsOverride', {width: Number(width), height: Number(height), deviceScaleFactor: 1, mobile: false}); await call('Page.navigate', {url}); let ready = false; for (let attempt = 0; attempt < 150; attempt++) { const {result} = await call('Runtime.evaluate', {expression: `JSON.stringify({ready: document.body?.dataset.vimReady, error: document.querySelector('#error:not([hidden])')?.textContent})`, returnByValue: true}); const state = JSON.parse(result.value || '{}'); if (state.error) throw new Error(state.error); if (state.ready) { ready = true; break; } await delay(200); } if(ready && process.env.PAGESWIKI_TASK_INDEX_BROWSER==='1'){ const evaluate=async expression=>{const r=await call('Runtime.evaluate',{expression,returnByValue:true,awaitPromise:true});if(r.exceptionDetails)throw Error(JSON.stringify(r.exceptionDetails));return r.result.value;}; const key=async(key,modifiers=0)=>{await call('Input.dispatchKeyEvent',{type:'keyDown',key,code:'Key'+key.toUpperCase(),modifiers});await call('Input.dispatchKeyEvent',{type:'keyUp',key,code:'Key'+key.toUpperCase(),modifiers});}; await evaluate(`document.querySelector('.task-index-projects button').click();new Promise((resolve,reject)=>{let n=0;const id=setInterval(()=>{if(document.querySelector('.task-index-grid').getAttribute('aria-busy')!=='true'){clearInterval(id);document.querySelector('.task-index-grid tbody tr').click();resolve();}else if(++n>100){clearInterval(id);reject(Error('index loading'));}},30);})`); const selected=()=>evaluate(`document.querySelector('.task-index-grid tr[aria-selected=true]').dataset.task`); const before=await selected();await key('j');if(await selected()===before)throw Error('Native j did not move');await key('k');if(await selected()!==before)throw Error('Native k did not move'); await key('j',2);if(await evaluate(`document.querySelector('.task-index-projects [aria-current=true]').dataset.project`)!=='none')throw Error('Native Ctrl+j did not switch project');await key('k',2); await evaluate(`new Promise(resolve=>{const id=setInterval(()=>{if(document.querySelector('.task-index-grid').getAttribute('aria-busy')!=='true'){clearInterval(id);resolve();}},30)})`); } if(ready && process.env.PAGESWIKI_DASHBOARD_DRAG==='1'){ const evaluate=async expression=>{const r=await call('Runtime.evaluate',{expression,returnByValue:true,awaitPromise:true});if(r.exceptionDetails)throw Error(JSON.stringify(r.exceptionDetails));return r.result.value;}; const rect=async selector=>evaluate(`(()=>{const n=document.querySelector(${JSON.stringify(selector)});n.scrollIntoView({block:'center',behavior:'instant'});const r=n.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2};})()`); const drag=async(from,to)=>{await call('Input.dispatchMouseEvent',{type:'mouseMoved',...from});await call('Input.dispatchMouseEvent',{type:'mousePressed',...from,button:'left',buttons:1,clickCount:1});for(let n=1;n<=8;n++)await call('Input.dispatchMouseEvent',{type:'mouseMoved',x:from.x+(to.x-from.x)*n/8,y:from.y+(to.y-from.y)*n/8,buttons:1});await call('Input.dispatchMouseEvent',{type:'mouseReleased',...to,button:'left',buttons:0,clickCount:1});}; await evaluate(`scrollTo({top:0,behavior:'instant'})`); const coordinates=await evaluate(`(()=>{const point=s=>{const r=document.querySelector(s).getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2};};return {from:point('[data-widget=progress] .widget-drag'),to:point('[data-widget=today] .widget-header')};})()`);await drag(coordinates.from,coordinates.to); if(await evaluate(`document.querySelector('#dashboard-grid').firstElementChild.dataset.widget`)!=='today')throw Error('Pointer reorder failed: '+JSON.stringify(coordinates)); const grip=await rect('[data-widget=tasks] .widget-resize');await drag(grip,{x:grip.x,y:grip.y-84}); if(await evaluate(`document.querySelector('[data-widget=tasks] [data-size=height]').value`)!=='4')throw Error('Pointer resize failed'); await evaluate(`document.querySelector('#dashboard-controls button:last-child').click()`); let saved=false;for(let n=0;n<50;n++){if(await evaluate(`document.querySelector('#dashboard-status').textContent.includes('保存しました')`)){saved=true;break;}await delay(100);}if(!saved)throw Error('Pointer layout save failed'); const layout=await evaluate(`fetch('/_/api/v1/extension/organizer.tasks/dashboard').then(r=>r.json())`);if(layout.widgets[0].id!=='today'||layout.widgets.find(w=>w.id==='tasks').height!==4)throw Error('Pointer layout persistence failed'); await evaluate(`document.querySelector('#dashboard-controls button[aria-pressed]').click();scrollTo(0,0)`); } if (ready && process.env.PAGESWIKI_SLIDES_BROWSER === '1') { const evaluate = async expression => (await call('Runtime.evaluate', {expression, returnByValue:true})).result.value; const initialHistory = await evaluate('history.length'); await evaluate("document.querySelector('.slides-frame').focus()"); const key = async (key, code) => {await call('Input.dispatchKeyEvent',{type:'keyDown',key,code:key,windowsVirtualKeyCode:code});await call('Input.dispatchKeyEvent',{type:'keyUp',key,code:key,windowsVirtualKeyCode:code});}; await key('ArrowRight',39); let advanced=false;for(let n=0;n<30;n++){if(await evaluate("document.querySelector('.slides-frame').parentElement.dataset.slideIndex") === '1'){advanced=true;break;}await delay(100);} if(!advanced)throw Error('Slide keyboard navigation failed'); await key('ArrowLeft',37);await delay(150); if(await evaluate("document.querySelector('.slides-frame').parentElement.dataset.slideIndex") !== '0')throw Error('Slide previous navigation failed'); if(await evaluate('history.length') !== initialHistory)throw Error('Slides polluted browser history'); } if (screenshot) { const {data} = await call('Page.captureScreenshot', {format: 'png'}); await writeFile(screenshot, Buffer.from(data, 'base64')); } if (!ready) throw new Error('Vim startup timed out'); console.log('Vim initialized and exported startup report'); } finally { socket?.close(); browser.kill(); }