import {createServer} from 'node:http'; import {readFile,realpath,appendFile} from 'node:fs/promises'; import {resolve,extname,sep} from 'node:path'; import {chromium} from 'playwright'; let input='';for await(const c of process.stdin)input+=c; const {root:raw,actions=[],width=1280}=JSON.parse(input), root=await realpath(raw); const server=createServer(async(req,res)=>{try{ if(req.method==='POST'&&req.url==='/api/leads'){ let body='';for await(const c of req)body+=c;if(body.length>10000)throw Error('too large'); const d=JSON.parse(body);const ok=typeof d.name==='string'&&d.name.trim()&&typeof d.email==='string'&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(d.email)&&Number.isInteger(d.seats)&&d.seats>=1&&d.seats<=8; res.writeHead(ok?201:400,{'Content-Type':'application/json'}); if(ok)await appendFile(resolve(root,'submissions.jsonl'),JSON.stringify(d)+'\n'); res.end(JSON.stringify(ok?{ok:true}:{error:'Check name, email and seats (1-8).'}));return; } if(req.method!=='GET'){res.writeHead(404);res.end();return;} const pathname=decodeURIComponent(new URL(req.url,'http://localhost').pathname); const p=await realpath(resolve(root,'.'+(pathname==='/'?'/index.html':pathname))); if(!p.startsWith(root+sep))throw Error('outside'); res.setHeader('Content-Type',({'.html':'text/html','.css':'text/css','.js':'text/javascript'})[extname(p)]||'text/plain');res.end(await readFile(p)); }catch{res.writeHead(404);res.end('Not found')}}); await new Promise(r=>server.listen(0,'127.0.0.1',r));let browser; try{ const origin=`http://127.0.0.1:${server.address().port}`;browser=await chromium.launch({headless:true,channel:'chrome'}); const ctx=await browser.newContext({viewport:{width,height:900},serviceWorkers:'block'}); await ctx.route('**/*',r=>new URL(r.request().url()).origin===origin?r.continue():r.abort()); if(ctx.routeWebSocket)await ctx.routeWebSocket(/.*/,ws=>ws.close()); const page=await ctx.newPage();page.setDefaultTimeout(2500);const errors=[]; page.on('pageerror',e=>errors.push(e.message));await page.goto(origin); for(const a of actions.slice(0,25)){try{if(a.op==='fill')await page.locator(a.selector).fill(String(a.value));else if(a.op==='click')await page.locator(a.selector).click();else if(a.op==='reload')await page.reload();else throw Error('unknown action')}catch(e){errors.push(String(e).slice(0,300))}} await page.waitForTimeout(200); const state=await page.evaluate(()=>({text:document.body.innerText,overflow:document.documentElement.scrollWidth>innerWidth,controls:[...document.querySelectorAll('input,button')].map(e=>({id:e.id,value:e.value,valid:e.checkValidity()}))})); console.log(JSON.stringify({state,errors,note:'Fresh browser per call; trusted server supplies original /api/leads behavior; submit all actions together.'})); }finally{if(browser)await browser.close();await new Promise(r=>server.close(r))}