// Anonymous production browser acceptance. No local overrides or business write calls. import fs from 'node:fs'; import path from 'node:path'; import assert from 'node:assert/strict'; import {spawn} from 'node:child_process'; const verified=JSON.parse(fs.readFileSync('work/live-S2-readback-20261102.json','utf8')); const template=JSON.parse(fs.readFileSync('work/first-live-S2-template.json','utf8')); assert.ok(verified.ok);assert.equal(verified.artifactId,'b7NOby5ys0'); const base='https://kangshifu.fmode.cn',output='work/live-S2-browser-verified-20261102.json'; const runId=Date.now(); assert.equal(fs.existsSync(output),false,'Preserve prior browser acceptance'); const profile=path.resolve('work/browser-S2-'+Date.now());fs.mkdirSync(profile); const browser=spawn('C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',[ '--headless=new','--disable-gpu','--no-first-run','--no-default-browser-check','--disable-background-networking', '--remote-debugging-address=127.0.0.1','--remote-debugging-port=0','--user-data-dir='+profile,'about:blank' ],{windowsHide:true,stdio:'ignore'}); const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms)); const checks=[],errors=[],requests=[],observations=[],screenshots=[]; let socket; try{ let port; for(let i=0;i<100;i++){try{port=Number(fs.readFileSync(path.join(profile,'DevToolsActivePort'),'utf8').split('\n')[0]);}catch{}if(port)break;await sleep(100);} assert.ok(port,'browser debugger'); const tabs=await(await fetch('http://127.0.0.1:'+port+'/json/list')).json(); socket=new WebSocket(tabs.find(t=>t.type==='page').webSocketDebuggerUrl); await new Promise((resolve,reject)=>{socket.addEventListener('open',resolve,{once:true});socket.addEventListener('error',reject,{once:true});}); let seq=0;const pending=new Map(); socket.addEventListener('message',({data})=>{ const message=JSON.parse(data); if(message.id&&pending.has(message.id)){const p=pending.get(message.id);clearTimeout(p.timer);pending.delete(message.id);message.error?p.reject(Error(message.error.message)):p.resolve(message.result);} if(message.method==='Runtime.exceptionThrown')errors.push({runtime:message.params.exceptionDetails.text}); if(message.method==='Network.loadingFailed'&&message.params.errorText!=='net::ERR_ABORTED')errors.push({network:message.params.errorText}); if(message.method==='Log.entryAdded'&&message.params.entry.level==='error'&&!message.params.entry.url?.endsWith('/favicon.ico'))errors.push({console:message.params.entry.text}); if(message.method==='Network.requestWillBeSent'){ const r=message.params.request;let cloudPath=null; if(r.url.endsWith('/api/functions')){try{cloudPath=JSON.parse(r.postData||'{}').path??null;}catch{}} requests.push({url:r.url,method:r.method,headerNames:Object.keys(r.headers||{}),cloudPath}); } }); const cdp=(method,params={})=>new Promise((resolve,reject)=>{ const id=++seq,timer=setTimeout(()=>{pending.delete(id);reject(Error(method+' timeout'));},30000); pending.set(id,{resolve,reject,timer});socket.send(JSON.stringify({id,method,params})); }); const evaluate=async expression=>{ const r=await cdp('Runtime.evaluate',{expression,returnByValue:true,awaitPromise:true}); if(r.exceptionDetails)throw Error(r.exceptionDetails.text);return r.result.value; }; const check=(name,passed)=>{checks.push({name,passed:Boolean(passed)});assert.ok(passed,name);}; const helpers=`function find(root,selector){const hit=root.querySelector(selector);if(hit)return hit;for(const n of root.querySelectorAll('*'))if(n.shadowRoot){const found=find(n.shadowRoot,selector);if(found)return found;}return null;} function text(root){let out='';for(const n of root.childNodes){if(n.nodeType===Node.TEXT_NODE)out+=n.textContent;else if(n.nodeType===Node.ELEMENT_NODE&&!['STYLE','SCRIPT','NOSCRIPT','TEMPLATE'].includes(n.tagName)){out+=text(n);if(n.shadowRoot)out+=text(n.shadowRoot);}}return out;}`; const deepText=()=>evaluate(`(()=>{${helpers}return text(document);})()`); const compact=value=>value.replace(/\s/g,''); const quoteText=value=>value.replace(/\u2009/g,''); const screenshot=async label=>{ const shot=await cdp('Page.captureScreenshot',{format:'png'}),file='work/live-S2-'+label+'-'+runId+'.png'; fs.writeFileSync(file,Buffer.from(shot.data,'base64'),{flag:'wx'});screenshots.push(file); }; const navigate=async route=>{ await cdp('Page.navigate',{url:base+route});let ready=false; for(let i=0;i<120;i++){await sleep(200);try{ready=await evaluate("import('/src/services/board-service.js').then(m=>m.boardService.status.get()==='ready')");}catch{}if(ready)break;} check(route+' public data loaded',ready);await sleep(250); }; await cdp('Page.enable');await cdp('Runtime.enable');await cdp('Network.enable');await cdp('Log.enable'); for(const mobile of [false,true]){ const viewport=mobile?'390px':'desktop'; await cdp('Emulation.setDeviceMetricsOverride',mobile?{width:390,height:844,deviceScaleFactor:1,mobile:true}:{width:1440,height:1000,deviceScaleFactor:1,mobile:false}); for(const route of ['/members','/stages','/reports','/report/'+verified.artifactId]){ await navigate(route);const content=compact(await deepText()); // The members route presents the employee, while report routes present the artifact. const expectedVisible=route==='/members'?content.includes('员工待绑定·f83edd27dda7'): route==='/stages'?content.includes('S2')&&content.includes('用户需求与痛点'): content.includes(compact(template.title)); check(route+' '+viewport+' relevant content visible',expectedVisible); check(route+' '+viewport+' no page overflow',await evaluate('document.documentElement.scrollWidth<=innerWidth')); if(!route.startsWith('/report/'))continue; check('S2 title '+viewport,content.includes(compact(template.title))); check('classroom boundary '+viewport,content.includes('课堂过程成果')&&content.includes('未经员工正式确认')); check('historical sample boundary '+viewport,content.includes('已超过2年')&&content.includes('不能据此估计人群比例')); check('series separated '+viewport,content.includes('燃魂拌面')&&content.includes('香辣拌面')&&content.includes('不合并为同一款产品')); check('observations and questions '+viewport,content.includes('样本内2篇明确说量少')&&content.includes('值得继续核实的问题')); check('unknowns retained '+viewport,content.includes('未知')&&content.includes('支付意愿')&&content.includes('KANO')); for(const [index,question]of template.pendingQuestions.entries())check('pending question '+(index+1)+' '+viewport,content.includes(compact(question))); await screenshot('report-'+(mobile?'mobile':'desktop')); for(const [key,entry]of Object.entries(template.report.evidence)){ const selector=JSON.stringify('[data-anchor="'+key+'"]'); check('evidence button '+key+' '+viewport,await evaluate(`(()=>{${helpers}const button=find(document,${selector});if(!button)return false;button.scrollIntoView({block:'center'});return true;})()`)); await sleep(300); const point=await evaluate(`(()=>{${helpers}const r=find(document,${selector}).getBoundingClientRect();return {x:r.left+r.width/2,y:r.top+r.height/2};})()`); await cdp('Input.dispatchMouseEvent',{type:'mousePressed',...point,button:'left',clickCount:1}); await cdp('Input.dispatchMouseEvent',{type:'mouseReleased',...point,button:'left',clickCount:1}); await sleep(350); const drawer=await evaluate(`(()=>{${helpers}const host=find(document,'kf-drawer');const panel=host?.shadowRoot.querySelector('.panel');const body=host?.shadowRoot.querySelector('.body');const r=panel?.getBoundingClientRect();const style=panel?getComputedStyle(panel):null;return {open:host?.open===true,visible:!!r&&r.width>0&&r.height>0&&r.right>0&&r.left li > p')].map(p=>p.textContent):[]};})()`); check('drawer visible '+key+' '+viewport,drawer.open&&drawer.visible); check('verbatim quote '+key+' '+viewport,JSON.stringify(drawer.quotes.map(quoteText))===JSON.stringify(entry.quotes.map(q=>quoteText(q.text)))); check('registered source '+key+' '+viewport,drawer.text.includes('已关联原始资料')&&!drawer.text.includes('未关联来源记录')); check('open drawer no overflow '+key+' '+viewport,await evaluate('document.documentElement.scrollWidth<=innerWidth')); await screenshot('evidence-'+key+'-'+(mobile?'mobile':'desktop')); observations.push({viewport:mobile?390:1440,evidence:key,sourceId:entry.sourceId,drawerVisible:true,quoteCount:drawer.quotes.length,input:'browser mouse event'}); await cdp('Input.dispatchKeyEvent',{type:'keyDown',key:'Escape',code:'Escape',windowsVirtualKeyCode:27}); await cdp('Input.dispatchKeyEvent',{type:'keyUp',key:'Escape',code:'Escape',windowsVirtualKeyCode:27});await sleep(300); check('drawer closed '+key+' '+viewport,await evaluate(`(()=>{${helpers}return find(document,'kf-drawer')?.open===false;})()`)); } } } await navigate('/report/'+verified.originalS1ArtifactId);check('S1 still readable',compact(await deepText()).includes('S1资料小结')); check('no browser errors',errors.length===0); const cloudRequests=requests.filter(r=>r.url.endsWith('/api/functions')); check('public cloud reads observed',cloudRequests.length>0); check('only public board cloud reads',cloudRequests.every(r=>r.method==='POST'&&r.cloudPath==='/ksfGetPublicBoard')); check('anonymous browser requests',!requests.some(r=>r.headerNames.some(k=>/master|authorization|session.token|ksf.service.token/i.test(k)))); const result={ok:true,operation:'live-S2-production-browser-verified',at:new Date().toISOString(),base,artifactId:verified.artifactId, browserVerified:true,scope:'production website, fresh anonymous Edge browser, no module overrides',readOnly:true,businessWrites:0, viewports:[1440,390],evidenceDrawersChecked:observations.length,quoteComparison:'All characters equal except display U+2009 thin spaces', checks,errors,observations,screenshots}; fs.writeFileSync(output,JSON.stringify(result,null,2)+'\n',{flag:'wx'}); console.log(JSON.stringify({ok:true,checks:checks.length,evidenceDrawersChecked:observations.length,screenshots:screenshots.length,browserVerified:true,businessWrites:0},null,2)); }catch(error){ const result={ok:false,at:new Date().toISOString(),artifactId:verified.artifactId,browserVerified:false,readOnly:true,businessWrites:0, checks,errors,observations,screenshots,error:error.message}; fs.writeFileSync(output,JSON.stringify(result,null,2)+'\n',{flag:'wx'});console.error(JSON.stringify(result,null,2));process.exitCode=1; }finally{socket?.close();browser.kill();}