@testrelic/maestro-analytics 1.3.2 → 1.4.0-next.124

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
- 'use strict';var core=require('@testrelic/core'),fs=require('fs'),path=require('path'),fastXmlParser=require('fast-xml-parser'),yaml=require('yaml'),child_process=require('child_process'),os$1=require('os'),crypto=require('crypto'),url=require('url'),zlib=require('zlib'),stream=require('stream');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;var bt=".testrelic",Dr="testrelic-config.json",Nr=".testrelic",Or=5,Ur=new Set(["__proto__","constructor","prototype"]),me=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,projectName:null,queueMaxAge:6048e5,queueDirectory:`${bt}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),Hr={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function ye(e){let t=path.resolve(e);for(let r=0;r<=Or;r++){let n=path.join(t,bt,Dr);if(fs.existsSync(n))try{if(fs.statSync(n).isFile())return n}catch{}let o=path.join(t,Nr);if(fs.existsSync(o))try{if(fs.statSync(o).isFile())return process.stderr.write(`[testrelic] Deprecation: config file ".testrelic" has moved to ".testrelic/testrelic-config.json". Please migrate your config file to the new location.
2
- `),o}catch{}let s=path.dirname(t);if(s===t)break;t=s;}return null}function be(e){try{let t=fs.readFileSync(e,"utf-8"),r=JSON.parse(t);return typeof r!="object"||r===null||Array.isArray(r)||!xt(r)?null:r}catch{return null}}function xt(e){for(let t of Object.keys(e)){if(Ur.has(t))return false;let r=e[t];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!xt(r))return false}return true}function K(e){let t=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(e);if(t)return process.env[t[1]]??null;let r=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(e);return r?process.env[r[1]]??null:e}function Y(e){let t=Object.create(null);for(let r of Object.keys(e)){let n=e[r];typeof n=="string"&&n.startsWith("$")?t[r]=K(n):typeof n=="object"&&n!==null&&!Array.isArray(n)?t[r]=Y(n):t[r]=n;}return t}function he(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let r=parseInt(t[1],10),n=t[2],o=Hr[n];return !o||r<=0?null:r*o}function xe(e,t){let r=Object.create(null);if(Object.assign(r,me),e){let l=e.cloud;l&&typeof l=="object"&&(typeof l.endpoint=="string"&&(r.endpoint=l.endpoint),typeof l.upload=="string"&&(r.uploadStrategy=l.upload),typeof l.timeout=="number"&&(r.timeout=l.timeout),typeof l.apiKey=="string"&&l.apiKey.length>0&&(r.apiKey=l.apiKey));let c=e["testrelic-repo"]??e.project;c&&typeof c=="object"&&typeof c.name=="string"&&(r.projectName=c.name);let d=e.queue;if(d&&typeof d=="object"){if(typeof d.maxAge=="string"){let u=he(d.maxAge);u!==null&&(r.queueMaxAge=u);}typeof d.directory=="string"&&(r.queueDirectory=d.directory);}}if(t){if(typeof t.apiKey=="string"&&t.apiKey.length>0){let l=t.apiKey.startsWith("$")?K(t.apiKey):t.apiKey;l&&(r.apiKey=l);}if(typeof t.endpoint=="string"){let l=t.endpoint.startsWith("$")?K(t.endpoint):t.endpoint;l&&(r.endpoint=l);}if(typeof t.upload=="string"&&(r.uploadStrategy=t.upload),typeof t.timeout=="number"&&(r.timeout=t.timeout),typeof t.projectName=="string"&&(r.projectName=t.projectName),typeof t.queueMaxAge=="string"){let l=he(t.queueMaxAge);l!==null&&(r.queueMaxAge=l);}typeof t.queueDirectory=="string"&&(r.queueDirectory=t.queueDirectory),typeof t.uploadArtifacts=="boolean"&&(r.uploadArtifacts=t.uploadArtifacts),typeof t.artifactMaxSizeMb=="number"&&(r.artifactMaxSizeMb=t.artifactMaxSizeMb);}let n=process.env.TESTRELIC_API_KEY;n&&n.length>0&&(r.apiKey=n);let o=process.env.TESTRELIC_CLOUD_ENDPOINT;o&&core.isValidEndpointUrl(o)&&(r.endpoint=o);let s=process.env.TESTRELIC_UPLOAD_STRATEGY;s&&["batch","realtime","both"].includes(s)&&(r.uploadStrategy=s);let i=process.env.TESTRELIC_CLOUD_TIMEOUT;if(i){let l=parseInt(i,10);!isNaN(l)&&l>=1e3&&l<=12e4&&(r.timeout=l);}let a=Object.freeze(r);return core.isValidCloudConfig(a)?a:me}var jr=["authorization","cookie","set-cookie","x-api-key"],zr=["password","secret","token","apiKey","api_key"],qr=1024*1024;function Gr(e){let t=e??{},r=process.env.TESTRELIC_CAPTURE_NETWORK==="1"||process.env.TESTRELIC_CAPTURE_NETWORK?.toLowerCase()==="true";return Object.freeze({enabled:t.enabled??r??false,proxyPort:t.proxyPort??(process.env.TESTRELIC_PROXY_PORT?Number.parseInt(process.env.TESTRELIC_PROXY_PORT,10):8080),proxyHost:t.proxyHost??process.env.TESTRELIC_PROXY_HOST??"127.0.0.1",harPath:t.harPath??process.env.TESTRELIC_HAR_PATH??null,outputDir:t.outputDir??null,skipCertInstall:t.skipCertInstall??false,includeUrls:Object.freeze(t.includeUrls?[...t.includeUrls]:[]),excludeUrls:Object.freeze(t.excludeUrls?[...t.excludeUrls]:[]),redactHeaders:Object.freeze(t.redactHeaders?[...t.redactHeaders]:[...jr]),redactBodyFields:Object.freeze(t.redactBodyFields?[...t.redactBodyFields]:[...zr]),maxBodyBytes:t.maxBodyBytes??qr})}var Vr=new Set(["__proto__","constructor","prototype"]);function wt(e){if(typeof e!="object"||e===null)return false;for(let t of Object.keys(e))if(Vr.has(t))return true;return false}function Jr(e){if(typeof e!="object"||e===null||wt(e))return false;let t=e;return !(t.outputPath!==void 0&&typeof t.outputPath!="string"||t.htmlReportPath!==void 0&&typeof t.htmlReportPath!="string"||t.openReport!==void 0&&typeof t.openReport!="boolean"||t.includeScreenshots!==void 0&&typeof t.includeScreenshots!="boolean"||t.includeVideo!==void 0&&typeof t.includeVideo!="boolean"||t.includeAiAnalysis!==void 0&&typeof t.includeAiAnalysis!="boolean"||t.includeLogs!==void 0&&typeof t.includeLogs!="boolean"||t.includeFlowMetadata!==void 0&&typeof t.includeFlowMetadata!="boolean"||t.quiet!==void 0&&typeof t.quiet!="boolean"||t.metadata!==void 0&&t.metadata!==null&&(typeof t.metadata!="object"||wt(t.metadata)))}function Wr(e){if(e!==void 0&&!Jr(e))throw core.createError(core.ErrorCode.CONFIG_INVALID,"Invalid Maestro reporter configuration");let t=Object.create(null),r=e?.outputPath??"./test-results/testrelic-maestro.json";return t.outputPath=r,t.htmlReportPath=e?.htmlReportPath??r.replace(/\.json$/,".html"),t.openReport=e?.openReport??true,t.includeScreenshots=e?.includeScreenshots??true,t.includeVideo=e?.includeVideo??true,t.includeAiAnalysis=e?.includeAiAnalysis??true,t.includeLogs=e?.includeLogs??true,t.includeFlowMetadata=e?.includeFlowMetadata??true,t.flowsDir=e?.flowsDir??null,t.testRunId=e?.testRunId??null,t.metadata=e?.metadata??null,t.quiet=e?.quiet??false,t.reportMode=e?.reportMode??"batch",t.cloud=Kr(e?.cloud??null),t.network=Gr(e?.network),Object.freeze(t)}function Kr(e){let t=ye(process.cwd()),r=t?be(t):null,n=r?Y(r):null,o=xe(n,e??void 0);return o.apiKey?o:null}var Qr=new fastXmlParser.XMLParser({ignoreAttributes:false,attributeNamePrefix:"@_",allowBooleanAttributes:true,parseAttributeValue:true,trimValues:true});function X(e){return e==null?[]:Array.isArray(e)?e:[e]}function kt(e){return !e||typeof e!="object"?[]:X(e.property).map(n=>({name:String(n["@_name"]??""),value:String(n["@_value"]??"")}))}function Zr(e){let t=String(e["@_name"]??"unnamed"),r=String(e["@_classname"]??t),n=Number(e["@_time"]??0),o=e["@_id"]!=null?String(e["@_id"]):null,s=String(e["@_status"]??"").toUpperCase(),i=e.failure,a=e.error,l=e.skipped!==void 0,c="SUCCESS";return i?c="FAILURE":a?c="ERROR":l?c="SKIPPED":s==="FAILURE"||s==="FAILED"?c="FAILURE":s==="ERROR"?c="ERROR":s==="SKIPPED"&&(c="SKIPPED"),{id:o,name:t,classname:r,time:n,status:c,failureMessage:i?String(i["@_message"]??i["#text"]??""):null,failureType:i?String(i["@_type"]??""):null,errorMessage:a?String(a["@_message"]??a["#text"]??""):null,errorType:a?String(a["@_type"]??""):null,properties:kt(e.properties)}}function vt(e){let t=String(e["@_name"]??"Test Suite"),r=e["@_device"]!=null?String(e["@_device"]):null,n=Number(e["@_tests"]??0),o=Number(e["@_failures"]??0),s=Number(e["@_errors"]??0),i=Number(e["@_skipped"]??0),a=Number(e["@_time"]??0),c=X(e.testcase).map(Zr);return {name:t,device:r,tests:n,failures:o,errors:s,skipped:i,time:a,testCases:c,properties:kt(e.properties)}}function Ct(e){let t=Qr.parse(e),r=[];if(t.testsuites){let l=t.testsuites;r=X(l.testsuite).map(vt);}else t.testsuite&&(r=X(t.testsuite).map(vt));let n=0,o=0,s=0,i=0,a=0;for(let l of r)n+=l.tests,o+=l.failures,s+=l.errors,i+=l.skipped,a+=l.time;return {testSuites:r,totalTests:n,totalFailures:o,totalErrors:s,totalSkipped:i,totalTime:a}}function we(e){let t=fs.readFileSync(e,"utf-8");return Ct(t)}var sn=new Set(["tapOn","doubleTapOn","longPressOn","inputText","eraseText","pasteText","swipe","scroll","scrollUntilVisible","hideKeyboard","pressKey","setClipboard","copyTextFrom"]),an=new Set(["assertVisible","assertNotVisible","assertTrue","assertScreenshot","assertNoDefectsWithAI","assertWithAI","assertCondition"]),ln=new Set(["launchApp","killApp","stopApp","clearState","openLink","back","clearKeychain"]),cn=new Set(["setAirplaneMode","toggleAirplaneMode","setLocation","setOrientation","setPermissions","addMedia","travel"]),dn=new Set(["takeScreenshot","startRecording","stopRecording"]),un=new Set(["runScript","evalScript"]),pn=new Set(["runFlow","repeat","retry","waitForAnimationToEnd","extendedWaitUntil"]),fn=new Set(["assertWithAI","assertNoDefectsWithAI","extractTextWithAI"]),gn=new Set(["inputText","pasteText"]),mn=200,hn=400;function Mt(e){return fn.has(e)?"ai":an.has(e)?"assertion":sn.has(e)?"interaction":ln.has(e)?"navigation":cn.has(e)?"device":dn.has(e)?"media":un.has(e)?"script":pn.has(e)?"flow_control":"other"}var yn={tapOnElement:"tapOn",assertCondition:"assertVisible",backPress:"back",applyConfiguration:"applyConfiguration",defineVariables:"defineVariables"};function Rt(e){let t=e.replace(/Command$/,"");return yn[t]??t}var bn=new Set(["metadata","command","commandName","name","status","duration","durationMs","timestamp","time","error","errorMessage","selector","commands","subSteps","children","sequenceNumber"]);function xn(e){for(let t of Object.keys(e)){if(bn.has(t))continue;let r=e[t];if(r&&typeof r=="object"&&!Array.isArray(r))return t}}function St(e){if(e.selector&&typeof e.selector=="object"){let t=e.selector;if(typeof t.textRegex=="string")return t.textRegex;if(typeof t.text=="string")return t.text;if(typeof t.id=="string")return `#${t.id}`}if(e.condition&&typeof e.condition=="object"){let t=e.condition,r=t.visible??t.notVisible;if(r){if(typeof r.textRegex=="string")return r.textRegex;if(typeof r.text=="string")return r.text}}if(typeof e.path=="string")return e.path}function Tt(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026`}function wn(e){return e.length===0?"":`[REDACTED ${e.length} chars]`}function At(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.x=="number"&&typeof t.y=="number")return `${t.x},${t.y}`}function It(e,t){let r={};switch(e){case "inputText":case "pasteText":{let n=t.text??t.value;typeof n=="string"&&(r.text=gn.has(e)?wn(n):n);break}case "swipe":case "scroll":case "scrollUntilVisible":{typeof t.direction=="string"&&(r.direction=t.direction);let n=At(t.start??t.startRelative),o=At(t.end??t.endRelative);n&&(r.start=n),o&&(r.end=o),typeof t.duration=="number"&&(r.swipeDurationMs=t.duration),typeof t.timeout=="number"&&(r.timeoutMs=t.timeout);break}case "setLocation":{typeof t.latitude=="number"&&(r.latitude=t.latitude),typeof t.longitude=="number"&&(r.longitude=t.longitude);break}case "pressKey":case "back":{typeof t.key=="string"?r.key=t.key:typeof t.code=="string"&&(r.key=t.code);break}case "setOrientation":{typeof t.orientation=="string"&&(r.orientation=t.orientation);break}case "setAirplaneMode":case "toggleAirplaneMode":{(typeof t.value=="string"||typeof t.value=="boolean")&&(r.value=t.value);break}case "setPermissions":{t.permissions&&typeof t.permissions=="object"&&(r.permissions=t.permissions);break}case "addMedia":{Array.isArray(t.mediaPaths)?r.mediaPaths=t.mediaPaths:typeof t.path=="string"&&(r.mediaPaths=[t.path]);break}case "launchApp":case "killApp":case "stopApp":case "clearState":{let n=t.appId??t.packageName??t.bundleId;typeof n=="string"&&(r.appId=n),t.arguments&&(r.arguments=t.arguments);break}case "openLink":{typeof t.url=="string"?r.url=t.url:typeof t.link=="string"&&(r.url=t.link);break}case "runScript":case "evalScript":{typeof t.path=="string"&&(r.path=t.path);let n=t.script??t.scriptString;typeof n=="string"&&(r.script=Tt(n,mn)),typeof t.sourceDescription=="string"&&(r.sourceDescription=t.sourceDescription);break}case "assertWithAI":case "assertNoDefectsWithAI":case "extractTextWithAI":{let n=t.assertion??t.prompt??t.question;typeof n=="string"&&(r.prompt=Tt(n,hn));break}case "extendedWaitUntil":case "waitForAnimationToEnd":{typeof t.timeout=="number"&&(r.timeoutMs=t.timeout);break}case "repeat":case "retry":{typeof t.times=="number"&&(r.times=t.times),typeof t.maxRetries=="number"&&(r.maxRetries=t.maxRetries),typeof t.condition=="object"&&t.condition&&(r.condition=t.condition);break}case "runFlow":{typeof t.file=="string"&&(r.file=t.file),typeof t.flowId=="string"&&(r.flowId=t.flowId);break}default:for(let n of ["text","value","url"]){let o=t[n];if(typeof o=="string"||typeof o=="number"||typeof o=="boolean"){r[n]=o;break}}}return Object.keys(r).length>0?r:void 0}function ve(e,t,r){let n=[e.commands,t.commands,t.subSteps,t.children];for(let o of n)if(Array.isArray(o)&&o.length>0)return o.map((s,i)=>ke(s,i,r));return []}function ke(e,t,r){let n,o,s,i=[];if(typeof e.command=="object"&&e.command!==null&&!Array.isArray(e.command)){let y=e.command,h=Object.keys(y)[0]??`step-${t}`;n=Rt(h);let g=y[h]??{};o=St(g),s=It(n,g),i=ve(g,e,r);}else {let y=xn(e);if(y){n=Rt(y);let h=e[y]??{};o=St(h),s=It(n,h),i=ve(h,e,r);}else n=e.command??e.commandName??e.name??`step-${t}`,o=e.selector??void 0,i=ve({},e,r);}let a=e.metadata??{},l=vn(a.status??e.status),c=a.duration??e.duration??e.durationMs??0,d=typeof a.sequenceNumber=="number"?a.sequenceNumber:void 0,u;typeof a.timestamp=="number"?u=new Date(a.timestamp).toISOString():u=e.timestamp??e.time??r;let p=e.error??e.errorMessage??void 0;return {command:n,category:Mt(n),status:l,duration:c,timestamp:u,...o?{selector:o}:{},...p?{error:p}:{},...s?{details:s}:{},...d!==void 0?{sequenceNumber:d}:{},...i.length>0?{children:i}:{}}}function vn(e){if(!e)return "completed";let t=e.toLowerCase();return t==="failed"||t==="error"?"failed":t==="skipped"?"skipped":"completed"}function Et(e,t){let r=t??new Date().toISOString();try{let n=JSON.parse(e);if(Array.isArray(n))return n.map((o,s)=>ke(o,s,r));if(typeof n=="object"&&n!==null){let o=n,s=o.commands??o.steps??o.data;if(Array.isArray(s))return s.map((i,a)=>ke(i,a,r))}return []}catch{return []}}function Ce(e,t){try{let r=fs.readFileSync(e,"utf-8");return Et(r,t)}catch{return []}}function Re(e){if(!fs.existsSync(e))return [];try{return fs.readdirSync(e,{recursive:!0}).map(String).filter(t=>path.basename(t).startsWith("commands")&&t.endsWith(".json")).map(t=>path.join(e,t))}catch{return []}}function An(e){let t=[];for(let r of e)if(typeof r=="object"&&r!==null){let n=r;if(typeof n.runFlow=="string")t.push(n.runFlow);else if(typeof n.runFlow=="object"&&n.runFlow!==null){let o=n.runFlow;typeof o.file=="string"&&t.push(o.file);}}return t}function Pt(e){if(!e)return [];let t=[],r=Array.isArray(e)?e:[e];for(let n of r)if(typeof n=="string")t.push(n);else if(typeof n=="object"&&n!==null){let o=n;if(typeof o.runFlow=="string")t.push(o.runFlow);else if(typeof o.runFlow=="object"&&o.runFlow!==null){let s=o.runFlow;typeof s.file=="string"&&t.push(s.file);}typeof o.runScript=="string"&&t.push(o.runScript);}return t}function _t(e,t){let r=e.split(/^---\s*$/m,2),n=r[0]??"",o=r[1]??"",s={};try{let b=yaml.parseDocument(n).toJS();typeof b=="object"&&b!==null&&!Array.isArray(b)&&(s=b);}catch{}let i=[];if(o.trim())try{let b=yaml.parseDocument(o).toJS();Array.isArray(b)&&(i=b);}catch{}let a=typeof s.appId=="string"?s.appId:null,l=typeof s.name=="string"?s.name:null,c=[];if(Array.isArray(s.tags))for(let g of s.tags)typeof g=="string"&&c.push(g);let d={};if(typeof s.env=="object"&&s.env!==null&&!Array.isArray(s.env))for(let[g,b]of Object.entries(s.env))d[g]=String(b);let u={};if(typeof s.properties=="object"&&s.properties!==null&&!Array.isArray(s.properties))for(let[g,b]of Object.entries(s.properties))u[g]=String(b);let p=Pt(s.onFlowStart),y=Pt(s.onFlowComplete),h=An(i);return {appId:a,name:l,tags:c,env:d,properties:u,onFlowStart:p,onFlowComplete:y,subflowRefs:h,filePath:t}}function Se(e){let t=fs.readFileSync(e,"utf-8");return _t(t,e)}function Te(e){if(!fs.existsSync(e))return [];let t=[];function r(n){try{let o=fs.readdirSync(n,{withFileTypes:!0});for(let s of o){let i=path.join(n,s.name);if(s.isDirectory())r(i);else if(s.isFile()){let a=path.extname(s.name).toLowerCase();(a===".yaml"||a===".yml")&&t.push(i);}}}catch{}}return r(e),t}var _n=/^(\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?)\s+\[?\s*(\w+)\s*\]?\s+(.+)$/,Ln=/^\[?(\d{2}:\d{2}:\d{2}(?:\.\d+)?)\]?\s+\[?\s*(\w+)\s*\]?\s+(.+)$/;function Lt(e){let t=e.toUpperCase();return t==="DEBUG"||t==="TRACE"||t==="VERBOSE"?"DEBUG":t==="INFO"?"INFO":t==="WARN"||t==="WARNING"?"WARN":t==="ERROR"||t==="FATAL"||t==="SEVERE"?"ERROR":"INFO"}function Dn(e,t){let r=/^(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?$/.exec(t);if(!r)return new Date().toISOString();let n=Number(r[1]),o=Number(r[2]),s=Number(r[3]),i=r[4]?Number(r[4].padEnd(3,"0")):0;return new Date(e.getFullYear(),e.getMonth(),e.getDate(),n,o,s,i).toISOString()}function Dt(e,t){let r=[],n=e.split(`
3
- `),o=t instanceof Date?t:null,s=typeof t=="string"?t:t instanceof Date?`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`:new Date().toISOString().split("T")[0];for(let i of n){let a=i.trim();if(!a)continue;let l=_n.exec(a);if(l){r.push({timestamp:l[1],level:Lt(l[2]),message:l[3],source:null});continue}if(l=Ln.exec(a),l){let c=o?Dn(o,l[1]):`${s}T${l[1]}`;r.push({timestamp:c,level:Lt(l[2]),message:l[3],source:null});continue}if(r.length>0){let c=r[r.length-1];r[r.length-1]={...c,message:c.message+`
4
- `+a};}}return r}function Ae(e,t){try{let r=fs.readFileSync(e,"utf-8");return Dt(r,t)}catch{return []}}function Ie(e){for(let t of e){let r=t.message.toLowerCase();if(r.includes("android")||r.includes("adb")||r.includes("uiautomator")||r.includes("emulator"))return "android";if(r.includes("ios")||r.includes("xcuitest")||r.includes("simulator")||r.includes("xctest"))return "ios";if(r.includes("web driver")||r.includes("chrome")||r.includes("chromium"))return "web"}return "unknown"}function Me(e){if(!fs.existsSync(e))return [];try{return fs.readdirSync(e,{recursive:!0}).map(String).filter(t=>path.basename(t)==="maestro.log"||t.endsWith(".log")).map(t=>path.join(e,t))}catch{return []}}var jn=/(?:defect|issue|bug|error|warning|problem)/i,zn=/(?:critical|severe|major|blocker)/i,qn=/(?:warning|moderate|minor)/i,Ee=/(?:cut[\s-]?off|overlap|truncat|misalign|overflow|clip|obscur|hidden\s+text|broken\s+layout)/i,Q=/(?:spelling|typo|misspell|grammar)/i,Z=/(?:i18n|internationali[sz]ation|locali[sz]ation|untranslated|missing\s+translation)/i,Le=/(?:layout|spacing|padding|margin|alignment|centering|position)/i,De=/(?:accessib|a11y|contrast|screen\s*reader|alt\s*text|aria)/i;function Fe(e){return Q.test(e)?"spelling":Z.test(e)?"i18n":De.test(e)?"accessibility":Le.test(e)?"layout":"ui"}function Pe(e){return zn.test(e)?"critical":qn.test(e)?"warning":"info"}function _e(e){return e.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim()}function Gn(e){let t=[],r=_e(e),n=/<li[^>]*>([\s\S]*?)<\/li>/gi,o;for(;(o=n.exec(e))!==null;){let s=o[1],i=_e(s);!i||i.length<5||(jn.test(i)||Ee.test(i)||Q.test(i)||Z.test(i))&&t.push({type:Fe(i),severity:Pe(i),description:i,location:null,screenshot:null});}if(t.length===0){let s=/<p[^>]*>([\s\S]*?)<\/p>/gi;for(;(o=s.exec(e))!==null;){let i=_e(o[1]);!i||i.length<10||(Ee.test(i)||Q.test(i)||Z.test(i)||Le.test(i)||De.test(i))&&t.push({type:Fe(i),severity:Pe(i),description:i,location:null,screenshot:null});}}if(t.length===0&&r.length>20){let s=r.split(/[.!?]+/).filter(i=>i.trim().length>10);for(let i of s){let a=i.trim();(Ee.test(a)||Q.test(a)||Z.test(a)||Le.test(a)||De.test(a))&&t.push({type:Fe(a),severity:Pe(a),description:a,location:null,screenshot:null});}}return t}function Nt(e){let t=Gn(e);return {defects:t,totalDefects:t.length,hasIssues:t.length>0,rawHtml:e}}function Ne(e){try{let t=fs.readFileSync(e,"utf-8");return Nt(t)}catch{return {defects:[],totalDefects:0,hasIssues:false,rawHtml:null}}}function Oe(e){if(!fs.existsSync(e))return [];try{return fs.readdirSync(e,{recursive:!0}).map(String).filter(t=>{let r=path.basename(t).toLowerCase();return path.extname(t).toLowerCase()===".html"&&(r.includes("insight")||r.includes("ai")||r.includes("analysis"))}).map(t=>path.join(e,t))}catch{return []}}var Xn=new Set([".png",".jpg",".jpeg",".webp"]),Qn=new Set([".mp4",".webm",".mov"]);function Ot(e){let t=[];if(!fs.existsSync(e))return t;function r(n){try{let o=fs.readdirSync(n,{withFileTypes:!0});for(let s of o){let i=path.join(n,s.name);s.isDirectory()?r(i):s.isFile()&&t.push(i);}}catch{}}return r(e),t}function Ue(e,t){let r=[],n=[],o=[],s=[],i=[],a=null,l=[];e&&l.push(...Ot(e)),t&&l.push(...Ot(t));let c=new Set;for(let d of l){if(c.has(d))continue;c.add(d);let u=path.basename(d).toLowerCase(),p=path.extname(d).toLowerCase();if(Xn.has(p)){r.push(d);continue}if(Qn.has(p)){n.push(d);continue}if(u==="maestro.log"||p===".log"&&u.includes("maestro")){o.push(d);continue}if(u.startsWith("commands")&&p===".json"){s.push(d);continue}if(p===".html"&&(u.includes("insight")||u.includes("ai")||u.includes("analysis"))){i.push(d);continue}if(p===".xml"&&(u.includes("report")||u.includes("junit"))){a||(a=d);continue}}return {screenshotPaths:r,videoPaths:n,logPaths:o,commandJsonPaths:s,aiReportPaths:i,junitReportPath:a}}function Zn(e){return {screenshots:e.screenshotPaths.length,videos:e.videoPaths.length,logs:e.logPaths.length,commandFiles:e.commandJsonPaths.length,aiReports:e.aiReportPaths.length,junitReport:e.junitReportPath?1:0}}function eo(e){switch(e){case "interaction":return "ui_action";case "assertion":return "assertion";case "ai":return "assertion";case "navigation":return "navigation";case "device":return "custom_step";case "media":return "custom_step";case "script":return "custom_step";case "flow_control":return "custom_step";case "recording":return "custom_step";default:return "custom_step"}}function to(e){let t=e.details;if(t)switch(e.command){case "inputText":case "pasteText":if(typeof t.text=="string")return `${e.command} \u2192 ${t.text}`;break;case "swipe":case "scroll":case "scrollUntilVisible":if(typeof t.direction=="string")return `${e.command} ${t.direction}`;break;case "setLocation":if(typeof t.latitude=="number"&&typeof t.longitude=="number")return `setLocation ${t.latitude},${t.longitude}`;break;case "pressKey":if(typeof t.key=="string")return `pressKey ${t.key}`;break;case "setOrientation":if(typeof t.orientation=="string")return `setOrientation ${t.orientation}`;break;case "launchApp":case "killApp":case "stopApp":case "clearState":if(typeof t.appId=="string")return `${e.command} ${t.appId}`;break;case "openLink":if(typeof t.url=="string")return `openLink ${t.url}`;break;case "runScript":case "evalScript":if(typeof t.path=="string")return `${e.command} ${t.path}`;if(typeof t.sourceDescription=="string")return `${e.command} ${t.sourceDescription}`;if(typeof t.script=="string")return `${e.command} ${t.script}`;break;case "assertWithAI":case "assertNoDefectsWithAI":case "extractTextWithAI":if(typeof t.prompt=="string")return `${e.command} \u2192 ${t.prompt}`;break;case "retry":if(typeof t.maxRetries=="number")return `retry \xD7 ${t.maxRetries}`;break;case "repeat":if(typeof t.times=="number")return `repeat \xD7 ${t.times}`;break;case "runFlow":if(typeof t.file=="string")return `runFlow ${t.file}`;break}return e.selector?`${e.command} \u2192 ${e.selector}`:e.command}function He(e,t){let r=Date.parse(e.timestamp),n=Number.isFinite(r)&&Number.isFinite(t)?Math.max(0,(r-t)/1e3):null,o=(e.children??[]).map(s=>He(s,t));return {title:to(e),category:eo(e.category),status:e.status==="failed"?"failed":"passed",duration:e.duration,timestamp:e.timestamp,videoOffset:n,error:e.error??null,children:o}}function ro(e,t){let r=Date.parse(e.timestamp),n=Date.parse(t.timestamp);return Number.isFinite(r)&&Number.isFinite(n)&&r!==n?r-n:0}function no(e,t){let r=Date.parse(e.startedAt),n=[...e.commands].sort((l,c)=>{let d=Date.parse(l.timestamp),u=Date.parse(c.timestamp);if(Number.isFinite(d)&&Number.isFinite(u)&&d!==u)return d-u;let p=l.sequenceNumber??0,y=c.sequenceNumber??0;return p-y}),o=[...e.assertions].sort((l,c)=>{let d=Date.parse(l.timestamp),u=Date.parse(c.timestamp);if(Number.isFinite(d)&&Number.isFinite(u)&&d!==u)return d-u;let p=l.sequenceNumber??0,y=c.sequenceNumber??0;return p-y}),s=[...n.map(l=>He(l,r)),...o.map(l=>He(l,r))];s.sort(ro);let i=e.screenshotPaths.length>0||e.videoPath?{screenshot:e.screenshotPaths[0]??void 0,video:e.videoPath??void 0}:null,a=[...e.tags];return e.platform!=="unknown"&&!a.includes(e.platform)&&a.push(e.platform),{title:e.flowName,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:0,tags:a,failure:e.failureMessage?{message:e.failureMessage,line:null,code:null,stack:null}:null,testId:`${e.flowFile}::${e.flowName}`,filePath:e.flowFile,suiteName:e.appId??"maestro-suite",testType:"mobile",isFlaky:false,retryStatus:null,expectedStatus:"passed",actualStatus:e.status,artifacts:i,networkRequests:null,apiCalls:t.length>0?[...t]:null,apiAssertions:null,actions:s.length>0?s:null,consoleLogs:null}}function Ut(e,t){let r=`${e.flowFile}::${e.flowName}`,n=t?.get(r)??[],o=no(e,n);return {url:e.appId??"maestro-flow",navigationType:"page_load",visitedAt:e.startedAt,duration:e.duration,specFile:e.flowFile,domContentLoadedAt:null,networkIdleAt:null,networkStats:null,tests:[o]}}function $e(e,t){return e.map(r=>Ut(r,t))}var Ht={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0};function oo(e){return e===null?"error":e>=200&&e<300?"2xx":e>=300&&e<400?"3xx":e>=400&&e<500?"4xx":e>=500&&e<600?"5xx":"error"}function Be(e,t){if(e.length===0)return null;let r=Math.min(e.length-1,Math.floor(t/100*e.length));return e[r]}function so(e){if(e.length===0)return {totalApiCalls:0,uniqueApiUrls:0,apiCallsByMethod:{},apiCallsByStatusRange:{...Ht},apiResponseTime:null};let t={},r={...Ht},n=new Set,o=[];for(let i of e)t[i.method]=(t[i.method]??0)+1,r[oo(i.responseStatusCode)]+=1,n.add(i.url),Number.isFinite(i.responseTimeMs)&&i.responseTimeMs>0&&o.push(i.responseTimeMs);o.sort((i,a)=>i-a);let s=o.length>0?{p50:Be(o,50)??0,p95:Be(o,95)??0,p99:Be(o,99)??0,avg:o.reduce((i,a)=>i+a,0)/o.length,min:o[0],max:o[o.length-1]}:null;return {totalApiCalls:e.length,uniqueApiUrls:n.size,apiCallsByMethod:t,apiCallsByStatusRange:r,apiResponseTime:s}}function G(e){let t=0,r=0,n=0,o=0,s=0,i=0,a=0,l=0,c=0,d=e.length,u=0,p={},y=new Set,h=[];for(let b of e){y.add(b.url);for(let x of b.tests){switch(t++,x.status){case "passed":r++;break;case "failed":n++;break;case "flaky":o++;break;case "skipped":s++;break;case "timedout":i++;break}if(x.actions)for(let T of x.actions)if(u++,T.category==="assertion")a++,T.status==="passed"?l++:c++;else {let R=T.category;p[R]=(p[R]??0)+1;}x.apiCalls&&x.apiCalls.length>0&&h.push(...x.apiCalls);}}let g=so(h);return {total:t,passed:r,failed:n,flaky:o,skipped:s,timedout:i,...g,totalAssertions:a,passedAssertions:l,failedAssertions:c,totalNavigations:d,uniqueNavigationUrls:y.size,totalTimelineSteps:e.length,totalActionSteps:u,actionStepsByCategory:p}}var $t=`
1
+ 'use strict';var core=require('@testrelic/core'),fs=require('fs'),path=require('path'),fastXmlParser=require('fast-xml-parser'),yaml=require('yaml'),child_process=require('child_process'),os=require('os'),crypto=require('crypto'),url=require('url'),zlib=require('zlib'),stream=require('stream');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;var xt=".testrelic",Ur="testrelic-config.json",zr=".testrelic",Hr=5,$r=new Set(["__proto__","constructor","prototype"]),he=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,projectName:null,queueMaxAge:6048e5,queueDirectory:`${xt}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),Br={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function ve(e){let t=path.resolve(e);for(let r=0;r<=Hr;r++){let o=path.join(t,xt,Ur);if(fs.existsSync(o))try{if(fs.statSync(o).isFile())return o}catch{}let n=path.join(t,zr);if(fs.existsSync(n))try{if(fs.statSync(n).isFile())return process.stderr.write(`[testrelic] Deprecation: config file ".testrelic" has moved to ".testrelic/testrelic-config.json". Please migrate your config file to the new location.
2
+ `),n}catch{}let s=path.dirname(t);if(s===t)break;t=s;}return null}function xe(e){try{let t=fs.readFileSync(e,"utf-8"),r=JSON.parse(t);return typeof r!="object"||r===null||Array.isArray(r)||!yt(r)?null:r}catch{return null}}function yt(e){for(let t of Object.keys(e)){if($r.has(t))return false;let r=e[t];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!yt(r))return false}return true}function Y(e){let t=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(e);if(t)return process.env[t[1]]??null;let r=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(e);return r?process.env[r[1]]??null:e}function X(e){let t=Object.create(null);for(let r of Object.keys(e)){let o=e[r];typeof o=="string"&&o.startsWith("$")?t[r]=Y(o):typeof o=="object"&&o!==null&&!Array.isArray(o)?t[r]=X(o):t[r]=o;}return t}function be(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let r=parseInt(t[1],10),o=t[2],n=Br[o];return !n||r<=0?null:r*n}function ye(e,t){let r=Object.create(null);if(Object.assign(r,he),e){let l=e.cloud;l&&typeof l=="object"&&(typeof l.endpoint=="string"&&(r.endpoint=l.endpoint),typeof l.upload=="string"&&(r.uploadStrategy=l.upload),typeof l.timeout=="number"&&(r.timeout=l.timeout),typeof l.apiKey=="string"&&l.apiKey.length>0&&(r.apiKey=l.apiKey));let c=e["testrelic-repo"]??e.project;c&&typeof c=="object"&&typeof c.name=="string"&&(r.projectName=c.name);let d=e.queue;if(d&&typeof d=="object"){if(typeof d.maxAge=="string"){let p=be(d.maxAge);p!==null&&(r.queueMaxAge=p);}typeof d.directory=="string"&&(r.queueDirectory=d.directory);}}if(t){if(typeof t.apiKey=="string"&&t.apiKey.length>0){let l=t.apiKey.startsWith("$")?Y(t.apiKey):t.apiKey;l&&(r.apiKey=l);}if(typeof t.endpoint=="string"){let l=t.endpoint.startsWith("$")?Y(t.endpoint):t.endpoint;l&&(r.endpoint=l);}if(typeof t.upload=="string"&&(r.uploadStrategy=t.upload),typeof t.timeout=="number"&&(r.timeout=t.timeout),typeof t.projectName=="string"&&(r.projectName=t.projectName),typeof t.queueMaxAge=="string"){let l=be(t.queueMaxAge);l!==null&&(r.queueMaxAge=l);}typeof t.queueDirectory=="string"&&(r.queueDirectory=t.queueDirectory),typeof t.uploadArtifacts=="boolean"&&(r.uploadArtifacts=t.uploadArtifacts),typeof t.artifactMaxSizeMb=="number"&&(r.artifactMaxSizeMb=t.artifactMaxSizeMb);}let o=process.env.TESTRELIC_API_KEY;o&&o.length>0&&(r.apiKey=o);let n=process.env.TESTRELIC_CLOUD_ENDPOINT;n&&core.isValidEndpointUrl(n)&&(r.endpoint=n);let s=process.env.TESTRELIC_UPLOAD_STRATEGY;s&&["batch","realtime","both"].includes(s)&&(r.uploadStrategy=s);let i=process.env.TESTRELIC_CLOUD_TIMEOUT;if(i){let l=parseInt(i,10);!isNaN(l)&&l>=1e3&&l<=12e4&&(r.timeout=l);}let a=Object.freeze(r);return core.isValidCloudConfig(a)?a:he}var qr=["authorization","cookie","set-cookie","x-api-key"],Vr=["password","secret","token","apiKey","api_key"],Jr=1024*1024;function Kr(e){let t=e??{},r=process.env.TESTRELIC_CAPTURE_NETWORK==="1"||process.env.TESTRELIC_CAPTURE_NETWORK?.toLowerCase()==="true";return Object.freeze({enabled:t.enabled??r??false,proxyPort:t.proxyPort??(process.env.TESTRELIC_PROXY_PORT?Number.parseInt(process.env.TESTRELIC_PROXY_PORT,10):8080),proxyHost:t.proxyHost??process.env.TESTRELIC_PROXY_HOST??"127.0.0.1",harPath:t.harPath??process.env.TESTRELIC_HAR_PATH??null,outputDir:t.outputDir??null,skipCertInstall:t.skipCertInstall??false,includeUrls:Object.freeze(t.includeUrls?[...t.includeUrls]:[]),excludeUrls:Object.freeze(t.excludeUrls?[...t.excludeUrls]:[]),redactHeaders:Object.freeze(t.redactHeaders?[...t.redactHeaders]:[...qr]),redactBodyFields:Object.freeze(t.redactBodyFields?[...t.redactBodyFields]:[...Vr]),maxBodyBytes:t.maxBodyBytes??Jr})}var Wr=new Set(["__proto__","constructor","prototype"]);function wt(e){if(typeof e!="object"||e===null)return false;for(let t of Object.keys(e))if(Wr.has(t))return true;return false}function Yr(e){if(typeof e!="object"||e===null||wt(e))return false;let t=e;return !(t.outputPath!==void 0&&typeof t.outputPath!="string"||t.htmlReportPath!==void 0&&typeof t.htmlReportPath!="string"||t.openReport!==void 0&&typeof t.openReport!="boolean"||t.includeScreenshots!==void 0&&typeof t.includeScreenshots!="boolean"||t.includeVideo!==void 0&&typeof t.includeVideo!="boolean"||t.includeAiAnalysis!==void 0&&typeof t.includeAiAnalysis!="boolean"||t.includeLogs!==void 0&&typeof t.includeLogs!="boolean"||t.includeFlowMetadata!==void 0&&typeof t.includeFlowMetadata!="boolean"||t.quiet!==void 0&&typeof t.quiet!="boolean"||t.metadata!==void 0&&t.metadata!==null&&(typeof t.metadata!="object"||wt(t.metadata)))}function Xr(e){if(e!==void 0&&!Yr(e))throw core.createError(core.ErrorCode.CONFIG_INVALID,"Invalid Maestro reporter configuration");let t=Object.create(null),r=e?.outputPath??"./test-results/testrelic-maestro.json";return t.outputPath=r,t.htmlReportPath=e?.htmlReportPath??r.replace(/\.json$/,".html"),t.openReport=e?.openReport??true,t.includeScreenshots=e?.includeScreenshots??true,t.includeVideo=e?.includeVideo??true,t.includeAiAnalysis=e?.includeAiAnalysis??true,t.includeLogs=e?.includeLogs??true,t.includeFlowMetadata=e?.includeFlowMetadata??true,t.flowsDir=e?.flowsDir??null,t.testRunId=e?.testRunId??null,t.metadata=e?.metadata??null,t.quiet=e?.quiet??false,t.reportMode=e?.reportMode??"batch",t.cloud=Qr(e?.cloud??null),t.network=Kr(e?.network),Object.freeze(t)}function Qr(e){let t=ve(process.cwd()),r=t?xe(t):null,o=r?X(r):null,n=ye(o,e??void 0);return n.apiKey?n:null}var q="1.1.0";var to=new fastXmlParser.XMLParser({ignoreAttributes:false,attributeNamePrefix:"@_",allowBooleanAttributes:true,parseAttributeValue:true,trimValues:true});function Q(e){return e==null?[]:Array.isArray(e)?e:[e]}function Ct(e){return !e||typeof e!="object"?[]:Q(e.property).map(o=>({name:String(o["@_name"]??""),value:String(o["@_value"]??"")}))}function ro(e){let t=String(e["@_name"]??"unnamed"),r=String(e["@_classname"]??t),o=Number(e["@_time"]??0),n=e["@_id"]!=null?String(e["@_id"]):null,s=String(e["@_status"]??"").toUpperCase(),i=e.failure,a=e.error,l=e.skipped!==void 0,c="SUCCESS";return i?c="FAILURE":a?c="ERROR":l?c="SKIPPED":s==="FAILURE"||s==="FAILED"?c="FAILURE":s==="ERROR"?c="ERROR":s==="SKIPPED"&&(c="SKIPPED"),{id:n,name:t,classname:r,time:o,status:c,failureMessage:i?String(i["@_message"]??i["#text"]??""):null,failureType:i?String(i["@_type"]??""):null,errorMessage:a?String(a["@_message"]??a["#text"]??""):null,errorType:a?String(a["@_type"]??""):null,properties:Ct(e.properties)}}function kt(e){let t=String(e["@_name"]??"Test Suite"),r=e["@_device"]!=null?String(e["@_device"]):null,o=Number(e["@_tests"]??0),n=Number(e["@_failures"]??0),s=Number(e["@_errors"]??0),i=Number(e["@_skipped"]??0),a=Number(e["@_time"]??0),c=Q(e.testcase).map(ro);return {name:t,device:r,tests:o,failures:n,errors:s,skipped:i,time:a,testCases:c,properties:Ct(e.properties)}}function Rt(e){let t=to.parse(e),r=[];if(t.testsuites){let l=t.testsuites;r=Q(l.testsuite).map(kt);}else t.testsuite&&(r=Q(t.testsuite).map(kt));let o=0,n=0,s=0,i=0,a=0;for(let l of r)o+=l.tests,n+=l.failures,s+=l.errors,i+=l.skipped,a+=l.time;return {testSuites:r,totalTests:o,totalFailures:n,totalErrors:s,totalSkipped:i,totalTime:a}}function we(e){let t=fs.readFileSync(e,"utf-8");return Rt(t)}var lo=new Set(["tapOn","doubleTapOn","longPressOn","inputText","eraseText","pasteText","swipe","scroll","scrollUntilVisible","hideKeyboard","pressKey","setClipboard","copyTextFrom"]),co=new Set(["assertVisible","assertNotVisible","assertTrue","assertScreenshot","assertNoDefectsWithAI","assertWithAI","assertCondition"]),po=new Set(["launchApp","killApp","stopApp","clearState","openLink","back","clearKeychain"]),uo=new Set(["setAirplaneMode","toggleAirplaneMode","setLocation","setOrientation","setPermissions","addMedia","travel"]),fo=new Set(["takeScreenshot","startRecording","stopRecording"]),go=new Set(["runScript","evalScript"]),mo=new Set(["runFlow","repeat","retry","waitForAnimationToEnd","extendedWaitUntil"]),ho=new Set(["assertWithAI","assertNoDefectsWithAI","extractTextWithAI"]),bo=new Set(["inputText","pasteText"]),vo=200,xo=400;function Et(e){return ho.has(e)?"ai":co.has(e)?"assertion":lo.has(e)?"interaction":po.has(e)?"navigation":uo.has(e)?"device":fo.has(e)?"media":go.has(e)?"script":mo.has(e)?"flow_control":"other"}var yo={tapOnElement:"tapOn",assertCondition:"assertVisible",backPress:"back",applyConfiguration:"applyConfiguration",defineVariables:"defineVariables"};function St(e){let t=e.replace(/Command$/,"");return yo[t]??t}var wo=new Set(["metadata","command","commandName","name","status","duration","durationMs","timestamp","time","error","errorMessage","selector","commands","subSteps","children","sequenceNumber"]);function ko(e){for(let t of Object.keys(e)){if(wo.has(t))continue;let r=e[t];if(r&&typeof r=="object"&&!Array.isArray(r))return t}}function Tt(e){if(e.selector&&typeof e.selector=="object"){let t=e.selector;if(typeof t.textRegex=="string")return t.textRegex;if(typeof t.text=="string")return t.text;if(typeof t.id=="string")return `#${t.id}`}if(e.condition&&typeof e.condition=="object"){let t=e.condition,r=t.visible??t.notVisible;if(r){if(typeof r.textRegex=="string")return r.textRegex;if(typeof r.text=="string")return r.text}}if(typeof e.path=="string")return e.path}function At(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026`}function Co(e){return e.length===0?"":`[REDACTED ${e.length} chars]`}function Mt(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.x=="number"&&typeof t.y=="number")return `${t.x},${t.y}`}function It(e,t){let r={};switch(e){case "inputText":case "pasteText":{let o=t.text??t.value;typeof o=="string"&&(r.text=bo.has(e)?Co(o):o);break}case "swipe":case "scroll":case "scrollUntilVisible":{typeof t.direction=="string"&&(r.direction=t.direction);let o=Mt(t.start??t.startRelative),n=Mt(t.end??t.endRelative);o&&(r.start=o),n&&(r.end=n),typeof t.duration=="number"&&(r.swipeDurationMs=t.duration),typeof t.timeout=="number"&&(r.timeoutMs=t.timeout);break}case "setLocation":{typeof t.latitude=="number"&&(r.latitude=t.latitude),typeof t.longitude=="number"&&(r.longitude=t.longitude);break}case "pressKey":case "back":{typeof t.key=="string"?r.key=t.key:typeof t.code=="string"&&(r.key=t.code);break}case "setOrientation":{typeof t.orientation=="string"&&(r.orientation=t.orientation);break}case "setAirplaneMode":case "toggleAirplaneMode":{(typeof t.value=="string"||typeof t.value=="boolean")&&(r.value=t.value);break}case "setPermissions":{t.permissions&&typeof t.permissions=="object"&&(r.permissions=t.permissions);break}case "addMedia":{Array.isArray(t.mediaPaths)?r.mediaPaths=t.mediaPaths:typeof t.path=="string"&&(r.mediaPaths=[t.path]);break}case "launchApp":case "killApp":case "stopApp":case "clearState":{let o=t.appId??t.packageName??t.bundleId;typeof o=="string"&&(r.appId=o),t.arguments&&(r.arguments=t.arguments);break}case "openLink":{typeof t.url=="string"?r.url=t.url:typeof t.link=="string"&&(r.url=t.link);break}case "runScript":case "evalScript":{typeof t.path=="string"&&(r.path=t.path);let o=t.script??t.scriptString;typeof o=="string"&&(r.script=At(o,vo)),typeof t.sourceDescription=="string"&&(r.sourceDescription=t.sourceDescription);break}case "assertWithAI":case "assertNoDefectsWithAI":case "extractTextWithAI":{let o=t.assertion??t.prompt??t.question;typeof o=="string"&&(r.prompt=At(o,xo));break}case "extendedWaitUntil":case "waitForAnimationToEnd":{typeof t.timeout=="number"&&(r.timeoutMs=t.timeout);break}case "repeat":case "retry":{typeof t.times=="number"&&(r.times=t.times),typeof t.maxRetries=="number"&&(r.maxRetries=t.maxRetries),typeof t.condition=="object"&&t.condition&&(r.condition=t.condition);break}case "runFlow":{typeof t.file=="string"&&(r.file=t.file),typeof t.flowId=="string"&&(r.flowId=t.flowId);break}default:for(let o of ["text","value","url"]){let n=t[o];if(typeof n=="string"||typeof n=="number"||typeof n=="boolean"){r[o]=n;break}}}return Object.keys(r).length>0?r:void 0}function ke(e,t,r){let o=[e.commands,t.commands,t.subSteps,t.children];for(let n of o)if(Array.isArray(n)&&n.length>0)return n.map((s,i)=>Ce(s,i,r));return []}function Ce(e,t,r){let o,n,s,i=[];if(typeof e.command=="object"&&e.command!==null&&!Array.isArray(e.command)){let b=e.command,h=Object.keys(b)[0]??`step-${t}`;o=St(h);let g=b[h]??{};n=Tt(g),s=It(o,g),i=ke(g,e,r);}else {let b=ko(e);if(b){o=St(b);let h=e[b]??{};n=Tt(h),s=It(o,h),i=ke(h,e,r);}else o=e.command??e.commandName??e.name??`step-${t}`,n=e.selector??void 0,i=ke({},e,r);}let a=e.metadata??{},l=Ro(a.status??e.status),c=a.duration??e.duration??e.durationMs??0,d=typeof a.sequenceNumber=="number"?a.sequenceNumber:void 0,p;typeof a.timestamp=="number"?p=new Date(a.timestamp).toISOString():p=e.timestamp??e.time??r;let u=e.error??e.errorMessage??void 0;return {command:o,category:Et(o),status:l,duration:c,timestamp:p,...n?{selector:n}:{},...u?{error:u}:{},...s?{details:s}:{},...d!==void 0?{sequenceNumber:d}:{},...i.length>0?{children:i}:{}}}function Ro(e){if(!e)return "completed";let t=e.toLowerCase();return t==="failed"||t==="error"?"failed":t==="skipped"?"skipped":"completed"}function Ft(e,t){let r=t??new Date().toISOString();try{let o=JSON.parse(e);if(Array.isArray(o))return o.map((n,s)=>Ce(n,s,r));if(typeof o=="object"&&o!==null){let n=o,s=n.commands??n.steps??n.data;if(Array.isArray(s))return s.map((i,a)=>Ce(i,a,r))}return []}catch{return []}}function Re(e,t){try{let r=fs.readFileSync(e,"utf-8");return Ft(r,t)}catch{return []}}function Se(e){if(!fs.existsSync(e))return [];try{return fs.readdirSync(e,{recursive:!0}).map(String).filter(t=>path.basename(t).startsWith("commands")&&t.endsWith(".json")).map(t=>path.join(e,t))}catch{return []}}function Eo(e){let t=[];for(let r of e)if(typeof r=="object"&&r!==null){let o=r;if(typeof o.runFlow=="string")t.push(o.runFlow);else if(typeof o.runFlow=="object"&&o.runFlow!==null){let n=o.runFlow;typeof n.file=="string"&&t.push(n.file);}}return t}function Pt(e){if(!e)return [];let t=[],r=Array.isArray(e)?e:[e];for(let o of r)if(typeof o=="string")t.push(o);else if(typeof o=="object"&&o!==null){let n=o;if(typeof n.runFlow=="string")t.push(n.runFlow);else if(typeof n.runFlow=="object"&&n.runFlow!==null){let s=n.runFlow;typeof s.file=="string"&&t.push(s.file);}typeof n.runScript=="string"&&t.push(n.runScript);}return t}function _t(e,t){let r=e.split(/^---\s*$/m,2),o=r[0]??"",n=r[1]??"",s={};try{let v=yaml.parseDocument(o).toJS();typeof v=="object"&&v!==null&&!Array.isArray(v)&&(s=v);}catch{}let i=[];if(n.trim())try{let v=yaml.parseDocument(n).toJS();Array.isArray(v)&&(i=v);}catch{}let a=typeof s.appId=="string"?s.appId:null,l=typeof s.name=="string"?s.name:null,c=[];if(Array.isArray(s.tags))for(let g of s.tags)typeof g=="string"&&c.push(g);let d={};if(typeof s.env=="object"&&s.env!==null&&!Array.isArray(s.env))for(let[g,v]of Object.entries(s.env))d[g]=String(v);let p={};if(typeof s.properties=="object"&&s.properties!==null&&!Array.isArray(s.properties))for(let[g,v]of Object.entries(s.properties))p[g]=String(v);let u=Pt(s.onFlowStart),b=Pt(s.onFlowComplete),h=Eo(i);return {appId:a,name:l,tags:c,env:d,properties:p,onFlowStart:u,onFlowComplete:b,subflowRefs:h,filePath:t}}function Te(e){let t=fs.readFileSync(e,"utf-8");return _t(t,e)}function Ae(e){if(!fs.existsSync(e))return [];let t=[];function r(o){try{let n=fs.readdirSync(o,{withFileTypes:!0});for(let s of n){let i=path.join(o,s.name);if(s.isDirectory())r(i);else if(s.isFile()){let a=path.extname(s.name).toLowerCase();(a===".yaml"||a===".yml")&&t.push(i);}}}catch{}}return r(e),t}var No=/^(\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?)\s+\[?\s*(\w+)\s*\]?\s+(.+)$/,Oo=/^\[?(\d{2}:\d{2}:\d{2}(?:\.\d+)?)\]?\s+\[?\s*(\w+)\s*\]?\s+(.+)$/;function Lt(e){let t=e.toUpperCase();return t==="DEBUG"||t==="TRACE"||t==="VERBOSE"?"DEBUG":t==="INFO"?"INFO":t==="WARN"||t==="WARNING"?"WARN":t==="ERROR"||t==="FATAL"||t==="SEVERE"?"ERROR":"INFO"}function Uo(e,t){let r=/^(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?$/.exec(t);if(!r)return new Date().toISOString();let o=Number(r[1]),n=Number(r[2]),s=Number(r[3]),i=r[4]?Number(r[4].padEnd(3,"0")):0;return new Date(e.getFullYear(),e.getMonth(),e.getDate(),o,n,s,i).toISOString()}function Nt(e,t){let r=[],o=e.split(`
3
+ `),n=t instanceof Date?t:null,s=typeof t=="string"?t:t instanceof Date?`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`:new Date().toISOString().split("T")[0];for(let i of o){let a=i.trim();if(!a)continue;let l=No.exec(a);if(l){r.push({timestamp:l[1],level:Lt(l[2]),message:l[3],source:null});continue}if(l=Oo.exec(a),l){let c=n?Uo(n,l[1]):`${s}T${l[1]}`;r.push({timestamp:c,level:Lt(l[2]),message:l[3],source:null});continue}if(r.length>0){let c=r[r.length-1];r[r.length-1]={...c,message:c.message+`
4
+ `+a};}}return r}function Me(e,t){try{let r=fs.readFileSync(e,"utf-8");return Nt(r,t)}catch{return []}}function Ie(e){for(let t of e){let r=t.message.toLowerCase();if(r.includes("android")||r.includes("adb")||r.includes("uiautomator")||r.includes("emulator"))return "android";if(r.includes("ios")||r.includes("xcuitest")||r.includes("simulator")||r.includes("xctest"))return "ios";if(r.includes("web driver")||r.includes("chrome")||r.includes("chromium"))return "web"}return "unknown"}function Ee(e){if(!fs.existsSync(e))return [];try{return fs.readdirSync(e,{recursive:!0}).map(String).filter(t=>path.basename(t)==="maestro.log"||t.endsWith(".log")).map(t=>path.join(e,t))}catch{return []}}var qo=/(?:defect|issue|bug|error|warning|problem)/i,Vo=/(?:critical|severe|major|blocker)/i,Jo=/(?:warning|moderate|minor)/i,Fe=/(?:cut[\s-]?off|overlap|truncat|misalign|overflow|clip|obscur|hidden\s+text|broken\s+layout)/i,Z=/(?:spelling|typo|misspell|grammar)/i,ee=/(?:i18n|internationali[sz]ation|locali[sz]ation|untranslated|missing\s+translation)/i,Le=/(?:layout|spacing|padding|margin|alignment|centering|position)/i,Ne=/(?:accessib|a11y|contrast|screen\s*reader|alt\s*text|aria)/i;function De(e){return Z.test(e)?"spelling":ee.test(e)?"i18n":Ne.test(e)?"accessibility":Le.test(e)?"layout":"ui"}function Pe(e){return Vo.test(e)?"critical":Jo.test(e)?"warning":"info"}function _e(e){return e.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim()}function Ko(e){let t=[],r=_e(e),o=/<li[^>]*>([\s\S]*?)<\/li>/gi,n;for(;(n=o.exec(e))!==null;){let s=n[1],i=_e(s);!i||i.length<5||(qo.test(i)||Fe.test(i)||Z.test(i)||ee.test(i))&&t.push({type:De(i),severity:Pe(i),description:i,location:null,screenshot:null});}if(t.length===0){let s=/<p[^>]*>([\s\S]*?)<\/p>/gi;for(;(n=s.exec(e))!==null;){let i=_e(n[1]);!i||i.length<10||(Fe.test(i)||Z.test(i)||ee.test(i)||Le.test(i)||Ne.test(i))&&t.push({type:De(i),severity:Pe(i),description:i,location:null,screenshot:null});}}if(t.length===0&&r.length>20){let s=r.split(/[.!?]+/).filter(i=>i.trim().length>10);for(let i of s){let a=i.trim();(Fe.test(a)||Z.test(a)||ee.test(a)||Le.test(a)||Ne.test(a))&&t.push({type:De(a),severity:Pe(a),description:a,location:null,screenshot:null});}}return t}function Ot(e){let t=Ko(e);return {defects:t,totalDefects:t.length,hasIssues:t.length>0,rawHtml:e}}function Oe(e){try{let t=fs.readFileSync(e,"utf-8");return Ot(t)}catch{return {defects:[],totalDefects:0,hasIssues:false,rawHtml:null}}}function Ue(e){if(!fs.existsSync(e))return [];try{return fs.readdirSync(e,{recursive:!0}).map(String).filter(t=>{let r=path.basename(t).toLowerCase();return path.extname(t).toLowerCase()===".html"&&(r.includes("insight")||r.includes("ai")||r.includes("analysis"))}).map(t=>path.join(e,t))}catch{return []}}var en=new Set([".png",".jpg",".jpeg",".webp"]),tn=new Set([".mp4",".webm",".mov"]);function Ut(e){let t=[];if(!fs.existsSync(e))return t;function r(o){try{let n=fs.readdirSync(o,{withFileTypes:!0});for(let s of n){let i=path.join(o,s.name);s.isDirectory()?r(i):s.isFile()&&t.push(i);}}catch{}}return r(e),t}function ze(e,t){let r=[],o=[],n=[],s=[],i=[],a=null,l=[];e&&l.push(...Ut(e)),t&&l.push(...Ut(t));let c=new Set;for(let d of l){if(c.has(d))continue;c.add(d);let p=path.basename(d).toLowerCase(),u=path.extname(d).toLowerCase();if(en.has(u)){r.push(d);continue}if(tn.has(u)){o.push(d);continue}if(p==="maestro.log"||u===".log"&&p.includes("maestro")){n.push(d);continue}if(p.startsWith("commands")&&u===".json"){s.push(d);continue}if(u===".html"&&(p.includes("insight")||p.includes("ai")||p.includes("analysis"))){i.push(d);continue}if(u===".xml"&&(p.includes("report")||p.includes("junit"))){a||(a=d);continue}}return {screenshotPaths:r,videoPaths:o,logPaths:n,commandJsonPaths:s,aiReportPaths:i,junitReportPath:a}}function rn(e){return {screenshots:e.screenshotPaths.length,videos:e.videoPaths.length,logs:e.logPaths.length,commandFiles:e.commandJsonPaths.length,aiReports:e.aiReportPaths.length,junitReport:e.junitReportPath?1:0}}function on(e){switch(e){case "interaction":return "interaction";case "assertion":return "assertion";case "ai":return "ai";case "navigation":return "navigation";case "device":return "device";case "media":return "media";case "script":return "script";case "flow_control":return "flow_control";case "recording":return "media";default:return "other"}}function nn(e){switch(e){case "interaction":return "ui_action";case "assertion":return "assertion";case "ai":return "assertion";case "navigation":return "navigation";case "device":return "custom_step";case "media":return "custom_step";case "script":return "custom_step";case "flow_control":return "custom_step";case "recording":return "custom_step";default:return "custom_step"}}function sn(e){let t=e.details;if(t)switch(e.command){case "inputText":case "pasteText":if(typeof t.text=="string")return `${e.command} \u2192 ${t.text}`;break;case "swipe":case "scroll":case "scrollUntilVisible":if(typeof t.direction=="string")return `${e.command} ${t.direction}`;break;case "setLocation":if(typeof t.latitude=="number"&&typeof t.longitude=="number")return `setLocation ${t.latitude},${t.longitude}`;break;case "pressKey":if(typeof t.key=="string")return `pressKey ${t.key}`;break;case "setOrientation":if(typeof t.orientation=="string")return `setOrientation ${t.orientation}`;break;case "launchApp":case "killApp":case "stopApp":case "clearState":if(typeof t.appId=="string")return `${e.command} ${t.appId}`;break;case "openLink":if(typeof t.url=="string")return `openLink ${t.url}`;break;case "runScript":case "evalScript":if(typeof t.path=="string")return `${e.command} ${t.path}`;if(typeof t.sourceDescription=="string")return `${e.command} ${t.sourceDescription}`;if(typeof t.script=="string")return `${e.command} ${t.script}`;break;case "assertWithAI":case "assertNoDefectsWithAI":case "extractTextWithAI":if(typeof t.prompt=="string")return `${e.command} \u2192 ${t.prompt}`;break;case "retry":if(typeof t.maxRetries=="number")return `retry \xD7 ${t.maxRetries}`;break;case "repeat":if(typeof t.times=="number")return `repeat \xD7 ${t.times}`;break;case "runFlow":if(typeof t.file=="string")return `runFlow ${t.file}`;break}return e.selector?`${e.command} \u2192 ${e.selector}`:e.command}function He(e,t){let r=Date.parse(e.timestamp),o=Number.isFinite(r)&&Number.isFinite(t)?Math.max(0,(r-t)/1e3):null,n=(e.children??[]).map(s=>He(s,t));return {title:sn(e),category:nn(e.category),kind:on(e.category),selector:e.selector??null,status:e.status==="failed"?"failed":"passed",duration:e.duration,timestamp:e.timestamp,videoOffset:o,error:e.error??null,children:n}}function an(e,t){let r=Date.parse(e.timestamp),o=Date.parse(t.timestamp);return Number.isFinite(r)&&Number.isFinite(o)&&r!==o?r-o:0}function ln(e){return {platform:e.platform,platformVersion:null,deviceName:e.deviceId??null,automationName:"maestro",appId:e.appId,appTestMode:e.platform==="web"?"mobile-web":"native",udid:e.deviceId??null}}function cn(e){return e.logEntries.map(t=>({level:t.level==="ERROR"?"error":t.level==="WARN"?"warn":t.level==="DEBUG"?"debug":"info",text:t.message,timestamp:t.timestamp,location:null,source:"driver",tag:t.source??null,pid:null,stackTrace:null}))}function dn(e){return e.aiDefects.map(t=>({type:t.type,severity:t.severity,description:t.description,location:t.location,screenshot:t.screenshot}))}function pn(e,t){let r=Date.parse(e.startedAt),o=[...e.commands].sort((l,c)=>{let d=Date.parse(l.timestamp),p=Date.parse(c.timestamp);if(Number.isFinite(d)&&Number.isFinite(p)&&d!==p)return d-p;let u=l.sequenceNumber??0,b=c.sequenceNumber??0;return u-b}),n=[...e.assertions].sort((l,c)=>{let d=Date.parse(l.timestamp),p=Date.parse(c.timestamp);if(Number.isFinite(d)&&Number.isFinite(p)&&d!==p)return d-p;let u=l.sequenceNumber??0,b=c.sequenceNumber??0;return u-b}),s=[...o.map(l=>He(l,r)),...n.map(l=>He(l,r))];s.sort(an);let i=e.screenshotPaths.length>0||e.videoPath?{screenshot:e.screenshotPaths[0]??void 0,...e.screenshotPaths.length>0?{screenshots:[...e.screenshotPaths]}:{},video:e.videoPath??void 0}:null,a=[...e.tags];return {title:e.flowName,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:0,tags:a,failure:e.failureMessage?{message:e.failureMessage,line:null,code:null,stack:null}:null,testId:`${e.flowFile}::${e.flowName}`,filePath:e.flowFile,suiteName:e.appId??"maestro-suite",testType:"mobile",isFlaky:false,retryStatus:null,expectedStatus:"passed",actualStatus:e.status,artifacts:i,networkRequests:null,apiCalls:t.length>0?[...t]:null,apiAssertions:null,actions:s.length>0?s:null,consoleLogs:e.logEntries.length>0?cn(e):null,device:ln(e),aiDefects:e.aiDefects.length>0?dn(e):null}}function zt(e,t){let r=`${e.flowFile}::${e.flowName}`,o=t?.get(r)??[],n=pn(e,o);return {url:e.appId??"maestro-flow",navigationType:"page_load",visitedAt:e.startedAt,duration:e.duration,specFile:e.flowFile,domContentLoadedAt:null,networkIdleAt:null,networkStats:null,tests:[n]}}function $e(e,t){return e.map(r=>zt(r,t))}var Ht={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0};function un(e){return e===null?"error":e>=200&&e<300?"2xx":e>=300&&e<400?"3xx":e>=400&&e<500?"4xx":e>=500&&e<600?"5xx":"error"}function Be(e,t){if(e.length===0)return null;let r=Math.min(e.length-1,Math.floor(t/100*e.length));return e[r]}function fn(e){if(e.length===0)return {totalApiCalls:0,uniqueApiUrls:0,apiCallsByMethod:{},apiCallsByStatusRange:{...Ht},apiResponseTime:null};let t={},r={...Ht},o=new Set,n=[];for(let i of e)t[i.method]=(t[i.method]??0)+1,r[un(i.responseStatusCode)]+=1,o.add(i.url),Number.isFinite(i.responseTimeMs)&&i.responseTimeMs>0&&n.push(i.responseTimeMs);n.sort((i,a)=>i-a);let s=n.length>0?{p50:Be(n,50)??0,p95:Be(n,95)??0,p99:Be(n,99)??0,avg:n.reduce((i,a)=>i+a,0)/n.length,min:n[0],max:n[n.length-1]}:null;return {totalApiCalls:e.length,uniqueApiUrls:o.size,apiCallsByMethod:t,apiCallsByStatusRange:r,apiResponseTime:s}}function V(e){let t=0,r=0,o=0,n=0,s=0,i=0,a=0,l=0,c=0,d=e.length,p=0,u={},b=new Set,h=[];for(let v of e){b.add(v.url);for(let x of v.tests){switch(t++,x.status){case "passed":r++;break;case "failed":o++;break;case "flaky":n++;break;case "skipped":s++;break;case "timedout":i++;break}if(x.actions)for(let T of x.actions)if(p++,T.category==="assertion")a++,T.status==="passed"?l++:c++;else {let R=T.category;u[R]=(u[R]??0)+1;}x.apiCalls&&x.apiCalls.length>0&&h.push(...x.apiCalls);}}let g=fn(h);return {total:t,passed:r,failed:o,flaky:n,skipped:s,timedout:i,...g,totalAssertions:a,passedAssertions:l,failedAssertions:c,totalNavigations:d,uniqueNavigationUrls:b.size,totalTimelineSteps:e.length,totalActionSteps:p,actionStepsByCategory:u}}var $t=`
5
5
  /* \u2500\u2500 Theme Variables (verbatim from Appium) \u2500\u2500 */
