import{spawn as T}from"node:child_process";import{existsSync as S}from"node:fs";import{dirname as k,resolve as $,relative as I}from"node:path";var m=new Map,l=8,M={name:"run_playwright_test",description:`Run a Playwright test file and return results. Use this after writing a test to verify it works. If it fails, fix the issues and run again. Maximum ${l} attempts per session.`,inputSchema:{type:"object",properties:{scriptPath:{type:"string",description:"Path to the Playwright test file (e.g., tests/login.spec.js)"}},required:["scriptPath"]},async execute({scriptPath:o},i){let x=`${i?.sessionId||"default"}:${o}`,t=(m.get(x)||0)+1;if(m.set(x,t),t>l)return{success:!1,executionCount:t,maxReached:!0,error:`Maximum ${l} executions reached. Stop retrying and return your best result.`};let h=i?.projectRoot||process.cwd(),e=$(h,o),y=I(h,e);return y.startsWith("..")||$(e)!==e&&y.includes("..")?{success:!1,executionCount:t,error:"Path traversal detected: scriptPath must be within the project root."}:S(e)?new Promise(d=>{let j=k(e),u=T("npx",["playwright","test",e,"--reporter=line"],{cwd:h,env:{...process.env,FORCE_COLOR:"0"}}),c="",f="";u.stdout.on("data",s=>{c+=s.toString()}),u.stderr.on("data",s=>{f+=s.toString()});let w=setTimeout(()=>{u.kill("SIGTERM"),d({success:!1,executionCount:t,error:"Test timed out after 60 seconds",stdout:c.slice(-2e3),stderr:f.slice(-1e3)})},6e4);u.on("close",s=>{clearTimeout(w);let p=`${c}
${f}`.split(`
`),g="",C=null;for(let a=0;a<p.length;a++){let r=p[a];if(r.includes("Error:")||r.includes("error:")||r.includes("\u2718")){g+=`${r}
`;for(let n=a+1;n<Math.min(a+5,p.length);n++)g+=`${p[n]}
`}if(r.includes("at ")&&r.includes(".spec.")){let n=r.match(/:(\d+):\d+/);n&&(C=parseInt(n[1]))}}d(s===0?{success:!0,executionCount:t,message:"All tests passed!",output:c.slice(-500)}:{success:!1,executionCount:t,remainingAttempts:l-t,error:g.slice(0,1500)||"Test failed (see output)",failedAtLine:C,stdout:c.slice(-1500),stderr:f.slice(-500),hint:t<l?"Fix the error and run again.":"Last attempt - make your best fix."})}),u.on("error",s=>{clearTimeout(w),d({success:!1,executionCount:t,error:`Failed to run test: ${s.message}`})})}):{success:!1,executionCount:t,error:`Test file not found: ${e}. Make sure you wrote the file first using the write tool.`}},resetCount(o){for(let i of m.keys())i.startsWith(`${o}:`)&&m.delete(i)}};function b(o){M.resetCount(o)}export{b as resetExecutionCount,M as runPlaywrightTestTool};
