import{dirname}from"node:path";import{mkdir,writeFile}from"node:fs/promises";function JUnit(e){return new JUnitReporter(e)}var JUnitReporter=class{#e;#t=[];constructor(e){this.#e=e}onEvalStart(){}onCaseComplete(){}async onEvalComplete(r){this.#t.push(r);let i=renderJUnit(this.#t,{suiteName:this.#e.suiteName});await mkdir(dirname(this.#e.filePath),{recursive:!0}),await writeFile(this.#e.filePath,i)}};function renderJUnit(e,t){let n=e[0];if(e.length===1&&n!==void 0)return renderJUnitDocument([renderTestSuite(n,{suiteName:t.suiteName??n.id})]);let r=sum(e,e=>e.failed+e.scored),i=sum(e,e=>e.skipped),a=sum(e,e=>e.cases.length),o=sum(e,durationSeconds),s=e.map(e=>renderTestSuite(e,{indent:`  `,suiteName:e.id})).join(`
`);return renderJUnitDocument([`<testsuites name="${escapeXml(t.suiteName??`eve evals`)}" tests="${a}" failures="${r}" skipped="${i}" time="${formatSeconds(o)}">`,s,`</testsuites>`])}function renderJUnitDocument(e){return[`<?xml version="1.0" encoding="UTF-8"?>`,...e,``].join(`
`)}function renderTestSuite(e,t){let n=e.failed+e.scored,r=e.skipped,i=e.cases.map(renderTestCase).join(``),a=t.indent??``;return[`${a}<testsuite name="${escapeXml(t.suiteName)}" tests="${e.cases.length}" failures="${n}" skipped="${r}" time="${formatSeconds(durationSeconds(e))}">`,indentLines(i,a),`${a}</testsuite>`].filter(e=>e.length>0).join(`
`)}function renderTestCase(e){let t=`classname="eve.eval" name="${escapeXml(e.case.id)}"`;if(e.verdict===`passed`)return`  <testcase ${t}/>`;if(e.verdict===`skipped`)return[`  <testcase ${t}>`,`    <skipped message="${escapeXml(e.skipReason??`skipped`)}"/>`,`  </testcase>`].join(`
`);let n=failureMessage(e);return[`  <testcase ${t}>`,`    <failure message="${escapeXml(n)}">${escapeXml(JSON.stringify(buildFailureDetail(e),null,2))}</failure>`,`  </testcase>`].join(`
`)}function buildFailureDetail(e){return{verdict:e.verdict,error:e.error,checks:e.checks,scores:e.scores.map(e=>({name:e.name,score:e.score})),logs:e.result.logs}}function failureMessage(e){if(e.error!==void 0)return e.error;let t=e.checks.find(e=>!e.passed);return t===void 0?e.verdict===`scored`?`score below threshold`:e.skipReason??e.verdict:t.message===void 0?t.name:`${t.name}: ${t.message}`}function durationSeconds(e){let t=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return Math.max(0,t/1e3)}function formatSeconds(e){return e.toFixed(3)}function indentLines(e,t){return e.length===0||t.length===0?e:e.split(`
`).map(e=>`${t}${e}`).join(`
`)}function sum(e,t){return e.reduce((e,n)=>e+t(n),0)}function escapeXml(e){return e.replace(/&/g,`&amp;`).replace(/"/g,`&quot;`).replace(/'/g,`&apos;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}export{JUnit};