6
6
  :root,[data-theme="dark"]{
7
7
  --bg:#0f1117;--bg-1:#161b22;--bg-2:#1c2128;--bg-3:#21262d;--bg-code:#13111c;
@@ -373,7 +373,7 @@ body{font-family:Inter,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Rob
373
373
  <path fill-rule="evenodd" clip-rule="evenodd" d="M4.75 1.08009C2.034 2.66209 -0.130999 7.63009 0.610001 10.5821C0.969001 12.0121 3.021 15.2131 5.17 17.6971C14.375 28.3321 18 39.7791 18 58.2101V71.0001H12.434C1.16501 71.0001 0 73.4641 0 97.3051C0 106.858 0.298003 128.922 0.662003 146.337L1.323 178H33.606C65.786 178 65.897 178.007 68.544 180.284C72.228 183.453 72.244 189.21 68.579 192.877L65.957 195.5L33.479 195.801L1 196.103V204.551V213H24.577H48.154L51.077 215.923C55.007 219.853 55.007 224.147 51.077 228.077L48.154 231H26.469H4.783L5.41901 233.534C5.76901 234.927 7.143 238.527 8.472 241.534L10.89 247H40.945H71L71.006 241.75C71.017 230.748 76.027 221.606 84.697 216.767C97.854 209.424 114.086 213.895 121.323 226.857C123.659 231.041 124.418 233.833 124.789 239.607L125.263 247H155.187H185.11L187.528 241.534C188.857 238.527 190.231 234.927 190.581 233.534L191.217 231H169.531H147.846L144.923 228.077C142.928 226.082 142 224.152 142 222C142 219.848 142.928 217.918 144.923 215.923L147.846 213H171.423H195V204.551V196.103L162.521 195.801L130.043 195.5L127.421 192.877C123.991 189.445 123.835 183.869 127.074 180.421L129.349 178H162.013H194.677L195.338 146.337C195.702 128.922 196 106.858 196 97.3051C196 73.4641 194.835 71.0001 183.566 71.0001H178V58.2101C178 39.6501 181.397 28.7731 190.538 18.0651C195.631 12.0971 196.572 9.00809 194.511 5.02109C192.672 1.46509 190.197 9.12233e-05 186.028 9.12233e-05C179.761 9.12233e-05 168.713 14.8831 163.388 30.5001C160.975 37.5771 160.608 40.3751 160.213 54.7501L159.765 71.0001H150.732H141.7L142.286 53.2501C142.904 34.5511 144.727 24.3761 148.938 16.1211C151.823 10.4671 151.628 5.90109 148.364 2.63609C145 -0.726907 140.105 -0.887909 136.596 2.25009C133.481 5.03609 128.686 17.0811 126.507 27.5921C125.569 32.1191 124.617 43.0901 124.28 53.2501L123.69 71.0001H115.345H107V38.4231V5.84609L104.077 2.92309C102.082 0.928088 100.152 9.12233e-05 98 9.12233e-05C95.848 9.12233e-05 93.918 0.928088 91.923 2.92309L89 5.84609V38.4231V71.0001H80.655H72.31L71.72 53.2501C71.383 43.0901 70.431 32.1191 69.493 27.5921C67.314 17.0811 62.519 5.03609 59.404 2.25009C55.998 -0.795909 51.059 -0.710905 47.646 2.45209C44.221 5.62609 44.191 9.92109 47.539 17.4911C51.71 26.9241 53.007 34.4791 53.676 53.2501L54.31 71.0001H45.272H36.235L35.787 54.7501C35.392 40.3751 35.025 37.5771 32.612 30.5001C27.194 14.6091 16.228 -0.02891 9.787 0.03009C7.979 0.04709 5.712 0.519093 4.75 1.08009ZM42.687 108.974C33.431 112.591 20.036 125.024 18.408 131.512C17.476 135.223 20.677 140.453 28.253 147.599C37.495 156.319 44.191 159.471 53.5 159.485C59.317 159.494 61.645 158.953 67.274 156.289C77.634 151.385 88.987 139.161 88.996 132.9C89.004 127.304 76.787 114.707 66.745 109.956C59.16 106.368 50.285 106.006 42.687 108.974ZM129.255 109.904C119.151 114.768 106.996 127.33 107.004 132.9C107.013 139.108 118.562 151.475 128.939 156.389C134.338 158.945 136.744 159.496 142.521 159.498C152.526 159.501 160.369 155.502 169.771 145.605C180.444 134.368 180.278 130.975 168.486 119.388C160.043 111.094 152.727 107.595 143 107.201C136.364 106.933 134.78 107.244 129.255 109.904ZM48.5 125.922C46.3 126.969 43.152 128.945 41.505 130.314L38.511 132.802L40.504 135.005C41.601 136.216 44.434 138.342 46.8 139.728C52.577 143.114 57.36 142.466 64.009 137.395L68.978 133.606L66.756 131.24C60.944 125.054 54.357 123.135 48.5 125.922ZM138.386 125.063C136.674 125.571 133.375 127.677 131.057 129.743L126.841 133.5L131.901 137.343C138.65 142.468 143.407 143.124 149.2 139.728C151.566 138.342 154.351 136.269 155.389 135.122C157.684 132.587 156.742 131.097 150.58 127.511C145.438 124.519 142.329 123.895 138.386 125.063ZM91.923 162.923C89.043 165.804 89 166.008 89 176.973C89 184.805 89.435 188.941 90.47 190.941C92.356 194.589 96.918 196.273 101.03 194.84C105.82 193.17 107 189.638 107 176.973C107 166.008 106.957 165.804 104.077 162.923C102.082 160.928 100.152 160 98 160C95.848 160 93.918 160.928 91.923 162.923ZM94.5 232.155C91.026 234.055 90 236.229 90 241.691V247H98H106V242.082C106 235.732 105.37 234.242 101.928 232.463C98.591 230.737 97.197 230.679 94.5 232.155Z" fill="url(#paint0_linear_55_11)"/>
374
374
  <defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
375
375
  <stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
376
- </linearGradient></defs></svg>`;var zt=`
376
+ </linearGradient></defs></svg>`;var Gt=`
377
377
  /* \u2500\u2500 Utilities \u2500\u2500 */
378
378
  function esc(s){if(!s)return '';return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;')}
379
379
  function fmtDur(ms){if(!ms||ms<=0)return '\\u2014';if(ms<1000)return Math.round(ms)+'ms';if(ms<60000)return (ms/1000).toFixed(1)+'s';var m=Math.floor(ms/60000),s=Math.round((ms%60000)/1000);return s>0?m+'m '+s+'s':m+'m'}
@@ -398,13 +398,11 @@ var currentFilter='all';
398
398
  var searchQuery='';
399
399
  var openFlowIdx=-1;
400
400
 
401
+ /* The platform is a device fact now, not a tag the builder appended. */
401
402
  function detectPlatform(){
402
403
  for(var i=0;i<flows.length;i++){
403
- var tags=flows[i].test.tags||[];
404
- for(var j=0;j<tags.length;j++){
405
- var t=tags[j].toLowerCase();
406
- if(t==='android'||t==='ios'||t==='web')return t;
407
- }
404
+ var d=flows[i].test.device;
405
+ if(d&&d.platform&&d.platform!=='unknown')return d.platform;
408
406
  }
409
407
  return '';
410
408
  }
@@ -677,18 +675,28 @@ function closeDrawer(){
677
675
  }
678
676
 
679
677
  function renderDrawerContent(flow){
680
- var tabs=['Overview','Steps','Assertions','Screenshots','AI Defects'];
678
+ var t=flow.test;
679
+ /* Every tab is now about THIS flow. Screenshots and AI Defects used to take
680
+ no flow argument at all and showed the whole run on every flow. */
681
+ var tabs=[
682
+ {name:'Overview',html:function(){return renderOverviewTab(flow);}},
683
+ {name:'Steps',html:function(){return renderStepsTab(flow);}},
684
+ {name:'Replay',html:function(){return renderReplay(t);}},
685
+ {name:'Assertions',html:function(){return renderAssertionsTab(flow);}},
686
+ {name:'Driver log',n:(t.consoleLogs||[]).length,html:function(){return renderDriverLogTab(t);}},
687
+ {name:'Screenshots',n:testScreenshots(t).length,html:function(){return renderShotStrip(t);}},
688
+ {name:'AI Defects',n:(t.aiDefects||[]).length,html:function(){return renderFlowAiDefects(t);}}
689
+ ];
690
+
681
691
  var h='<div class="seg-ctrl">';
682
- tabs.forEach(function(name,i){
683
- h+='<button class="seg-btn'+(i===0?' active':'')+'" data-seg="tab'+i+'">'+name+'</button>';
692
+ tabs.forEach(function(tab,i){
693
+ var label=tab.name+(tab.n?' ('+tab.n+')':'');
694
+ h+='<button class="seg-btn'+(i===0?' active':'')+'" data-seg="tab'+i+'">'+label+'</button>';
684
695
  });
685
696
  h+='</div>';
686
-
687
- h+='<div class="seg-pane active" data-seg-pane="tab0">'+renderOverviewTab(flow)+'</div>';
688
- h+='<div class="seg-pane" data-seg-pane="tab1">'+renderStepsTab(flow)+'</div>';
689
- h+='<div class="seg-pane" data-seg-pane="tab2">'+renderAssertionsTab(flow)+'</div>';
690
- h+='<div class="seg-pane" data-seg-pane="tab3">'+renderScreenshotsTab()+'</div>';
691
- h+='<div class="seg-pane" data-seg-pane="tab4">'+renderAiDefectsTab()+'</div>';
697
+ tabs.forEach(function(tab,i){
698
+ h+='<div class="seg-pane'+(i===0?' active':'')+'" data-seg-pane="tab'+i+'">'+tab.html()+'</div>';
699
+ });
692
700
 
693
701
  $('drawer-body').innerHTML=h;
694
702
  }
@@ -796,7 +804,7 @@ function renderRootCauseAnalysis(t,flow){
796
804
  h+='</div></div>';
797
805
  return h;
798
806
  }
799
- `;var Gt=`
807
+ `;var Vt=`
800
808
  function renderStepsTab(flow){
801
809
  var actions=flow.test.actions||[];
802
810
  if(actions.length===0)return '<div class="no-tests">No step data available for this flow.</div>';
@@ -838,7 +846,7 @@ function renderStepsTab(flow){
838
846
  var dotCls='cmd-dot '+(isFailed?'cmd-dot-fail':'cmd-dot-pass');
839
847
  h+='<div class="'+rowCls+'">';
840
848
  h+='<div class="'+dotCls+'"></div>';
841
- h+=getCmdBadge(a.category);
849
+ h+=a.kind?'<span class="cmd-kind k-'+esc(a.kind)+'">'+esc(a.kind)+'</span>':getCmdBadge(a.category);
842
850
  h+='<div class="cmd-title" title="'+esc(a.title)+'">'+esc(a.title)+'</div>';
843
851
  if(isSlow||isFailed&&a.duration>2000)h+='<span class="cmd-badge cmd-badge-slow">SLOW</span>';
844
852
  h+='<div class="cmd-dur">'+fmtDur(a.duration)+'</div>';
@@ -867,7 +875,7 @@ function getCmdBadge(cat){
867
875
  var pair=m[cat]||['CMD','cmd-badge-cmd'];
868
876
  return '<span class="cmd-badge '+pair[1]+'">'+pair[0]+'</span>';
869
877
  }
870
- `;var Vt=`
878
+ `;var Jt=`
871
879
  function renderAssertionsTab(flow){
872
880
  var actions=flow.test.actions||[];
873
881
  var asserts=actions.filter(function(a){return a.category==='assertion'});
@@ -898,7 +906,7 @@ function renderAssertionsTab(flow){
898
906
  h+='</tbody></table>';
899
907
  return h;
900
908
  }
901
- `;var Jt=`
909
+ `;var Kt=`
902
910
  function renderAiDefectsTab(){
903
911
  if(aiDefects.length===0)return '<div class="ai-empty">\\u2714 No AI defects detected.</div>';
904
912
  var h='<div style="font-size:12px;color:var(--fg-1);margin-bottom:16px">'+aiDefects.length+' defect'+(aiDefects.length>1?'s':'')+' found by Maestro AI analysis</div>';
@@ -997,7 +1005,10 @@ function renderScreenshotsTab(){
997
1005
  var name=p.split(/[\\/\\\\]/).pop()||'screenshot';
998
1006
  var isFail=name.toLowerCase().indexOf('fail')>=0||name.toLowerCase().indexOf('error')>=0;
999
1007
  h+='<div class="screenshot-card'+(isFail?' failure-shot':'')+'" data-lb-idx="'+i+'">'
1000
- +'<img src="'+esc(p)+'" alt="'+esc(name)+'" loading="lazy" onerror="this.parentElement.style.display=\\'none\\'"/>'
1008
+ /* No lazy loading: this grid lives in a seg-pane that starts hidden, and
1009
+ Chrome never fetches a lazy image inside display:none \u2014 the cards came
1010
+ up blank until something else forced a reflow. */
1011
+ +'<img src="'+esc(p)+'" alt="'+esc(name)+'" onerror="this.parentElement.style.display=\\'none\\'"/>'
1001
1012
  +'<div class="screenshot-card-label">'+(isFail?'Failure Screenshot':esc(name))+'</div></div>';
1002
1013
  });
1003
1014
  h+='</div>';
@@ -1142,23 +1153,593 @@ document.addEventListener('input',function(e){
1142
1153
  document.addEventListener('keydown',function(e){
1143
1154
  if(e.key==='Escape'&&$('drawer').classList.contains('open'))closeDrawer();
1144
1155
  });
1145
- `;var io=`
1156
+ `;var Yt=`
1157
+ function vNum(v){return typeof v==='number'?v:0;}
1158
+
1159
+ /* Every flow's TestResult, in the order the list shows them. */
1160
+ function flowTests(){
1161
+ var out=[];
1162
+ for(var i=0;i<flows.length;i++)out.push(flows[i].test);
1163
+ return out;
1164
+ }
1165
+
1166
+ /* \u2500\u2500 Device identity \u2500\u2500 */
1167
+
1168
+ var DEVICE_GLYPH={
1169
+ android:'<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><rect x="5" y="2" width="14" height="20" rx="2.5"/><path d="M10 18.5h4"/></svg>',
1170
+ ios:'<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><rect x="6" y="2" width="12" height="20" rx="3"/><path d="M10 19h4"/></svg>',
1171
+ web:'<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a15 15 0 010 18a15 15 0 010-18"/></svg>'
1172
+ };
1173
+
1174
+ function deviceGlyph(p){
1175
+ return DEVICE_GLYPH[p]||'<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="5" y="2" width="14" height="20" rx="2.5"/></svg>';
1176
+ }
1177
+
1178
+ function deviceHeadline(d){
1179
+ if(!d)return '';
1180
+ var os=d.platform==='ios'?'iOS':d.platform==='android'?'Android':d.platform==='web'?'Web':'Device';
1181
+ return d.platformVersion?os+' '+d.platformVersion:os;
1182
+ }
1183
+
1184
+ function shortAppId(v){
1185
+ var s=String(v);
1186
+ if(s.indexOf('/')<0&&s.indexOf('\\\\')<0)return s;
1187
+ var parts=s.split(/[\\/\\\\]/);
1188
+ return parts[parts.length-1]||s;
1189
+ }
1190
+
1191
+ function renderDeviceStrip(){
1192
+ var el=$('device-strip');
1193
+ if(!el)return;
1194
+ var ts=flowTests(),d=null,seen={},count=0;
1195
+ for(var i=0;i<ts.length;i++){
1196
+ var dv=ts[i].device;
1197
+ if(!dv||dv.platform==='unknown')continue;
1198
+ if(!d)d=dv;
1199
+ var key=(dv.platform||'')+'|'+(dv.deviceName||'');
1200
+ if(!seen[key]){seen[key]=1;count++;}
1201
+ }
1202
+ if(!d){el.innerHTML='';return;}
1203
+
1204
+ var h='<div class="devstrip"><div class="dev-id">';
1205
+ h+='<span class="dev-icon dev-icon-'+esc(d.platform||'unknown')+'">'+deviceGlyph(d.platform)+'</span>';
1206
+ h+='<span><span class="dev-name">'+esc(deviceHeadline(d))+'</span><br>';
1207
+ h+='<span class="dev-sub">'+esc(d.deviceName||'device not named')+'</span></span>';
1208
+ h+='</div><span class="dev-rule"></span><div class="dev-facts">';
1209
+ var facts=[{k:'Driver',v:d.automationName},{k:'App',v:d.appId},{k:'Mode',v:d.appTestMode}];
1210
+ for(var f=0;f<facts.length;f++){
1211
+ if(!facts[f].v)continue;
1212
+ h+='<span class="dev-fact"><span class="dev-fact-k">'+esc(facts[f].k)+'</span>';
1213
+ h+='<span class="dev-fact-v">'+esc(shortAppId(facts[f].v))+'</span></span>';
1214
+ }
1215
+ h+='</div>';
1216
+ if(count>1)h+='<span class="dev-more">'+count+' devices in this run</span>';
1217
+ el.innerHTML=h+'</div>';
1218
+ }
1219
+
1220
+ function deviceBadge(d){
1221
+ if(!d||!d.platform||d.platform==='unknown')return '';
1222
+ var cls=d.platform==='ios'?'trb trb-device-ios':d.platform==='web'?'trb trb-device-web':'trb trb-device';
1223
+ var label=deviceHeadline(d);
1224
+ if(d.deviceName)label+=' \\u00b7 '+d.deviceName;
1225
+ return '<span class="'+cls+'" title="'+esc(label)+'">'+esc(label)+'</span>';
1226
+ }
1227
+
1228
+ /* \u2500\u2500 Mobile cards \u2500\u2500 */
1229
+
1230
+ var KIND_ORDER=['interaction','assertion','gesture','lifecycle','device','keyboard','navigation','find','alert','context','screenshot','media','script','flow_control','ai','other'];
1231
+ var KIND_COLOR={interaction:'#60a5fa',assertion:'#34d399',gesture:'#e879f9',lifecycle:'#fbbf24',device:'#fb923c',keyboard:'#f59e0b',navigation:'#a78bfa',find:'#8b949e',alert:'#ef4444',context:'#484f58',screenshot:'#60a5fa',media:'#60a5fa',script:'#484f58',flow_control:'#484f58',ai:'#2dd4a8',other:'#484f58'};
1232
+
1233
+ function countKinds(steps,into){
1234
+ for(var i=0;i<steps.length;i++){
1235
+ var k=steps[i].kind||'other';
1236
+ into[k]=(into[k]||0)+1;
1237
+ if(steps[i].children&&steps[i].children.length)countKinds(steps[i].children,into);
1238
+ }
1239
+ }
1240
+
1241
+ function renderStepKindCard(){
1242
+ var ts=flowTests(),counts={},total=0,k;
1243
+ for(var i=0;i<ts.length;i++)countKinds(ts[i].actions||[],counts);
1244
+ for(k in counts){if(counts.hasOwnProperty(k))total+=counts[k];}
1245
+ if(total===0)return '';
1246
+ var present=[];
1247
+ for(var o=0;o<KIND_ORDER.length;o++){
1248
+ if(counts[KIND_ORDER[o]])present.push({k:KIND_ORDER[o],n:counts[KIND_ORDER[o]]});
1249
+ }
1250
+ present.sort(function(a,b){return b.n-a.n;});
1251
+ var max=present[0].n||1;
1252
+ var h='<div class="tcard"><div class="tcard-h">By step category<span class="tcard-sub">'+total+' steps</span></div>';
1253
+ for(var p=0;p<Math.min(present.length,7);p++){
1254
+ var c=KIND_COLOR[present[p].k]||'#8b949e';
1255
+ var pct=Math.max(2,Math.round((present[p].n/max)*100));
1256
+ h+='<div class="krow"><span class="krow-k" style="color:'+c+'">'+esc(present[p].k)+'</span>';
1257
+ h+='<span class="krow-track"><span class="krow-fill" style="width:'+pct+'%;background:'+c+'"></span></span>';
1258
+ h+='<span class="krow-n">'+present[p].n+'</span></div>';
1259
+ }
1260
+ return h+'</div>';
1261
+ }
1262
+
1263
+ function renderDriverLogCard(){
1264
+ var ts=flowTests(),total=0,errors=0,warns=0,sample=null;
1265
+ for(var i=0;i<ts.length;i++){
1266
+ var logs=ts[i].consoleLogs||[];
1267
+ total+=logs.length;
1268
+ for(var j=0;j<logs.length;j++){
1269
+ if(logs[j].level==='error'){errors++;if(!sample)sample=logs[j];}
1270
+ else if(logs[j].level==='warn')warns++;
1271
+ }
1272
+ }
1273
+ if(total===0)return '';
1274
+ var other=Math.max(0,total-errors-warns);
1275
+ var h='<div class="tcard"><div class="tcard-h">Driver log<span class="tcard-sub">'+total+' lines</span></div>';
1276
+ h+='<div class="verdict-bar">';
1277
+ if(errors)h+='<span style="flex:'+errors+';background:#ef4444;border-radius:999px"></span>';
1278
+ if(warns)h+='<span style="flex:'+warns+';background:#f59e0b;border-radius:999px"></span>';
1279
+ if(other)h+='<span style="flex:'+other+';background:rgba(255,255,255,.08);border-radius:999px"></span>';
1280
+ h+='</div><div class="lgrid">';
1281
+ h+='<div class="lrow"><span class="lrow-src" style="background:rgba(239,68,68,.12);color:#ef4444">error</span><span class="lrow-l">lines</span><span class="lrow-n" style="color:#ef4444">'+errors+'</span></div>';
1282
+ h+='<div class="lrow"><span class="lrow-src" style="background:rgba(245,158,11,.12);color:#f59e0b">warn</span><span class="lrow-l">lines</span><span class="lrow-n" style="color:#f59e0b">'+warns+'</span></div>';
1283
+ h+='</div>';
1284
+ if(sample)h+='<div class="lsample">'+esc(String(sample.text||''))+'</div>';
1285
+ return h+'</div>';
1286
+ }
1287
+
1288
+ function renderAiDefectCard(){
1289
+ var ts=flowTests(),bySev={critical:0,warning:0,info:0},total=0;
1290
+ for(var i=0;i<ts.length;i++){
1291
+ var ds=ts[i].aiDefects||[];
1292
+ for(var j=0;j<ds.length;j++){total++;bySev[ds[j].severity]=(bySev[ds[j].severity]||0)+1;}
1293
+ }
1294
+ if(total===0)return '';
1295
+ var h='<div class="tcard"><div class="tcard-h">AI defects</div>';
1296
+ h+='<div class="tbig"><span class="tbig-n">'+total+'</span><span class="tbig-l">found</span></div><div class="lgrid">';
1297
+ var rows=[{k:'critical',c:'#ef4444'},{k:'warning',c:'#f59e0b'},{k:'info',c:'#60a5fa'}];
1298
+ for(var r=0;r<rows.length;r++){
1299
+ h+='<div class="lrow"><span class="vc-dot" style="background:'+rows[r].c+'"></span>';
1300
+ h+='<span class="lrow-l">'+rows[r].k+'</span><span class="lrow-n">'+(bySev[rows[r].k]||0)+'</span></div>';
1301
+ }
1302
+ return h+'</div></div>';
1303
+ }
1304
+
1305
+ function renderTypeBand(){
1306
+ var el=$('type-band');
1307
+ if(!el)return;
1308
+ var cards=[];
1309
+ var a=renderStepKindCard();if(a)cards.push(a);
1310
+ var b=renderDriverLogCard();if(b)cards.push(b);
1311
+ var c=renderAiDefectCard();if(c)cards.push(c);
1312
+ el.innerHTML=cards.length?'<div class="tband">'+cards.join('')+'</div>':'';
1313
+ }
1314
+
1315
+ /* \u2500\u2500 Needs attention \u2500\u2500 */
1316
+
1317
+ function failingStep(t){
1318
+ var acts=t.actions||[];
1319
+ for(var i=0;i<acts.length;i++)if(acts[i].status==='failed')return acts[i];
1320
+ return null;
1321
+ }
1322
+
1323
+ function correlatedLog(t,atMs){
1324
+ var logs=t.consoleLogs||[],best=null,bestGap=Infinity;
1325
+ for(var i=0;i<logs.length;i++){
1326
+ var e=logs[i];
1327
+ if(e.level!=='error')continue;
1328
+ var ms=Date.parse(e.timestamp);
1329
+ if(!isFinite(ms))continue;
1330
+ var gap=Math.abs(ms-atMs);
1331
+ if(gap<bestGap&&gap<=5000){best=e;bestGap=gap;}
1332
+ }
1333
+ return best;
1334
+ }
1335
+
1336
+ function mobileEvidenceChips(t){
1337
+ var h='',acts=t.actions||[],gestures=0,failedSteps=0,i;
1338
+ for(i=0;i<acts.length;i++){
1339
+ if(acts[i].kind==='gesture')gestures++;
1340
+ if(acts[i].status==='failed')failedSteps++;
1341
+ }
1342
+ if(acts.length>0)h+='<span class="nchip'+(failedSteps>0?' nchip-bad':'')+'">'+acts.length+' step'+(acts.length===1?'':'s')+(failedSteps>0?' \\u00b7 '+failedSteps+' failed':'')+'</span>';
1343
+ if(gestures>0)h+='<span class="nchip nchip-gesture">'+gestures+' gesture'+(gestures===1?'':'s')+'</span>';
1344
+ var errs=0,logs=t.consoleLogs||[];
1345
+ for(i=0;i<logs.length;i++)if(logs[i].level==='error')errs++;
1346
+ if(errs>0)h+='<span class="nchip nchip-bad">'+errs+' log error'+(errs===1?'':'s')+'</span>';
1347
+ var shots=testScreenshots(t).length;
1348
+ if(shots>0)h+='<span class="nchip">'+shots+' screenshot'+(shots===1?'':'s')+'</span>';
1349
+ if(t.artifacts&&t.artifacts.video)h+='<span class="nchip">recording</span>';
1350
+ var defects=(t.aiDefects||[]).length;
1351
+ if(defects>0)h+='<span class="nchip nchip-bad">'+defects+' AI defect'+(defects===1?'':'s')+'</span>';
1352
+ return h;
1353
+ }
1354
+
1355
+ function renderNeedsAttention(){
1356
+ var el=$('needs-attention');
1357
+ if(!el)return;
1358
+ var bad=[],i;
1359
+ for(i=0;i<flows.length;i++){
1360
+ var st=flows[i].test.status;
1361
+ if(st==='failed'||st==='timedout'||st==='flaky')bad.push(flows[i]);
1362
+ }
1363
+ if(bad.length===0){el.innerHTML='';return;}
1364
+
1365
+ var h='<div class="needs"><div class="needs-head"><span class="needs-title">Needs attention</span>';
1366
+ h+='<span class="needs-count">'+bad.length+'</span></div><div class="needs-list">';
1367
+ for(var j=0;j<Math.min(bad.length,8);j++){
1368
+ var t=bad[j].test;
1369
+ h+='<div class="needs-card" data-flow-idx="'+bad[j].idx+'">';
1370
+ h+='<div class="needs-body"><div class="needs-row1"><span class="needs-name">'+esc(t.title)+'</span>';
1371
+ h+='<span class="trb trb-type">mobile</span>'+deviceBadge(t.device);
1372
+ h+='<span class="needs-file">'+esc(t.filePath)+'</span></div>';
1373
+
1374
+ var step=failingStep(t);
1375
+ if(step){
1376
+ h+='<div class="needs-evidence"><div class="needs-step">';
1377
+ h+='<span class="cmd-kind k-'+esc(step.kind||'other')+'">'+esc(step.kind||'step')+'</span>';
1378
+ h+='<span class="needs-step-t">'+esc(step.title||'')+'</span>';
1379
+ h+='<span class="needs-step-d">'+fmtDur(step.duration||0)+'</span></div>';
1380
+ if(step.error)h+='<div class="needs-cause">'+esc(String(step.error))+'</div>';
1381
+ var log=correlatedLog(t,Date.parse(step.timestamp));
1382
+ if(log){
1383
+ var ts='';
1384
+ try{ts=new Date(log.timestamp).toISOString().substr(11,12);}catch(e){ts='';}
1385
+ h+='<div class="needs-log"><span class="needs-log-t">driver log \\u00b7 '+esc(ts)+'</span>&nbsp;&nbsp;'+esc(String(log.text||''))+'</div>';
1386
+ }
1387
+ h+='</div>';
1388
+ }else if(t.failure&&t.failure.message){
1389
+ h+='<div class="needs-cause">'+esc(String(t.failure.message).split('\\n')[0])+'</div>';
1390
+ }
1391
+
1392
+ h+='<div class="needs-chips">'+mobileEvidenceChips(t)+'</div></div>';
1393
+ h+='<div class="needs-right"><div class="needs-dur">'+fmtDur(t.duration)+'</div>';
1394
+ h+='<div class="needs-open">Open<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M9 18l6-6-6-6"/></svg></div></div></div>';
1395
+ }
1396
+ el.innerHTML=h+'</div></div>';
1397
+ }
1398
+
1399
+ /* \u2500\u2500 Per-flow evidence \u2500\u2500 */
1400
+
1401
+ /* Screenshots belong to the flow that produced them. The Screenshots tab
1402
+ took no flow argument and showed the whole run's shots on every flow. */
1403
+ function testScreenshots(t){
1404
+ var a=t.artifacts;
1405
+ if(a&&a.screenshots&&a.screenshots.length)return a.screenshots;
1406
+ if(a&&a.screenshot)return [a.screenshot];
1407
+ return [];
1408
+ }
1409
+
1410
+ function renderShotStrip(t){
1411
+ var shots=testScreenshots(t);
1412
+ if(shots.length===0)return '<div class="artifact-empty">No screenshots for this flow</div>';
1413
+ var h='<div class="shot-strip">';
1414
+ for(var i=0;i<shots.length;i++){
1415
+ var src=String(shots[i]);
1416
+ var name=src.split(/[\\/\\\\]/).pop()||('shot '+(i+1));
1417
+ var isFail=/fail|error/i.test(name);
1418
+ h+='<div class="shot'+(isFail?' is-failure':'')+'" data-lightbox="'+esc(src)+'">';
1419
+ h+='<img src="'+esc(src)+'" alt="'+esc(name)+'">';
1420
+ h+='<div class="shot-cap" title="'+esc(name)+'">'+esc(name)+'</div></div>';
1421
+ }
1422
+ return h+'</div>';
1423
+ }
1424
+
1425
+ /* Steps against the recording, using the videoOffset the timeline builder
1426
+ has always computed and the local report never read. */
1427
+ function renderReplay(t){
1428
+ var video=t.artifacts&&t.artifacts.video;
1429
+ var acts=t.actions||[];
1430
+ if(!video&&acts.length===0)return '<div class="artifact-empty">No recording for this flow</div>';
1431
+
1432
+ var withOffsets=[],i,maxOff=0;
1433
+ for(i=0;i<acts.length;i++){
1434
+ if(typeof acts[i].videoOffset==='number'){
1435
+ withOffsets.push(acts[i]);
1436
+ if(acts[i].videoOffset>maxOff)maxOff=acts[i].videoOffset;
1437
+ }
1438
+ }
1439
+ var span=maxOff>0?maxOff:(t.duration||0)/1000;
1440
+ if(span<=0)span=1;
1441
+
1442
+ var h='<div class="replay">';
1443
+ if(video)h+='<div class="replay-video"><video id="replay-video" src="'+esc(video)+'" controls preload="metadata"></video></div>';
1444
+ h+='<div class="replay-side">';
1445
+ if(withOffsets.length>0){
1446
+ h+='<div class="scrub">';
1447
+ for(i=0;i<withOffsets.length;i++){
1448
+ var w=withOffsets[i],pct=Math.min(99,Math.max(0,(w.videoOffset/span)*100));
1449
+ var failed=w.status==='failed';
1450
+ var col=failed?'#ef4444':(KIND_COLOR[w.kind||'other']||'#8b949e');
1451
+ h+='<span class="scrub-mark'+(failed?' is-failed':'')+'" style="left:'+pct.toFixed(2)+'%;background:'+col+'" data-seek="'+w.videoOffset.toFixed(2)+'" title="'+esc(w.title||'')+'"></span>';
1452
+ }
1453
+ h+='</div><div class="scrub-legend"><span>0.0s</span><span>'+span.toFixed(1)+'s</span></div>';
1454
+ }
1455
+ h+='<div class="replay-steps">';
1456
+ for(i=0;i<acts.length;i++){
1457
+ var a=acts[i],failed2=a.status==='failed';
1458
+ h+='<div class="rstep'+(failed2?' is-failed':'')+'"'+(typeof a.videoOffset==='number'?' data-seek="'+a.videoOffset.toFixed(2)+'"':'')+'>';
1459
+ h+='<span class="rstep-n">'+(i+1<10?'0':'')+(i+1)+'</span>';
1460
+ h+='<span class="cmd-kind k-'+esc(a.kind||'other')+'">'+esc(a.kind||'step')+'</span>';
1461
+ h+='<span class="rstep-t" title="'+esc(a.title||'')+'">'+esc(a.title||'')+'</span>';
1462
+ if(typeof a.videoOffset==='number')h+='<span class="rstep-off">'+a.videoOffset.toFixed(1)+'s</span>';
1463
+ h+='<span class="rstep-d">'+fmtDur(a.duration||0)+'</span></div>';
1464
+ }
1465
+ return h+'</div></div></div>';
1466
+ }
1467
+
1468
+ /* The driver log, per flow. Maestro's report had no log surface at all. */
1469
+ function renderDriverLogTab(t){
1470
+ var logs=t.consoleLogs||[];
1471
+ if(logs.length===0)return '<div class="artifact-empty">No driver log lines for this flow</div>';
1472
+ var errs=0,warns=0,i;
1473
+ for(i=0;i<logs.length;i++){
1474
+ if(logs[i].level==='error')errs++;else if(logs[i].level==='warn')warns++;
1475
+ }
1476
+ var h='<div class="console-panel"><div class="console-header">';
1477
+ h+='<span class="console-title">Driver log ('+logs.length+')</span>';
1478
+ if(errs>0)h+='<span class="apisec-badge ab-bad" style="background:rgba(239,68,68,.12);color:#ef4444;font-size:10px;font-weight:700;padding:1px 7px;border-radius:4px">'+errs+' errors</span>';
1479
+ if(warns>0)h+='<span style="background:rgba(245,158,11,.12);color:#f59e0b;font-size:10px;font-weight:700;padding:1px 7px;border-radius:4px">'+warns+' warnings</span>';
1480
+ h+='</div><div class="console-list">';
1481
+ var SHOW=200;
1482
+ for(i=0;i<Math.min(logs.length,SHOW);i++)h+=renderLogRow(logs[i]);
1483
+ h+='</div>';
1484
+ if(logs.length>SHOW)h+='<div class="console-more">'+(logs.length-SHOW)+' more lines not shown</div>';
1485
+ return h+'</div>';
1486
+ }
1487
+
1488
+ function renderLogRow(e){
1489
+ var lv=(e.level||'info').toLowerCase();
1490
+ var color=lv==='error'?'#f87171':lv==='warn'?'#fbbf24':lv==='debug'?'#a78bfa':'#60a5fa';
1491
+ var badge=lv==='error'?'E':lv==='warn'?'W':lv==='debug'?'D':'I';
1492
+ var h='<div class="console-entry console-level-'+esc(lv)+'" data-console-level="'+esc(lv)+'">';
1493
+ h+='<span class="console-level-badge" style="color:'+color+'">'+badge+'</span>';
1494
+ var ts='';
1495
+ try{ts=new Date(e.timestamp).toISOString().substr(11,12);}catch(err){ts=String(e.timestamp||'');}
1496
+ h+='<span class="console-time">'+esc(ts)+'</span>';
1497
+ if(e.tag)h+='<span class="console-tag" title="'+esc(String(e.tag))+'">'+esc(String(e.tag))+'</span>';
1498
+ h+='<span class="console-text">'+esc(String(e.text||''))+'</span></div>';
1499
+ return h;
1500
+ }
1501
+
1502
+ function renderFlowAiDefects(t){
1503
+ var defects=t.aiDefects||[];
1504
+ if(defects.length===0)return '<div class="artifact-empty">No AI defects for this flow</div>';
1505
+ var h='';
1506
+ for(var i=0;i<defects.length;i++){
1507
+ var d=defects[i];
1508
+ h+='<div class="aidef aidef-'+esc(d.severity||'info')+'">';
1509
+ if(d.screenshot)h+='<div class="aidef-shot"><img src="'+esc(d.screenshot)+'" alt=""></div>';
1510
+ h+='<div class="aidef-body"><div class="aidef-pills">';
1511
+ h+='<span class="aidef-sev aidef-sev-'+esc(d.severity||'info')+'">'+esc(d.severity||'info')+'</span>';
1512
+ h+='<span class="aidef-type">'+esc(d.type||'ui')+'</span></div>';
1513
+ h+='<div class="aidef-desc">'+esc(d.description||'')+'</div>';
1514
+ if(d.location)h+='<div class="aidef-loc">'+esc(d.location)+'</div>';
1515
+ h+='</div></div>';
1516
+ }
1517
+ return h;
1518
+ }
1519
+
1520
+ /* Clicking a step or a scrub mark seeks the recording. */
1521
+ document.addEventListener('click',function(e){
1522
+ var el=e.target.closest?e.target.closest('[data-seek]'):null;
1523
+ if(el){
1524
+ var v=document.getElementById('replay-video');
1525
+ if(v){
1526
+ var at=parseFloat(el.getAttribute('data-seek'));
1527
+ if(isFinite(at)){try{v.currentTime=at;}catch(err){}}
1528
+ }
1529
+ return;
1530
+ }
1531
+ var card=e.target.closest?e.target.closest('.needs-card'):null;
1532
+ if(card){
1533
+ var idx=parseInt(card.getAttribute('data-flow-idx'),10);
1534
+ if(!isNaN(idx)&&typeof openDrawer==='function')openDrawer(idx);
1535
+ }
1536
+ });
1537
+ `;var Xt=`
1538
+ /* \u2500\u2500 Device strip \u2500\u2500 */
1539
+ .devstrip{background:var(--bg-1);border:1px solid var(--bd);border-radius:12px;padding:14px 20px;display:flex;align-items:center;gap:26px;flex-wrap:wrap;margin-bottom:20px}
1540
+ .dev-id{display:flex;align-items:center;gap:11px}
1541
+ .dev-icon{width:34px;height:34px;border-radius:9px;display:flex;align-items:center;justify-content:center;flex-shrink:0}
1542
+ .dev-icon-android{background:rgba(52,211,153,.1);border:1px solid rgba(52,211,153,.22);color:#34d399}
1543
+ .dev-icon-ios{background:rgba(96,165,250,.1);border:1px solid rgba(96,165,250,.22);color:#60a5fa}
1544
+ .dev-icon-web{background:rgba(167,139,250,.1);border:1px solid rgba(167,139,250,.22);color:#a78bfa}
1545
+ .dev-icon-unknown{background:rgba(255,255,255,.04);border:1px solid var(--bd);color:var(--fg-1)}
1546
+ .dev-name{font-size:14px;font-weight:700;line-height:1.25}
1547
+ .dev-sub{font-size:10.5px;color:var(--fg-1)}
1548
+ .dev-rule{width:1px;height:30px;background:var(--bd)}
1549
+ .dev-facts{display:flex;gap:28px;flex-wrap:wrap}
1550
+ .dev-fact{display:flex;flex-direction:column;gap:2px}
1551
+ .dev-fact-k{font-size:9.5px;color:var(--fg-2);letter-spacing:.06em;text-transform:uppercase}
1552
+ .dev-fact-v{font-size:11.5px;color:var(--fg);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
1553
+ .dev-more{margin-left:auto;font-size:11px;color:var(--fg-1);border:1px solid var(--bd);border-radius:8px;padding:5px 11px;display:flex;align-items:center;gap:7px}
1554
+
1555
+ /* Row + drawer device badge */
1556
+ .trb-device{background:rgba(52,211,153,.1);color:#34d399}
1557
+ .trb-device-ios{background:rgba(96,165,250,.1);color:#60a5fa}
1558
+ .trb-device-web{background:rgba(167,139,250,.1);color:#a78bfa}
1559
+
1560
+ /* \u2500\u2500 Verdict band \u2500\u2500 */
1561
+ .verdict{display:flex;gap:16px;align-items:stretch;margin-bottom:20px;flex-wrap:wrap}
1562
+ .verdict-main{flex:1 1 480px;background:var(--bg-1);border:1px solid var(--bd);border-radius:12px;padding:18px 22px;display:flex;flex-direction:column;gap:14px;min-width:0}
1563
+ .verdict-main.v-failed{border-color:rgba(239,68,68,.22)}
1564
+ .verdict-main.v-passed{border-color:rgba(34,197,94,.18)}
1565
+ .verdict-head{display:flex;align-items:baseline;gap:12px;flex-wrap:wrap}
1566
+ .verdict-title{font-size:21px;font-weight:700;letter-spacing:-.01em}
1567
+ .verdict-where{font-size:12px;color:var(--fg-1)}
1568
+ .verdict-where code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;color:var(--fg)}
1569
+ .verdict-dur{margin-left:auto;display:flex;align-items:center;gap:6px;font-size:12px;color:var(--fg-1)}
1570
+ .verdict-bar{display:flex;height:8px;gap:2px}
1571
+ .verdict-bar>span{border-radius:999px}
1572
+ .verdict-bar-empty{flex:1;background:rgba(255,255,255,.06)}
1573
+ .vb-passed{background:#22c55e}.vb-failed{background:#ef4444}.vb-flaky{background:#f59e0b}
1574
+ .vb-timedout{background:#f97316}.vb-skipped{background:#6b7280}
1575
+ .verdict-counts{display:flex;align-items:center;gap:20px;flex-wrap:wrap}
1576
+ .vc{display:flex;align-items:center;gap:7px}
1577
+ .vc-dot{width:9px;height:9px;border-radius:50%}
1578
+ .vc-n{font-size:14px;font-weight:700}
1579
+ .vc-l{font-size:12px;color:var(--fg-1)}
1580
+ .verdict-zeros{margin-left:auto;font-size:11px;color:var(--fg-2)}
1581
+ .verdict-side{width:300px;flex:0 0 auto;background:var(--bg-1);border:1px solid var(--bd);border-radius:12px;padding:18px 20px;display:flex;flex-direction:column;gap:12px}
1582
+ .verdict-side-label{font-size:10px;font-weight:600;color:var(--fg-2);letter-spacing:.06em;text-transform:uppercase}
1583
+ .verdict-side-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px 10px}
1584
+ .vs-n{font-size:17px;font-weight:700}
1585
+ .vs-n small{font-size:11px;font-weight:500;color:var(--fg-1)}
1586
+ .vs-l{font-size:10px;color:var(--fg-1)}
1587
+ .vs-bad{color:#ef4444}
1588
+
1589
+ /* \u2500\u2500 Type band cards \u2500\u2500 */
1590
+ .tband{display:grid;gap:16px;margin-bottom:20px;grid-template-columns:repeat(auto-fit,minmax(300px,1fr))}
1591
+ .tcard{background:var(--bg-1);border:1px solid var(--bd);border-radius:12px;padding:16px 20px;display:flex;flex-direction:column;gap:12px;min-width:0}
1592
+ .tcard-h{font-size:10px;font-weight:600;color:var(--fg-2);letter-spacing:.06em;text-transform:uppercase;display:flex;align-items:center;gap:8px}
1593
+ .tcard-sub{margin-left:auto;font-weight:500;letter-spacing:0;text-transform:none;font-size:10px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
1594
+ .krow{display:flex;align-items:center;gap:10px}
1595
+ .krow-k{width:78px;font-size:11px;font-weight:700}
1596
+ .krow-track{display:block;flex:1;height:6px;border-radius:999px;background:rgba(255,255,255,.06);overflow:hidden}
1597
+ .krow-fill{display:block;height:100%;border-radius:999px;min-width:3px}
1598
+ .krow-n{font-size:11px;color:var(--fg-1);width:34px;text-align:right}
1599
+ .lgrid{display:flex;flex-direction:column;gap:7px}
1600
+ .lrow{display:flex;align-items:center;gap:9px}
1601
+ .lrow-src{font-size:9px;font-weight:700;padding:1px 6px;border-radius:4px}
1602
+ .lrow-l{font-size:11px;color:var(--fg-1);flex:1}
1603
+ .lrow-n{font-size:12px;font-weight:700}
1604
+ .lsample{font-size:10px;color:var(--fg-2);border-top:1px solid var(--bd);padding-top:8px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
1605
+ .tbig{display:flex;align-items:baseline;gap:8px}
1606
+ .tbig-n{font-size:28px;font-weight:800;line-height:1}
1607
+ .tbig-l{font-size:11px;color:var(--fg-1)}
1608
+
1609
+ /* \u2500\u2500 Needs attention \u2500\u2500 */
1610
+ .needs{margin-bottom:20px}
1611
+ .needs-head{display:flex;align-items:center;gap:8px;padding:0 2px 10px}
1612
+ .needs-title{font-size:11px;font-weight:700;letter-spacing:.06em;text-transform:uppercase}
1613
+ .needs-count{font-size:10px;font-weight:700;color:#ef4444;background:rgba(239,68,68,.12);padding:1px 7px;border-radius:4px}
1614
+ .needs-list{display:flex;flex-direction:column;gap:10px}
1615
+ .needs-card{background:var(--bg-1);border:1px solid rgba(239,68,68,.2);border-left:3px solid #ef4444;border-radius:10px;padding:14px 18px;display:flex;gap:20px;align-items:flex-start;cursor:pointer}
1616
+ .needs-card:hover{border-color:rgba(239,68,68,.4)}
1617
+ .needs-card.nc-flaky{border-color:rgba(245,158,11,.2);border-left-color:#f59e0b}
1618
+ .needs-body{flex:1;min-width:0;display:flex;flex-direction:column;gap:9px}
1619
+ .needs-row1{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
1620
+ .needs-name{font-size:14px;font-weight:600}
1621
+ .needs-file{font-size:11px;color:var(--fg-2);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
1622
+ .needs-cause{font-size:12.5px;color:var(--fg-err)}
1623
+ .needs-cause em{font-style:normal}
1624
+ .needs-evidence{background:var(--bg-code);border:1px solid var(--bd);border-radius:8px;padding:10px 13px;display:flex;flex-direction:column;gap:7px}
1625
+ .needs-step{display:flex;align-items:center;gap:9px;flex-wrap:wrap}
1626
+ .needs-step-t{font-size:11px;color:#d4d4d4;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
1627
+ .needs-step-d{margin-left:auto;font-size:10px;color:var(--fg-2)}
1628
+ .needs-log{font-size:10.5px;color:#fb923c;border-top:1px solid var(--bd);padding-top:7px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
1629
+ .needs-log-t{color:var(--fg-2)}
1630
+ .needs-chips{display:flex;gap:6px;flex-wrap:wrap;align-items:center}
1631
+ .nchip{display:flex;align-items:center;gap:5px;font-size:10px;color:var(--fg-1);background:var(--bg-2);border:1px solid var(--bd);padding:2px 8px;border-radius:999px}
1632
+ .nchip-bad{color:#ef4444;background:rgba(239,68,68,.1);border-color:rgba(239,68,68,.22)}
1633
+ .nchip-gesture{color:#e879f9;background:rgba(232,121,249,.1);border-color:rgba(232,121,249,.22)}
1634
+ .needs-right{display:flex;flex-direction:column;align-items:flex-end;gap:8px;flex-shrink:0}
1635
+ .needs-dur{font-size:13px;font-weight:700;color:var(--fg-1)}
1636
+ .needs-open{display:flex;align-items:center;gap:4px;font-size:11px;font-weight:600;color:#2dd4a8}
1637
+
1638
+ /* \u2500\u2500 Step kind badges \u2500\u2500 */
1639
+ .cmd-kind{font-size:9px;font-weight:700;padding:1px 6px;border-radius:999px;letter-spacing:.04em;text-transform:uppercase;flex-shrink:0;min-width:60px;text-align:center}
1640
+ .k-gesture{background:rgba(232,121,249,.12);color:#e879f9}
1641
+ .k-interaction{background:rgba(96,165,250,.12);color:#60a5fa}
1642
+ .k-assertion{background:rgba(52,211,153,.12);color:#34d399}
1643
+ .k-lifecycle{background:rgba(251,191,36,.12);color:#fbbf24}
1644
+ .k-device{background:rgba(251,146,60,.12);color:#fb923c}
1645
+ .k-keyboard{background:rgba(245,158,11,.12);color:#f59e0b}
1646
+ .k-navigation{background:rgba(167,139,250,.12);color:#a78bfa}
1647
+ .k-find{background:rgba(255,255,255,.05);color:var(--fg-1)}
1648
+ .k-alert{background:rgba(239,68,68,.12);color:#ef4444}
1649
+ .k-screenshot,.k-media{background:rgba(96,165,250,.1);color:#60a5fa}
1650
+ .k-context,.k-script,.k-flow_control,.k-other{background:rgba(255,255,255,.04);color:var(--fg-2)}
1651
+ .k-ai{background:rgba(3,183,156,.14);color:#2dd4a8}
1652
+ .cmd-selector{font-size:10px;color:var(--fg-2);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:220px}
1653
+
1654
+ /* \u2500\u2500 Device log panel \u2500\u2500
1655
+ Maestro had no log surface at all, so it has none of these base classes;
1656
+ the new Driver log tab rendered as unstyled text without them. */
1657
+ .console-panel{border:1px solid var(--bd);border-radius:8px;overflow:hidden;background:var(--bg-1)}
1658
+ .console-header{font-size:11px;font-weight:700;color:var(--fg-1);text-transform:uppercase;letter-spacing:.06em;display:flex;align-items:center;gap:8px;padding:8px 12px;border-bottom:1px solid var(--bd);background:var(--bg-2)}
1659
+ .console-title{font-size:11px;font-weight:700}
1660
+ .console-list{max-height:400px;overflow-y:auto;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px;background:var(--bg)}
1661
+ .console-entry{display:flex;align-items:baseline;gap:8px;padding:3px 10px;border-bottom:1px solid rgba(255,255,255,.03);line-height:20px}
1662
+ .console-entry:hover{background:rgba(255,255,255,.03)}
1663
+ .console-level-badge{font-weight:700;font-size:9px;min-width:14px;text-align:center;flex-shrink:0}
1664
+ .console-time{color:var(--fg-2);font-size:10px;white-space:nowrap;min-width:76px;flex-shrink:0}
1665
+ .console-text{flex:1;min-width:0;word-break:break-word;white-space:pre-wrap;color:var(--fg)}
1666
+ .console-loc{color:var(--fg-2);font-size:10px;white-space:nowrap;margin-left:auto;max-width:180px;overflow:hidden;text-overflow:ellipsis}
1667
+ .console-more{font-size:10.5px;color:var(--fg-2);padding:8px 12px;border-top:1px solid var(--bd)}
1668
+
1669
+ /* \u2500\u2500 Device log provenance \u2500\u2500 */
1670
+ .console-source{font-size:9px;font-weight:700;padding:1px 6px;border-radius:4px;background:rgba(255,255,255,.04);color:var(--fg-1);flex-shrink:0}
1671
+ .console-source-crashlog{background:rgba(239,68,68,.12);color:#ef4444}
1672
+ .console-tag{font-size:10px;color:#fb923c;flex-shrink:0;width:104px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
1673
+ .console-pid{font-size:10px;color:var(--fg-2);flex-shrink:0;width:52px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
1674
+ .console-stack{grid-column:1/-1;font-size:10px;color:var(--fg-2);white-space:pre-wrap;padding:4px 0 6px 24px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
1675
+
1676
+ /* \u2500\u2500 Replay: steps against the recording \u2500\u2500 */
1677
+ .replay{display:flex;gap:22px;flex-wrap:wrap}
1678
+ .replay-video{width:232px;flex-shrink:0}
1679
+ .replay-video video{width:100%;border-radius:12px;border:1px solid var(--bd);background:#000;display:block}
1680
+ .replay-side{flex:1;min-width:280px;display:flex;flex-direction:column;gap:12px}
1681
+ .scrub{position:relative;height:10px;border-radius:999px;background:rgba(255,255,255,.06)}
1682
+ .scrub-mark{position:absolute;top:-3px;width:3px;height:16px;border-radius:2px;cursor:pointer}
1683
+ .scrub-mark.is-failed{top:-5px;width:4px;height:20px;background:#ef4444}
1684
+ .scrub-legend{display:flex;justify-content:space-between;font-size:10px;color:var(--fg-2);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
1685
+ .replay-steps{display:flex;flex-direction:column;gap:4px;max-height:320px;overflow-y:auto}
1686
+ .rstep{display:flex;align-items:center;gap:10px;padding:6px 10px;border-radius:7px;cursor:pointer}
1687
+ .rstep:hover{background:var(--bg-2)}
1688
+ .rstep.is-failed{background:rgba(239,68,68,.07);border:1px solid rgba(239,68,68,.18)}
1689
+ .rstep-n{font-size:10px;color:var(--fg-2);width:22px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
1690
+ .rstep-t{font-size:11.5px;flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
1691
+ .rstep-off{font-size:10px;color:var(--fg-2);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
1692
+ .rstep-d{font-size:11px;color:var(--fg-1);width:52px;text-align:right}
1693
+ .rstep.is-failed .rstep-d{color:#ef4444;font-weight:700}
1694
+
1695
+ /* \u2500\u2500 Screenshot strip: every shot, not only the first \u2500\u2500 */
1696
+ .shot-strip{display:flex;gap:10px;flex-wrap:wrap}
1697
+ .shot{width:118px;border-radius:8px;border:1px solid var(--bd);overflow:hidden;background:var(--bg-2);cursor:pointer}
1698
+ .shot img{width:100%;display:block}
1699
+ .shot-cap{font-size:9.5px;color:var(--fg-2);padding:4px 6px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1700
+ .shot.is-failure{border-color:rgba(239,68,68,.4)}
1701
+
1702
+ /* \u2500\u2500 AI defects \u2500\u2500 */
1703
+ .aidef{border-left:3px solid #6b7280;background:var(--bg-1);border:1px solid var(--bd);border-radius:10px;padding:14px 18px;display:flex;gap:16px;align-items:flex-start;margin-bottom:10px}
1704
+ .aidef-critical{border-left-color:#ef4444}
1705
+ .aidef-warning{border-left-color:#f59e0b}
1706
+ .aidef-info{border-left-color:#60a5fa}
1707
+ .aidef-body{flex:1;min-width:0;display:flex;flex-direction:column;gap:9px}
1708
+ .aidef-pills{display:flex;align-items:center;gap:8px}
1709
+ .aidef-sev{font-size:9px;font-weight:700;padding:1px 7px;border-radius:999px;letter-spacing:.04em;text-transform:uppercase}
1710
+ .aidef-sev-critical{background:rgba(239,68,68,.14);color:#ef4444}
1711
+ .aidef-sev-warning{background:rgba(245,158,11,.14);color:#f59e0b}
1712
+ .aidef-sev-info{background:rgba(96,165,250,.14);color:#60a5fa}
1713
+ .aidef-type{font-size:9px;font-weight:700;padding:1px 7px;border-radius:999px;background:rgba(255,255,255,.04);color:var(--fg-1);letter-spacing:.04em;text-transform:uppercase}
1714
+ .aidef-desc{font-size:13.5px;line-height:1.55}
1715
+ .aidef-loc{font-size:10.5px;color:var(--fg-2);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
1716
+ .aidef-shot{width:92px;flex-shrink:0;border-radius:8px;border:1px solid var(--bd);overflow:hidden}
1717
+ .aidef-shot img{width:100%;display:block}
1718
+
1719
+ @media (max-width:900px){
1720
+ .verdict-side{width:100%}
1721
+ }
1722
+ `;var gn=`
1146
1723
  (function(){
1147
1724
  var payload=JSON.parse(document.getElementById('report-data').textContent);
1148
1725
  var report=payload.report;
1149
1726
  var aiDefects=payload.aiDefects||[];
1150
1727
  var screenshotPaths=payload.screenshotPaths||[];
1151
1728
 
1152
- ${zt}
1153
- ${qt}
1154
1729
  ${Gt}
1730
+ ${qt}
1155
1731
  ${Vt}
1156
1732
  ${Jt}
1733
+ ${Kt}
1157
1734
  ${Wt}
1735
+ ${Yt}
1158
1736
 
1159
1737
  applyTheme();
1160
1738
  renderRunMeta();
1739
+ renderDeviceStrip();
1161
1740
  renderHeroStrip();
1741
+ renderTypeBand();
1742
+ renderNeedsAttention();
1162
1743
  renderWaterfall();
1163
1744
  renderFilterBar();
1164
1745
  renderFlowList();
@@ -1170,10 +1751,10 @@ document.addEventListener('keydown',function(e){
1170
1751
  <head>
1171
1752
  <meta charset="UTF-8">
1172
1753
  <meta name="viewport" content="width=device-width,initial-scale=1">
1173
- <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data: blob: file: 'self'; media-src blob: 'self'; connect-src 'self';">
1754
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data: blob: file: 'self'; media-src blob: data: file: 'self'; connect-src 'self';">
1174
1755
  <title>TestRelic Maestro Test Report</title>
1175
1756
  <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(Bt).toString("base64")}">
1176
- <style>${$t}</style>
1757
+ <style>${$t}${Xt}</style>
1177
1758
  <script>(function(){var p=localStorage.getItem('tr-theme')||'system';var t=p==='system'?(window.matchMedia('(prefers-color-scheme:light)').matches?'light':'dark'):p;document.documentElement.setAttribute('data-theme',t);})()</script>
1178
1759
  </head>
1179
1760
  <body>
@@ -1197,7 +1778,10 @@ document.addEventListener('keydown',function(e){
1197
1778
  </div>
1198
1779
  </div>
1199
1780
 
1781
+ <div id="device-strip"></div>
1200
1782
  <div id="hero-strip" class="hero-strip"></div>
1783
+ <div id="type-band"></div>
1784
+ <div id="needs-attention"></div>
1201
1785
  <div id="waterfall" class="waterfall-card"></div>
1202
1786
  <div id="filter-bar" class="filter-bar"></div>
1203
1787
  <div id="flow-list"></div>
@@ -1225,52 +1809,52 @@ document.addEventListener('keydown',function(e){
1225
1809
  <div class="drawer-body" id="drawer-body"></div>
1226
1810
  </aside>
1227
1811
  <script id="report-data" type="application/json">${t}</script>
1228
- <script>${io}</script>
1812
+ <script>${gn}</script>
1229
1813
  </body>
1230
- </html>`}function ze(e,t,r,n){let o=path.resolve(n),s=path.dirname(o);fs.existsSync(s)||fs.mkdirSync(s,{recursive:true});let a=JSON.stringify({report:e,aiDefects:t,screenshotPaths:r}),l=je(a);fs.writeFileSync(o,l,"utf-8");}function fo(e){let t=60-e.length;return t>0?e+" ".repeat(t):e}function O(e){return `\u2502 ${fo(e)} \u2502
1231
- `}function qe(e,t,r,n,o){if(n||e.total===0)return;let s=`\u250C${"\u2500".repeat(62)}\u2510
1814
+ </html>`}function Ge(e,t,r,o){let n=path.resolve(o),s=path.dirname(n);fs.existsSync(s)||fs.mkdirSync(s,{recursive:true});let a=JSON.stringify({report:e,aiDefects:t,screenshotPaths:r}),l=je(a);fs.writeFileSync(n,l,"utf-8");}function yn(e){let t=60-e.length;return t>0?e+" ".repeat(t):e}function O(e){return `\u2502 ${yn(e)} \u2502
1815
+ `}function qe(e,t,r,o,n){if(o||e.total===0)return;let s=`\u250C${"\u2500".repeat(62)}\u2510
1232
1816
  `,i=`\u2514${"\u2500".repeat(62)}\u2518
1233
- `,a=O(""),l=s;l+=O("TestRelic AI - Maestro Test Report"),l+=a;let c=[];if(e.passed>0&&c.push(`${e.passed} \u2713`),e.failed>0&&c.push(`${e.failed} \u2717`),e.flaky>0&&c.push(`${e.flaky} \u26A0`),e.skipped>0&&c.push(`${e.skipped} skipped`),e.timedout>0&&c.push(`${e.timedout} timedout`),l+=O(`Flows: ${e.total} total (${c.join(" ")})`),e.totalAssertions>0&&(l+=O(`Assertions: ${e.totalAssertions} total (${e.passedAssertions} \u2713 ${e.failedAssertions} \u2717)`)),e.totalActionSteps>0){let d=[],u=e.actionStepsByCategory;u.ui_action&&d.push(`${u.ui_action} UI`),u.navigation&&d.push(`${u.navigation} nav`),u.custom_step&&d.push(`${u.custom_step} custom`);let p=d.length>0?` (${d.join(" ")})`:"";l+=O(`Steps: ${e.totalActionSteps} total${p}`);}if(o&&o.length>0){let d=o.filter(h=>h.severity==="critical").length,u=o.filter(h=>h.severity==="warning").length,p=o.filter(h=>h.severity==="info").length,y=[];d>0&&y.push(`${d} critical`),u>0&&y.push(`${u} warning`),p>0&&y.push(`${p} info`),l+=O(`AI Defects: ${o.length} found (${y.join(" ")})`);}l+=O(`Report: ${r}`),l+=O(`Data: ${t}`),l+=i,l+=`For more information visit us at https://docs.testrelic.ai
1234
- `,process.stderr.write(l);}function Ge(e){let t=process.platform,r,n;t==="darwin"?(r="open",n=[e]):t==="win32"?(r="cmd",n=["/c","start","",e]):(r="xdg-open",n=[e]),child_process.execFile(r,n,()=>{});}function vo(){let e=[];try{let r=path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));e.push(path.join(r,"proxy-addon","testrelic_capture.py")),e.push(path.join(r,"..","src","proxy-addon","testrelic_capture.py"));}catch{}let t=globalThis.__dirname;t&&e.push(path.join(t,"proxy-addon","testrelic_capture.py"));for(let r of e)if(fs.existsSync(r))return path.resolve(r);return null}function ko(e){if(e)return fs.mkdirSync(e,{recursive:true}),e;let t=crypto.randomBytes(6).toString("hex"),r=path.join(os$1.tmpdir(),`testrelic-maestro-network-${t}`);return fs.mkdirSync(r,{recursive:true}),r}async function Co(){return new Promise(e=>{let t=child_process.spawn("mitmdump",["--version"]),r=false,n=o=>{r||(r=true,e(o));};t.on("error",()=>n(false)),t.on("close",o=>n(o===0)),setTimeout(()=>{try{t.kill();}catch{}n(false);},5e3);})}async function Xt(e){let{config:t,verbose:r=true}=e;if(!t.enabled)return null;if(!await Co())return r&&process.stderr.write("\u26A0 TestRelic: --capture-network requested but `mitmdump` is not on PATH.\n Install mitmproxy (`brew install mitmproxy` / `pipx install mitmproxy`)\n or supply --har-path to import a HAR file instead.\n"),null;let n=vo();if(!n)return r&&process.stderr.write(`\u26A0 TestRelic: network-capture addon not found in package; skipping capture.
1235
- `),null;let o=ko(e.outputDir??t.outputDir??void 0),s=path.join(o,"network.jsonl"),i=["--listen-host",t.proxyHost,"--listen-port",String(t.proxyPort),"-s",n,"--set",`testrelic_output=${s}`,"--set",`testrelic_redact_headers=${t.redactHeaders.join(",")}`,"--set",`testrelic_redact_body_fields=${t.redactBodyFields.join(",")}`,"--set",`testrelic_max_body_bytes=${t.maxBodyBytes}`,"--set","console_eventlog_verbosity=warn","--set","termlog_verbosity=warn"],a;try{a=child_process.spawn("mitmdump",i,{stdio:["ignore","pipe","pipe"]});}catch(c){return r&&process.stderr.write(`\u26A0 TestRelic: failed to spawn mitmdump: ${c.message}
1236
- `),null}a.stdout?.on("data",c=>{r&&process.stderr.write(`[mitmdump] ${c.toString("utf-8")}`);}),a.stderr?.on("data",c=>{r&&process.stderr.write(`[mitmdump] ${c.toString("utf-8")}`);}),await new Promise(c=>setTimeout(c,750));let l=()=>new Promise(c=>{if(a.killed||a.exitCode!==null){c();return}let d=false,u=()=>{d||(d=true,c());};a.once("close",u),a.once("exit",u);try{a.kill("SIGINT");}catch{try{a.kill();}catch{}}setTimeout(()=>{if(!d){try{a.kill("SIGKILL");}catch{}u();}},4e3);});return {outputPath:s,outputDir:o,host:t.proxyHost,port:t.proxyPort,stop:l}}var $={teardown:async()=>{}};function er(e){let t=child_process.spawnSync(e,["--version"],{stdio:"ignore"});return t.error===void 0||t.error.code!=="ENOENT"}function E(e,t){e||process.stderr.write(`${t}
1237
- `);}function U(e,t,r,n){e||(t==="android"?process.stderr.write(`\u2139 TestRelic: real-device Android capture \u2014 set the device proxy manually:
1817
+ `,a=O(""),l=s;l+=O("TestRelic AI - Maestro Test Report"),l+=a;let c=[];if(e.passed>0&&c.push(`${e.passed} \u2713`),e.failed>0&&c.push(`${e.failed} \u2717`),e.flaky>0&&c.push(`${e.flaky} \u26A0`),e.skipped>0&&c.push(`${e.skipped} skipped`),e.timedout>0&&c.push(`${e.timedout} timedout`),l+=O(`Flows: ${e.total} total (${c.join(" ")})`),e.totalAssertions>0&&(l+=O(`Assertions: ${e.totalAssertions} total (${e.passedAssertions} \u2713 ${e.failedAssertions} \u2717)`)),e.totalActionSteps>0){let d=[],p=e.actionStepsByCategory;p.ui_action&&d.push(`${p.ui_action} UI`),p.navigation&&d.push(`${p.navigation} nav`),p.custom_step&&d.push(`${p.custom_step} custom`);let u=d.length>0?` (${d.join(" ")})`:"";l+=O(`Steps: ${e.totalActionSteps} total${u}`);}if(n&&n.length>0){let d=n.filter(h=>h.severity==="critical").length,p=n.filter(h=>h.severity==="warning").length,u=n.filter(h=>h.severity==="info").length,b=[];d>0&&b.push(`${d} critical`),p>0&&b.push(`${p} warning`),u>0&&b.push(`${u} info`),l+=O(`AI Defects: ${n.length} found (${b.join(" ")})`);}l+=O(`Report: ${r}`),l+=O(`Data: ${t}`),l+=i,l+=`For more information visit us at https://docs.testrelic.ai
1818
+ `,process.stderr.write(l);}function Ve(e){let t=process.platform,r,o;t==="darwin"?(r="open",o=[e]):t==="win32"?(r="cmd",o=["/c","start","",e]):(r="xdg-open",o=[e]),child_process.execFile(r,o,()=>{});}function Mn(){let e=[];try{let r=path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));e.push(path.join(r,"proxy-addon","testrelic_capture.py")),e.push(path.join(r,"..","src","proxy-addon","testrelic_capture.py"));}catch{}let t=globalThis.__dirname;t&&e.push(path.join(t,"proxy-addon","testrelic_capture.py"));for(let r of e)if(fs.existsSync(r))return path.resolve(r);return null}function In(e){if(e)return fs.mkdirSync(e,{recursive:true}),e;let t=crypto.randomBytes(6).toString("hex"),r=path.join(os.tmpdir(),`testrelic-maestro-network-${t}`);return fs.mkdirSync(r,{recursive:true}),r}async function En(){return new Promise(e=>{let t=child_process.spawn("mitmdump",["--version"]),r=false,o=n=>{r||(r=true,e(n));};t.on("error",()=>o(false)),t.on("close",n=>o(n===0)),setTimeout(()=>{try{t.kill();}catch{}o(false);},5e3);})}async function er(e){let{config:t,verbose:r=true}=e;if(!t.enabled)return null;if(!await En())return r&&process.stderr.write("\u26A0 TestRelic: --capture-network requested but `mitmdump` is not on PATH.\n Install mitmproxy (`brew install mitmproxy` / `pipx install mitmproxy`)\n or supply --har-path to import a HAR file instead.\n"),null;let o=Mn();if(!o)return r&&process.stderr.write(`\u26A0 TestRelic: network-capture addon not found in package; skipping capture.
1819
+ `),null;let n=In(e.outputDir??t.outputDir??void 0),s=path.join(n,"network.jsonl"),i=["--listen-host",t.proxyHost,"--listen-port",String(t.proxyPort),"-s",o,"--set",`testrelic_output=${s}`,"--set",`testrelic_redact_headers=${t.redactHeaders.join(",")}`,"--set",`testrelic_redact_body_fields=${t.redactBodyFields.join(",")}`,"--set",`testrelic_max_body_bytes=${t.maxBodyBytes}`,"--set","console_eventlog_verbosity=warn","--set","termlog_verbosity=warn"],a;try{a=child_process.spawn("mitmdump",i,{stdio:["ignore","pipe","pipe"]});}catch(c){return r&&process.stderr.write(`\u26A0 TestRelic: failed to spawn mitmdump: ${c.message}
1820
+ `),null}a.stdout?.on("data",c=>{r&&process.stderr.write(`[mitmdump] ${c.toString("utf-8")}`);}),a.stderr?.on("data",c=>{r&&process.stderr.write(`[mitmdump] ${c.toString("utf-8")}`);}),await new Promise(c=>setTimeout(c,750));let l=()=>new Promise(c=>{if(a.killed||a.exitCode!==null){c();return}let d=false,p=()=>{d||(d=true,c());};a.once("close",p),a.once("exit",p);try{a.kill("SIGINT");}catch{try{a.kill();}catch{}}setTimeout(()=>{if(!d){try{a.kill("SIGKILL");}catch{}p();}},4e3);});return {outputPath:s,outputDir:n,host:t.proxyHost,port:t.proxyPort,stop:l}}var H={teardown:async()=>{}};function or(e){let t=child_process.spawnSync(e,["--version"],{stdio:"ignore"});return t.error===void 0||t.error.code!=="ENOENT"}function E(e,t){e||process.stderr.write(`${t}
1821
+ `);}function U(e,t,r,o){e||(t==="android"?process.stderr.write(`\u2139 TestRelic: real-device Android capture \u2014 set the device proxy manually:
1238
1822
  Settings \u2192 Wi-Fi \u2192 (long-press your network) \u2192 Modify \u2192 Proxy: Manual
1239
- Host: ${r} Port: ${n}
1823
+ Host: ${r} Port: ${o}
1240
1824
  Then install mitmproxy CA: open http://mitm.it from the device after the proxy is reachable.
1241
1825
  `):t==="ios"&&process.stderr.write(`\u2139 TestRelic: real-device iOS capture \u2014 set the device proxy manually:
1242
1826
  Settings \u2192 Wi-Fi \u2192 (i) on your network \u2192 Configure Proxy \u2192 Manual
1243
- Server: ${r} Port: ${n}
1827
+ Server: ${r} Port: ${o}
1244
1828
  Then install + TRUST the mitmproxy CA:
1245
1829
  1. Open http://mitm.it from Safari on the device \u2192 install profile.
1246
1830
  2. Settings \u2192 General \u2192 About \u2192 Certificate Trust Settings \u2192 enable mitmproxy.
1247
- `));}async function Qt(e,t){return new Promise(r=>{let n=t?["-s",t,...e]:e,o=child_process.spawn("adb",n,{stdio:["ignore","pipe","pipe"]}),s="",i="";o.stdout?.on("data",a=>{s+=a.toString();}),o.stderr?.on("data",a=>{i+=a.toString();}),o.on("error",()=>r({code:127,stdout:s,stderr:i||"adb not on PATH"})),o.on("close",a=>r({code:a??1,stdout:s,stderr:i}));})}async function Ao(e){let{deviceId:t,proxyHost:r,proxyPort:n,quiet:o,skipCertInstall:s}=e;if(!er("adb"))return E(o,"\u26A0 TestRelic: `adb` not on PATH; skipping automatic Android proxy setup. See manual instructions:"),U(o,"android",r,n),$;let i=await Qt(["shell","settings","put","global","http_proxy",`${r}:${n}`],t);return i.code!==0?(E(o,`\u26A0 TestRelic: adb set proxy failed: ${i.stderr.trim()||"unknown error"}`),U(o,"android",r,n),$):(E(o,`\u2139 TestRelic: Android proxy set to ${r}:${n} on ${t??"default device"}.`),s||E(o,`\u2139 TestRelic: if HTTPS calls fail, install the mitmproxy CA on the emulator:
1831
+ `));}async function tr(e,t){return new Promise(r=>{let o=t?["-s",t,...e]:e,n=child_process.spawn("adb",o,{stdio:["ignore","pipe","pipe"]}),s="",i="";n.stdout?.on("data",a=>{s+=a.toString();}),n.stderr?.on("data",a=>{i+=a.toString();}),n.on("error",()=>r({code:127,stdout:s,stderr:i||"adb not on PATH"})),n.on("close",a=>r({code:a??1,stdout:s,stderr:i}));})}async function _n(e){let{deviceId:t,proxyHost:r,proxyPort:o,quiet:n,skipCertInstall:s}=e;if(!or("adb"))return E(n,"\u26A0 TestRelic: `adb` not on PATH; skipping automatic Android proxy setup. See manual instructions:"),U(n,"android",r,o),H;let i=await tr(["shell","settings","put","global","http_proxy",`${r}:${o}`],t);return i.code!==0?(E(n,`\u26A0 TestRelic: adb set proxy failed: ${i.stderr.trim()||"unknown error"}`),U(n,"android",r,o),H):(E(n,`\u2139 TestRelic: Android proxy set to ${r}:${o} on ${t??"default device"}.`),s||E(n,`\u2139 TestRelic: if HTTPS calls fail, install the mitmproxy CA on the emulator:
1248
1832
  open http://mitm.it from Chrome on the emulator and follow prompts,
1249
1833
  OR for a system-level install:
1250
1834
  adb root && adb remount && adb push <mitm-ca>.0 /system/etc/security/cacerts/ && adb reboot
1251
- Set --skip-cert-install to silence this hint.`),{teardown:async()=>{await Qt(["shell","settings","put","global","http_proxy",":0"],t);}})}async function Io(e){return new Promise(t=>{let r=child_process.spawn("xcrun",e,{stdio:["ignore","pipe","pipe"]}),n="",o="";r.stdout?.on("data",s=>{n+=s.toString();}),r.stderr?.on("data",s=>{o+=s.toString();}),r.on("error",()=>t({code:127,stdout:n,stderr:o||"xcrun not on PATH"})),r.on("close",s=>t({code:s??1,stdout:n,stderr:o}));})}async function Mo(e){let{proxyHost:t,proxyPort:r,quiet:n,skipCertInstall:o}=e;if(process.platform!=="darwin")return E(n,"\u26A0 TestRelic: iOS simulator capture requires macOS; the host is not Darwin. Skipping setup."),U(n,"ios",t,r),$;if(!er("xcrun"))return E(n,"\u26A0 TestRelic: `xcrun` not on PATH; skipping automatic iOS simulator setup."),U(n,"ios",t,r),$;if(!o){let s=path.join(process.env.HOME??"",".mitmproxy","mitmproxy-ca-cert.pem");if(fs.existsSync(s)){let i=e.deviceId??"booted",a=await Io(["simctl","keychain",i,"add-root-cert",s]);a.code===0?E(n,`\u2139 TestRelic: installed mitmproxy CA on iOS simulator (${i}).`):(E(n,`\u26A0 TestRelic: failed to add-root-cert via simctl: ${a.stderr.trim()}`),U(n,"ios",t,r));}else E(n,`\u26A0 TestRelic: mitmproxy CA not found at ${s}. Run mitmdump once to generate it,
1252
- then re-run with --capture-network. Falling back to manual instructions:`),U(n,"ios",t,r);}return E(n,`\u2139 TestRelic: in the iOS simulator, configure Wi-Fi \u2192 (i) \u2192 Manual proxy:
1835
+ Set --skip-cert-install to silence this hint.`),{teardown:async()=>{await tr(["shell","settings","put","global","http_proxy",":0"],t);}})}async function Ln(e){return new Promise(t=>{let r=child_process.spawn("xcrun",e,{stdio:["ignore","pipe","pipe"]}),o="",n="";r.stdout?.on("data",s=>{o+=s.toString();}),r.stderr?.on("data",s=>{n+=s.toString();}),r.on("error",()=>t({code:127,stdout:o,stderr:n||"xcrun not on PATH"})),r.on("close",s=>t({code:s??1,stdout:o,stderr:n}));})}async function Nn(e){let{proxyHost:t,proxyPort:r,quiet:o,skipCertInstall:n}=e;if(process.platform!=="darwin")return E(o,"\u26A0 TestRelic: iOS simulator capture requires macOS; the host is not Darwin. Skipping setup."),U(o,"ios",t,r),H;if(!or("xcrun"))return E(o,"\u26A0 TestRelic: `xcrun` not on PATH; skipping automatic iOS simulator setup."),U(o,"ios",t,r),H;if(!n){let s=path.join(process.env.HOME??"",".mitmproxy","mitmproxy-ca-cert.pem");if(fs.existsSync(s)){let i=e.deviceId??"booted",a=await Ln(["simctl","keychain",i,"add-root-cert",s]);a.code===0?E(o,`\u2139 TestRelic: installed mitmproxy CA on iOS simulator (${i}).`):(E(o,`\u26A0 TestRelic: failed to add-root-cert via simctl: ${a.stderr.trim()}`),U(o,"ios",t,r));}else E(o,`\u26A0 TestRelic: mitmproxy CA not found at ${s}. Run mitmdump once to generate it,
1836
+ then re-run with --capture-network. Falling back to manual instructions:`),U(o,"ios",t,r);}return E(o,`\u2139 TestRelic: in the iOS simulator, configure Wi-Fi \u2192 (i) \u2192 Manual proxy:
1253
1837
  Server: ${t} Port: ${r}
1254
- (We do not set host-wide \`networksetup\` proxy automatically; see docs.)`),$}async function tr(e){switch(e.platform){case "android":return Ao(e);case "ios":return Mo(e);case "web":return E(e.quiet,"\u2139 TestRelic: --capture-network ignored for Maestro web flows (browser already handles HTTP)."),$;default:return E(e.quiet,"\u26A0 TestRelic: target platform unknown; printing manual proxy setup instructions:"),U(e.quiet,"android",e.proxyHost,e.proxyPort),U(e.quiet,"ios",e.proxyHost,e.proxyPort),$}}function Lo(){let e=crypto.randomBytes(8).toString("hex");return path.join(os$1.tmpdir(),`testrelic-maestro-${e}`)}function nr(e,t){let r=[];e.platform&&r.push("--platform",e.platform),e.device&&r.push("--device",e.device),r.push("test");let n=path.join(t,"report.xml"),o=path.join(t,"artifacts"),s=path.join(t,"debug");if(r.push("--format","junit"),r.push("--output",n),r.push("--test-output-dir",o),r.push("--debug-output",s),e.analyze&&r.push("--analyze"),e.includeTags&&r.push("--include-tags",e.includeTags),e.excludeTags&&r.push("--exclude-tags",e.excludeTags),e.shards&&e.shards>1&&r.push("--shards",String(e.shards)),e.config&&r.push("--config",e.config),e.env)for(let[i,a]of Object.entries(e.env))r.push("-e",`${i}=${a}`);return e.maestroArgs&&r.push(...e.maestroArgs),r.push(...e.flowPaths),r}function Do(e){switch((e??"").toLowerCase()){case "android":return "android";case "ios":return "ios";case "web":return "web";default:return "unknown"}}function No(e,t,r,n,o,s,i){return new Promise(a=>{let l=[],c=[],d=child_process.spawn("maestro",e,{stdio:["inherit","pipe","pipe"]});d.stdout.on("data",u=>{l.push(u),s||process.stdout.write(u);}),d.stderr.on("data",u=>{c.push(u),s||process.stderr.write(u);}),d.on("close",async u=>{try{await i();}catch{}a({exitCode:u??1,junitPath:t,testOutputDir:r,debugOutputDir:n,stdout:Buffer.concat(l).toString("utf-8"),stderr:Buffer.concat(c).toString("utf-8"),networkJsonlDir:o});}),d.on("error",async u=>{try{await i();}catch{}a({exitCode:127,junitPath:t,testOutputDir:r,debugOutputDir:n,stdout:"",stderr:`Failed to start maestro CLI: ${u.message}`,networkJsonlDir:o});});})}async function Oo(e,t={}){let r=e.outputDir?path.resolve(e.outputDir):Lo();fs.mkdirSync(path.join(r,"artifacts"),{recursive:true}),fs.mkdirSync(path.join(r,"debug"),{recursive:true});let n=nr(e,r),o=path.join(r,"report.xml"),s=path.join(r,"artifacts"),i=path.join(r,"debug"),a=null,l=null,c=t.network;if(c?.enabled){let p=path.join(r,"network");a=await Xt({config:c,outputDir:p,verbose:!e.quiet}),a&&(l=await tr({platform:Do(e.platform),deviceId:e.device,proxyHost:a.host,proxyPort:a.port,skipCertInstall:c.skipCertInstall,quiet:e.quiet}));}let d=a?.outputDir??null,u=async()=>{if(a&&await new Promise(p=>setTimeout(p,500)),l)try{await l.teardown();}catch{}if(a)try{await a.stop();}catch{}};return No(n,o,s,i,d,e.quiet,u)}var ir="[REDACTED]";function or(e,t){if(!e)return null;let r=new Set(t.map(o=>o.toLowerCase())),n={};for(let[o,s]of Object.entries(e))n[o]=r.has(o.toLowerCase())?ir:s;return n}function Ve(e,t){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>Ve(n,t));let r={};for(let[n,o]of Object.entries(e))r[n]=t.has(n)?ir:Ve(o,t);return r}function sr(e,t){if(!e||t.length===0)return e;try{let r=JSON.parse(e),n=Ve(r,new Set(t));return JSON.stringify(n)}catch{return e}}function Je(e,t,r){return {...e,requestHeaders:or(e.requestHeaders,t),responseHeaders:or(e.responseHeaders,t),requestBody:sr(e.requestBody,r),responseBody:e.isBinary?e.responseBody:sr(e.responseBody,r)}}function We(e,t,r){let n=o=>typeof o=="string"?e.includes(o):o.test(e);return r.some(n)?false:t.length===0?true:t.some(n)}function $o(e){let t=e.trim();if(!t)return null;try{let r=JSON.parse(t);return typeof r.url!="string"||typeof r.method!="string"?null:{id:r.id??`api-call-${Date.now()}`,timestamp:r.timestamp??new Date().toISOString(),method:r.method,url:r.url,requestHeaders:r.requestHeaders??null,requestBody:r.requestBody??null,responseStatusCode:r.responseStatusCode??null,responseStatusText:r.responseStatusText??null,responseHeaders:r.responseHeaders??null,responseBody:r.responseBody??null,responseTimeMs:typeof r.responseTimeMs=="number"?r.responseTimeMs:0,isBinary:r.isBinary??!1,error:r.error??null}}catch{return null}}function Bo(e,t){let r=[];for(let n of e.split(/\r?\n/)){let o=$o(n);o&&We(o.url,t.includeUrls,t.excludeUrls)&&r.push(Je(o,t.redactHeaders,t.redactBodyFields));}return r}function jo(e,t){try{return Bo(fs.readFileSync(e,"utf-8"),t)}catch{return []}}function zo(e){if(!fs.existsSync(e))return [];try{return fs.readdirSync(e,{recursive:!0}).map(String).filter(t=>t.endsWith(".jsonl")).map(t=>path.join(e,t))}catch{return []}}function ar(e){if(!e||e.length===0)return null;let t={};for(let r of e)typeof r.name=="string"&&typeof r.value=="string"&&(t[r.name]=r.value);return Object.keys(t).length>0?t:null}function qo(e){return e?typeof e.text=="string"?e.text:Array.isArray(e.params)?e.params.map(t=>`${encodeURIComponent(t.name)}=${encodeURIComponent(t.value??"")}`).join("&"):null:null}function Go(e){return e?/^(image|audio|video|application\/(octet-stream|pdf|zip|protobuf))/.test(e):false}function Vo(e,t){let r=e.request,n=e.response;if(!r?.method||!r.url)return null;let o=n?.content,s=Go(o?.mimeType);return {id:`har-call-${t}`,timestamp:e.startedDateTime??new Date().toISOString(),method:r.method,url:r.url,requestHeaders:ar(r.headers),requestBody:qo(r.postData),responseStatusCode:typeof n?.status=="number"&&n.status>0?n.status:null,responseStatusText:n?.statusText??null,responseHeaders:ar(n?.headers),responseBody:o?.text??null,responseTimeMs:typeof e.time=="number"?e.time:0,isBinary:s,error:null}}function Jo(e,t){let r;try{r=JSON.parse(e);}catch{return []}let n=r.log?.entries??[],o=[];return n.forEach((s,i)=>{let a=Vo(s,i);a&&We(a.url,t.includeUrls,t.excludeUrls)&&o.push(Je(a,t.redactHeaders,t.redactBodyFields));}),o}function Wo(e,t){try{return Jo(fs.readFileSync(e,"utf-8"),t)}catch{return []}}function Ko(e,t){let r=new Map;for(let o of t)r.set(o.testId,[]);if(e.length===0||t.length===0)return r;let n=t.map(o=>({testId:o.testId,startMs:Date.parse(o.startedAt),endMs:Date.parse(o.completedAt)}));for(let o of e){let s=Date.parse(o.timestamp);if(!Number.isFinite(s))continue;let i=n.find(l=>Number.isFinite(l.startMs)&&Number.isFinite(l.endMs)&&s>=l.startMs&&s<=l.endMs);if(i){r.get(i.testId).push(o);continue}let a=null;for(let l of n){if(!Number.isFinite(l.startMs)||!Number.isFinite(l.endMs))continue;let c=s<l.startMs?l.startMs-s:s-l.endMs;(!a||c<a.dist)&&(a={testId:l.testId,dist:c});}a&&r.get(a.testId).push(o);}return r}function dr(e,t,r){if(!t.enabled&&!t.harPath)return new Map;let n=[];if(e)for(let o of zo(e))n.push(...jo(o,t));return t.harPath&&fs.existsSync(t.harPath)&&n.push(...Wo(t.harPath,t)),n.length===0?new Map:Ko(n,r)}function ur(e){return e.map((t,r)=>({...t,id:`api-call-${r}`}))}var Qo=new Set(["localhost","127.0.0.1","0.0.0.0"]);function Ke(e){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&Qo.has(t.hostname)))throw core.createError(core.ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${t.protocol}//${t.hostname}`)}var Zo=3e3;async function ee(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Zo);try{return (await fetch(`${e}/health`,{method:"GET",signal:t.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function fr(e){return new Promise(t=>setTimeout(t,e))}async function pr(e){try{let r=(await e.json()).error;if(r&&typeof r.message=="string")return r.message}catch{}return `HTTP ${e.status}`}async function te(e,t,r){let n=new AbortController,o=setTimeout(()=>n.abort(),r);try{let s=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:n.signal});if(s.ok){let a=await s.json();return {accessToken:a.accessToken,refreshToken:a.refreshToken,expiresIn:a.expiresIn,orgId:a.orgId,orgName:a.orgName,userId:a.userId,userName:a.userName}}if(s.status===429){let a=s.headers.get("Retry-After"),l=a?parseInt(a,10)*1e3:5e3;if(!isNaN(l)&&l>0){await fr(l);let c=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:n.signal});if(c.ok){let d=await c.json();return {accessToken:d.accessToken,refreshToken:d.refreshToken,expiresIn:d.expiresIn,orgId:d.orgId,orgName:d.orgName,userId:d.userId,userName:d.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return s.status===400?{code:"validation_error",message:await pr(s),statusCode:400}:s.status===401?{code:"invalid_key",message:"API key is invalid or has been revoked.",statusCode:401}:s.status===403?{code:"expired_key",message:"API key has expired.",statusCode:403}:{code:"server_error",message:await pr(s),statusCode:s.status}}catch(s){return s instanceof DOMException&&s.name==="AbortError"?{code:"timeout",message:"Token exchange timed out.",statusCode:null}:{code:"network_error",message:"Failed to reach cloud for token exchange.",statusCode:null}}finally{clearTimeout(o);}}function re(e){return "code"in e&&typeof e.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(e.code)}async function Ye(e,t,r){let n=new AbortController,o=setTimeout(()=>n.abort(),r);try{let s=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:n.signal});if(s.status===429){let a=s.headers.get("Retry-After"),l=a?parseInt(a,10)*1e3:5e3;!isNaN(l)&&l>0&&(await fr(l),s=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:n.signal}));}if(!s.ok)return null;let i=await s.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn}}catch{return null}finally{clearTimeout(o);}}async function Xe(e,t,r,n,o,s){let i=new AbortController,a=setTimeout(()=>i.abort(),o);try{let l={gitId:r,displayName:n};s&&(l.branch=s);let c=await fetch(`${e}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(l),signal:i.signal});if(!c.ok)return null;let d=await c.json();return {repoId:d.repoId,displayName:d.displayName}}catch{return null}finally{clearTimeout(a);}}var os=5e3;function H(e,t){try{return child_process.execSync(e,{cwd:t,timeout:os,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function Qe(e){let t=H("git rev-parse --abbrev-ref HEAD",e),r=H("git rev-parse --short HEAD",e),n=H("git log -1 --pretty=%s",e),o=H("git log -1 --format=%an",e)??H("git config user.name",e),s=ss(e),i=s?j(s):null;return {branch:t,commitSha:r,commitMessage:n,commitAuthor:o,remoteUrl:i}}function ss(e){let t=H("git remote get-url origin",e);if(t)return t;let r=H("git remote",e);if(!r)return null;let n=r.split(`
1255
- `)[0]?.trim();return n?H(`git remote get-url ${n}`,e):null}function j(e){let t=e.trim();return t=t.replace(/^[a-z+]+:\/\//,""),t=t.replace(/^[^@]+@/,""),t=t.replace(/:(?!\d)/,"/"),t=t.replace(/\.git$/,""),t=t.replace(/\/+$/,""),t=t.replace(/^[^@/]+@/,""),t.toLowerCase()}function Ze(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function gr(e){try{let t=fs.readFileSync(path.join(e,"package.json"),"utf-8"),r=JSON.parse(t);return typeof r.name=="string"&&r.name.length>0?r.name:null}catch{return null}}function z(e){let t=gr(e);return t||`local/${path.basename(e)}`}var us="1.0.0",mr=10;function oe(e,t,r,n,o,s,i,a){try{fs.mkdirSync(e,{recursive:!0});let l=Date.now(),c=`${l}-${t}-${r}.json`,d=path.join(e,c),u={version:us,queuedAt:new Date(l).toISOString(),reason:n,retryCount:0,targetEndpoint:o,method:s,payload:i,headers:a},p=d+".tmp";fs.writeFileSync(p,JSON.stringify(u,null,2),"utf-8"),fs.renameSync(p,d);}catch(l){l.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
1838
+ (We do not set host-wide \`networksetup\` proxy automatically; see docs.)`),H}async function nr(e){switch(e.platform){case "android":return _n(e);case "ios":return Nn(e);case "web":return E(e.quiet,"\u2139 TestRelic: --capture-network ignored for Maestro web flows (browser already handles HTTP)."),H;default:return E(e.quiet,"\u26A0 TestRelic: target platform unknown; printing manual proxy setup instructions:"),U(e.quiet,"android",e.proxyHost,e.proxyPort),U(e.quiet,"ios",e.proxyHost,e.proxyPort),H}}function $n(){let e=crypto.randomBytes(8).toString("hex");return path.join(os.tmpdir(),`testrelic-maestro-${e}`)}function ir(e,t){let r=[];e.platform&&r.push("--platform",e.platform),e.device&&r.push("--device",e.device),r.push("test");let o=path.join(t,"report.xml"),n=path.join(t,"artifacts"),s=path.join(t,"debug");if(r.push("--format","junit"),r.push("--output",o),r.push("--test-output-dir",n),r.push("--debug-output",s),e.analyze&&r.push("--analyze"),e.includeTags&&r.push("--include-tags",e.includeTags),e.excludeTags&&r.push("--exclude-tags",e.excludeTags),e.shards&&e.shards>1&&r.push("--shards",String(e.shards)),e.config&&r.push("--config",e.config),e.env)for(let[i,a]of Object.entries(e.env))r.push("-e",`${i}=${a}`);return e.maestroArgs&&r.push(...e.maestroArgs),r.push(...e.flowPaths),r}function Bn(e){switch((e??"").toLowerCase()){case "android":return "android";case "ios":return "ios";case "web":return "web";default:return "unknown"}}function jn(e,t,r,o,n,s,i){return new Promise(a=>{let l=[],c=[],d=child_process.spawn("maestro",e,{stdio:["inherit","pipe","pipe"]});d.stdout.on("data",p=>{l.push(p),s||process.stdout.write(p);}),d.stderr.on("data",p=>{c.push(p),s||process.stderr.write(p);}),d.on("close",async p=>{try{await i();}catch{}a({exitCode:p??1,junitPath:t,testOutputDir:r,debugOutputDir:o,stdout:Buffer.concat(l).toString("utf-8"),stderr:Buffer.concat(c).toString("utf-8"),networkJsonlDir:n});}),d.on("error",async p=>{try{await i();}catch{}a({exitCode:127,junitPath:t,testOutputDir:r,debugOutputDir:o,stdout:"",stderr:`Failed to start maestro CLI: ${p.message}`,networkJsonlDir:n});});})}async function Gn(e,t={}){let r=e.outputDir?path.resolve(e.outputDir):$n();fs.mkdirSync(path.join(r,"artifacts"),{recursive:true}),fs.mkdirSync(path.join(r,"debug"),{recursive:true});let o=ir(e,r),n=path.join(r,"report.xml"),s=path.join(r,"artifacts"),i=path.join(r,"debug"),a=null,l=null,c=t.network;if(c?.enabled){let u=path.join(r,"network");a=await er({config:c,outputDir:u,verbose:!e.quiet}),a&&(l=await nr({platform:Bn(e.platform),deviceId:e.device,proxyHost:a.host,proxyPort:a.port,skipCertInstall:c.skipCertInstall,quiet:e.quiet}));}let d=a?.outputDir??null,p=async()=>{if(a&&await new Promise(u=>setTimeout(u,500)),l)try{await l.teardown();}catch{}if(a)try{await a.stop();}catch{}};return jn(o,n,s,i,d,e.quiet,p)}var cr="[REDACTED]";function ar(e,t){if(!e)return null;let r=new Set(t.map(n=>n.toLowerCase())),o={};for(let[n,s]of Object.entries(e))o[n]=r.has(n.toLowerCase())?cr:s;return o}function Je(e,t){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>Je(o,t));let r={};for(let[o,n]of Object.entries(e))r[o]=t.has(o)?cr:Je(n,t);return r}function lr(e,t){if(!e||t.length===0)return e;try{let r=JSON.parse(e),o=Je(r,new Set(t));return JSON.stringify(o)}catch{return e}}function Ke(e,t,r){return {...e,requestHeaders:ar(e.requestHeaders,t),responseHeaders:ar(e.responseHeaders,t),requestBody:lr(e.requestBody,r),responseBody:e.isBinary?e.responseBody:lr(e.responseBody,r)}}function We(e,t,r){let o=n=>typeof n=="string"?e.includes(n):n.test(e);return r.some(o)?false:t.length===0?true:t.some(o)}function Jn(e){let t=e.trim();if(!t)return null;try{let r=JSON.parse(t);return typeof r.url!="string"||typeof r.method!="string"?null:{id:r.id??`api-call-${Date.now()}`,timestamp:r.timestamp??new Date().toISOString(),method:r.method,url:r.url,requestHeaders:r.requestHeaders??null,requestBody:r.requestBody??null,responseStatusCode:r.responseStatusCode??null,responseStatusText:r.responseStatusText??null,responseHeaders:r.responseHeaders??null,responseBody:r.responseBody??null,responseTimeMs:typeof r.responseTimeMs=="number"?r.responseTimeMs:0,isBinary:r.isBinary??!1,error:r.error??null}}catch{return null}}function Kn(e,t){let r=[];for(let o of e.split(/\r?\n/)){let n=Jn(o);n&&We(n.url,t.includeUrls,t.excludeUrls)&&r.push(Ke(n,t.redactHeaders,t.redactBodyFields));}return r}function Wn(e,t){try{return Kn(fs.readFileSync(e,"utf-8"),t)}catch{return []}}function Yn(e){if(!fs.existsSync(e))return [];try{return fs.readdirSync(e,{recursive:!0}).map(String).filter(t=>t.endsWith(".jsonl")).map(t=>path.join(e,t))}catch{return []}}function dr(e){if(!e||e.length===0)return null;let t={};for(let r of e)typeof r.name=="string"&&typeof r.value=="string"&&(t[r.name]=r.value);return Object.keys(t).length>0?t:null}function Xn(e){return e?typeof e.text=="string"?e.text:Array.isArray(e.params)?e.params.map(t=>`${encodeURIComponent(t.name)}=${encodeURIComponent(t.value??"")}`).join("&"):null:null}function Qn(e){return e?/^(image|audio|video|application\/(octet-stream|pdf|zip|protobuf))/.test(e):false}function Zn(e,t){let r=e.request,o=e.response;if(!r?.method||!r.url)return null;let n=o?.content,s=Qn(n?.mimeType);return {id:`har-call-${t}`,timestamp:e.startedDateTime??new Date().toISOString(),method:r.method,url:r.url,requestHeaders:dr(r.headers),requestBody:Xn(r.postData),responseStatusCode:typeof o?.status=="number"&&o.status>0?o.status:null,responseStatusText:o?.statusText??null,responseHeaders:dr(o?.headers),responseBody:n?.text??null,responseTimeMs:typeof e.time=="number"?e.time:0,isBinary:s,error:null}}function es(e,t){let r;try{r=JSON.parse(e);}catch{return []}let o=r.log?.entries??[],n=[];return o.forEach((s,i)=>{let a=Zn(s,i);a&&We(a.url,t.includeUrls,t.excludeUrls)&&n.push(Ke(a,t.redactHeaders,t.redactBodyFields));}),n}function ts(e,t){try{return es(fs.readFileSync(e,"utf-8"),t)}catch{return []}}function rs(e,t){let r=new Map;for(let n of t)r.set(n.testId,[]);if(e.length===0||t.length===0)return r;let o=t.map(n=>({testId:n.testId,startMs:Date.parse(n.startedAt),endMs:Date.parse(n.completedAt)}));for(let n of e){let s=Date.parse(n.timestamp);if(!Number.isFinite(s))continue;let i=o.find(l=>Number.isFinite(l.startMs)&&Number.isFinite(l.endMs)&&s>=l.startMs&&s<=l.endMs);if(i){r.get(i.testId).push(n);continue}let a=null;for(let l of o){if(!Number.isFinite(l.startMs)||!Number.isFinite(l.endMs))continue;let c=s<l.startMs?l.startMs-s:s-l.endMs;(!a||c<a.dist)&&(a={testId:l.testId,dist:c});}a&&r.get(a.testId).push(n);}return r}function fr(e,t,r){if(!t.enabled&&!t.harPath)return new Map;let o=[];if(e)for(let n of Yn(e))o.push(...Wn(n,t));return t.harPath&&fs.existsSync(t.harPath)&&o.push(...ts(t.harPath,t)),o.length===0?new Map:rs(o,r)}function gr(e){return e.map((t,r)=>({...t,id:`api-call-${r}`}))}var ss=new Set(["localhost","127.0.0.1","0.0.0.0"]);function Ye(e){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&ss.has(t.hostname)))throw core.createError(core.ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${t.protocol}//${t.hostname}`)}var is=3e3;async function te(e){let t=new AbortController,r=setTimeout(()=>t.abort(),is);try{return (await fetch(`${e}/health`,{method:"GET",signal:t.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function hr(e){return new Promise(t=>setTimeout(t,e))}async function mr(e){try{let r=(await e.json()).error;if(r&&typeof r.message=="string")return r.message}catch{}return `HTTP ${e.status}`}async function re(e,t,r){let o=new AbortController,n=setTimeout(()=>o.abort(),r);try{let s=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:o.signal});if(s.ok){let a=await s.json();return {accessToken:a.accessToken,refreshToken:a.refreshToken,expiresIn:a.expiresIn,orgId:a.orgId,orgName:a.orgName,userId:a.userId,userName:a.userName}}if(s.status===429){let a=s.headers.get("Retry-After"),l=a?parseInt(a,10)*1e3:5e3;if(!isNaN(l)&&l>0){await hr(l);let c=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:o.signal});if(c.ok){let d=await c.json();return {accessToken:d.accessToken,refreshToken:d.refreshToken,expiresIn:d.expiresIn,orgId:d.orgId,orgName:d.orgName,userId:d.userId,userName:d.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return s.status===400?{code:"validation_error",message:await mr(s),statusCode:400}:s.status===401?{code:"invalid_key",message:"API key is invalid or has been revoked.",statusCode:401}:s.status===403?{code:"expired_key",message:"API key has expired.",statusCode:403}:{code:"server_error",message:await mr(s),statusCode:s.status}}catch(s){return s instanceof DOMException&&s.name==="AbortError"?{code:"timeout",message:"Token exchange timed out.",statusCode:null}:{code:"network_error",message:"Failed to reach cloud for token exchange.",statusCode:null}}finally{clearTimeout(n);}}function oe(e){return "code"in e&&typeof e.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(e.code)}async function Xe(e,t,r){let o=new AbortController,n=setTimeout(()=>o.abort(),r);try{let s=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:o.signal});if(s.status===429){let a=s.headers.get("Retry-After"),l=a?parseInt(a,10)*1e3:5e3;!isNaN(l)&&l>0&&(await hr(l),s=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:o.signal}));}if(!s.ok)return null;let i=await s.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn}}catch{return null}finally{clearTimeout(n);}}async function Qe(e,t,r,o,n,s){let i=new AbortController,a=setTimeout(()=>i.abort(),n);try{let l={gitId:r,displayName:o};s&&(l.branch=s);let c=await fetch(`${e}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(l),signal:i.signal});if(!c.ok)return null;let d=await c.json();return {repoId:d.repoId,displayName:d.displayName}}catch{return null}finally{clearTimeout(a);}}var ps=5e3;function z(e,t){try{return child_process.execSync(e,{cwd:t,timeout:ps,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function Ze(e){let t=z("git rev-parse --abbrev-ref HEAD",e),r=z("git rev-parse --short HEAD",e),o=z("git log -1 --pretty=%s",e),n=z("git log -1 --format=%an",e)??z("git config user.name",e),s=us(e),i=s?B(s):null;return {branch:t,commitSha:r,commitMessage:o,commitAuthor:n,remoteUrl:i}}function us(e){let t=z("git remote get-url origin",e);if(t)return t;let r=z("git remote",e);if(!r)return null;let o=r.split(`
1839
+ `)[0]?.trim();return o?z(`git remote get-url ${o}`,e):null}function B(e){let t=e.trim();return t=t.replace(/^[a-z+]+:\/\//,""),t=t.replace(/^[^@]+@/,""),t=t.replace(/:(?!\d)/,"/"),t=t.replace(/\.git$/,""),t=t.replace(/\/+$/,""),t=t.replace(/^[^@/]+@/,""),t.toLowerCase()}function et(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function br(e){try{let t=fs.readFileSync(path.join(e,"package.json"),"utf-8"),r=JSON.parse(t);return typeof r.name=="string"&&r.name.length>0?r.name:null}catch{return null}}function j(e){let t=br(e);return t||`local/${path.basename(e)}`}var vs="1.0.0",vr=10;function se(e,t,r,o,n,s,i,a){try{fs.mkdirSync(e,{recursive:!0});let l=Date.now(),c=`${l}-${t}-${r}.json`,d=path.join(e,c),p={version:vs,queuedAt:new Date(l).toISOString(),reason:o,retryCount:0,targetEndpoint:n,method:s,payload:i,headers:a},u=d+".tmp";fs.writeFileSync(u,JSON.stringify(p,null,2),"utf-8"),fs.renameSync(u,d);}catch(l){l.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
1256
1840
  `):process.stderr.write(`\u26A0 TestRelic: Unable to queue upload data.
1257
- `);}}async function tt(e,t,r){let n;try{n=fs.readdirSync(e).filter(s=>s.endsWith(".json")&&!s.endsWith(".tmp")).sort();}catch{return}if(n.length===0)return;let o=[];for(let s=0;s<n.length;s+=mr)o.push(n.slice(s,s+mr));for(let s of o)for(let i of s){let a=path.join(e,i);try{if(!fs.statSync(a).isFile())continue;let c=fs.readFileSync(a,"utf-8"),d=JSON.parse(c);if(!core.isValidQueueEntry(d)){fs.unlinkSync(a);continue}let u=d;if((await fetch(u.targetEndpoint,{method:u.method,headers:{...u.headers,Authorization:`Bearer ${r}`},body:JSON.stringify(u.payload)})).ok)fs.unlinkSync(a);else return}catch{return}}}function rt(e,t){try{let r=fs.readdirSync(e).filter(o=>o.endsWith(".json")&&!o.endsWith(".tmp")),n=Date.now();for(let o of r){let s=path.join(e,o);try{let i=fs.readFileSync(s,"utf-8"),l=JSON.parse(i).queuedAt;if(typeof l=="string"){let c=new Date(l).getTime();n-c>t&&fs.unlinkSync(s);}}catch{try{fs.unlinkSync(s);}catch{}}}}catch{}}var bs=3e5,xs=864e5,ws=6e4,br=3e4,xr="https://platform.testrelic.ai/settings/api-keys";function wr(e){return new Promise(t=>{let r=setTimeout(t,e);typeof r?.unref=="function"&&r.unref();})}var J=class{constructor(t){this.gitMetadata=null;this.repoId=null;this.failureReason=null;this.flushPromise=null;this.healthCheckTimer=null;this.config=t,this.authState={mode:"pending",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null};}async initialize(){if(!this.config||!this.config.apiKey){this.setLocalMode("no_api_key"),process.stderr.write(`\u2139 TestRelic: No API key configured. Running in local mode.
1258
- `);return}try{if(Ke(this.config.endpoint),this.gitMetadata=Qe(),!await ee(this.config.endpoint)){this.setLocalMode("cloud_unreachable"),process.stderr.write(`\u26A0 TestRelic: Cloud unreachable. Switching to local mode.
1259
- `);return}let r=await te(this.config.endpoint,this.config.apiKey,this.config.timeout);if(re(r)){this.handleAuthError(r.code,r.statusCode);return}let n=r;this.authState={mode:"cloud",accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:Date.now()+n.expiresIn*1e3,orgId:n.orgId,orgName:n.orgName,userId:n.userId,userName:n.userName},process.stderr.write(`\u2713 TestRelic: Connected to cloud (${n.orgName} / ${n.userName})
1260
- `),await this.resolveRepoId(),this.config.queueDirectory&&(rt(this.config.queueDirectory,this.config.queueMaxAge),this.startBackgroundFlush()),this.startHealthCheck();}catch(t){this.setLocalMode("unexpected_error"),process.stderr.write(`\u26A0 TestRelic: Unexpected error during cloud initialization. ${t instanceof Error?t.message:String(t)}
1261
- `);}}getMode(){return this.authState.mode}isCloudMode(){return this.authState.mode==="cloud"}isLocalMode(){return this.authState.mode==="local"}getAccessToken(){return this.authState.accessToken}getRepoId(){return this.repoId}getGitMetadata(){return this.gitMetadata}getConfig(){return this.config}getFailureReason(){return this.failureReason}getEndpoint(){return this.config?.endpoint??"https://platform.testrelic.ai/api/v1"}async ensureValidToken(){if(!this.isCloudMode()||!this.authState.accessToken)return false;let t=this.authState.expiresAt??0;if(Date.now()+bs<t)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await Ye(this.config.endpoint,this.authState.refreshToken,this.config.timeout);return r?(this.authState.accessToken=r.accessToken,this.authState.refreshToken=r.refreshToken,this.authState.expiresAt=Date.now()+r.expiresIn*1e3,!0):(this.switchToLocalMode("token_refresh_failed"),!1)}catch{return this.switchToLocalMode("token_refresh_error"),false}}switchToLocalMode(t){this.authState.mode!=="local"&&(this.authState.mode="local",this.failureReason=t,process.stderr.write(`\u26A0 TestRelic: Switched to local mode (${t}).
1262
- `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,wr(br)]);}catch{}this.flushPromise=null;}this.authState={mode:"local",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null},this.repoId=null,this.gitMetadata=null;}setLocalMode(t){this.authState.mode="local",this.failureReason=t;}handleAuthError(t,r){switch(t){case "invalid_key":this.setLocalMode("invalid_api_key"),process.stderr.write(`\u26A0 TestRelic: API key is invalid or revoked. Running in local mode.
1263
- \u2192 Manage keys: ${xr}
1841
+ `);}}async function rt(e,t,r){let o;try{o=fs.readdirSync(e).filter(s=>s.endsWith(".json")&&!s.endsWith(".tmp")).sort();}catch{return}if(o.length===0)return;let n=[];for(let s=0;s<o.length;s+=vr)n.push(o.slice(s,s+vr));for(let s of n)for(let i of s){let a=path.join(e,i);try{if(!fs.statSync(a).isFile())continue;let c=fs.readFileSync(a,"utf-8"),d=JSON.parse(c);if(!core.isValidQueueEntry(d)){fs.unlinkSync(a);continue}let p=d;if((await fetch(p.targetEndpoint,{method:p.method,headers:{...p.headers,Authorization:`Bearer ${r}`},body:JSON.stringify(p.payload)})).ok)fs.unlinkSync(a);else return}catch{return}}}function ot(e,t){try{let r=fs.readdirSync(e).filter(n=>n.endsWith(".json")&&!n.endsWith(".tmp")),o=Date.now();for(let n of r){let s=path.join(e,n);try{let i=fs.readFileSync(s,"utf-8"),l=JSON.parse(i).queuedAt;if(typeof l=="string"){let c=new Date(l).getTime();o-c>t&&fs.unlinkSync(s);}}catch{try{fs.unlinkSync(s);}catch{}}}}catch{}}var Ss=3e5,Ts=864e5,As=6e4,wr=3e4,kr="https://platform.testrelic.ai/settings/api-keys";function Cr(e){return new Promise(t=>{let r=setTimeout(t,e);typeof r?.unref=="function"&&r.unref();})}var K=class{constructor(t){this.gitMetadata=null;this.repoId=null;this.failureReason=null;this.flushPromise=null;this.healthCheckTimer=null;this.config=t,this.authState={mode:"pending",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null};}async initialize(){if(!this.config||!this.config.apiKey){this.setLocalMode("no_api_key"),process.stderr.write(`\u2139 TestRelic: No API key configured. Running in local mode.
1842
+ `);return}try{if(Ye(this.config.endpoint),this.gitMetadata=Ze(),!await te(this.config.endpoint)){this.setLocalMode("cloud_unreachable"),process.stderr.write(`\u26A0 TestRelic: Cloud unreachable. Switching to local mode.
1843
+ `);return}let r=await re(this.config.endpoint,this.config.apiKey,this.config.timeout);if(oe(r)){this.handleAuthError(r.code,r.statusCode);return}let o=r;this.authState={mode:"cloud",accessToken:o.accessToken,refreshToken:o.refreshToken,expiresAt:Date.now()+o.expiresIn*1e3,orgId:o.orgId,orgName:o.orgName,userId:o.userId,userName:o.userName},process.stderr.write(`\u2713 TestRelic: Connected to cloud (${o.orgName} / ${o.userName})
1844
+ `),await this.resolveRepoId(),this.config.queueDirectory&&(ot(this.config.queueDirectory,this.config.queueMaxAge),this.startBackgroundFlush()),this.startHealthCheck();}catch(t){this.setLocalMode("unexpected_error"),process.stderr.write(`\u26A0 TestRelic: Unexpected error during cloud initialization. ${t instanceof Error?t.message:String(t)}
1845
+ `);}}getMode(){return this.authState.mode}isCloudMode(){return this.authState.mode==="cloud"}isLocalMode(){return this.authState.mode==="local"}getAccessToken(){return this.authState.accessToken}getRepoId(){return this.repoId}getGitMetadata(){return this.gitMetadata}getConfig(){return this.config}getFailureReason(){return this.failureReason}getEndpoint(){return this.config?.endpoint??"https://platform.testrelic.ai/api/v1"}async ensureValidToken(){if(!this.isCloudMode()||!this.authState.accessToken)return false;let t=this.authState.expiresAt??0;if(Date.now()+Ss<t)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await Xe(this.config.endpoint,this.authState.refreshToken,this.config.timeout);return r?(this.authState.accessToken=r.accessToken,this.authState.refreshToken=r.refreshToken,this.authState.expiresAt=Date.now()+r.expiresIn*1e3,!0):(this.switchToLocalMode("token_refresh_failed"),!1)}catch{return this.switchToLocalMode("token_refresh_error"),false}}switchToLocalMode(t){this.authState.mode!=="local"&&(this.authState.mode="local",this.failureReason=t,process.stderr.write(`\u26A0 TestRelic: Switched to local mode (${t}).
1846
+ `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,Cr(wr)]);}catch{}this.flushPromise=null;}this.authState={mode:"local",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null},this.repoId=null,this.gitMetadata=null;}setLocalMode(t){this.authState.mode="local",this.failureReason=t;}handleAuthError(t,r){switch(t){case "invalid_key":this.setLocalMode("invalid_api_key"),process.stderr.write(`\u26A0 TestRelic: API key is invalid or revoked. Running in local mode.
1847
+ \u2192 Manage keys: ${kr}
1264
1848
  `);break;case "expired_key":this.setLocalMode("expired_api_key"),process.stderr.write(`\u26A0 TestRelic: API key has expired. Running in local mode.
1265
- \u2192 Generate a new key: ${xr}
1849
+ \u2192 Generate a new key: ${kr}
1266
1850
  `);break;case "rate_limited":this.setLocalMode("rate_limited"),process.stderr.write(`\u26A0 TestRelic: Rate limited during authentication. Running in local mode.
1267
1851
  `);break;default:this.setLocalMode(`auth_error_${r??"unknown"}`),process.stderr.write(`\u26A0 TestRelic: Cloud authentication failed. Running in local mode.
1268
- `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let t=this.gitMetadata?.remoteUrl?j(this.gitMetadata.remoteUrl):null,r=t?Ze(t):this.config.projectName??z(process.cwd()),n=t??this.config.projectName??z(process.cwd()),o=this.readRepoCache(n);if(o){this.repoId=o.repoId;return}try{let s=await Xe(this.config.endpoint,this.authState.accessToken,n,r,this.config.timeout,this.gitMetadata?.branch);s&&(this.repoId=s.repoId,this.writeRepoCache(n,s.repoId,s.displayName));}catch{}}readRepoCache(t){if(!this.config)return null;let r=path.join(this.config.queueDirectory,"..","cache","repo.json");try{if(!fs.existsSync(r))return null;let n=fs.readFileSync(r,"utf-8"),o=JSON.parse(n);if(o.gitId!==t||Date.now()-o.resolvedAt>xs)return null;let s=this.hashApiKey();return s&&o.apiKeyHash!==s?null:o}catch{return null}}writeRepoCache(t,r,n){if(!this.config)return;let o=path.join(this.config.queueDirectory,"..","cache"),s=path.join(o,"repo.json");try{fs.mkdirSync(o,{recursive:!0});let i={repoId:r,gitId:t,displayName:n,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},a=s+".tmp";fs.writeFileSync(a,JSON.stringify(i,null,2),"utf-8"),fs.renameSync(a,s);}catch{}}hashApiKey(){return this.config?.apiKey?crypto.createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let t=this.authState.accessToken,r=this.config.queueDirectory,n=this.config.endpoint;this.flushPromise=Promise.race([tt(r,n,t),wr(br)]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let t=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await ee(t))return;if(this.config?.apiKey){let n=await te(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!re(n)){let o=n;this.authState={mode:"cloud",accessToken:o.accessToken,refreshToken:o.refreshToken,expiresAt:Date.now()+o.expiresIn*1e3,orgId:o.orgId,orgName:o.orgName,userId:o.userId,userName:o.userName},this.failureReason=null,process.stderr.write(`\u2713 TestRelic: Cloud connectivity restored.
1269
- `),this.startBackgroundFlush();}}}catch{}},ws),typeof this.healthCheckTimer?.unref=="function"&&this.healthCheckTimer.unref();}};var ks=1048576,se=[1e3,3e3,9e3],ie=3;function le(e,t,r,n,o){let s=n?.provider&&n.provider!=="unknown"?n.provider:"local";return {runId:e.testRunId,repoGitId:t,startedAt:e.startedAt,summary:e.summary,timeline:e.timeline,environment:s,testFramework:"maestro",testType:"mobile",...o&&o.length>0?{tests:o}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...e.completedAt?{finishedAt:e.completedAt}:{},...e.totalDuration?{duration:e.totalDuration}:{},...n?.provider?{ciProvider:n.provider}:{},...n?.runUrl?{ciRunUrl:n.runUrl}:{}}}async function ae(e){return new Promise(t=>setTimeout(t,e))}async function vr(e,t,r){for(let n=0;n<ie;n++)try{let o=await fetch(e,t);if(o.ok)return o;if(o.status===401&&r&&n===0){let s=await r();if(s){let i={...t,headers:{...t.headers,Authorization:`Bearer ${s}`}},a=await fetch(e,i);if(a.ok)return a}return null}if(o.status===429&&n<ie-1){let s=o.headers.get("Retry-After"),i=s?parseInt(s,10)*1e3:se[n];!isNaN(i)&&i>0?await ae(i):await ae(se[n]);continue}if(o.status>=500&&n<ie-1){await ae(se[n]);continue}return o}catch{if(n<ie-1){await ae(se[n]);continue}return null}return null}function Cs(e){let t=JSON.stringify(e),r={"Content-Type":"application/json"};if(Buffer.byteLength(t,"utf-8")>ks){let n=zlib.gzipSync(Buffer.from(t,"utf-8"));return r["Content-Encoding"]="gzip",{body:n,headers:r}}return {body:t,headers:r}}async function ot(e,t,r,n){let o=`${e}/runs`,{body:s,headers:i}=Cs(r);i.Authorization=`Bearer ${t}`;let a=await vr(o,{method:"POST",headers:i,body:s},n);return a?.ok?{success:true,statusCode:a.status,error:null}:a?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:a?`Upload failed with status ${a.status}`:"Upload failed after retries",statusCode:a?.status??null,payload:r,targetEndpoint:o,method:"POST"}}function Rs(e){let t={};for(let[r,n]of Object.entries(e))n!=null&&(t[r]=n);return t}async function Ss(e,t,r){let n=`${e}/runs/init`;try{let o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(Rs(r))});return o.ok?{runId:(await o.json()).runId}:null}catch{return null}}async function Ts(e,t,r,n){let o=`${e}/runs/${r}/finalize`;return (await vr(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)}))?.ok??false}var Fs=5,ce=[1e3,3e3,9e3],q=3,Ps={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".mov":"video/quicktime",".zip":"application/zip"},st=0,it=[];async function _s(){st>=Fs&&await new Promise(e=>it.push(e)),st++;}function Ls(){st--,it.length>0&&it.shift()();}async function de(e){return new Promise(t=>setTimeout(t,e))}function Ds(e){let t=e.substring(e.lastIndexOf(".")).toLowerCase();return Ps[t]??"application/octet-stream"}function Ns(e){try{return fs.statSync(e).size}catch{return 0}}async function Os(e,t,r,n,o){let s=`${e}/artifacts/upload-url`,i=JSON.stringify({runId:r.runId,testId:r.testId,fileName:path.basename(r.filePath),contentType:o,type:r.type,sizeBytes:n});for(let a=0;a<q;a++)try{let l=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:i});if(l.ok)return await l.json();if(l.status>=500&&a<q-1){await de(ce[a]);continue}return null}catch{if(a<q-1){await de(ce[a]);continue}return null}return null}async function Us(e,t,r,n){for(let o=0;o<q;o++)try{let s=fs.createReadStream(t),i=stream.Readable.toWeb(s),a=await fetch(e,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(n)},body:i,duplex:"half"});if(a.ok)return !0;if(a.status>=500&&o<q-1){await de(ce[o]);continue}return !1}catch{if(o<q-1){await de(ce[o]);continue}return false}return false}async function Hs(e,t,r){try{return (await fetch(`${e}/artifacts/confirm`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({artifactId:r})})).ok}catch{return false}}async function kr(e,t,r,n){let o=Ns(r.filePath);if(o===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(o>n*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let s=Ds(r.filePath);await _s();try{let i=await Os(e,t,r,o,s);if(!i)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await Us(i.uploadUrl,r.filePath,s,o))return {success:!1,storageKey:i.storageKey,artifactId:i.artifactId,error:"presigned_put_failed"};let l=await Hs(e,t,i.artifactId);return {success:l,storageKey:i.storageKey,artifactId:i.artifactId,error:l?null:"confirm_failed"}}finally{Ls();}}async function at(e,t,r,n){let o=new Map,s=r.map(async i=>{let a=await kr(e,t,i,n);o.set(i.filePath,a);});return await Promise.allSettled(s),o}function $s(e){return e.GITHUB_ACTIONS!=="true"?null:{provider:"github-actions",buildId:e.GITHUB_RUN_ID??null,commitSha:e.GITHUB_SHA??null,branch:e.GITHUB_REF_NAME??null,runUrl:e.GITHUB_SERVER_URL&&e.GITHUB_REPOSITORY&&e.GITHUB_RUN_ID?`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`:null}}function Bs(e){return e.GITLAB_CI!=="true"?null:{provider:"gitlab-ci",buildId:e.CI_PIPELINE_ID??null,commitSha:e.CI_COMMIT_SHA??null,branch:e.CI_COMMIT_BRANCH??e.CI_COMMIT_REF_NAME??null,runUrl:e.CI_PIPELINE_URL??null}}function js(e){if(!e.JENKINS_URL)return null;let t=e.GIT_BRANCH??null;return t?.startsWith("origin/")&&(t=t.slice(7)),{provider:"jenkins",buildId:e.BUILD_ID??null,commitSha:e.GIT_COMMIT??null,branch:t,runUrl:e.BUILD_URL??null}}function zs(e){return e.CIRCLECI!=="true"?null:{provider:"circleci",buildId:e.CIRCLE_BUILD_NUM??null,commitSha:e.CIRCLE_SHA1??null,branch:e.CIRCLE_BRANCH??null,runUrl:e.CIRCLE_BUILD_URL??null}}function qs(e){if(!e.BITBUCKET_PIPELINE_UUID)return null;let t=e.BITBUCKET_WORKSPACE&&e.BITBUCKET_REPO_SLUG&&e.BITBUCKET_PIPELINE_UUID?`https://bitbucket.org/${e.BITBUCKET_WORKSPACE}/${e.BITBUCKET_REPO_SLUG}/pipelines/results/${e.BITBUCKET_PIPELINE_UUID}`:null;return {provider:"bitbucket-pipelines",buildId:e.BITBUCKET_BUILD_NUMBER??null,commitSha:e.BITBUCKET_COMMIT??null,branch:e.BITBUCKET_BRANCH??null,runUrl:t}}var Gs=[$s,Bs,js,zs,qs];function ue(e){let t=e??process.env;for(let r of Gs){let n=r(t);if(n)return n}return null}function Vs(e){let t=[];for(let r of e){let n=r,o=n.tests;if(!Array.isArray(o)||o.length===0){t.push(r);continue}for(let s of o){t.push({timestamp:s.startedAt,title:s.title,category:"test",navigationType:n.navigationType,url:n.url,visitedAt:n.visitedAt,duration:s.duration,status:s.status,test_status:s.status,test_id:s.testId,test_title:s.title,specfile:s.filePath,suiteName:s.suiteName,type:"test",...s.failure?{error:s.failure.message,errorMessage:s.failure.message}:{}});for(let i of s.actions??[])t.push({timestamp:i.timestamp,title:i.title,category:i.category,status:i.status,test_status:s.status,duration:i.duration,error:i.error,test_id:s.testId,test_title:s.title,specfile:s.filePath,url:n.url,type:i.category==="assertion"?"assert":"action"});}}return t}function Cr(e){let r=e.getGitMetadata()?.remoteUrl;return r?j(r):e.getConfig()?.projectName??z(process.cwd())}async function lt(e,t,r,n,o,s,i,a,l,c,d){try{let u=d?.length??0,p=(a?.length??0)+(l?.length??0)+u>0;if(e.isCloudMode()&&p&&await e.ensureValidToken()){let h=e.getEndpoint(),g=e.getAccessToken(),b=t?.artifactMaxSizeMb??50,x=[];for(let R of a??[])x.push({filePath:R,runId:r,testId:"maestro-suite",type:"screenshot"});let T=new Set;for(let R of d??[])x.push({filePath:R.path,runId:r,testId:R.testId,type:"video"}),T.add(R.path);for(let R of l??[])T.has(R)||x.push({filePath:R,runId:r,testId:"maestro-suite",type:"video"});if(x.length>0){let R=await at(h,g,x,b),D=Array.from(R.entries()),I=D.filter(([,m])=>m.success).length,f=D.filter(([,m])=>!m.success);if(I>0){let m=x.filter(k=>k.type==="video").length,w=d?.length??0,v=x.filter(k=>k.type==="screenshot").length,S=[];if(v>0&&S.push(`${v} screenshot(s)`),m>0){let k=w>0?` (${w} per-flow)`:"";S.push(`${m} video(s)${k}`);}process.stderr.write(`\u2713 TestRelic: Uploaded ${I} artifact(s) [${S.join(", ")}] to cloud storage.
1852
+ `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let t=this.gitMetadata?.remoteUrl?B(this.gitMetadata.remoteUrl):null,r=t?et(t):this.config.projectName??j(process.cwd()),o=t??this.config.projectName??j(process.cwd()),n=this.readRepoCache(o);if(n){this.repoId=n.repoId;return}try{let s=await Qe(this.config.endpoint,this.authState.accessToken,o,r,this.config.timeout,this.gitMetadata?.branch);s&&(this.repoId=s.repoId,this.writeRepoCache(o,s.repoId,s.displayName));}catch{}}readRepoCache(t){if(!this.config)return null;let r=path.join(this.config.queueDirectory,"..","cache","repo.json");try{if(!fs.existsSync(r))return null;let o=fs.readFileSync(r,"utf-8"),n=JSON.parse(o);if(n.gitId!==t||Date.now()-n.resolvedAt>Ts)return null;let s=this.hashApiKey();return s&&n.apiKeyHash!==s?null:n}catch{return null}}writeRepoCache(t,r,o){if(!this.config)return;let n=path.join(this.config.queueDirectory,"..","cache"),s=path.join(n,"repo.json");try{fs.mkdirSync(n,{recursive:!0});let i={repoId:r,gitId:t,displayName:o,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},a=s+".tmp";fs.writeFileSync(a,JSON.stringify(i,null,2),"utf-8"),fs.renameSync(a,s);}catch{}}hashApiKey(){return this.config?.apiKey?crypto.createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let t=this.authState.accessToken,r=this.config.queueDirectory,o=this.config.endpoint;this.flushPromise=Promise.race([rt(r,o,t),Cr(wr)]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let t=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await te(t))return;if(this.config?.apiKey){let o=await re(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!oe(o)){let n=o;this.authState={mode:"cloud",accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:Date.now()+n.expiresIn*1e3,orgId:n.orgId,orgName:n.orgName,userId:n.userId,userName:n.userName},this.failureReason=null,process.stderr.write(`\u2713 TestRelic: Cloud connectivity restored.
1853
+ `),this.startBackgroundFlush();}}}catch{}},As),typeof this.healthCheckTimer?.unref=="function"&&this.healthCheckTimer.unref();}};var Is=1048576,ie=[1e3,3e3,9e3],ae=3;function ce(e,t,r,o,n){let s=o?.provider&&o.provider!=="unknown"?o.provider:"local";return {runId:e.testRunId,repoGitId:t,startedAt:e.startedAt,summary:e.summary,timeline:e.timeline,environment:s,testFramework:"maestro",testType:"mobile",...n&&n.length>0?{tests:n}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...e.completedAt?{finishedAt:e.completedAt}:{},...e.totalDuration?{duration:e.totalDuration}:{},...o?.provider?{ciProvider:o.provider}:{},...o?.runUrl?{ciRunUrl:o.runUrl}:{}}}async function le(e){return new Promise(t=>setTimeout(t,e))}async function Rr(e,t,r){for(let o=0;o<ae;o++)try{let n=await fetch(e,t);if(n.ok)return n;if(n.status===401&&r&&o===0){let s=await r();if(s){let i={...t,headers:{...t.headers,Authorization:`Bearer ${s}`}},a=await fetch(e,i);if(a.ok)return a}return null}if(n.status===429&&o<ae-1){let s=n.headers.get("Retry-After"),i=s?parseInt(s,10)*1e3:ie[o];!isNaN(i)&&i>0?await le(i):await le(ie[o]);continue}if(n.status>=500&&o<ae-1){await le(ie[o]);continue}return n}catch{if(o<ae-1){await le(ie[o]);continue}return null}return null}function Es(e){let t=JSON.stringify(e),r={"Content-Type":"application/json"};if(Buffer.byteLength(t,"utf-8")>Is){let o=zlib.gzipSync(Buffer.from(t,"utf-8"));return r["Content-Encoding"]="gzip",{body:o,headers:r}}return {body:t,headers:r}}async function st(e,t,r,o){let n=`${e}/runs`,{body:s,headers:i}=Es(r);i.Authorization=`Bearer ${t}`;let a=await Rr(n,{method:"POST",headers:i,body:s},o);return a?.ok?{success:true,statusCode:a.status,error:null}:a?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:a?`Upload failed with status ${a.status}`:"Upload failed after retries",statusCode:a?.status??null,payload:r,targetEndpoint:n,method:"POST"}}function Fs(e){let t={};for(let[r,o]of Object.entries(e))o!=null&&(t[r]=o);return t}async function Ds(e,t,r){let o=`${e}/runs/init`;try{let n=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(Fs(r))});return n.ok?{runId:(await n.json()).runId}:null}catch{return null}}async function Ps(e,t,r,o){let n=`${e}/runs/${r}/finalize`;return (await Rr(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(o)}))?.ok??false}var Us=5,de=[1e3,3e3,9e3],G=3,zs={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".mov":"video/quicktime",".zip":"application/zip"},it=0,at=[];async function Hs(){it>=Us&&await new Promise(e=>at.push(e)),it++;}function $s(){it--,at.length>0&&at.shift()();}async function pe(e){return new Promise(t=>setTimeout(t,e))}function Bs(e){let t=e.substring(e.lastIndexOf(".")).toLowerCase();return zs[t]??"application/octet-stream"}function js(e){try{return fs.statSync(e).size}catch{return 0}}async function Gs(e,t,r,o,n){let s=`${e}/artifacts/upload-url`,i=JSON.stringify({runId:r.runId,testId:r.testId,fileName:path.basename(r.filePath),contentType:n,type:r.type,sizeBytes:o});for(let a=0;a<G;a++)try{let l=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:i});if(l.ok)return await l.json();if(l.status>=500&&a<G-1){await pe(de[a]);continue}return null}catch{if(a<G-1){await pe(de[a]);continue}return null}return null}async function qs(e,t,r,o){for(let n=0;n<G;n++)try{let s=fs.createReadStream(t),i=stream.Readable.toWeb(s),a=await fetch(e,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(o)},body:i,duplex:"half"});if(a.ok)return !0;if(a.status>=500&&n<G-1){await pe(de[n]);continue}return !1}catch{if(n<G-1){await pe(de[n]);continue}return false}return false}async function Vs(e,t,r){try{return (await fetch(`${e}/artifacts/confirm`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({artifactId:r})})).ok}catch{return false}}async function Sr(e,t,r,o){let n=js(r.filePath);if(n===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(n>o*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let s=Bs(r.filePath);await Hs();try{let i=await Gs(e,t,r,n,s);if(!i)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await qs(i.uploadUrl,r.filePath,s,n))return {success:!1,storageKey:i.storageKey,artifactId:i.artifactId,error:"presigned_put_failed"};let l=await Vs(e,t,i.artifactId);return {success:l,storageKey:i.storageKey,artifactId:i.artifactId,error:l?null:"confirm_failed"}}finally{$s();}}async function lt(e,t,r,o){let n=new Map,s=r.map(async i=>{let a=await Sr(e,t,i,o);n.set(i.filePath,a);});return await Promise.allSettled(s),n}function Js(e){return e.GITHUB_ACTIONS!=="true"?null:{provider:"github-actions",buildId:e.GITHUB_RUN_ID??null,commitSha:e.GITHUB_SHA??null,branch:e.GITHUB_REF_NAME??null,runUrl:e.GITHUB_SERVER_URL&&e.GITHUB_REPOSITORY&&e.GITHUB_RUN_ID?`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`:null}}function Ks(e){return e.GITLAB_CI!=="true"?null:{provider:"gitlab-ci",buildId:e.CI_PIPELINE_ID??null,commitSha:e.CI_COMMIT_SHA??null,branch:e.CI_COMMIT_BRANCH??e.CI_COMMIT_REF_NAME??null,runUrl:e.CI_PIPELINE_URL??null}}function Ws(e){if(!e.JENKINS_URL)return null;let t=e.GIT_BRANCH??null;return t?.startsWith("origin/")&&(t=t.slice(7)),{provider:"jenkins",buildId:e.BUILD_ID??null,commitSha:e.GIT_COMMIT??null,branch:t,runUrl:e.BUILD_URL??null}}function Ys(e){return e.CIRCLECI!=="true"?null:{provider:"circleci",buildId:e.CIRCLE_BUILD_NUM??null,commitSha:e.CIRCLE_SHA1??null,branch:e.CIRCLE_BRANCH??null,runUrl:e.CIRCLE_BUILD_URL??null}}function Xs(e){if(!e.BITBUCKET_PIPELINE_UUID)return null;let t=e.BITBUCKET_WORKSPACE&&e.BITBUCKET_REPO_SLUG&&e.BITBUCKET_PIPELINE_UUID?`https://bitbucket.org/${e.BITBUCKET_WORKSPACE}/${e.BITBUCKET_REPO_SLUG}/pipelines/results/${e.BITBUCKET_PIPELINE_UUID}`:null;return {provider:"bitbucket-pipelines",buildId:e.BITBUCKET_BUILD_NUMBER??null,commitSha:e.BITBUCKET_COMMIT??null,branch:e.BITBUCKET_BRANCH??null,runUrl:t}}var Qs=[Js,Ks,Ws,Ys,Xs];function ue(e){let t=e??process.env;for(let r of Qs){let o=r(t);if(o)return o}return null}function Zs(e){let t=[];for(let r of e){let o=r,n=o.tests;if(!Array.isArray(n)||n.length===0){t.push(r);continue}for(let s of n){t.push({timestamp:s.startedAt,title:s.title,category:"test",navigationType:o.navigationType,url:o.url,visitedAt:o.visitedAt,duration:s.duration,status:s.status,test_status:s.status,test_id:s.testId,test_title:s.title,specfile:s.filePath,suiteName:s.suiteName,type:"test",...s.failure?{error:s.failure.message,errorMessage:s.failure.message}:{}});for(let i of s.actions??[])t.push({timestamp:i.timestamp,title:i.title,category:i.category,status:i.status,test_status:s.status,duration:i.duration,error:i.error,test_id:s.testId,test_title:s.title,specfile:s.filePath,url:o.url,type:i.category==="assertion"?"assert":"action"});}}return t}function Tr(e){let r=e.getGitMetadata()?.remoteUrl;return r?B(r):e.getConfig()?.projectName??j(process.cwd())}async function ct(e,t,r,o,n,s,i,a,l,c,d){try{let p=d?.length??0,u=(a?.length??0)+(l?.length??0)+p>0;if(e.isCloudMode()&&u&&await e.ensureValidToken()){let h=e.getEndpoint(),g=e.getAccessToken(),v=t?.artifactMaxSizeMb??50,x=[];for(let R of a??[])x.push({filePath:R,runId:r,testId:"maestro-suite",type:"screenshot"});let T=new Set;for(let R of d??[])x.push({filePath:R.path,runId:r,testId:R.testId,type:"video"}),T.add(R.path);for(let R of l??[])T.has(R)||x.push({filePath:R,runId:r,testId:"maestro-suite",type:"video"});if(x.length>0){let R=await lt(h,g,x,v),L=Array.from(R.entries()),M=L.filter(([,m])=>m.success).length,f=L.filter(([,m])=>!m.success);if(M>0){let m=x.filter(k=>k.type==="video").length,y=d?.length??0,w=x.filter(k=>k.type==="screenshot").length,S=[];if(w>0&&S.push(`${w} screenshot(s)`),m>0){let k=y>0?` (${y} per-flow)`:"";S.push(`${m} video(s)${k}`);}process.stderr.write(`\u2713 TestRelic: Uploaded ${M} artifact(s) [${S.join(", ")}] to cloud storage.
1270
1854
  `);}if(f.length>0){process.stderr.write(`\u26A0 TestRelic: ${f.length} artifact(s) failed to upload:
1271
- `);for(let[m,w]of f){let v=x.find(k=>k.filePath===m),S=v?`[${v.type}] ${m}`:m;process.stderr.write(` \u2717 ${S} \u2014 reason: ${w.error??"unknown"}
1272
- `);}}}}if(e.isCloudMode())if(await e.ensureValidToken()){let h=e.getGitMetadata(),g=ue(),b=Cr(e),x=Vs(n.timeline),T={...n,timeline:x},R=le(T,b,h,g,c),D=await ot(e.getEndpoint(),e.getAccessToken(),R,async()=>await e.ensureValidToken()?e.getAccessToken():null);if(D.success)process.stderr.write(`\u2713 TestRelic: Cloud upload succeeded \u2192 ${e.getEndpoint()}/runs/${r}
1273
- `);else {let I=D,f=t?.queueDirectory??".testrelic/queue";oe(f,r,"batch",I.reason,I.targetEndpoint,I.method,I.payload,{"Content-Type":"application/json"}),process.stderr.write(`\u26A0 TestRelic: Cloud upload failed, queued for retry.
1274
- `);}}else {let h=t?.queueDirectory??".testrelic/queue",g=e.getGitMetadata(),b=ue(),x=Cr(e),T=le(n,x,g,b);oe(h,r,"batch",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs`,"POST",T,{"Content-Type":"application/json"});}await e.dispose();}catch{try{await e.dispose();}catch{}}}function Sr(e,t,r){if(t.length===0)return null;let n=path.basename(e,path.extname(e)).toLowerCase(),o=t.find(a=>path.basename(a,path.extname(a)).toLowerCase()===n);if(o)return o;let s=t.find(a=>path.basename(a).toLowerCase().includes(n));if(s)return s;let i=t.find(a=>{let l=path.basename(a,path.extname(a)).toLowerCase();return l.length>=3&&(n.startsWith(l)||n.includes(l))});if(i)return i;if(r){let a=path.basename(r,path.extname(r)).toLowerCase(),l=t.find(d=>path.basename(d,path.extname(d)).toLowerCase()===a);if(l)return l;let c=t.find(d=>path.basename(d).toLowerCase().includes(a));if(c)return c}return null}function Xs(e,t){if(t.length===0)return [];let r=path.basename(e,path.extname(e)).toLowerCase(),n=t.filter(o=>{let s=path.basename(o).toLowerCase(),i=path.basename(o,path.extname(o)).toLowerCase();return s.startsWith(r)||s.includes(r)?true:i.length>=3&&(r.startsWith(i)||r.includes(i))});return n.length>0?n:t.slice()}function Qs(e){for(let t of e)if(t.command==="startRecording"){let r=t.metadata,n=r?.path??r?.recording??r?.fileName;if(typeof n=="string")return n;if(typeof t.selector=="string")return t.selector}return null}function Tr(e){return path.basename(e).replace(/^commands[-_]?/i,"").replace(/\.json$/i,"").replace(/^\(/,"").replace(/\)$/,"").toLowerCase()}function Zs(e){let t=new Map;for(let[r,n]of e){let o=Tr(r),s=Qs(n);s&&o&&t.set(o,s);}return t}function ei(e,t){let r=path.basename(t,path.extname(t)).toLowerCase();if(!r||e.size===0)return {commands:[],matchedAnyFile:false};let n=o=>Tr(o);for(let[o,s]of e)if(n(o)===r)return {commands:s,matchedAnyFile:true};for(let[o,s]of e){let i=n(o);if(i.length>=3&&i.includes(r))return {commands:s,matchedAnyFile:true}}for(let[o,s]of e){let i=n(o);if(i.length>=3&&r.includes(i))return {commands:s,matchedAnyFile:true}}return {commands:[],matchedAnyFile:false}}function ti(e){switch(e){case "android":return "Android";case "ios":return "iOS";case "web":return "Web";default:return}}function ri(e,t,r){let n=e.logEntries.length>0?e.logEntries.map(o=>({level:o.level.toLowerCase(),message:o.message,timestamp:o.timestamp,source:o.source})):void 0;return {testId:`${e.flowFile}::${e.flowName}`,title:e.flowName,status:e.status,duration:e.duration,suiteName:e.appId??"maestro-suite",filePath:e.flowFile,testType:"mobile",isFlaky:false,startedAt:e.startedAt,completedAt:e.completedAt,tags:e.tags,failure:e.failureMessage?{message:e.failureMessage}:null,retry:0,retryCount:0,retryStatus:null,source:"maestro",platform:e.platform!=="unknown"?e.platform:void 0,os:ti(e.platform),deviceName:e.deviceId,...n?{consoleLogs:n}:{},...t&&t.length>0?{apiCalls:t}:{},...r&&r.length>0?{actions:r}:{}}}function ni(e,t,r){if(e.length===0)return [];let n=Date.parse(t),o=Date.parse(r);return Number.isNaN(n)||Number.isNaN(o)?e.slice():e.filter(s=>{let i=Date.parse(s.timestamp);return Number.isNaN(i)?true:i>=n&&i<=o})}async function oi(e){let{config:t}=e,r=new Date().toISOString(),n=t.testRunId??crypto.randomUUID(),o=Ue(e.testOutputDir,e.debugOutputDir),s=e.junitPath??o.junitReportPath,i=e.debugOutputDir?Me(e.debugOutputDir):o.logPaths,a=[];for(let f of i){let m;try{let{statSync:v}=await import('fs');m=v(f).mtime;}catch{}let w=Ae(f,m);w.length>0&&a.push(...w);}let l=e.platform??"unknown";if(l==="unknown"&&a.length>0){let f=Ie(a);f!=="unknown"&&(l=f);}let c=new Map;if(e.flowsDir&&fs.existsSync(e.flowsDir)){let f=Te(e.flowsDir);for(let m of f){let w=Se(m),v=w.name??m;c.set(v,w);}}let d=new Map,u=e.testOutputDir?Re(e.testOutputDir):o.commandJsonPaths;for(let f of u)d.set(f,Ce(f));let p=[],y=e.testOutputDir?Oe(e.testOutputDir):o.aiReportPaths;for(let f of y){let m=Ne(f);p.push(...m.defects);}let h=Zs(d),g=[];if(s&&fs.existsSync(s)){let f=we(s),m=Array.from(d.values()).flat(),w=m.filter(S=>S.category==="assertion"),v=m.filter(S=>S.category!=="assertion");for(let S of f.testSuites)for(let k of S.testCases){let C=k.name,M=c.get(C),N=k.status==="SUCCESS"?"passed":k.status==="SKIPPED"?"skipped":"failed",F=k.time*1e3,L=k.classname||C,W=path.basename(L,path.extname(L)).toLowerCase(),Ir=h.get(W)??null,{commands:ct,matchedAnyFile:dt}=ei(d,L),ut=dt?ct.filter(B=>B.category!=="assertion"):v,pt=dt?ct.filter(B=>B.category==="assertion"):w,ft=[...ut,...pt].reduce((B,Mr)=>{let ge=Date.parse(Mr.timestamp);return Number.isFinite(ge)&&ge<B?ge:B},Number.POSITIVE_INFINITY),fe=Number.isFinite(ft)?new Date(ft).toISOString():r,gt=new Date(new Date(fe).getTime()+F).toISOString();g.push({flowName:C,flowFile:L,appId:M?.appId??null,platform:l,deviceId:e.device,status:N,duration:F,startedAt:fe,completedAt:gt,tags:M?.tags??[],properties:M?.properties??{},commands:ut,assertions:pt,screenshotPaths:Xs(L,o.screenshotPaths),videoPath:Sr(L,o.videoPaths,Ir),aiDefects:p,logEntries:ni(a,fe,gt),failureMessage:k.failureMessage??k.errorMessage??null,failureType:k.failureType??k.errorType??null,subflowRefs:M?.subflowRefs??[],metadata:M??null});}}if(g.length===0&&c.size>0)for(let[,f]of c)g.push({flowName:f.name??f.filePath,flowFile:f.filePath,appId:f.appId,platform:l,deviceId:e.device,status:"passed",duration:0,startedAt:r,completedAt:r,tags:f.tags,properties:f.properties,commands:[],assertions:[],screenshotPaths:[],videoPath:null,aiDefects:[],logEntries:a.slice(),failureMessage:null,failureType:null,subflowRefs:f.subflowRefs,metadata:f});let b=(()=>{if(!t.network?.enabled&&!t.network?.harPath)return;let f=g.map(v=>({testId:`${v.flowFile}::${v.flowName}`,startedAt:v.startedAt,completedAt:v.completedAt})),m=dr(e.networkJsonlDir??null,t.network,f);if(m.size===0)return;let w=new Map;for(let[v,S]of m)w.set(v,ur(S));return w})(),x=$e(g,b),T=G(x),R=new Date().toISOString(),D=Date.now()-new Date(r).getTime(),I={schemaVersion:"1.0.0",testRunId:n,startedAt:r,completedAt:R,totalDuration:D,summary:T,ci:null,metadata:t.metadata??null,timeline:x,shardRunIds:null};if(fs.mkdirSync(path.dirname(path.resolve(t.outputPath)),{recursive:true}),fs.writeFileSync(path.resolve(t.outputPath),JSON.stringify(I,null,2),"utf-8"),ze(I,p,o.screenshotPaths,path.resolve(t.htmlReportPath)),qe(T,t.outputPath,t.htmlReportPath,t.quiet,p),t.openReport&&Ge(path.resolve(t.htmlReportPath)),t.cloud){let f=new J(t.cloud);await f.initialize();let m=t.includeVideo?o.videoPaths:[],w=[];if(m.length>0){for(let C of g){let M=path.basename(C.flowFile,path.extname(C.flowFile)).toLowerCase(),N=h.get(M)??null,F=Sr(C.flowFile,m,N);if(F){let L=`${C.flowFile}::${C.flowName}`;w.some(W=>W.path===F&&W.testId===L)||w.push({path:F,testId:L});}}if(m.length===1){let C=m[0];for(let M of g){let N=`${M.flowFile}::${M.flowName}`;w.some(F=>F.testId===N)||w.push({path:C,testId:N});}}}let v=new Set(w.map(C=>C.path)),S=m.filter(C=>!v.has(C)),k=g.map((C,M)=>{let N=`${C.flowFile}::${C.flowName}`,F=x[M]?.tests?.[0];return ri(C,b?.get(N),F?.actions??null)});await lt(f,t.cloud,n,I,R,D,T,t.includeScreenshots?o.screenshotPaths:[],S,k,w);}return {report:I,flowResults:g,aiDefects:p,artifacts:o}}function ui(e){return "tests"in e&&"visitedAt"in e}function Ar(e){let t=[],r=[],n="",o="",s="";for(let c of e)try{let d=fs.readFileSync(c,"utf-8"),u=JSON.parse(d);s||(s=u.testRunId),(!n||u.startedAt<n)&&(n=u.startedAt),(!o||u.completedAt&&u.completedAt>o)&&(o=u.completedAt);for(let p of u.timeline)t.push(p),ui(p)&&r.push(p);}catch{process.stderr.write(`\u26A0 TestRelic: Unable to read report file: ${c}
1275
- `);}let i=G(r),a=n?new Date(n).getTime():Date.now(),l=o?new Date(o).getTime():Date.now();return {schemaVersion:"1.0.0",testRunId:s||`maestro-merged-${Date.now()}`,startedAt:n||new Date().toISOString(),completedAt:o||new Date().toISOString(),totalDuration:l-a,summary:i,ci:null,metadata:null,timeline:t,shardRunIds:null}}function pi(e,t){if(!fs.existsSync(e))throw new Error(`Directory does not exist: ${e}`);let r=fs.readdirSync(e).filter(o=>path.extname(o)===".json"&&o.includes("testrelic")).map(o=>path.join(e,o)),n=Ar(r);return fs.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),n}exports.CloudClient=J;exports.DEFAULT_CLOUD_CONFIG=me;exports.buildMaestroArgs=nr;exports.buildSummary=G;exports.buildTimeline=$e;exports.buildTimelineEntry=Ut;exports.buildUploadPayload=le;exports.categorizeCommand=Mt;exports.cleanupExpiredQueue=rt;exports.collectArtifacts=Ue;exports.collectGitMetadata=Qe;exports.deriveNonGitProjectId=z;exports.deriveRepoDisplayName=Ze;exports.detectCI=ue;exports.detectPlatformFromLogs=Ie;exports.discoverAiReports=Oe;exports.discoverCommandFiles=Re;exports.discoverConfigFile=ye;exports.discoverFlowFiles=Te;exports.discoverLogFiles=Me;exports.enforceHttps=Ke;exports.exchangeToken=te;exports.finalizeAndUpload=lt;exports.finalizeRun=Ts;exports.flushQueue=tt;exports.generateHtmlReport=ze;exports.getArtifactStats=Zn;exports.healthCheck=ee;exports.initRealtimeRun=Ss;exports.isAuthError=re;exports.mergeCloudConfig=xe;exports.mergeReports=Ar;exports.mergeReportsFromDirectory=pi;exports.normalizeGitRemoteUrl=j;exports.openInBrowser=Ge;exports.orchestrateReport=oi;exports.parseAiReportFile=Ne;exports.parseAiReportHtml=Nt;exports.parseCommandsFile=Ce;exports.parseCommandsJson=Et;exports.parseConfigFile=be;exports.parseDuration=he;exports.parseFlowFile=Se;exports.parseFlowYaml=_t;exports.parseJUnitFile=we;exports.parseJUnitXml=Ct;exports.parseLogContent=Dt;exports.parseLogFile=Ae;exports.printConsoleSummary=qe;exports.readPackageJsonName=gr;exports.refreshAccessToken=Ye;exports.renderHtmlDocument=je;exports.resolveConfig=Wr;exports.resolveEnvVar=K;exports.resolveEnvVars=Y;exports.resolveRepo=Xe;exports.runMaestro=Oo;exports.uploadArtifact=kr;exports.uploadArtifacts=at;exports.uploadBatchRun=ot;exports.writeToQueue=oe;//# sourceMappingURL=index.cjs.map
1855
+ `);for(let[m,y]of f){let w=x.find(k=>k.filePath===m),S=w?`[${w.type}] ${m}`:m;process.stderr.write(` \u2717 ${S} \u2014 reason: ${y.error??"unknown"}
1856
+ `);}}}}if(e.isCloudMode())if(await e.ensureValidToken()){let h=e.getGitMetadata(),g=ue(),v=Tr(e),x=Zs(o.timeline),T={...o,timeline:x},R=ce(T,v,h,g,c),L=await st(e.getEndpoint(),e.getAccessToken(),R,async()=>await e.ensureValidToken()?e.getAccessToken():null);if(L.success)process.stderr.write(`\u2713 TestRelic: Cloud upload succeeded \u2192 ${e.getEndpoint()}/runs/${r}
1857
+ `);else {let M=L,f=t?.queueDirectory??".testrelic/queue";se(f,r,"batch",M.reason,M.targetEndpoint,M.method,M.payload,{"Content-Type":"application/json"}),process.stderr.write(`\u26A0 TestRelic: Cloud upload failed, queued for retry.
1858
+ `);}}else {let h=t?.queueDirectory??".testrelic/queue",g=e.getGitMetadata(),v=ue(),x=Tr(e),T=ce(o,x,g,v);se(h,r,"batch",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs`,"POST",T,{"Content-Type":"application/json"});}await e.dispose();}catch{try{await e.dispose();}catch{}}}function Mr(e,t,r){if(t.length===0)return null;let o=path.basename(e,path.extname(e)).toLowerCase(),n=t.find(a=>path.basename(a,path.extname(a)).toLowerCase()===o);if(n)return n;let s=t.find(a=>path.basename(a).toLowerCase().includes(o));if(s)return s;let i=t.find(a=>{let l=path.basename(a,path.extname(a)).toLowerCase();return l.length>=3&&(o.startsWith(l)||o.includes(l))});if(i)return i;if(r){let a=path.basename(r,path.extname(r)).toLowerCase(),l=t.find(d=>path.basename(d,path.extname(d)).toLowerCase()===a);if(l)return l;let c=t.find(d=>path.basename(d).toLowerCase().includes(a));if(c)return c}return null}function ni(e,t){if(t.length===0)return [];let r=path.basename(e,path.extname(e)).toLowerCase(),o=t.filter(n=>{let s=path.basename(n).toLowerCase(),i=path.basename(n,path.extname(n)).toLowerCase();return s.startsWith(r)||s.includes(r)?true:i.length>=3&&(r.startsWith(i)||r.includes(i))});return o.length>0?o:t.slice()}function si(e){for(let t of e)if(t.command==="startRecording"){let r=t.metadata,o=r?.path??r?.recording??r?.fileName;if(typeof o=="string")return o;if(typeof t.selector=="string")return t.selector}return null}function Ir(e){return path.basename(e).replace(/^commands[-_]?/i,"").replace(/\.json$/i,"").replace(/^\(/,"").replace(/\)$/,"").toLowerCase()}function ii(e){let t=new Map;for(let[r,o]of e){let n=Ir(r),s=si(o);s&&n&&t.set(n,s);}return t}function ai(e,t){let r=path.basename(t,path.extname(t)).toLowerCase();if(!r||e.size===0)return {commands:[],matchedAnyFile:false};let o=n=>Ir(n);for(let[n,s]of e)if(o(n)===r)return {commands:s,matchedAnyFile:true};for(let[n,s]of e){let i=o(n);if(i.length>=3&&i.includes(r))return {commands:s,matchedAnyFile:true}}for(let[n,s]of e){let i=o(n);if(i.length>=3&&r.includes(i))return {commands:s,matchedAnyFile:true}}return {commands:[],matchedAnyFile:false}}function li(e){switch(e){case "android":return "Android";case "ios":return "iOS";case "web":return "Web";default:return}}function ci(e,t,r){let o=e.logEntries.length>0?e.logEntries.map(n=>({level:n.level.toLowerCase(),message:n.message,timestamp:n.timestamp,source:n.source})):void 0;return {testId:`${e.flowFile}::${e.flowName}`,title:e.flowName,status:e.status,duration:e.duration,suiteName:e.appId??"maestro-suite",filePath:e.flowFile,testType:"mobile",isFlaky:false,startedAt:e.startedAt,completedAt:e.completedAt,tags:e.tags,failure:e.failureMessage?{message:e.failureMessage}:null,retry:0,retryCount:0,retryStatus:null,source:"maestro",platform:e.platform!=="unknown"?e.platform:void 0,os:li(e.platform),deviceName:e.deviceId,...o?{consoleLogs:o}:{},...t&&t.length>0?{apiCalls:t}:{},...r&&r.length>0?{actions:r}:{}}}function di(e,t,r){if(e.length===0)return [];let o=Date.parse(t),n=Date.parse(r);return Number.isNaN(o)||Number.isNaN(n)?e.slice():e.filter(s=>{let i=Date.parse(s.timestamp);return Number.isNaN(i)?true:i>=o&&i<=n})}async function pi(e){let{config:t}=e,r=new Date().toISOString(),o=t.testRunId??crypto.randomUUID(),n=ze(e.testOutputDir,e.debugOutputDir),s=e.junitPath??n.junitReportPath,i=e.debugOutputDir?Ee(e.debugOutputDir):n.logPaths,a=[];for(let f of i){let m;try{let{statSync:w}=await import('fs');m=w(f).mtime;}catch{}let y=Me(f,m);y.length>0&&a.push(...y);}let l=e.platform??"unknown";if(l==="unknown"&&a.length>0){let f=Ie(a);f!=="unknown"&&(l=f);}let c=new Map;if(e.flowsDir&&fs.existsSync(e.flowsDir)){let f=Ae(e.flowsDir);for(let m of f){let y=Te(m),w=y.name??m;c.set(w,y);}}let d=new Map,p=e.testOutputDir?Se(e.testOutputDir):n.commandJsonPaths;for(let f of p)d.set(f,Re(f));let u=[],b=e.testOutputDir?Ue(e.testOutputDir):n.aiReportPaths;for(let f of b){let m=Oe(f);u.push(...m.defects);}let h=ii(d),g=[];if(s&&fs.existsSync(s)){let f=we(s),m=Array.from(d.values()).flat(),y=m.filter(S=>S.category==="assertion"),w=m.filter(S=>S.category!=="assertion");for(let S of f.testSuites)for(let k of S.testCases){let C=k.name,I=c.get(C),N=k.status==="SUCCESS"?"passed":k.status==="SKIPPED"?"skipped":"failed",F=k.time*1e3,_=k.classname||C,W=path.basename(_,path.extname(_)).toLowerCase(),Fr=h.get(W)??null,{commands:dt,matchedAnyFile:pt}=ai(d,_),ut=pt?dt.filter($=>$.category!=="assertion"):w,ft=pt?dt.filter($=>$.category==="assertion"):y,gt=[...ut,...ft].reduce(($,Dr)=>{let me=Date.parse(Dr.timestamp);return Number.isFinite(me)&&me<$?me:$},Number.POSITIVE_INFINITY),ge=Number.isFinite(gt)?new Date(gt).toISOString():r,mt=new Date(new Date(ge).getTime()+F).toISOString();g.push({flowName:C,flowFile:_,appId:I?.appId??null,platform:l,deviceId:e.device,status:N,duration:F,startedAt:ge,completedAt:mt,tags:I?.tags??[],properties:I?.properties??{},commands:ut,assertions:ft,screenshotPaths:ni(_,n.screenshotPaths),videoPath:Mr(_,n.videoPaths,Fr),aiDefects:u,logEntries:di(a,ge,mt),failureMessage:k.failureMessage??k.errorMessage??null,failureType:k.failureType??k.errorType??null,subflowRefs:I?.subflowRefs??[],metadata:I??null});}}if(g.length===0&&c.size>0)for(let[,f]of c)g.push({flowName:f.name??f.filePath,flowFile:f.filePath,appId:f.appId,platform:l,deviceId:e.device,status:"passed",duration:0,startedAt:r,completedAt:r,tags:f.tags,properties:f.properties,commands:[],assertions:[],screenshotPaths:[],videoPath:null,aiDefects:[],logEntries:a.slice(),failureMessage:null,failureType:null,subflowRefs:f.subflowRefs,metadata:f});let v=(()=>{if(!t.network?.enabled&&!t.network?.harPath)return;let f=g.map(w=>({testId:`${w.flowFile}::${w.flowName}`,startedAt:w.startedAt,completedAt:w.completedAt})),m=fr(e.networkJsonlDir??null,t.network,f);if(m.size===0)return;let y=new Map;for(let[w,S]of m)y.set(w,gr(S));return y})(),x=$e(g,v),T=V(x),R=new Date().toISOString(),L=Date.now()-new Date(r).getTime(),M={schemaVersion:q,testRunId:o,startedAt:r,completedAt:R,totalDuration:L,summary:T,ci:null,metadata:t.metadata??null,timeline:x,shardRunIds:null};if(fs.mkdirSync(path.dirname(path.resolve(t.outputPath)),{recursive:true}),fs.writeFileSync(path.resolve(t.outputPath),JSON.stringify(M,null,2),"utf-8"),Ge(M,u,n.screenshotPaths,path.resolve(t.htmlReportPath)),qe(T,t.outputPath,t.htmlReportPath,t.quiet,u),t.openReport&&Ve(path.resolve(t.htmlReportPath)),t.cloud){let f=new K(t.cloud);await f.initialize();let m=t.includeVideo?n.videoPaths:[],y=[];if(m.length>0){for(let C of g){let I=path.basename(C.flowFile,path.extname(C.flowFile)).toLowerCase(),N=h.get(I)??null,F=Mr(C.flowFile,m,N);if(F){let _=`${C.flowFile}::${C.flowName}`;y.some(W=>W.path===F&&W.testId===_)||y.push({path:F,testId:_});}}if(m.length===1){let C=m[0];for(let I of g){let N=`${I.flowFile}::${I.flowName}`;y.some(F=>F.testId===N)||y.push({path:C,testId:N});}}}let w=new Set(y.map(C=>C.path)),S=m.filter(C=>!w.has(C)),k=g.map((C,I)=>{let N=`${C.flowFile}::${C.flowName}`,F=x[I]?.tests?.[0];return ci(C,v?.get(N),F?.actions??null)});await ct(f,t.cloud,o,M,R,L,T,t.includeScreenshots?n.screenshotPaths:[],S,k,y);}return {report:M,flowResults:g,aiDefects:u,artifacts:n}}function vi(e){return "tests"in e&&"visitedAt"in e}function Er(e){let t=[],r=[],o="",n="",s="";for(let c of e)try{let d=fs.readFileSync(c,"utf-8"),p=JSON.parse(d);s||(s=p.testRunId),(!o||p.startedAt<o)&&(o=p.startedAt),(!n||p.completedAt&&p.completedAt>n)&&(n=p.completedAt);for(let u of p.timeline)t.push(u),vi(u)&&r.push(u);}catch{process.stderr.write(`\u26A0 TestRelic: Unable to read report file: ${c}
1859
+ `);}let i=V(r),a=o?new Date(o).getTime():Date.now(),l=n?new Date(n).getTime():Date.now();return {schemaVersion:q,testRunId:s||`maestro-merged-${Date.now()}`,startedAt:o||new Date().toISOString(),completedAt:n||new Date().toISOString(),totalDuration:l-a,summary:i,ci:null,metadata:null,timeline:t,shardRunIds:null}}function xi(e,t){if(!fs.existsSync(e))throw new Error(`Directory does not exist: ${e}`);let r=fs.readdirSync(e).filter(n=>path.extname(n)===".json"&&n.includes("testrelic")).map(n=>path.join(e,n)),o=Er(r);return fs.writeFileSync(t,JSON.stringify(o,null,2),"utf-8"),o}exports.CloudClient=K;exports.DEFAULT_CLOUD_CONFIG=he;exports.SCHEMA_VERSION=q;exports.buildMaestroArgs=ir;exports.buildSummary=V;exports.buildTimeline=$e;exports.buildTimelineEntry=zt;exports.buildUploadPayload=ce;exports.categorizeCommand=Et;exports.cleanupExpiredQueue=ot;exports.collectArtifacts=ze;exports.collectGitMetadata=Ze;exports.deriveNonGitProjectId=j;exports.deriveRepoDisplayName=et;exports.detectCI=ue;exports.detectPlatformFromLogs=Ie;exports.discoverAiReports=Ue;exports.discoverCommandFiles=Se;exports.discoverConfigFile=ve;exports.discoverFlowFiles=Ae;exports.discoverLogFiles=Ee;exports.enforceHttps=Ye;exports.exchangeToken=re;exports.finalizeAndUpload=ct;exports.finalizeRun=Ps;exports.flushQueue=rt;exports.generateHtmlReport=Ge;exports.getArtifactStats=rn;exports.healthCheck=te;exports.initRealtimeRun=Ds;exports.isAuthError=oe;exports.mergeCloudConfig=ye;exports.mergeReports=Er;exports.mergeReportsFromDirectory=xi;exports.normalizeGitRemoteUrl=B;exports.openInBrowser=Ve;exports.orchestrateReport=pi;exports.parseAiReportFile=Oe;exports.parseAiReportHtml=Ot;exports.parseCommandsFile=Re;exports.parseCommandsJson=Ft;exports.parseConfigFile=xe;exports.parseDuration=be;exports.parseFlowFile=Te;exports.parseFlowYaml=_t;exports.parseJUnitFile=we;exports.parseJUnitXml=Rt;exports.parseLogContent=Nt;exports.parseLogFile=Me;exports.printConsoleSummary=qe;exports.readPackageJsonName=br;exports.refreshAccessToken=Xe;exports.renderHtmlDocument=je;exports.resolveConfig=Xr;exports.resolveEnvVar=Y;exports.resolveEnvVars=X;exports.resolveRepo=Qe;exports.runMaestro=Gn;exports.uploadArtifact=Sr;exports.uploadArtifacts=lt;exports.uploadBatchRun=st;exports.writeToQueue=se;//# sourceMappingURL=index.cjs.map
1276
1860
  //# sourceMappingURL=index.cjs.map