saffron-ai 1.0.1 → 1.1.0
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/CHANGELOG.md +107 -0
- package/README.md +1 -2
- package/dist-pkg/cli.js +329 -294
- package/package.json +2 -2
- package/skills/saffron/references/syntax.md +23 -3
- package/templates/playwright/saffron-helpers.ts +652 -0
package/dist-pkg/cli.js
CHANGED
|
@@ -1,67 +1,84 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
2
|
+
import Ne from"node:fs";import V from"node:path";import x$ from"node:readline";import{Command as v$}from"commander";import qm from"node:fs";import Hm from"node:path";import{AstBuilder as Jm,dialects as Rd,GherkinClassicTokenMatcher as Vm,Parser as Wm}from"@cucumber/gherkin";import{IdGenerator as Gm,StepKeywordType as Ro}from"@cucumber/messages";import ud from"node:fs";import Om from"node:path";import Tr from"node:fs";import gn from"node:path";var ve=/\{data:([A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+)\}/g,Ar=gn.resolve("data"),Xt,cd=process.cwd(),mo=new Map;function Ut(e,t="data",n){cd=gn.resolve(e),Ar=gn.isAbsolute(t)?t:gn.join(e,t),Xt=n?.trim()||void 0,mo.clear()}var it=()=>({dir:Ar,env:Xt,root:cd});function ld(e,t){let n=s=>s!==null&&typeof s=="object"&&!Array.isArray(s);if(!n(e)||!n(t))return t;let r={...e};for(let[s,o]of Object.entries(t))r[s]=s in e?ld(e[s],o):o;return r}function ad(e,t){try{return JSON.parse(Tr.readFileSync(e,"utf8"))}catch(n){throw new Error(`data file ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function Am(e){if(mo.has(e))return mo.get(e);let t=gn.join(Ar,`${e}.json`),n=Xt?gn.join(Ar,`${e}.${Xt}.json`):void 0,r=Tr.existsSync(t),s=n!==void 0&&Tr.existsSync(n);if(!r&&!s)throw new Error(`data file ${gn.relative(process.cwd(),t)||t} does not exist${Xt?` (nor ${e}.${Xt}.json for the "${Xt}" environment)`:""}`);let o=r?ad(t,`${e}.json`):void 0;if(s){let a=ad(n,`${e}.${Xt}.json`);o=r?ld(o,a):a}return mo.set(e,o),o}function er(e){let[t,...n]=e.split("."),r=Am(t),s=[t];for(let o of n){let a=r,i=a&&typeof a=="object"?Array.isArray(a)?a[Number(o)]:Object.hasOwn(a,o)?a[o]:void 0:void 0;if(i===void 0)throw new Error(`"${o}" does not exist under ${s.join(".")} (in ${t}.json)`);r=i,s.push(o)}return r}function Le(e){let t;try{t=er(e)}catch(n){throw new Error(`{data:${e}}: ${n instanceof Error?n.message:String(n)}`)}if(t===null||typeof t=="object")throw new Error(`{data:${e}} is ${Array.isArray(t)?"a list":"an object"}, not a single value. Point at one entry, for example {data:${e}.${Array.isArray(t)?"0":Object.keys(t??{})[0]??"key"}}`);return String(t)}function en(e){let t;try{t=er(e)}catch(s){throw new Error(`{data:${e}}: ${s instanceof Error?s.message:String(s)}`)}let n=Array.isArray(t)?t:[t];if(n.length===0)throw new Error(`{data:${e}} is an empty list: there is nothing to check`);let r=n.find(s=>s===null||typeof s=="object");if(r!==void 0)throw new Error(`{data:${e}} must be a list of plain values (text, numbers); it contains ${Array.isArray(r)?"a list":"an object"}`);return n.map(String)}function wo(e){en(e)}function dd(e){return e.replace(ve,(t,n)=>{let r=en(n);return Array.isArray(er(n))?`${t} (a data list, currently: ${r.map(o=>`"${o}"`).join(", ")})`:r[0]})}function Em(e){let t=[],n=[],r="",s=!1,o=!1,a=-1,i=()=>{n.push(a>=0?r.slice(0,a)+r.slice(a).trim():r.trim()),r="",a=-1},c=()=>{i(),(o||n.some(l=>l!==""))&&t.push(n),n=[],o=!1};for(let l=0;l<e.length;l++){let d=e[l];s?d==='"'&&e[l+1]==='"'?(r+='"',l++):d==='"'?(s=!1,a=r.length):r+=d:d==='"'&&r.trim()===""?(r="",s=o=!0):d===","?i():d===`
|
|
3
3
|
`||d==="\r"?(d==="\r"&&e[l+1]===`
|
|
4
|
-
`&&l++,c()):r+=d}return c(),t}function
|
|
5
|
-
`)){let s=r.trim().replace(/^export\s+/,"");if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o<=0)continue;let a=s.slice(0,o).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(a))continue;let i=s.slice(o+1).trim(),c=/^(?:"((?:\\.|[^"\\])*)"|'([^']*)')\s*(?:#.*)?$/.exec(i);c?i=c[1]!==void 0?c[1].replace(/\\(["\\])/g,"$1"):c[2]:i=i.replace(/\s+#.*$/,""),n[a]=i}return n}function
|
|
6
|
-
`),n=new Map,r=new Map,s;return{source:t.map((a,i)=>{let c=/^\s*("""|```)/.exec(a)?.[1];if(s)return c===s&&(s=void 0),a;if(c)return s=c,a;let l=a.match(
|
|
7
|
-
`),definitions:n,invocations:r}}function
|
|
8
|
-
`).filter(
|
|
4
|
+
`&&l++,c()):r+=d}return c(),t}function yo(e){let t=i=>{throw new Error(`Examples: {data:${e}}: ${i}`)},n=Xt?gn.join(Ar,`${e}.${Xt}.csv`):void 0,r=n&&Tr.existsSync(n)?n:gn.join(Ar,`${e}.csv`);if(!e.includes(".")&&Tr.existsSync(r)){let[i,...c]=Em(Tr.readFileSync(r,"utf8"));(!i||c.length===0)&&t(`${e}.csv needs a header row and at least one data row`);let l=c.findIndex(d=>d.length>i.length);return l>=0&&t(`${e}.csv row ${l+2} has ${c[l].length} fields for ${i.length} columns: quote a value that holds a comma`),{headers:i,rows:c.map(d=>Object.fromEntries(i.map((u,p)=>[u,d[p]??""])))}}let s;try{s=er(e)}catch(i){return t(`${i instanceof Error?i.message:String(i)} (looked for ${e.split(".")[0]}.csv and ${e.split(".")[0]}.json in the data folder)`)}(!Array.isArray(s)||s.length===0||s.some(i=>i===null||typeof i!="object"||Array.isArray(i)))&&t('must be a non-empty list of records, like [{ "role": "Admin", "menu": "Users" }]');let o=s,a=[...new Set(o.flatMap(i=>Object.keys(i)))];return{headers:a,rows:o.map(i=>Object.fromEntries(a.map(c=>[c,i[c]===void 0||i[c]===null?"":String(i[c])])))}}function zt(e){return e.replace(ve,(t,n)=>Le(n))}function hn(e){let t=new Set;for(let n of e)if(n)for(let r of n.matchAll(ve))t.add(r[1]);return t}function Er(e){let t=new Map;for(let n of hn(e))try{t.set(n,Le(n))}catch{}return t}function bo(e,t,n=new Set){let r=new Map;for(let[c,l]of t)r.set(l,[...r.get(l)??[],c]);let s=[];for(let[c,l]of r){let d=l.length===1?l:l.filter(u=>n.has(u));d.length===1&&s.push([d[0],c])}s.sort((c,l)=>l[1].length-c[1].length);for(let[c,l]of s)if(l!==""&&e===l)return`{data:${c}}`;let o=new Map(s.filter(([,c])=>c.length>=3).map(([c,l])=>[l,`{data:${c}}`]));if(o.size===0)return e;let a=[...o.keys()].map(c=>{let l=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return c.length>=4?l:`(?<![\\p{L}\\p{N}])${l}(?![\\p{L}\\p{N}])`}).join("|"),i=new RegExp(a,"gu");return e.split(/(\{(?:env|data|unique|date)[^{}]*\}|<[^<>\s]+>)/).map((c,l)=>l%2?c:c.replace(i,d=>o.get(d))).join("")}var Se=/\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g;function md(e,t){return e.replace(Se,(n,r)=>{if(!t.has(r))throw new Error(`{env:${r}} is not referenced by this scenario: a recording can only use the environment variables its scenario names`);let s=process.env[r];if(s===void 0)throw new Error(`environment variable ${r} is not set (referenced as {env:${r}}): export it or add it to .env`);return s})}function pa(e){let t=new Set;for(let n of e)if(n)for(let r of n.matchAll(Se))t.add(r[1]);return t}function at(e){let t=[];for(let n of e.steps){t.push(n.text,n.resolvedText),n.docString&&t.push(n.docString),n.resolvedDocString&&t.push(n.resolvedDocString);for(let r of n.table??[])t.push(...r);for(let r of n.resolvedTable??[])t.push(...r)}return t}function Or(e){let t=at(e);return[...t,..._r(t)]}function _r(e){let t=[];for(let n of hn(e))try{t.push(...en(n))}catch{}return t}function ct(e){let t=at(e);return pa([...t,..._r(t)])}function Te(e){let t=new Map;for(let n of ct(e)){let r=process.env[n];r!==void 0&&t.set(n,r)}return t}var Nn=3,fa=String.raw`\{(?:env:[A-Za-z_][A-Za-z0-9_]*|data:[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+|unique:[A-Za-z0-9_-]+(?::digits)?)\\?\}`,_m=/\{(env:[A-Za-z_][A-Za-z0-9_]*|data:[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+)\\\}/g,wd=e=>`${e.slice(0,-1)}\\}`,us=e=>e.replace(_m,"{$1}"),vo={'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"};function xo(e,t,n,r){let s="";for(let o of e.split("")){let a=o.charCodeAt(0);if(t?.test(o)||a<32&&!vo[o]){let i=a.toString(16).padStart(4,"0");s+="\\u"+(n?i.toUpperCase():i)}else vo[o]?s+=vo[o]:o==="/"&&r?s+="\\/":s+=o}return s}function Cm(e){return[e,e.replace(/%[0-9A-F]{2}/g,t=>t.toLowerCase())]}function fd(e,t,n){return e.replace(/[&<>"'+]|[^\x00-\x7f]/gu,r=>t[r]??(n&&r>"\x7F"?n(r.codePointAt(0)):r))}function Pm(e,t){let n="";for(let r of e){let s=r<=" "||r>="\x7F"||t.test(r);n+=s?[...Buffer.from(r,"utf8")].map(o=>"%"+o.toString(16).toUpperCase().padStart(2,"0")).join(""):r}return n}var Im=[/["#<>']/,/["#<>?^`{}]/,/["#<>?^`{|}]/,/["#<>?^`{}/:;=@[\\\]|]/,/["#<>?^`{}/:;=@[\\\]|']/];function jm(e){let t=/[^\x00-\x7f]/,n=new Set([e]);for(let[i,c,l]of[[void 0,!1,!1],[void 0,!1,!0],[t,!1,!1],[t,!0,!1],[t,!1,!0],[/[<>&\u2028\u2029]/,!1,!1],[/[^\x00-\x7f]|[<>&'+`"]/,!0,!1]])n.add(xo(e,i,c,l));let r=i=>xo(i,void 0,!1,!1).replaceAll('\\"','"').replaceAll("'","\\'"),s=i=>i.replace(/["'`>]/g,c=>`\\x${c.charCodeAt(0).toString(16)}`),o=i=>i.replace(/\s+/g,"\\s+");for(let i of[e,ue(e),ue(e).replaceAll("/","\\/")])for(let c of[i,r(i),i.replaceAll("'","\\'"),s(i),o(i),s(o(i))])n.add(c),n.add(xo(c,void 0,!1,!1));let a=i=>{try{for(let c of Cm(i()))n.add(c)}catch{}};a(()=>encodeURIComponent(e)),a(()=>encodeURIComponent(encodeURIComponent(e))),a(()=>encodeURIComponent(e).replaceAll("'","%27")),a(()=>encodeURI(e)),a(()=>new URLSearchParams([["",e]]).toString().slice(1));for(let i of Im)a(()=>Pm(e,i));for(let i of[{"&":"&","<":"<",">":">"},{"&":"&","<":"<",">":">",'"':""","'":"'"},{"&":"&","<":"<",">":">",'"':""","'":"'"},{"&":"&","<":"<",">":">",'"':""","'":"'"},{"&":"&","<":"<",">":">",'"':""","'":"'"},{"&":"&","<":"<",">":">",'"':""","'":"'","+":"+"}])n.add(fd(e,i));if(e.includes("'"))for(let i of[e,xo(e,void 0,!1,!1)])n.add(i.replaceAll("'","''"));return n.add(e.replaceAll("~","~0").replaceAll("/","~1")),n.add(fd(e,{"&":"&","<":"<",">":">",'"':""","'":"'","+":"+"},i=>`&#x${i.toString(16).toUpperCase()};`)),[...n]}var Cr=e=>e.map(t=>`{env:${t}}`).join(""),ue=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ga=e=>ue(e).replace(/%[0-9a-f]{2}/gi,t=>t.replace(/[a-f]/gi,n=>`[${n.toUpperCase()}${n.toLowerCase()}]`)),Nm=e=>Buffer.from(e,"utf8").toString("latin1");function mn(e,t={}){let n=[...e.entries()].filter(([,m])=>m.length>=Nn).sort((m,$)=>$[1].length-m[1].length),r=m=>t.encodings?m.replace(/%[0-9a-f]{2}/gi,$=>$.toUpperCase()):m,s=t.encodings?ga:ue,o=new Map,a=new Map,i=new Set,c=new Set;for(let[m,$]of n){t.standaloneBelow!==void 0&&$.length<t.standaloneBelow&&c.add($);let T=t.encodings&&$.length>=6&&$.toLowerCase()!==$.toUpperCase(),R=t.encodings?[...new Set((T?[$,$.toLowerCase(),$.toUpperCase()]:[$]).flatMap(jm))]:[$];for(let k of R){let C=t.bytes?[Nm(k),.../^[\x00-\xff]*$/.test(k)?[k]:[]]:[k];for(let P of C){let w=r(P);o.has(w)||o.set(w,m),T&&(i.add(w),a.has(w.toLowerCase())||a.set(w.toLowerCase(),m))}}}let l=new Set(n.map(([,m])=>m)),d=new Map(n.filter(([,m])=>/^\d{6,}$/.test(m)).map(([m,$])=>[$,m])),u=[...d.keys()].map(m=>`(?<!\\d)${[...m].join("[\\s\\u00a0\\u202f-]?")}(?!\\d)`),p=m=>o.get(r(m))??a.get(r(m).toLowerCase())??d.get(m.replace(/\D/g,"")),f=new Set(["u"]);for(let[,m]of n)for(let $ of m){let T=vo[$]??($==="/"?"\\/":void 0);T&&f.add(T.slice(1))}let g=new RegExp(`\\\\[${[...f].map(ue).join("")}]`);if(o.size===0)return{empty:!0,mask:m=>m,matches:()=>[],occursIn:()=>!1,isValue:()=>!1,hiddenByEscape:g};let y=m=>i.has(m)?[...m].map($=>$.toLowerCase()===$.toUpperCase()?ue($):`(?:${ue($.toLowerCase())}|${ue($.toUpperCase())})`).join(""):s(m),h=[...o.keys()].sort((m,$)=>$.length-m.length).map(m=>c.has(m)?`(?<![A-Za-z0-9])${y(m)}(?![A-Za-z0-9])`:y(m)).concat(u).join("|"),S=new RegExp(`(${fa})|${h}`,"g"),v=new RegExp(`(${fa})|${h}`,"y"),x=new RegExp(h),b=m=>{let $=[];S.lastIndex=0;for(let T=S.exec(m);T!==null;T=S.exec(m)){if(T[1]!==void 0)continue;let R=T.index,k=R+T[0].length,C=[p(T[0])];for(let P=R+1;P<k;P++){v.lastIndex=P;let w=v.exec(m);w&&w[1]===void 0&&P+w[0].length>k&&(k=P+w[0].length,C.push(p(w[0])))}$.push({start:R,end:k,names:[...new Set(C)]}),S.lastIndex=k}return $};return{empty:!1,hiddenByEscape:g,occursIn:m=>x.test(m),isValue:m=>l.has(m),matches:b,mask(m){let $="",T=0;for(let R of b(m))$+=m.slice(T,R.start)+Cr(R.names),T=R.end;return T===0?m:$+m.slice(T)}}}function Pr(e,t,n=r=>r){let r=new Map;for(let a of e)for(let i of a.split(/[\s"'`]+/)){let c=i.replace(/^[.,;:!?()[\]]+|[.,;:!?()[\]]+$/g,""),l=[...c.matchAll(Se)].map(p=>p[1]);if(l.length===0||l.some(p=>!t.has(p)))continue;let d=c.replace(Se,(p,f)=>t.get(f));if(d===c||d.length<Nn||c===`{env:${l[0]}}`)continue;let u=n(d);r.has(u)||r.set(u,c.split(/(\{env:[A-Za-z_][A-Za-z0-9_]*\})/).map((p,f)=>f%2?p:n(p)).join(""))}if(r.size===0)return a=>a;let s=[...r.keys()].sort((a,i)=>i.length-a.length).map(ue).join("|"),o=new RegExp(`(${fa})|${s}`,"g");return a=>a.replace(o,(i,c)=>c!==void 0?i:r.get(i))}var pd=new WeakMap,gd=new WeakMap;function ha(e,t){if(t.size===0)return e;let n=gd.get(t);return n||(n=mn(t,{encodings:!0,standaloneBelow:6}),gd.set(t,n)),yd(n.mask(e),t)}function So(e,t){let n=Pr(e,t);return r=>ha(n(r),t)}var hd=new WeakMap;function yd(e,t){if(!e.includes("\u2026"))return e;let n=hd.get(t);if(n===void 0){let s=[...t].filter(([,a])=>[...a].length>=7),o=s.map(([,a],i)=>{let c=[...a].slice(0,Math.min([...a].length-1,64)),l=c.slice(6).reduceRight((d,u)=>`(?:${ue(u)}${d})?`,"");return`(?<v${i}>${ue(c.slice(0,6).join(""))}${l})`});n=o.length>0?{pattern:new RegExp(`(?<![\\p{L}\\p{N}])(?:${o.join("|")})\u2026`,"gu"),names:s.map(([a])=>a)}:null,hd.set(t,n)}if(!n)return e;let{names:r}=n;return e.replace(n.pattern,(...s)=>{let o=s.at(-1),a=Number(Object.keys(o).find(i=>o[i]!==void 0).slice(1));return`${Cr([r[a]])}\u2026`})}function Ge(e,t){let n=pd.get(t);return n||(n=mn(t,{encodings:!0}),pd.set(t,n)),yd(n.mask(e),t)}function bd(e){for(let[t,n]of Object.entries(ma(e)))process.env[t]===void 0&&(process.env[t]=n)}function ma(e){let t=Om.join(e,".env"),n=Object.create(null);if(!ud.existsSync(t))return n;for(let r of ud.readFileSync(t,"utf8").split(`
|
|
5
|
+
`)){let s=r.trim().replace(/^export\s+/,"");if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o<=0)continue;let a=s.slice(0,o).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(a))continue;let i=s.slice(o+1).trim(),c=/^(?:"((?:\\.|[^"\\])*)"|'([^']*)')\s*(?:#.*)?$/.exec(i);c?i=c[1]!==void 0?c[1].replace(/\\(["\\])/g,"$1"):c[2]:i=i.replace(/\s+#.*$/,""),n[a]=i}return n}function qt(e,t){return e.replace(/<([^<>]+)>/g,(n,r)=>Object.hasOwn(t,r)?t[r]:n)}function lt(e){if(!e||e.length===0)return{};let t={};if(e.every(n=>n.length===2)){for(let[n,r]of e)t[`table:${n}`]=r;return t}if(e.length>=2){let[n,...r]=e;if(n.some(s=>!s))return{};r.forEach((s,o)=>{n.forEach((a,i)=>{s[i]!==void 0&&(t[`table:${o+1}:${a}`]=s[i])})})}return t}function tr(e){return e!==void 0?{docstring:e}:{}}function Mn(e){let t=new Map;for(let r of e){let s={...lt(r.resolvedTable??r.table),...tr(r.resolvedDocString??r.docString)};for(let[o,a]of Object.entries(s)){let i=t.get(o);i||t.set(o,i=new Set),i.add(a)}}let n={};for(let[r,s]of t)s.size===1&&(n[r]=[...s][0]);return n}function wa(e){return e.replace(/\\.|["'`]|>>/g,t=>t[0]==="\\"?t:t===">>"?"\\>\\>":`\\${t}`)}var fe={quoted:e=>JSON.stringify(e).slice(1,-1),regex:e=>wa(ue(e).replaceAll("/","\\/")),pattern:e=>ue(e)};function wn(e,t,n=s=>s,r=!1){let s="",o=0;for(let a of e.matchAll(/(["'])((?:\\.|(?!\1)[^\\])*)\1|(?<!xpath)=\/((?:[^/\\]|\\.)*)\/([a-z]*)/g)){let[i,c,l,d,u]=a;if(!r&&c===void 0&&/[uv]/.test(u))continue;let p=c==="'"?l.replace(/\\.|"/g,y=>y==="\\'"?"'":y==='"'?'\\"':y):l,f=c===void 0?void 0:t(p,"quoted"),g=c==="'"?`'${f.replace(/\\.|'/g,y=>y==='\\"'?'"':y==="'"?"\\'":y)}'`:`"${f}"`;s+=n(e.slice(o,a.index))+(c!==void 0?g:`=/${t(d,"regex")}/${u}`),o=a.index+i.length}return s+n(e.slice(o))}var ya=/^As "([^"]+)"\s+(?=\S)/,Ht="default",ht=e=>e||Ht;function Jt(e){return ya.exec(e)?.[1].trim()||void 0}function xd(e,t){let n=ya.exec(e)?.[0],r=me(t);return n?`${n}${r}`:r}var me=e=>e.replace(ya,"");function tt(e,t){let n=t;return e.map(r=>{let s=Jt(r);return s!==void 0&&(n=s===Ht?void 0:s),n})}function vd(e){if(!(!/^As\s+"[^"]*"\s+\S/.test(e)||Jt(e)!==void 0))return`"${e}" starts like a browser session but names none. Write As "name" and the step after one space, as in As "buyer" I open the cart; the name cannot be empty.`}var we=e=>e??"";function Dn(e){return new Set(e.map(t=>we(t.session))).size>1}function fs(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"session"}function $o(e,t=[],n){let r,s,o,a=!1,i=!1,c;return e.map((l,d)=>{let u=r,p=/^\s*("""|```)/.exec(l)?.[1];if(p)return c?c===p&&(c=void 0):c=p,u;if(c)return u;if(/^\s*Feature:/.test(l))r=s=o=void 0,a=i=!1;else if(/^\s*Rule:/.test(l))a=!0,i=!1,r=o=s;else if(/^\s*Background:/.test(l))i=!0,r=a?s:void 0;else if(n?.has(d)||/^\s*(?:Scenario(?: Outline| Template)?|Example):/.test(l))i=!1,r=a?o:s;else if(/^\s*StepSet:/.test(l))i=!1,r=void 0;else{let f=/^\s*(?:Given|When|Then|And|But|\*)\s+(.+?)\s*$/.exec(l)?.[1],g=/^\s*StepSet\s+([^\s:].*?)\s*$/.exec(l)?.[1],y=f?[f]:t.find(h=>h.name===g)?.steps;y?.length&&(r=tt(y,r).at(-1),i&&(a?o=r:s=r))}return u})}function Sd(e,t,n){if(!n)return;let r=[...new Set(e)].filter(o=>o!==Ht&&!t.includes(o)).sort();return r.length<2?void 0:`${`${r.slice(0,-1).join(", ")} and ${r.at(-1)}`} ${r.length===2?"both":"all"} start signed in from storageState (${n}), as the same person; give each its own sessions entry in saffron.config.json.`}import ps from"node:fs";import ko from"node:path";import{AstBuilder as Mm,GherkinClassicTokenMatcher as Dm,Parser as Fm}from"@cucumber/gherkin";import{IdGenerator as Lm}from"@cucumber/messages";var Be=class extends Error{},Bm=/^(\s*)StepSet:\s*(.+?)\s*$/,Um=/^(\s*)StepSet\s+([^\s:].*?)\s*$/;function ba(e){let t=e.split(`
|
|
6
|
+
`),n=new Map,r=new Map,s;return{source:t.map((a,i)=>{let c=/^\s*("""|```)/.exec(a)?.[1];if(s)return c===s&&(s=void 0),a;if(c)return s=c,a;let l=a.match(Bm);if(l)return n.set(i+1,l[2]),`${l[1]}Scenario: ${l[2]}`;let d=a.match(Um);return d?(r.set(i+1,d[2]),`${d[1]}* StepSet ${d[2]}`):a}).join(`
|
|
7
|
+
`),definitions:n,invocations:r}}function zm(e){return new Fm(new Mm(Lm.uuid()),new Dm).parse(e)}function kd(e,t){for(let n of e)n.scenario?t(n.scenario):"rule"in n&&n.rule&&kd(n.rule.children,t)}function Vt(e,t){let n=new Map;for(let r of e){let s=ko.relative(t,r),o,a;try{if(o=ba(ps.readFileSync(r,"utf8")),o.definitions.size===0)continue;a=zm(o.source)}catch(i){throw new Be(`${s}: ${i instanceof Error?i.message:String(i)}`)}a.feature&&kd(a.feature.children,i=>{let c=o.definitions.get(i.location.line);if(c===void 0)return;let l=n.get(c);if(l)throw new Be(`StepSet "${c}" is defined twice: ${l.file}:${l.line} and ${s}:${i.location.line}. Set names are unique across the project. If line ${i.location.line} was meant to INVOKE the set inside a scenario, remove the colon: "StepSet ${c}".`);if(i.examples.length>0)throw new Be(`StepSet "${c}" (${s}:${i.location.line}) has an Examples table: step sets take their values from the invoking scenario.`);for(let d of i.steps)if(o.invocations.has(d.location.line))throw new Be(`StepSet "${c}" (${s}:${i.location.line}) invokes another step set at line ${d.location.line}, and step sets cannot be nested.`);n.set(c,{name:c,file:s,line:i.location.line,steps:[...i.steps]})})}return n}var xa=[".feature",".saffron"];function Wt(e){return xa.some(t=>e.endsWith(t))}function mt(e,t,n){let r=ko.isAbsolute(t.features??"features")?t.features:ko.join(e,t.features??"features"),s=new Set(yn(r));for(let o of n)o.endsWith(".saffron")&&s.add(o);return Vt([...s].sort(),e)}var $d=new Set([".saffron","node_modules",".git"]);function Gt(e,t){if(!ps.existsSync(e))return[];let n=[],r=new Set,s=[],o=c=>["ENOENT","ELOOP"].includes(c.code??""),a=c=>{try{return ps.statSync(c)}catch(l){if(o(l))return;throw l}},i=(c,l=!1)=>{let d,u;try{if(d=ps.realpathSync(c),r.has(d))return;u=ps.readdirSync(c,{withFileTypes:!0})}catch(p){if(l&&o(p))return;throw p}r.add(d);for(let p of u){let f=ko.join(c,p.name);if(p.isSymbolicLink()){let g=a(f);g?.isDirectory()?$d.has(p.name)||s.push(f):g?.isFile()&&t(p.name)&&n.push(f)}else p.isDirectory()?$d.has(p.name)||i(f):p.isFile()&&t(p.name)&&n.push(f)}};i(e);for(let c=0;c<s.length;c++)i(s[c],!0);return n.sort()}function yn(e){return Gt(e,t=>t.endsWith(".saffron"))}function Td(e,t,n){return e.map(({step:r,source:s})=>{let o;switch(r.keywordType){case Ro.OUTCOME:n.setup=!1,o="assertion";break;case Ro.CONTEXT:case Ro.ACTION:n.setup=r.keywordType===Ro.CONTEXT,o="action";break;default:o=n.value}n.value=o;let a=r.dataTable?r.dataTable.rows.map(c=>c.cells.map(l=>l.value)):void 0,i=r.docString?.content;return{setup:n.setup,keyword:r.keyword.trim(),kind:o,text:r.text,resolvedText:qt(r.text,t),table:a,resolvedTable:a?.map(c=>c.map(l=>qt(l,t))),docString:i,resolvedDocString:i!==void 0?qt(i,t):void 0,source:s}})}function Ad(e,t,n,r,s){let o=[];for(let a of e){let i=r.get(a.location.line);if(i===void 0){o.push({step:a,source:{file:t,line:a.location.line,fromBackground:n}});continue}let c=s?.get(i);if(!c)throw new Be(`${t}:${a.location.line} invokes StepSet "${i}", which is not defined anywhere in the project.`);for(let l of c.steps)o.push({step:l,source:{file:c.file,line:l.location.line,fromStepSet:c.name,fromBackground:n}})}return o}function Km(e,t,n,r,s,o=!1,a=[]){let i=[...new Set([...a,...e.tags.map(l=>l.name)])],c=[];if(e.examples.length===0)c.push({params:{},label:"",tags:i});else{let l=0;for(let d of e.examples){let u=[...new Set([...i,...d.tags.map(g=>g.name)])],p=d.name.trim().match(/^\{data:([A-Za-z0-9_.-]+)\}$/);if(p&&!d.tableHeader){let g=`${t}:${d.location.line}`;if(!o)throw new Be(`${g} reads Examples from a data file, which only .saffron files understand. Rename the file to ${t.replace(/\.feature$/,".saffron")}: nothing else needs to change.`);let y;try{y=yo(p[1])}catch(v){throw new Be(`${g} ${v instanceof Error?v.message:String(v)}`)}let S=[...new Set([...r,...s].flatMap(v=>[v.step.text,v.step.docString?.content??"",...v.step.dataTable?.rows.flatMap(x=>x.cells.map(b=>b.value))??[]].flatMap(x=>[...x.matchAll(/<([^<>]+)>/g)].map(b=>b[1]))))].filter(v=>!y.headers.includes(v)&&!v.startsWith("table:")&&v!=="docstring");if(S.length>0)throw new Be(`${g} the scenario uses <${S.join(">, <")}>, but {data:${p[1]}} has the columns ${y.headers.map(v=>`"${v}"`).join(", ")}.`);for(let v of y.rows)l+=1,c.push({params:v,label:` (example ${l})`,tags:u});continue}let f=d.tableHeader?.cells.map(g=>g.value)??[];for(let g of d.tableBody){l+=1;let y={};g.cells.forEach((h,S)=>{y[f[S]]=h.value}),c.push({params:y,label:` (example ${l})`,line:g.location.line,tags:u})}}}return c.map(({params:l,label:d,line:u,tags:p})=>{let f={value:"action",setup:!1},g=[...Td(r,l,f),...Td(s,l,f)];for(let h of g){let S=vd(h.resolvedText);if(S){let v=h.source?`${h.source.file}:${h.source.line}`:t;throw new Be(`${v} ${S}${h.text!==h.resolvedText?` (with the Examples values of "${e.name}${d}")`:""}`)}}let y=tt(g.map(h=>h.resolvedText));return{featurePath:t,featureName:n,name:e.name,displayName:`${e.name}${d}`,tags:p,steps:g.map((h,S)=>y[S]===void 0?h:{...h,session:y[S]}),params:l,...e.examples.length>0?{exampleRows:c.map(h=>h.params)}:{},line:e.location.line,...u!==void 0?{exampleLine:u}:{}}})}function Ed(e,t){let n=qm.readFileSync(e,"utf8"),r=e.endsWith(".saffron"),s=r?ba(n):{source:n,definitions:new Map,invocations:new Map},o=new Wm(new Jm(Gm.uuid()),new Vm),a=Hm.relative(t,e),i;try{i=o.parse(s.source)}catch(c){let l=(c instanceof Error?c.message:String(c)).split(`
|
|
8
|
+
`).filter(u=>/^\(\d+:\d+\)/.test(u)).map(u=>`${a}${u.replace(/^\((\d+):(\d+)\)/,":$1:$2")}`),d=!r&&/^\s*StepSet\b/m.test(n);throw new Be(d?`${a} uses StepSet, which only .saffron files understand. Rename it to ${a.replace(/\.feature$/,".saffron")}: nothing else needs to change (a .saffron file accepts everything a .feature file does).`:`${a} is not valid Gherkin:
|
|
9
9
|
${l.join(`
|
|
10
10
|
`)||(c instanceof Error?c.message:String(c))}`)}return{doc:i,pre:s,relPath:a,isSaffron:r,lineCount:n.split(`
|
|
11
11
|
`).length-(n.endsWith(`
|
|
12
|
-
`)?1:0)}}function Zl(e,t){let{doc:n,pre:r,lineCount:s}=Yl(e,t),o=[],a=(c,l)=>Math.min(l,...c.map(d=>d.location.line)),i=c=>{for(let l of c)if(l.background){let{name:d,location:f}=l.background;o.push({kind:"background",name:d,line:f.line,start:f.line,rows:[]})}else if(l.scenario){let{name:d,location:f,tags:p,examples:u}=l.scenario,h=r.definitions.has(f.line)?"stepSet":"scenario",b=u.flatMap(g=>g.tableBody.map(S=>S.location.line));o.push({kind:h,name:d,line:f.line,start:a(p,f.line),rows:b})}else if("rule"in l&&l.rule){let{name:d,location:f,tags:p}=l.rule;o.push({kind:"rule",name:d,line:f.line,start:a(p,f.line),rows:[]}),i(l.rule.children)}};return n.feature&&i(n.feature.children),{blocks:o,lineCount:s}}function ss(e){let t=e.split(/\r?\n/),n=t.findIndex(c=>c.trim()!==""&&!c.trim().startsWith("#")),r=(n<0?t:t.slice(0,n)).map(c=>/^\s*#\s*language\s*:\s*([\w-]+)/.exec(c)?.[1]).find(Boolean),s=r&&Wl[r]||Wl.en,o=[...s.scenario,...s.scenarioOutline].map(c=>`${c.trim()}:`),a=[],i;return t.forEach((c,l)=>{let d=c.trim(),f=['"""',"```"].find(u=>d.startsWith(u));if(f){i?i===f&&(i=void 0):i=f;return}if(i)return;let p=o.find(u=>d.startsWith(u));p&&a.push({line:l+1,name:d.slice(p.length).trim()})}),a}function ft(e,t,n){let{doc:r,pre:s,relPath:o,isSaffron:a}=Yl(e,t);if(!r.feature)return[];let i=r.feature.name,c=[],l=(d,f,p)=>{let u=f;for(let h of d)if(h.background)u=[...f,...Kl(h.background.steps,o,!0,s.invocations,n)];else if(h.scenario){if(s.definitions.has(h.scenario.location.line))continue;c.push(...sm(h.scenario,o,i,u,Kl(h.scenario.steps,o,!1,s.invocations,n),a,p))}else"rule"in h&&h.rule&&l(h.rule.children,u,[...p,...h.rule.tags.map(b=>b.name)])};return l(r.feature.children,[],r.feature.tags.map(d=>d.name)),c}import zd from"node:fs";import bo from"node:path";import Md from"node:fs";import Dd from"node:path";import{createHash as dm,randomBytes as um,scryptSync as fd}from"node:crypto";var uo="__saffron_date_clock",Sr=/\{date(?:([+-]\d+)(?:([^\d{}:]+?)([+-]\d+))?)?(?::([^}]+))?\}/g,Xl="YYYY|YY|MMMM|MMM|MM|M|DD|D|dddd|ddd",ea=new RegExp(Xl,"g"),om=new Set(["YYYY","MM","M","DD","D"]),ed=/^[a-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$/,lo={locale:"en-US"},ta=e=>{let t=!1;try{t=ed.test(e)&&Intl.DateTimeFormat.supportedLocalesOf(e).length>0}catch{}return t?void 0:`"${e}" is not a locale this Node.js knows: use a tag such as en-US or de-DE`};function td(e="en-US",t){let n=ta(e);if(n)throw new Error(`dateLocale in saffron.config.json: ${n}`);if(t!==void 0){let r;try{r=new Intl.DateTimeFormat("en-US",{timeZone:t}).resolvedOptions().timeZone}catch{throw new Error(`timezone in saffron.config.json: "${t}" is not a time zone: use an IANA name such as Europe/Berlin`)}if(r.toLowerCase()===t.toLowerCase()&&r!==t)throw new Error(`timezone in saffron.config.json: write "${t}" as "${r}", as browsers require`);if(!/^[A-Za-z]/.test(r))throw new Error(`timezone in saffron.config.json: "${t}" is an offset, which browsers do not take: use an IANA name such as Europe/Berlin, or Etc/GMT-2 for a fixed +02:00`)}lo={locale:e,timeZone:t}}function na(e){if(e===void 0)return{format:"YYYY-MM-DD"};let t=e.lastIndexOf(":"),n=e.slice(t+1);return t>=0&&ed.test(n)?{format:e.slice(0,t),locale:n}:{format:e}}function nd(e){if(!lo.timeZone)return[e.getFullYear(),e.getMonth(),e.getDate()];let t=new Intl.DateTimeFormat("en-US",{timeZone:lo.timeZone,year:"numeric",month:"numeric",day:"numeric"}).formatToParts(e),n=r=>Number(t.find(s=>s.type===r).value);return[n("year"),n("month")-1,n("day")]}var Ql=(e,t)=>{let[n,r,s]=nd(e);return new Date(Date.UTC(n,r,s+t))};function im(e,t,n,r){let s=n.match(ea)??[],o=t[0]==="M"?"month":"weekday",a={timeZone:"UTC",calendar:"gregory",[o]:t.length===4?"long":"short"};return s.some(i=>i[0]==="D")&&(a.day="numeric"),s.some(i=>i[0]==="Y")&&(a.year="numeric"),o==="weekday"&&s.some(i=>i[0]==="M")&&(a.month=s.includes("MMMM")?"long":s.includes("MMM")?"short":"numeric"),new Intl.DateTimeFormat(r,a).formatToParts(e).find(i=>i.type===o)?.value??t}function rd(e,t,n,r){switch(t){case"YYYY":return String(e.getUTCFullYear());case"YY":return String(e.getUTCFullYear()%100).padStart(2,"0");case"MM":return String(e.getUTCMonth()+1).padStart(2,"0");case"M":return String(e.getUTCMonth()+1);case"DD":return String(e.getUTCDate()).padStart(2,"0");case"D":return String(e.getUTCDate());default:return im(e,t,n,r)}}var sd=(e,t,n)=>t.replace(ea,r=>rd(e,r,t,n));function am(e,t,n,r,s){let o=n.split(new RegExp(`(${Xl})`)),a=e.getUTCFullYear()!==t.getUTCFullYear(),i=a||e.getUTCMonth()!==t.getUTCMonth(),c=i||e.getUTCDate()!==t.getUTCDate(),l=h=>h[0]==="Y"?a:h[0]==="M"?i:c,d=o.flatMap((h,b)=>b%2&&l(h)?[b]:[]);if(d.length===0)return sd(e,n,s);let f=(h,b,g)=>o.slice(b,g).map((S,y)=>(b+y)%2?rd(h,S,n,s):S).join(""),p=d[d.length-1],u=/^[^\s,/-]*/.exec(o[p+1]??"")[0];return`${f(e,0,p+1)}${u}${r}${f(t,d[0],o.length)}`}function Ve(e,t=new Date){return e.replace(Sr,(n,r,s,o,a)=>{let{format:i,locale:c=lo.locale}=na(a);if(ta(c))return n;let l=Ql(t,Number(r??0));return o===void 0?sd(l,i,c):am(l,Ql(t,Number(o)),i,s,c)})}function fo(e){let t=new RegExp(`^${Sr.source}$`).exec(e);if(!t)return`${e} is not a date Saffron can resolve: write {date+N}, {date+N:FORMAT}, {date+N:FORMAT:LOCALE}, or a range such as {date+7 - +9:MMM D, YYYY}`;if([t[1],t[3]].some(o=>o!==void 0&&Math.abs(Number(o))>36600))return`${e} is more than a hundred years away: Saffron counts days within 36600 of today`;let{locale:n}=na(t[4]),r=n===void 0?void 0:ta(n);if(r)return`${e}: ${r}`;let s=t[4]?.includes(":")?t[4].slice(t[4].lastIndexOf(":")+1):void 0;if(n===void 0&&s!==void 0&&/^[A-Za-z]{2,3}(?:[-_][A-Za-z0-9]{1,8})*$/.test(s)&&!/^[YMDd]+$/.test(s))return`${e}: "${s}" is not a locale this Node.js knows: use a tag such as en-US or de-DE`}var ra=/\{date(?=[}:]|\s*[+-]\s*\d)[^{}]*\}/g,od=e=>e.match(ra)??[];function Kn(e){return[...e.matchAll(Sr)].some(({3:t,4:n})=>{let{format:r,locale:s}=na(n);return t!==void 0||s!==void 0||(r.match(ea)??[]).some(o=>!om.has(o))})}var cm=/\b(\d{4})-(\d{2})-(\d{2})\b/g,lm=400;function id(e,t=new Date,n=[]){let[r,s,o]=nd(t),a=Date.UTC(r,s,o);return e.replace(cm,(i,c,l,d)=>{if(n.some(p=>p.includes(i)))return i;let f=(Date.UTC(Number(c),Number(l)-1,Number(d))-a)/864e5;return Math.abs(f)>lm?i:f===0?"{date}":`{date${f>0?"+":""}${f}}`})}function vt(e){let t=e.replace(/(\d)[\s\u00a0\u202f'\u2019](?=\d{3}(?!\d))/g,"$1"),n=[...t.matchAll(/[-\u2212\u2013]?\d(?:[\d.,]*\d)?/g)];if(n.length!==1)return;let[r]=n,s=t.slice(0,r.index),o=t.slice(r.index+r[0].length),a=/[.,]$/.test(s)&&!/\d[.,]$/.test(s)&&/^\d+$/.test(r[0]),i=a?s.slice(0,-1):s,c=/^[-\u2212\u2013]/.test(r[0])||a&&/[-\u2212\u2013]$/.test(i)||/(?:^|[\s(:])[-\u2212\u2013][^\d\s.,()\-\u2212\u2013]{1,4}\s?$/.test(i)||/^[-\u2212\u2013](?!\d)/.test(o)||/\(\s?[^\d\s.,()]{0,4}\s?$/.test(i)&&/^\s?[^\d\s.,()]{0,4}\s?\)/.test(o)&&(/[.,]/.test(r[0])||/[^\d\s.,()]\s?$/.test(i)||/^\s?[^\d\s.,()]/.test(o)),l=a?`0${s.slice(-1)}${r[0]}`:r[0].replace(/^[-\u2212\u2013]/,""),d=Math.max(l.lastIndexOf("."),l.lastIndexOf(",")),f=d<0?l:l.slice(0,d),p=d<0?"":l.slice(d+1),u=d>=0&&(p.length!==3||/^0?$/.test(f)||f.includes(l[d]==="."?",":".")),h=u?f:l,b=h.split(/[.,]/),g=new Set(h.match(/[.,]/g)??[]);if(g.size>1||u&&g.has(l[d])||b[0]===""||b.slice(1).some(y=>y.length!==3))return;let S=+`${c?"-":""}${b.join("")}${u?`.${p}`:""}`;return Number.isFinite(S)?S:void 0}var En=(e,t)=>Math.abs(e-t)<.005,cd=e=>e.toFixed(2);function po(e,t){let n=e.trim(),r=ad(n,/^ ([+-]) /);if(/\s[-+*×]$|^[+*×]\s/.test(n)||r.some(o=>o.text.trim()===""))return{problem:`"${e}" is not an amount expression: write terms such as "before" + "breakfast"`};let s=0;for(let o of r){let a=1;for(let{text:i}of ad(o.text,/^ ([*×]) /)){let c=i.trim(),l=/^"([^"]+)"$/.exec(c)?.[1];if(l===void 0&&c.includes('"'))return{problem:`"${e}" is not an amount expression: write each captured name in double quotes on its own, operators between spaces, as in "before" + "breakfast"`};let d=l===void 0?c:t(l);if(d===void 0)return{problem:`no captured value named "${l}"`};let f=vt(d);if(f===void 0)return{problem:l===void 0?`"${c}" is not an amount`:`"${l}" (${d}) does not hold exactly one amount`};a*=f}s+=o.op==="-"?-a:a}return{amount:s}}function Yn(e,t,n=r=>r){return e.split(/("[^"]*")/).map((r,s)=>s%2===1?`"${n(r.slice(1,-1))}"`:t(r)??r).join("")}function sa(e){return e?e.replace(/"[^"]*"/g," ").split(/\s[-+*\u00d7]\s/).flatMap(t=>/[<{]/.test(t)?[]:[vt(t.trim())]).filter(t=>t!==void 0):[]}function ld(e,t){if(t.length===0)return e;let n=e.split(/(\s[-+*\u00d7]\s)/),r=(o,a)=>{if(a%2===1||/[<{]/.test(o))return;let i=vt(o.trim()),c=i===void 0?[]:t.filter(([,l])=>En(l,i));return c.length===1?c[0][0]:void 0},s=n.map(r);return n.map((o,a)=>s[a]!==void 0&&s.filter(i=>i===s[a]).length===1?o.replace(o.trim(),`<${s[a]}>`):o).join("")}function ad(e,t){let n=[],r="+",s=0,o=!1;for(let a=0;a<e.length;a++){if(e[a]==='"'&&(o=!o),o)continue;let i=t.exec(e.slice(a));i&&(n.push({op:r,text:e.slice(s,a)}),r=i[1],s=a+i[0].length,a=s-1)}return n.push({op:r,text:e.slice(s)}),n}function $r(e,t,n){let r=o=>pt(t,`<${o}>`)||/^\{(?:env|data):[^{}]+\}$/.test(n[o]??"")&&pt(t,n[o]),s=o=>Object.keys(n).some(a=>a!==o&&n[a]===n[o]&&r(a));return[...new Set([...fe(e).matchAll(/<([^<>]+)>/g)].map(o=>o[1]))].filter(o=>!r(o)&&!s(o))}function pd(e,t){if(t.trim()==="")return!1;let n=Tr(t).exact;return e.flatMap(s=>Et(s)).filter(s=>s!==void 0).some(s=>n.some(o=>t.length>=3?aa(o).test(s):xe(o).test(s)))||gd(e,t)}function aa(e){let t=/^\p{Lu}/u.test(e)?"(?<!\\p{Lu})":/^\p{L}/u.test(e)?"(?<!\\p{L})":/^\p{N}/u.test(e)?"(?<!\\p{N})":"",n=/\p{L}$/u.test(e)?"(?!\\p{Ll})":/\p{N}$/u.test(e)?"(?!\\p{N})":"";return new RegExp(`${t}${be(e)}${n}`,"u")}function gd(e,t){let n=vt(t);return e.some(r=>[r.target?.role,r.toTarget?.role].includes(t.trim())||n!==void 0&&r.action==="expectAmount"&&sa(r.value??"").some(s=>En(s,n)))}function On(e,t){return t.length>=3?cn(e,t)||gd(e,t):pd(e,t)}function os(e,t,n,r=[],s){for(let[,o]of e.matchAll(/\{data:([^{}]*<[^<>{}]+>[^{}]*)\}/g)){let a=p=>{try{return qe(o.replace(/<([^<>]+)>/g,(u,h)=>p[h]??u))}catch{return}},i=a(t),c=a(n);if(i===void 0||c===void 0||i===c)continue;if(s!==void 0){if(!xe(i).test(s)&&ca(r,i))return!0;continue}if(i.trim()===""?c.trim()!=="":On(r,i))return!0;let l=`{data:${o}}`,d=e.replace(/\{[^{}]*\}|<[^<>]+>/g," ");if((xe(i).test(d)||i.length>=4&&d.includes(i))&&JSON.stringify(r).split(l).length>e.split(l).length)return!0}return!1}var kr=e=>e.length>0&&e.filter(t=>Se.has(t.action)).every(t=>![t.value,t.action==="expectAttribute"?void 0:t.pattern].some(n=>n!==void 0&&n.trim()!=="")),ca=(e,t)=>{if(pd(e,t))return!0;if(t.trim()==="")return!1;let n=e.flatMap(r=>Et(r)).filter(r=>r!==void 0);return Tr(t).loose.some(r=>r!==""&&n.some(s=>xe(r,"iu").test(s)))};function go(e,t,n){return fe(e.replace(/\{data:[^{}]*\}/g," ")).includes(`<${t}>`)?!1:[...e.matchAll(/\{data:([^{}]*<[^<>{}]+>[^{}]*)\}/g)].filter(r=>r[1].includes(`<${t}>`)).every(r=>{try{return qe(r[1].replace(/<([^<>]+)>/g,(s,o)=>n[o]??s)).trim()===""}catch{return!1}})}function pt(e,t){let n=r=>typeof r=="string"?r.includes(t):Array.isArray(r)?r.some(n):r&&typeof r=="object"?Object.entries(r).some(([s,o])=>s!=="pageFingerprint"&&n(o)):!1;return e.some(n)}function _n(e){return[e.action==="expectDiffers"?void 0:e.action==="expectAmount"?e.value?.replace(/"[^"]*"/g,'""'):e.value,e.url,e.urlPattern,e.pattern,e.promptText,e.each,...[e.target,e.toTarget].flatMap(t=>[t?.name,t?.nameRegex,t?.label,t?.text,t?.placeholder,t?.testId,t?.frame,...t?.fallbackSelectors??[]])]}function Et(e){return[..._n(e),e.status,e.method,e.attribute]}function cn(e,t){if(t.trim()==="")return!1;let{exact:n,loose:r}=Tr(t),s=r.map(a=>xe(a,"iu")),o=a=>{let i=a.replace(Ce," ").replace(Ae," "),c=i.replace(/<[^<>]+>/g," ").normalize("NFC");return/[<>]/.test(t)?[c,i.normalize("NFC")]:[c]};return e.some(a=>Et(a).some(i=>i!==void 0&&o(i).some(c=>{let l=t.length<3?c.replace(la," "):c;return n.some(d=>l.includes(d))||s.some(d=>d.test(l))})))}function Zn(e,t,n,r,s,o){let a=s?Date.parse(s):NaN,i=Object.keys(n),c=oa(t,o,i),l=(d,f)=>ia(d,o,f);for(let[d,f]of i.entries())for(let p of i.slice(d+1))if(!(r[f]===void 0||r[p]===void 0||l(n[f],a)==="")&&!(l(n[f],a)!==l(n[p],a)||l(r[f])===l(r[p]))&&(pt(e,`<${f}>`)||pt(e,`<${p}>`)))return!0;for(let d of i.filter(f=>/\{env:/.test(n[f])&&r[f]!==void 0))if([...n[d].matchAll(Ce)].map(([p])=>p).some(p=>!t.includes(p)&&pt(e,p))){for(let p of i)if(!(p===d||/\{env:/.test(n[p])||r[p]===void 0||!t.includes(`<${p}>`)||pt(e,`<${p}>`))&&l(r[p])!==l(r[d]))return!0}return Object.entries(n).some(([d,f])=>{let p=r[d];if(p===void 0)return!1;let u=f.includes("{date")&&!Number.isNaN(a);if(p===f&&(!u||Ve(f,new Date(a))===Ve(p)))return!1;let h=t.includes(`<${d}>`),b=l(f,a),g=l(p);if(b.trim()==="")return g.trim()!==""&&!pt(e,`<${d}>`)&&e.some(x=>_n(x).some($=>$!==void 0));let S=vt(b),y=!h&&c.some(x=>(x.match(/[-\u2212\u2013]?\d[\d.,]*/g)??[]).some($=>En(vt($)??NaN,S??NaN))),w=x=>x.action==="expectAmount"?sa(x.value):x.value!==void 0&&/^expect/.test(x.action)?[vt(x.value)].filter($=>$!==void 0):[];if(S!==void 0&&!y&&e.some(x=>w(x).some($=>En($,S)))){let x=vt(g);if(x===void 0||!En(x,S))return!0}if(b!==g&&e.some(x=>_n(x).some($=>$!==void 0&&/^\{(?:env|data):[^{}]+\}$/.test($)&&t.includes($)&&l($,a)===b))||b!==g&&e.some(x=>[x.target?.role,x.toTarget?.role].includes(b)))return!0;let v=new Set(p===f?[]:oa(f,o,i));if(u){let x=f.replace(/\{date([+-]\d+)?:[^}]*\}/g,"{date$1}");x!==f&&h&&p!==f&&v.add(x);for(let $ of[0,1])for(let E of new Set([f,x])){let R=Ve(E,new Date(a-$*864e5));v.add(R)}}return[...v].some(x=>x.trim()!==""&&(h||!c.some($=>xe(x).test($)))&&wd(e,x,h||u,$=>oa($,o,i)))})}function hd(e,t){let n=Object.keys(t).filter(r=>t[r].trim()==="");return n.length>0&&e.some(r=>_n(r).some(s=>s!==void 0))&&n.some(r=>!pt(e,`<${r}>`))}function md(e,t,n={}){let r=/\{env:|\{date/;if(e.some(a=>Et(a).some(i=>i!==void 0&&(r.test(i)||/\{data:/.test(i))))||Object.values(t).some(a=>a.trim()==="")&&e.some(a=>a.value===""))return!0;let s=Object.values(t).filter(a=>a.trim()!=="");if(new Set(s).size<s.length)return!0;let o=a=>[a.replace(Qn(Object.keys(t))," ").normalize("NFC")];return Object.values(t).some(a=>{if(r.test(a)||[...a.matchAll(Ae)].some(([,c])=>!(c in n)))return!0;let i=a.replace(Ae,(c,l)=>n[l]);return[a,i].some(c=>c.trim()!==""&&wd(e,c,!0,o))})}function wd(e,t,n,r){let{exact:s,loose:o}=Tr(t),a=n&&t.length>=3,i=s.map(f=>ho(t,f,"u",n)),c=o.map(f=>xe(f,"iu")),l=f=>{let p=t.length<3?f.replace(la," "):f;return/^\{(?:env|data|unique|date)[^{}]*\}$/.test(t)&&p.includes(t)||i.some(u=>u.test(p))||(a?o.some(u=>p.toLowerCase().includes(u)):c.some(u=>u.test(p)))},d=f=>n?Et(f):_n(f);return e.some(f=>d(f).some(p=>p!==void 0&&r(p).some(l)))}function ho(e,t=e,n="gu",r=!0){let s=t.normalize("NFC");return r&&e.length>=3?new RegExp(be(s),n):xe(s,n)}function Rr(e,t,n,r=t){let s=e.normalize("NFC");return s.includes(r.normalize("NFC"))?ho(t,r,"u",n).test(t.length<3?s.replace(la," "):s):!1}function ia(e,t,n){return Ve(e,n===void 0||Number.isNaN(n)?new Date:new Date(n)).replace(Ae,(r,s)=>t?.[s]??yd(s)??r).replace(Ce,(r,s)=>process.env[s]??r)}function is(e,t,n,r,s){let o=r?Date.parse(r):NaN;return e.find(a=>{let i=t[a],c=n[a];return i===void 0||c===void 0?!0:i!==c&&ia(i,s,o)!==ia(c,s)})}function Qn(e){return new RegExp(`<(?:table:[^<>]+|docstring${[...e].map(t=>`|${be(t)}`).join("")})>`,"g")}var dd=String.raw`[\p{L}\p{N}\p{M}]`,ud=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u,la=/:nth-[a-z-]+\([^)]*\)|\bnth=-?\d+|\bh[1-6]\b/gi;function xe(e,t="u"){let n=[...e],r=n.length>=2&&ud.test(n[0])?"":`(?<!${dd})`,s=n.length>=2&&ud.test(n[n.length-1])?"":`(?!${dd})`;return new RegExp(`${r}${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}${s}`,t)}function Tr(e){let t=e.normalize("NFC"),n=[...new Set([t,...Object.values(ue).map(a=>a(t))])],r=t.toLowerCase(),s=new Set([r]);try{s.add(encodeURIComponent(t).toLowerCase()),s.add(encodeURIComponent(t).replaceAll("%20","+").toLowerCase())}catch{}let o=r.split(/[^\p{L}\p{N}\p{M}]+/u).filter(Boolean);if(o.length>1)for(let a of["-","_",""])s.add(o.join(a));return{exact:n,loose:[...s]}}function da(e){return e.length>=5||e.length>=3&&/\p{N}/u.test(e)}function oa(e,t,n){let r=(e??"").replace(n?Qn(n):/<[^<>]+>/g," ").normalize("NFC"),s=r.replace(Ae,(o,a)=>t?.[a]??yd(a)??o).replace(Ce,(o,a)=>process.env[a]??o);return s===r?[r]:[r,s]}function yd(e){try{return qe(e)}catch{return}}function bd(e,t){return e===t?"bare":e===`^${t}$`?"anchored":void 0}function vd(e){let t=xd(e);if(t===void 0)return;let n=um(16).toString("hex");return`s1:${n}:${fd(t,n,32).toString("hex")}`}function mo(e,t){let n=xd(e);if(n===void 0)return!1;let r=/^s1:([0-9a-f]{32}):([0-9a-f]{64})$/.exec(t);return r?fd(n,r[1],32).toString("hex")===r[2]:dm("sha256").update(n).digest("hex")===t}function xd(e){if(!/\{(?:env|data):/.test(e))return;let t=!1,n=e.replace(Ae,(s,o)=>{try{return qe(o)}catch{return t=!0,s}});if(!new RegExp(Ce.source).test(n))return;let r=n.replace(Ce,(s,o)=>{let a=process.env[o];return a===void 0&&(t=!0),a??s});return t?void 0:r}var Se=new Set(["expectVisible","expectNotVisible","expectText","expectUrl","expectValue","expectDiffers","expectMatches","expectAttribute","expectResponse","expectEach","expectDownload","expectAmount"]);function as(e){if(e.steps.some(n=>n.actions.some(r=>r.action==="waitForDownload"&&(r.downloads??1)>1)))return 4;if(e.rowsUseNewDates||Kn(JSON.stringify([e.steps,e.examples??{},e.data??{}]))||Object.values(e.data??{}).some(n=>n.includes("{date"))||e.examples&&e.steps.some(n=>hd(n.actions,e.examples))||e.rowBound?.some(n=>n.reason==="container"||n.reason==="session"||n.reason==="unwritten"||n.valueSha?.startsWith("s1:")))return 3;if((e.rowBound?.length??0)>0||Ye(e.steps.map(n=>n.gherkin)).some(n=>n!==void 0)||e.examples&&e.steps.some(n=>md(n.actions,e.examples,e.data)))return 2;let t=n=>n.clickCount!==void 0&&n.clickCount!==1||n.button!==void 0&&n.button!=="left"||(n.modifiers?.length??0)>0||n.clearSelection===!0||n.action==="selectOption"&&(n.value??"").includes(`
|
|
13
|
-
`)||[n.status,n.method,n.attribute].some(r=>r!==void 0&&/<[^<>]+>|\{(?:data|env|date|unique)[^{}]*\}/.test(r));return e.steps.some(n=>n.actions.some(t))?2:1}import{createHash as Td}from"node:crypto";import Ut from"node:fs";import Bt from"node:path";import Sd from"node:path";var wo=4,fm=new Set(["goto","click","fill","press","selectOption","check","uncheck","hover","waitFor","captureText","handleDialog","uploadFile","dragTo","waitForResponse","switchTab","closeTab","newTab","waitForDownload",...Se]),pm=["role","name","nameRegex","label","text","testId","placeholder","frame"],gm=["value","url","saveAs","compareTo","each","pattern","attribute","promptText","urlPattern","method","status","pageFingerprint"],ua=/[\u0000-\u001f\u007f-\u009f]/,$e=class extends Error{constructor(n,r){super(`${n}: ${r}`);this.file=n;this.problem=r}file;problem},gt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function K(e,t,n){if(!e)throw new $e(t,n)}function $d(e,t,n){K(gt(e),t,`${n} must be an object`);for(let r of pm)K(e[r]===void 0||typeof e[r]=="string",t,`${n}.${r} must be a string`);e.fallbackSelectors!==void 0&&K(Array.isArray(e.fallbackSelectors)&&e.fallbackSelectors.every(r=>typeof r=="string"),t,`${n}.fallbackSelectors must be a list of selectors`)}var hm=e=>["role","label","text","testId","placeholder"].some(t=>typeof e[t]=="string"&&e[t]!=="")||Array.isArray(e.fallbackSelectors)&&e.fallbackSelectors.some(t=>typeof t=="string"&&t.trim().length>0),mm={goto:["url"],click:["target"],fill:["target","value"],press:["value"],selectOption:["target","valueOrClear"],check:["target"],uncheck:["target"],hover:["target"],waitFor:["targetOrValue"],captureText:["target","saveAs"],handleDialog:[],uploadFile:["value"],dragTo:["target","toTarget"],waitForResponse:["urlPattern"],switchTab:["value"],closeTab:[],newTab:[],waitForDownload:[],expectVisible:["target"],expectNotVisible:["target"],expectText:["target","value"],expectUrl:["urlOrValue"],expectValue:["target","value"],expectDiffers:["compareTo","targetOrValue"],expectMatches:["target","pattern"],expectAttribute:["target","attribute","pattern"],expectResponse:["urlPattern"],expectEach:["target","each"],expectDownload:["valueOrPattern"],expectAmount:["target","value"]};function wm(e,t,n){let r=o=>typeof e[o]=="string",s=o=>gt(e[o])&&hm(e[o]);for(let o of mm[e.action])switch(o){case"target":case"toTarget":K(s(o),t,`${n} (${e.action}) needs a ${o} with a role, name, label, text, test id, placeholder or selector`);break;case"urlOrValue":K(r("url")||r("value"),t,`${n} (${e.action}) needs a url`);break;case"targetOrValue":K(s("target")||r("value"),t,`${n} (${e.action}) needs a target or a value`);break;case"valueOrClear":K(r("value")||e.clearSelection===!0,t,`${n} (${e.action}) needs value`);break;case"valueOrPattern":K(r("value")&&e.value!==""||r("pattern"),t,`${n} (${e.action}) needs a non-empty value or a pattern`);break;default:K(r(o),t,`${n} (${e.action}) needs ${o}`)}for(let o of["target","toTarget"])e[o]!==void 0&&K(s(o),t,`${n}.${o} has no usable locator`);if(e.downloads!==void 0&&K(e.action==="waitForDownload"&&Number.isInteger(e.downloads)&&e.downloads>=2&&e.downloads<=999,t,`${n}.downloads must be a whole number from 2, on a waitForDownload`),e.action==="expectUrl"){let o=e.url??e.value;K(typeof o=="string"&&o.length>0,t,`${n} (expectUrl) needs a non-empty url or value`)}for(let o of["url","saveAs","compareTo","each","pattern","attribute","urlPattern"])e[o]!==void 0&&K(e[o].length>0,t,`${n}.${o} must not be empty`);["press","uploadFile","switchTab","expectText"].includes(e.action)&&K(typeof e.value=="string"&&e.value.length>0,t,`${n} (${e.action}) needs a non-empty value`)}function ym(e,t,n){K(gt(e),t,`${n} must be an object`),K(typeof e.action=="string",t,`${n}.action is missing`),K(fm.has(e.action),t,`${n}.action "${e.action}" is not an action this runner knows. Recorded by a newer saffron-ai? Update, or re-record with --rerecord`);for(let r of gm)K(e[r]===void 0||typeof e[r]=="string",t,`${n}.${r} must be a string`);K(e.opensTab===void 0||typeof e.opensTab=="boolean",t,`${n}.opensTab must be true or false`),K(e.clearSelection===void 0||typeof e.clearSelection=="boolean",t,`${n}.clearSelection must be true or false`),K(e.clickCount===void 0||Number.isInteger(e.clickCount)&&e.clickCount>=1,t,`${n}.clickCount must be a whole number from 1`),K(e.button===void 0||["left","right","middle"].includes(e.button),t,`${n}.button must be "left", "right" or "middle"`),K(e.modifiers===void 0||Array.isArray(e.modifiers)&&e.modifiers.every(r=>["Alt","Control","ControlOrMeta","Meta","Shift"].includes(r)),t,`${n}.modifiers must be a list of Alt, Control, ControlOrMeta, Meta or Shift`),e.target!==void 0&&$d(e.target,t,`${n}.target`),e.toTarget!==void 0&&$d(e.toTarget,t,`${n}.toTarget`),wm(e,t,n)}function bm(e,t,n){K(gt(e),t,`${n} must be an object`),K(typeof e.gherkin=="string"&&e.gherkin.length>0,t,`${n}.gherkin (the step text) is missing`),K(typeof e.keyword=="string",t,`${n}.keyword is missing`),K(e.kind==="action"||e.kind==="assertion",t,`${n}.kind must be "action" or "assertion"`),K(Array.isArray(e.actions),t,`${n}.actions must be a list (empty for a recorded no-op)`),e.actions.forEach((r,s)=>ym(r,t,`${n}.actions[${s}]`)),e.table!==void 0&&K(Array.isArray(e.table)&&e.table.every(r=>Array.isArray(r)&&r.every(s=>typeof s=="string")),t,`${n}.table must be rows of strings`),K(e.docString===void 0||typeof e.docString=="string",t,`${n}.docString must be a string`),K(e.fromStepSet===void 0||typeof e.fromStepSet=="string",t,`${n}.fromStepSet must be a string`)}function fa(e,t){if(K(gt(e),t,"is not a JSON object"),K(e.version!==void 0,t,"has no version: not a Saffron recording"),K(Number.isInteger(e.version)&&e.version>=1&&e.version<=wo,t,typeof e.version=="number"&&e.version>wo?`is schema version ${e.version}; this saffron-ai reads versions 1 to ${wo}. Update saffron-ai to the release that wrote it`:`has schema version ${JSON.stringify(e.version)}; this saffron-ai reads versions 1 to ${wo}`),K(typeof e.feature=="string"&&e.feature.length>0,t,"feature (the feature file path) is missing"),K(!Sd.isAbsolute(e.feature)&&!Sd.win32.isAbsolute(e.feature)&&!e.feature.split(/[\\/]/).includes(".."),t,`names a feature file outside the project: ${JSON.stringify(e.feature)}`),K(typeof e.scenario=="string"&&e.scenario.length>0,t,"scenario (the scenario name) is missing"),K(e.recordedAt===void 0||typeof e.recordedAt=="string",t,"recordedAt must be a string"),K(e.recordedBy===void 0||e.recordedBy==="agent"||e.recordedBy==="manual",t,'recordedBy must be "agent" or "manual"'),K(Array.isArray(e.steps),t,"steps must be a list"),e.steps.forEach((n,r)=>bm(n,t,`steps[${r}]`)),e.data!==void 0&&K(gt(e.data)&&Object.values(e.data).every(n=>typeof n=="string"),t,"data must map references to strings"),e.examples!==void 0&&K(gt(e.examples)&&Object.values(e.examples).every(n=>typeof n=="string"),t,"examples must map columns to strings"),K(e.rowsUseNewDates===void 0||e.rowsUseNewDates===!0,t,"rowsUseNewDates must be true when present"),e.rowBound!==void 0){let n=e.steps.length;K(Array.isArray(e.rowBound)&&e.rowBound.every(r=>gt(r)&&typeof r.column=="string"&&Number.isInteger(r.step)&&r.step>=0&&r.step<n&&(r.reason==="list"||r.reason==="glued"||r.reason==="data"||r.reason==="value"||r.reason==="reads"||r.reason==="container"||r.reason==="session"||r.reason==="unwritten")&&(r.valueSha===void 0||typeof r.valueSha=="string"&&/^(?:[0-9a-f]{64}|s1:[0-9a-f]{32}:[0-9a-f]{64})$/.test(r.valueSha))),t,'rowBound must be a list of { column, step, reason: "list" | "glued" | "data" | "value" | "reads" | "container" | "session" | "unwritten", valueSha? } naming steps of this recording'),K(gt(e.examples),t,"rowBound needs examples, the row it was recorded on")}return e}function kd(e,t){K(gt(e),t,"is not a JSON object"),K(gt(e.meta),t,"meta is missing: not a Saffron proposal");let n=e.meta;K(n.mode==="record"||n.mode==="heal",t,'meta.mode must be "record" or "heal"'),K(typeof n.narrative=="string",t,"meta.narrative must be a string"),K(Array.isArray(n.adaptations)&&n.adaptations.every(r=>typeof r=="string"),t,"meta.adaptations must be a list of strings"),K(n.verified===void 0||typeof n.verified=="boolean",t,"meta.verified must be true or false"),K(gt(n.usage),t,"meta.usage is missing"),n.featureEdits!==void 0&&(K(Array.isArray(n.featureEdits)&&n.featureEdits.every(r=>gt(r)&&typeof r.index=="number"&&typeof r.text=="string"),t,"meta.featureEdits must be a list of { index, text }"),n.featureEdits.forEach((r,s)=>K(r.text.trim().length>0,t,`meta.featureEdits[${s}].text is empty: a feature edit must give the step's new text`)),n.featureEdits.forEach((r,s)=>K(!ua.test(r.text),t,`meta.featureEdits[${s}].text holds a line break or another control character`))),n.bound!==void 0&&K(gt(n.bound)&&["scenario","committed","recording"].every(r=>typeof n.bound[r]=="string"),t,"meta.bound must hold the scenario, committed and recording digests"),fa(e.cache,`${t} (cache)`)}var Ad=".saffron",Ed=e=>Td("sha1").update(e).digest("hex").slice(0,8),ga=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");function _d(e){return ga(e)||`unnamed-${Ed(e)}`}var Od=e=>ga(e)||"unnamed";function Cd(e){let t=ga(e);return t&&/[^\x00-\x7f]/.test(e)?`${t}-${Ed(e)}`:_d(e)}function Pd(e,t,n,r){let s;try{s=Ut.readFileSync(e,"utf8")}catch{return!0}try{return t(JSON.parse(s))}catch{return r.some(o=>new RegExp(`"${n}"\\s*:\\s*${be(JSON.stringify(o))}`).test(s))}}function vm(e,t,n){let r=Bt.join(e,`${Cd(t)}.json`),s=Bt.join(e,`${Od(t)}.json`);return s===r||Ut.existsSync(r)||!Ut.existsSync(s)?r:Pd(s,o=>n(o)===t,"scenario",[t])?s:r}var Rd=new Map;function Id(e){let t=Bt.join(e,"saffron.config.json"),n=Ut.statSync(t,{throwIfNoEntry:!1}),r=n?`${n.mtimeMs}:${n.ctimeMs}:${n.size}:${n.ino}`:"none",s=Rd.get(e);if(s?.stamp===r)return s.top;let o="features";try{let c=JSON.parse(Ut.readFileSync(t,"utf8"));typeof c?.features=="string"&&c.features.trim()&&(o=c.features)}catch{}let a=Bt.relative(e,Bt.resolve(e,o)),i=a.startsWith("..")||Bt.isAbsolute(a)?void 0:a.split(/[\\/]/)[0];return Rd.set(e,{stamp:r,top:i}),i}function pa(e,t,n=_d){let r=e.split(/[\\/]/).filter(Boolean),s=r.pop()??"unnamed",o=t===void 0||r[0]===t?r.slice(1):r,a=n([...o,Bt.basename(s,".feature")].join("-"));if(o.length===0)return a;let i=Td("sha1").update(e.replace(/\\/g,"/")).digest("hex").slice(0,6);return`${a}-${i}`}function Nd(e,t,n,r,s){let o=d=>vm(Bt.join(e,Ad,t,d),r,f=>s(f)?.scenario),a=o(pa(n,Id(e))),i=o(pa(n,void 0,Od));if(i===a||Ut.existsSync(a)||!Ut.existsSync(i))return a;let c=d=>typeof d=="string"?d.replace(/\\/g,"/"):d;return Pd(i,d=>c(s(d)?.feature)===c(n),"feature",[n,c(n)])?i:a}function me(e,t,n){return Nd(e,"cache",t,n,r=>r)}function jd(e,t){let n=new Map;for(let r of t){let s=me(e,r.featurePath,r.name),o=n.get(s)??new Set;o.add(`${r.featurePath} \u203A ${r.name}${r.line?` (line ${r.line})`:""}`),n.set(s,o)}return[...n.entries()].filter(([,r])=>r.size>1).map(([r,s])=>`${[...s].join(" and ")} both map to ${Bt.relative(e,r)}. Rename one scenario or one file.`)}var Xn="owner.json";function ln(e,t,n){return Bt.join(e,Ad,"artifacts",pa(t,Id(e)),Cd(n))}function xt(e,t,n){return Nd(e,"proposals",t,n,r=>r?.cache)}function Jt(e,t){try{return st(e)}catch(n){if(!(n instanceof $e))throw n;t?.(e,n.problem);return}}function st(e){if(!Ut.existsSync(e))return;let t;try{t=JSON.parse(Ut.readFileSync(e,"utf8"))}catch(n){throw new $e(e,`is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}return fa(t,e)}function Ar(e,t){Ut.mkdirSync(Bt.dirname(e),{recursive:!0}),Ut.writeFileSync(e,`${JSON.stringify({...t,version:as(t)},null,2)}
|
|
14
|
-
|
|
15
|
-
${t}`;function
|
|
16
|
-
`).replace(/\{[^{}]*\}|<[^<>]+>/g," "),c=d=>{try{return new RegExp(d).test("")}catch{return!1}},l=e.actions.some(d
|
|
17
|
-
`);if(
|
|
18
|
-
`)+1));d.set(S,{...d.get(S),[
|
|
19
|
-
`}import{Server as
|
|
20
|
-
`);return
|
|
21
|
-
`)):e).digest("hex"),
|
|
22
|
-
`)}function
|
|
12
|
+
`)?1:0)}}function Od(e,t){let{doc:n,pre:r,lineCount:s}=Ed(e,t),o=[],a=(c,l)=>Math.min(l,...c.map(d=>d.location.line)),i=c=>{for(let l of c)if(l.background){let{name:d,location:u}=l.background;o.push({kind:"background",name:d,line:u.line,start:u.line,rows:[]})}else if(l.scenario){let{name:d,location:u,tags:p,examples:f}=l.scenario,g=r.definitions.has(u.line)?"stepSet":"scenario",y=f.flatMap(h=>h.tableBody.map(S=>S.location.line));o.push({kind:g,name:d,line:u.line,start:a(p,u.line),rows:y})}else if("rule"in l&&l.rule){let{name:d,location:u,tags:p}=l.rule;o.push({kind:"rule",name:d,line:u.line,start:a(p,u.line),rows:[]}),i(l.rule.children)}};return n.feature&&i(n.feature.children),{blocks:o,lineCount:s}}function gs(e){let t=e.split(/\r?\n/),n=t.findIndex(c=>c.trim()!==""&&!c.trim().startsWith("#")),r=(n<0?t:t.slice(0,n)).map(c=>/^\s*#\s*language\s*:\s*([\w-]+)/.exec(c)?.[1]).find(Boolean),s=r&&Rd[r]||Rd.en,o=[...s.scenario,...s.scenarioOutline].map(c=>`${c.trim()}:`),a=[],i;return t.forEach((c,l)=>{let d=c.trim(),u=['"""',"```"].find(f=>d.startsWith(f));if(u){i?i===u&&(i=void 0):i=u;return}if(i)return;let p=o.find(f=>d.startsWith(f));p&&a.push({line:l+1,name:d.slice(p.length).trim()})}),a}function nt(e,t,n){let{doc:r,pre:s,relPath:o,isSaffron:a}=Ed(e,t);if(!r.feature)return[];let i=r.feature.name,c=[],l=(d,u,p)=>{let f=u;for(let g of d)if(g.background)f=[...u,...Ad(g.background.steps,o,!0,s.invocations,n)];else if(g.scenario){if(s.definitions.has(g.scenario.location.line))continue;c.push(...Km(g.scenario,o,i,f,Ad(g.scenario.steps,o,!1,s.invocations,n),a,p))}else"rule"in g&&g.rule&&l(g.rule.children,f,[...p,...g.rule.tags.map(y=>y.name)])};return l(r.feature.children,[],r.feature.tags.map(d=>d.name)),c}import Su from"node:fs";import No from"node:path";import mu from"node:fs";import wu from"node:path";import{createHash as nw,randomBytes as rw,scryptSync as Jd}from"node:crypto";var Ao="__saffron_date_clock",Fn=/\{date(?:([+-]\d+)(?:([^\d{}:]+?)([+-]\d+))?)?(?::([^}]+))?\}/g,Cd="YYYY|YY|MMMM|MMM|MM|M|DD|D|dddd|ddd",va=new RegExp(Cd,"g"),Ym=new Set(["YYYY","MM","M","DD","D"]),Pd=/^[a-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$/,To={locale:"en-US"},Sa=e=>{let t=!1;try{t=Pd.test(e)&&Intl.DateTimeFormat.supportedLocalesOf(e).length>0}catch{}return t?void 0:`"${e}" is not a locale this Node.js knows: use a tag such as en-US or de-DE`};function Id(e="en-US",t){let n=Sa(e);if(n)throw new Error(`dateLocale in saffron.config.json: ${n}`);if(t!==void 0){let r;try{r=new Intl.DateTimeFormat("en-US",{timeZone:t}).resolvedOptions().timeZone}catch{throw new Error(`timezone in saffron.config.json: "${t}" is not a time zone: use an IANA name such as Europe/Berlin`)}if(r.toLowerCase()===t.toLowerCase()&&r!==t)throw new Error(`timezone in saffron.config.json: write "${t}" as "${r}", as browsers require`);if(!/^[A-Za-z]/.test(r))throw new Error(`timezone in saffron.config.json: "${t}" is an offset, which browsers do not take: use an IANA name such as Europe/Berlin, or Etc/GMT-2 for a fixed +02:00`)}To={locale:e,timeZone:t}}function $a(e){if(e===void 0)return{format:"YYYY-MM-DD"};let t=e.lastIndexOf(":"),n=e.slice(t+1);return t>=0&&Pd.test(n)?{format:e.slice(0,t),locale:n}:{format:e}}function jd(e){if(!To.timeZone)return[e.getFullYear(),e.getMonth(),e.getDate()];let t=new Intl.DateTimeFormat("en-US",{timeZone:To.timeZone,year:"numeric",month:"numeric",day:"numeric"}).formatToParts(e),n=r=>Number(t.find(s=>s.type===r).value);return[n("year"),n("month")-1,n("day")]}var _d=(e,t)=>{let[n,r,s]=jd(e);return new Date(Date.UTC(n,r,s+t))};function Zm(e,t,n,r){let s=n.match(va)??[],o=t[0]==="M"?"month":"weekday",a={timeZone:"UTC",calendar:"gregory",[o]:t.length===4?"long":"short"};return s.some(i=>i[0]==="D")&&(a.day="numeric"),s.some(i=>i[0]==="Y")&&(a.year="numeric"),o==="weekday"&&s.some(i=>i[0]==="M")&&(a.month=s.includes("MMMM")?"long":s.includes("MMM")?"short":"numeric"),new Intl.DateTimeFormat(r,a).formatToParts(e).find(i=>i.type===o)?.value??t}function Nd(e,t,n,r){switch(t){case"YYYY":return String(e.getUTCFullYear());case"YY":return String(e.getUTCFullYear()%100).padStart(2,"0");case"MM":return String(e.getUTCMonth()+1).padStart(2,"0");case"M":return String(e.getUTCMonth()+1);case"DD":return String(e.getUTCDate()).padStart(2,"0");case"D":return String(e.getUTCDate());default:return Zm(e,t,n,r)}}var Md=(e,t,n)=>t.replace(va,r=>Nd(e,r,t,n));function Qm(e,t,n,r,s){let o=n.split(new RegExp(`(${Cd})`)),a=e.getUTCFullYear()!==t.getUTCFullYear(),i=a||e.getUTCMonth()!==t.getUTCMonth(),c=i||e.getUTCDate()!==t.getUTCDate(),l=g=>g[0]==="Y"?a:g[0]==="M"?i:c,d=o.flatMap((g,y)=>y%2&&l(g)?[y]:[]);if(d.length===0)return Md(e,n,s);let u=(g,y,h)=>o.slice(y,h).map((S,v)=>(y+v)%2?Nd(g,S,n,s):S).join(""),p=d[d.length-1],f=/^[^\s,/-]*/.exec(o[p+1]??"")[0];return`${u(e,0,p+1)}${f}${r}${u(t,d[0],o.length)}`}function Ke(e,t=new Date){return e.replace(Fn,(n,r,s,o,a)=>{let{format:i,locale:c=To.locale}=$a(a);if(Sa(c))return n;let l=_d(t,Number(r??0));return o===void 0?Md(l,i,c):Qm(l,_d(t,Number(o)),i,s,c)})}function Eo(e){let t=new RegExp(`^${Fn.source}$`).exec(e);if(!t)return`${e} is not a date Saffron can resolve: write {date+N}, {date+N:FORMAT}, {date+N:FORMAT:LOCALE}, or a range such as {date+7 - +9:MMM D, YYYY}`;if([t[1],t[3]].some(o=>o!==void 0&&Math.abs(Number(o))>36600))return`${e} is more than a hundred years away: Saffron counts days within 36600 of today`;let{locale:n}=$a(t[4]),r=n===void 0?void 0:Sa(n);if(r)return`${e}: ${r}`;let s=t[4]?.includes(":")?t[4].slice(t[4].lastIndexOf(":")+1):void 0;if(n===void 0&&s!==void 0&&/^[A-Za-z]{2,3}(?:[-_][A-Za-z0-9]{1,8})*$/.test(s)&&!/^[YMDd]+$/.test(s))return`${e}: "${s}" is not a locale this Node.js knows: use a tag such as en-US or de-DE`}var ka=/\{date(?=[}:]|\s*[+-]\s*\d)[^{}]*\}/g,Dd=e=>e.match(ka)??[];function nr(e){return[...e.matchAll(Fn)].some(({3:t,4:n})=>{let{format:r,locale:s}=$a(n);return t!==void 0||s!==void 0||(r.match(va)??[]).some(o=>!Ym.has(o))})}var Xm=/\b(\d{4})-(\d{2})-(\d{2})\b/g,ew=400;function Fd(e,t=new Date,n=[]){let[r,s,o]=jd(t),a=Date.UTC(r,s,o);return e.replace(Xm,(i,c,l,d)=>{if(n.some(p=>p.includes(i)))return i;let u=(Date.UTC(Number(c),Number(l)-1,Number(d))-a)/864e5;return Math.abs(u)>ew?i:u===0?"{date}":`{date${u>0?"+":""}${u}}`})}var Ra=new Set(Intl.supportedValuesOf("currency")),tw=new Set(["kr","rs","z\u0142","k\u010D","ft","lei","lv","\u043B\u0432","din","\u0434\u0435\u043D","\u0434\u0438\u043D"]),Ld=e=>/\p{Sc}/u.test(e)||Ra.has(e)||tw.has(e.toLowerCase().replace(/\.$/,""));function Rt(e){let t=e.replace(/(\d)[\s\u00a0\u202f'\u2019](?=\d{3}(?!\d))/g,"$1"),n=[...t.matchAll(/[-\u2212\u2013]?\d(?:[\d.,]*\d)?/g)];if(n.length!==1)return;let[r]=n,s=t.slice(0,r.index),o=t.slice(r.index+r[0].length),a=/[.,]$/.test(s)&&!/\d[.,]$/.test(s)&&/^\d+$/.test(r[0]),i=a?s.slice(0,-1):s,c=/\(\s*([^\d\s.,()]{0,4})\s*$/.exec(i),l=/^\s*([^\d\s.,()]{0,4})\s*\)/.exec(o),d=[c?.[1],l?.[1]].filter(k=>!!k),u=/[.,]/.test(r[0]),p=c&&l&&(d.length===0?u:d.every(k=>Ld(k)||u&&Ra.has(k.toUpperCase()))||u&&!d.some(k=>/^\p{L}{3,}$/u.test(k))),f=/([\p{L}\p{N}]+)$/u.exec(s)?.[1],g=f!==void 0&&!(/^\p{L}+$/u.test(f)&&(Ld(f)||Ra.has(f.toUpperCase()))),y=/^[-\u2212\u2013]/.test(r[0])&&!g||/^\s*[-\u2212\u2013]\s*(?:[^\d\s.,()\-\u2212\u2013]{1,4}\s*)?$/u.test(i)||a&&/[-\u2212\u2013]$/.test(i)||/(?:^|[\s(:])[-\u2212\u2013][^\d\s.,()\-\u2212\u2013]{1,4}\s?$/.test(i)||/^[-\u2212\u2013](?!\d)/.test(o)||p,h=a?`0${s.slice(-1)}${r[0]}`:r[0].replace(/^[-\u2212\u2013]/,""),S=Math.max(h.lastIndexOf("."),h.lastIndexOf(",")),v=S<0?h:h.slice(0,S),x=S<0?"":h.slice(S+1),b=S>=0&&(x.length!==3||/^0?$/.test(v)||v.includes(h[S]==="."?",":".")),m=b?v:h,$=m.split(/[.,]/),T=new Set(m.match(/[.,]/g)??[]);if(T.size>1||b&&T.has(h[S])||$[0]===""||$.slice(1).some(k=>k.length!==3))return;let R=+`${y?"-":""}${$.join("")}${b?`.${x}`:""}`;return Number.isFinite(R)?R:void 0}var Ln=(e,t)=>Math.abs(e-t)<.005,Ud=e=>e.toFixed(2);function Oo(e,t){let n=e.trim(),r=Bd(n,/^ ([+-]) /);if(/\s[-+*×]$|^[+*×]\s/.test(n)||r.some(o=>o.text.trim()===""))return{problem:`"${e}" is not an amount expression: write terms such as "before" + "breakfast"`};let s=0;for(let o of r){let a=1;for(let{text:i}of Bd(o.text,/^ ([*×]) /)){let c=i.trim(),l=/^"([^"]+)"$/.exec(c)?.[1];if(l===void 0&&c.includes('"'))return{problem:`"${e}" is not an amount expression: write each captured name in double quotes on its own, operators between spaces, as in "before" + "breakfast"`};let d=l===void 0?c:t(l);if(d===void 0)return{problem:`no captured value named "${l}"`};let u=Rt(d);if(u===void 0)return{problem:l===void 0?`"${c}" is not an amount`:`"${l}" (${d}) does not hold exactly one amount`};a*=u}s+=o.op==="-"?-a:a}return{amount:s}}function rr(e,t,n=r=>r){return e.split(/("[^"]*")/).map((r,s)=>s%2===1?`"${n(r.slice(1,-1))}"`:t(r)??r).join("")}function Ta(e){return e?e.replace(/"[^"]*"/g," ").split(/\s[-+*\u00d7]\s/).flatMap(t=>/[<{]/.test(t)?[]:[Rt(t.trim())]).filter(t=>t!==void 0):[]}function zd(e,t){if(t.length===0)return e;let n=e.split(/(\s[-+*\u00d7]\s)/),r=(o,a)=>{if(a%2===1||/[<{]/.test(o))return;let i=Rt(o.trim()),c=i===void 0?[]:t.filter(([,l])=>Ln(l,i));return c.length===1?c[0][0]:void 0},s=n.map(r);return n.map((o,a)=>s[a]!==void 0&&s.filter(i=>i===s[a]).length===1?o.replace(o.trim(),`<${s[a]}>`):o).join("")}function Bd(e,t){let n=[],r="+",s=0,o=!1;for(let a=0;a<e.length;a++){if(e[a]==='"'&&(o=!o),o)continue;let i=t.exec(e.slice(a));i&&(n.push({op:r,text:e.slice(s,a)}),r=i[1],s=a+i[0].length,a=s-1)}return n.push({op:r,text:e.slice(s)}),n}function Ir(e,t,n){let r=o=>wt(t,`<${o}>`)||/^\{(?:env|data):[^{}]+\}$/.test(n[o]??"")&&wt(t,n[o]),s=o=>Object.keys(n).some(a=>a!==o&&n[a]===n[o]&&r(a));return[...new Set([...me(e).matchAll(/<([^<>]+)>/g)].map(o=>o[1]))].filter(o=>!r(o)&&!s(o))}function Vd(e,t){if(t.trim()==="")return!1;let n=Mr(t).exact;return e.flatMap(s=>Pt(s)).filter(s=>s!==void 0).some(s=>n.some(o=>t.length>=3?Oa(o).test(s):Oe(o).test(s)))||Wd(e,t)}function Oa(e){let t=/^\p{Lu}/u.test(e)?"(?<!\\p{Lu})":/^\p{L}/u.test(e)?"(?<!\\p{L})":/^\p{N}/u.test(e)?"(?<!\\p{N})":"",n=/\p{L}$/u.test(e)?"(?!\\p{Ll})":/\p{N}$/u.test(e)?"(?!\\p{N})":"";return new RegExp(`${t}${ue(e)}${n}`,"u")}function Wd(e,t){let n=Rt(t);return e.some(r=>[r.target?.role,r.toTarget?.role].includes(t.trim())||n!==void 0&&r.action==="expectAmount"&&Ta(r.value??"").some(s=>Ln(s,n)))}function Un(e,t){return t.length>=3?bn(e,t)||Wd(e,t):Vd(e,t)}function hs(e,t,n,r=[],s){for(let[,o]of e.matchAll(/\{data:([^{}]*<[^<>{}]+>[^{}]*)\}/g)){let a=p=>{try{return Le(o.replace(/<([^<>]+)>/g,(f,g)=>p[g]??f))}catch{return}},i=a(t),c=a(n);if(i===void 0||c===void 0||i===c)continue;if(s!==void 0){if(!Oe(i).test(s)&&_a(r,i))return!0;continue}if(i.trim()===""?c.trim()!=="":Un(r,i))return!0;let l=`{data:${o}}`,d=e.replace(/\{[^{}]*\}|<[^<>]+>/g," ");if((Oe(i).test(d)||i.length>=4&&d.includes(i))&&JSON.stringify(r).split(l).length>e.split(l).length)return!0}return!1}var jr=e=>e.length>0&&e.filter(t=>$e.has(t.action)).every(t=>![t.value,t.action==="expectAttribute"?void 0:t.pattern].some(n=>n!==void 0&&n.trim()!=="")),_a=(e,t)=>{if(Vd(e,t))return!0;if(t.trim()==="")return!1;let n=e.flatMap(r=>Pt(r)).filter(r=>r!==void 0);return Mr(t).loose.some(r=>r!==""&&n.some(s=>Oe(r,"iu").test(s)))};function _o(e,t,n){return me(e.replace(/\{data:[^{}]*\}/g," ")).includes(`<${t}>`)?!1:[...e.matchAll(/\{data:([^{}]*<[^<>{}]+>[^{}]*)\}/g)].filter(r=>r[1].includes(`<${t}>`)).every(r=>{try{return Le(r[1].replace(/<([^<>]+)>/g,(s,o)=>n[o]??s)).trim()===""}catch{return!1}})}function wt(e,t){let n=r=>typeof r=="string"?r.includes(t):Array.isArray(r)?r.some(n):r&&typeof r=="object"?Object.entries(r).some(([s,o])=>s!=="pageFingerprint"&&n(o)):!1;return e.some(n)}function Bn(e){return[e.action==="expectDiffers"?void 0:e.action==="expectAmount"?e.value?.replace(/"[^"]*"/g,'""'):e.value,e.url,e.urlPattern,e.pattern,...(e.json??[]).flatMap(t=>[t.path,t.equals]),e.promptText,e.each,...[e.target,e.toTarget].flatMap(t=>[t?.name,t?.nameRegex,t?.label,t?.text,t?.placeholder,t?.testId,t?.frame,...t?.fallbackSelectors??[]])]}function Pt(e){return[...Bn(e),e.status,e.method,e.attribute]}function bn(e,t){if(t.trim()==="")return!1;let{exact:n,loose:r}=Mr(t),s=r.map(a=>Oe(a,"iu")),o=a=>{let i=a.replace(Se," ").replace(ve," "),c=i.replace(/<[^<>]+>/g," ").normalize("NFC");return/[<>]/.test(t)?[c,i.normalize("NFC")]:[c]};return e.some(a=>Pt(a).some(i=>i!==void 0&&o(i).some(c=>{let l=t.length<3?c.replace(Ca," "):c;return n.some(d=>l.includes(d))||s.some(d=>d.test(l))})))}function sr(e,t,n,r,s,o){let a=s?Date.parse(s):NaN,i=Object.keys(n),c=Aa(t,o,i),l=(d,u)=>Ea(d,o,u);for(let[d,u]of i.entries())for(let p of i.slice(d+1))if(!(r[u]===void 0||r[p]===void 0||l(n[u],a)==="")&&!(l(n[u],a)!==l(n[p],a)||l(r[u])===l(r[p]))&&(wt(e,`<${u}>`)||wt(e,`<${p}>`)))return!0;for(let d of i.filter(u=>/\{env:/.test(n[u])&&r[u]!==void 0))if([...n[d].matchAll(Se)].map(([p])=>p).some(p=>!t.includes(p)&&wt(e,p))){for(let p of i)if(!(p===d||/\{env:/.test(n[p])||r[p]===void 0||!t.includes(`<${p}>`)||wt(e,`<${p}>`))&&l(r[p])!==l(r[d]))return!0}return Object.entries(n).some(([d,u])=>{let p=r[d];if(p===void 0)return!1;let f=u.includes("{date")&&!Number.isNaN(a);if(p===u&&(!f||Ke(u,new Date(a))===Ke(p)))return!1;let g=t.includes(`<${d}>`),y=l(u,a),h=l(p);if(y.trim()==="")return h.trim()!==""&&!wt(e,`<${d}>`)&&e.some(m=>Bn(m).some($=>$!==void 0));let S=Rt(y),v=!g&&c.some(m=>(m.match(/[-\u2212\u2013]?\d[\d.,]*/g)??[]).some($=>Ln(Rt($)??NaN,S??NaN))),x=m=>m.action==="expectAmount"?Ta(m.value):m.value!==void 0&&/^expect/.test(m.action)?[Rt(m.value)].filter($=>$!==void 0):[];if(S!==void 0&&!v&&e.some(m=>x(m).some($=>Ln($,S)))){let m=Rt(h);if(m===void 0||!Ln(m,S))return!0}if(y!==h&&e.some(m=>Bn(m).some($=>$!==void 0&&/^\{(?:env|data):[^{}]+\}$/.test($)&&t.includes($)&&l($,a)===y))||y!==h&&e.some(m=>[m.target?.role,m.toTarget?.role].includes(y)))return!0;let b=new Set(p===u?[]:Aa(u,o,i));if(f){let m=u.replace(/\{date([+-]\d+)?:[^}]*\}/g,"{date$1}");m!==u&&g&&p!==u&&b.add(m);for(let $ of[0,1])for(let T of new Set([u,m])){let R=Ke(T,new Date(a-$*864e5));b.add(R)}}return[...b].some(m=>m.trim()!==""&&(g||!c.some($=>Oe(m).test($)))&&Yd(e,m,g||f,$=>Aa($,o,i)))})}function Gd(e,t){let n=Object.keys(t).filter(r=>t[r].trim()==="");return n.length>0&&e.some(r=>Bn(r).some(s=>s!==void 0))&&n.some(r=>!wt(e,`<${r}>`))}function Kd(e,t,n={}){let r=/\{env:|\{date/;if(e.some(a=>Pt(a).some(i=>i!==void 0&&(r.test(i)||/\{data:/.test(i))))||Object.values(t).some(a=>a.trim()==="")&&e.some(a=>a.value===""))return!0;let s=Object.values(t).filter(a=>a.trim()!=="");if(new Set(s).size<s.length)return!0;let o=a=>[a.replace(or(Object.keys(t))," ").normalize("NFC")];return Object.values(t).some(a=>{if(r.test(a)||[...a.matchAll(ve)].some(([,c])=>!(c in n)))return!0;let i=a.replace(ve,(c,l)=>n[l]);return[a,i].some(c=>c.trim()!==""&&Yd(e,c,!0,o))})}function Yd(e,t,n,r){let{exact:s,loose:o}=Mr(t),a=n&&t.length>=3,i=s.map(u=>Co(t,u,"u",n)),c=o.map(u=>Oe(u,"iu")),l=u=>{let p=t.length<3?u.replace(Ca," "):u;return/^\{(?:env|data|unique|date)[^{}]*\}$/.test(t)&&p.includes(t)||i.some(f=>f.test(p))||(a?o.some(f=>p.toLowerCase().includes(f)):c.some(f=>f.test(p)))},d=u=>n?Pt(u):Bn(u);return e.some(u=>d(u).some(p=>p!==void 0&&r(p).some(l)))}function Co(e,t=e,n="gu",r=!0){let s=t.normalize("NFC");return r&&e.length>=3?new RegExp(ue(s),n):Oe(s,n)}function Nr(e,t,n,r=t){let s=e.normalize("NFC");return s.includes(r.normalize("NFC"))?Co(t,r,"u",n).test(t.length<3?s.replace(Ca," "):s):!1}function Ea(e,t,n){return Ke(e,n===void 0||Number.isNaN(n)?new Date:new Date(n)).replace(ve,(r,s)=>t?.[s]??Zd(s)??r).replace(Se,(r,s)=>process.env[s]??r)}function ms(e,t,n,r,s){let o=r?Date.parse(r):NaN;return e.find(a=>{let i=t[a],c=n[a];return i===void 0||c===void 0?!0:i!==c&&Ea(i,s,o)!==Ea(c,s)})}function or(e){return new RegExp(`<(?:table:[^<>]+|docstring${[...e].map(t=>`|${ue(t)}`).join("")})>`,"g")}var qd=String.raw`[\p{L}\p{N}\p{M}]`,Hd=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u,Ca=/:nth-[a-z-]+\([^)]*\)|\bnth=-?\d+|\bh[1-6]\b/gi;function Oe(e,t="u"){let n=[...e],r=n.length>=2&&Hd.test(n[0])?"":`(?<!${qd})`,s=n.length>=2&&Hd.test(n[n.length-1])?"":`(?!${qd})`;return new RegExp(`${r}${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}${s}`,t)}function Mr(e){let t=e.normalize("NFC"),n=[...new Set([t,...Object.values(fe).map(a=>a(t))])],r=t.toLowerCase(),s=new Set([r]);try{s.add(encodeURIComponent(t).toLowerCase()),s.add(encodeURIComponent(t).replaceAll("%20","+").toLowerCase())}catch{}let o=r.split(/[^\p{L}\p{N}\p{M}]+/u).filter(Boolean);if(o.length>1)for(let a of["-","_",""])s.add(o.join(a));return{exact:n,loose:[...s]}}function Pa(e){return e.length>=5||e.length>=3&&/\p{N}/u.test(e)}function Aa(e,t,n){let r=(e??"").replace(n?or(n):/<[^<>]+>/g," ").normalize("NFC"),s=r.replace(ve,(o,a)=>t?.[a]??Zd(a)??o).replace(Se,(o,a)=>process.env[a]??o);return s===r?[r]:[r,s]}function Zd(e){try{return Le(e)}catch{return}}function Qd(e,t){return e===t?"bare":e===`^${t}$`?"anchored":void 0}function Xd(e){let t=eu(e);if(t===void 0)return;let n=rw(16).toString("hex");return`s1:${n}:${Jd(t,n,32).toString("hex")}`}function Po(e,t){let n=eu(e);if(n===void 0)return!1;let r=/^s1:([0-9a-f]{32}):([0-9a-f]{64})$/.exec(t);return r?Jd(n,r[1],32).toString("hex")===r[2]:nw("sha256").update(n).digest("hex")===t}function eu(e){if(!/\{(?:env|data):/.test(e))return;let t=!1,n=e.replace(ve,(s,o)=>{try{return Le(o)}catch{return t=!0,s}});if(!new RegExp(Se.source).test(n))return;let r=n.replace(Se,(s,o)=>{let a=process.env[o];return a===void 0&&(t=!0),a??s});return t?void 0:r}var $e=new Set(["expectVisible","expectNotVisible","expectText","expectUrl","expectValue","expectDiffers","expectMatches","expectAttribute","expectResponse","expectEach","expectDownload","expectAmount"]);function sw(e){return[e.target,e.toTarget].flatMap(r=>[...r?.fallbackSelectors??[],...r?.frame?[r.frame]:[]]).flatMap(r=>wn(r,s=>s,s=>s.replaceAll(">>","\0")).split("\0")).some(r=>!/^\s*(?:xpath=|\/\/)/.test(r)&&[...r.matchAll(/(["'])((?:\\.|(?!\1)[^\\])*)\1/g)].some(([,s,o])=>s==="'"&&/<[^<>']+>|\{(?:data|env|date|unique)[^{}']*\}/.test(o)))}function ws(e){if(e.steps.some(n=>n.actions.some(r=>r.json!==void 0||sw(r))))return 5;if(e.steps.some(n=>n.actions.some(r=>r.action==="waitForDownload"&&(r.downloads??1)>1)))return 4;if(e.rowsUseNewDates||nr(JSON.stringify([e.steps,e.examples??{},e.data??{}]))||Object.values(e.data??{}).some(n=>n.includes("{date"))||e.examples&&e.steps.some(n=>Gd(n.actions,e.examples))||e.rowBound?.some(n=>n.reason==="container"||n.reason==="session"||n.reason==="unwritten"||n.valueSha?.startsWith("s1:")))return 3;if((e.rowBound?.length??0)>0||tt(e.steps.map(n=>n.gherkin)).some(n=>n!==void 0)||e.examples&&e.steps.some(n=>Kd(n.actions,e.examples,e.data)))return 2;let t=n=>n.clickCount!==void 0&&n.clickCount!==1||n.button!==void 0&&n.button!=="left"||(n.modifiers?.length??0)>0||n.clearSelection===!0||n.action==="selectOption"&&(n.value??"").includes(`
|
|
13
|
+
`)||[n.status,n.method,n.attribute].some(r=>r!==void 0&&/<[^<>]+>|\{(?:data|env|date|unique)[^{}]*\}/.test(r));return e.steps.some(n=>n.actions.some(t))?2:1}import{createHash as iu}from"node:crypto";import Zt from"node:fs";import xn from"node:fs";import zn from"node:path";import{createHash as ow,randomBytes as iw}from"node:crypto";function It(e,t){try{if(!xn.statSync(t).isFile())return!1;let n=zn.relative(xn.realpathSync(e),xn.realpathSync(t));return n!==""&&n!==".."&&!n.startsWith(".."+zn.sep)&&!zn.isAbsolute(n)}catch{return!1}}var He=(e,t)=>zn.relative(e,t).split(zn.sep).join("/");function Kt(e){return ow("sha256").update(e).digest("hex")}function Ue(e,t,n){xn.mkdirSync(zn.dirname(e),{recursive:!0});let r=`${e}.${process.pid}-${iw(4).toString("hex")}.partial`;try{xn.writeFileSync(r,t),n!==void 0&&xn.chmodSync(r,n),xn.renameSync(r,e)}catch(s){throw xn.rmSync(r,{force:!0}),s}}function qn(e,t){let n=zn.join(e,t.file);if(It(zn.join(e,".saffron","artifacts"),n))try{let r=xn.readFileSync(n);return t.sha256&&Kt(r)!==t.sha256?void 0:r}catch{return}}import Yt from"node:path";import nu from"node:path";function ir(e){if(!Array.isArray(e)||e.length===0)return"must be a non-empty list of JSON field checks";for(let t of e){if(!t||typeof t!="object"||typeof t.path!="string"||!/^(?:\/(?:[^~]|~[01])*)*$/.test(t.path))return"each path must be a JSON Pointer, such as /order/status or /items/0/sku";if(t.equals!==void 0&&typeof t.equals!="string"||t.exists!==void 0&&typeof t.exists!="boolean"||typeof t.equals=="string"==(typeof t.exists=="boolean"))return"each check needs either equals (a string) or exists (true or false)";if(t.type!==void 0&&(!["string","number","boolean","null"].includes(t.type)||t.equals===void 0))return"type must be string, number, boolean or null, on an equals check"}}function ja(e){if(e.type===void 0||e.type==="string")return e.equals;let t;try{t=JSON.parse(e.equals)}catch{}if(typeof t=="number"&&Number.isInteger(t)&&!Number.isSafeInteger(t))throw new Error(`JSON field ${JSON.stringify(e.path)}: ${e.equals} is too large to compare exactly as a number; check it as a string`);if((e.type==="null"?t===null:typeof t===e.type)&&(typeof t!="number"||Number.isFinite(t)))return t;throw new Error(`JSON field ${JSON.stringify(e.path)}: expected value must be a valid ${e.type}`)}var aw=e=>e===null?"null":Array.isArray(e)?"array":typeof e,Ia=e=>`${aw(e)}${e===null||typeof e!="object"?` ${JSON.stringify(e)}`:""}`;function tu(e,t){if(e===void 0)return"response body is pending, unreadable or not a supported text content type";let n;try{n=JSON.parse(e)}catch{return"response body is not valid JSON"}for(let r of t){let s=n;for(let a of r.path===""?[]:r.path.slice(1).split("/")){let i=a.replace(/~1/g,"/").replace(/~0/g,"~");s=s!==null&&typeof s=="object"&&(!Array.isArray(s)||/^(0|[1-9]\d*)$/.test(i))&&Object.hasOwn(s,i)?s[i]:void 0}let o=`JSON field ${JSON.stringify(r.path)}`;if(r.exists!==void 0){if(s!==void 0!==r.exists)return`${o}: expected ${r.exists?"present, got missing":`absent, got ${Ia(s)}`}`}else{let a=ja(r);if(s!==a)return`${o}: expected ${Ia(a)}, got ${s===void 0?"missing":Ia(s)}`}}}var Io=5,cw=new Set(["goto","click","fill","press","selectOption","check","uncheck","hover","waitFor","captureText","handleDialog","uploadFile","dragTo","waitForResponse","switchTab","closeTab","newTab","waitForDownload",...$e]),lw=["role","name","nameRegex","label","text","testId","placeholder","frame"],dw=["value","url","saveAs","compareTo","each","pattern","attribute","promptText","urlPattern","method","status","pageFingerprint"],Na=/[\u0000-\u001f\u007f-\u009f]/,ke=class extends Error{constructor(n,r){super(`${n}: ${r}`);this.file=n;this.problem=r}file;problem},yt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function K(e,t,n){if(!e)throw new ke(t,n)}function ru(e,t,n){K(yt(e),t,`${n} must be an object`);for(let r of lw)K(e[r]===void 0||typeof e[r]=="string",t,`${n}.${r} must be a string`);e.fallbackSelectors!==void 0&&K(Array.isArray(e.fallbackSelectors)&&e.fallbackSelectors.every(r=>typeof r=="string"),t,`${n}.fallbackSelectors must be a list of selectors`)}var uw=e=>["role","label","text","testId","placeholder"].some(t=>typeof e[t]=="string"&&e[t]!=="")||Array.isArray(e.fallbackSelectors)&&e.fallbackSelectors.some(t=>typeof t=="string"&&t.trim().length>0),fw={goto:["url"],click:["target"],fill:["target","value"],press:["value"],selectOption:["target","valueOrClear"],check:["target"],uncheck:["target"],hover:["target"],waitFor:["targetOrValue"],captureText:["target","saveAs"],handleDialog:[],uploadFile:["value"],dragTo:["target","toTarget"],waitForResponse:["urlPattern"],switchTab:["value"],closeTab:[],newTab:[],waitForDownload:[],expectVisible:["target"],expectNotVisible:["target"],expectText:["target","value"],expectUrl:["urlOrValue"],expectValue:["target","value"],expectDiffers:["compareTo","targetOrValue"],expectMatches:["target","pattern"],expectAttribute:["target","attribute","pattern"],expectResponse:["urlPattern"],expectEach:["target","each"],expectDownload:["valueOrPattern"],expectAmount:["target","value"]};function pw(e,t,n){let r=o=>typeof e[o]=="string",s=o=>yt(e[o])&&uw(e[o]);for(let o of fw[e.action])switch(o){case"target":case"toTarget":K(s(o),t,`${n} (${e.action}) needs a ${o} with a role, name, label, text, test id, placeholder or selector`);break;case"urlOrValue":K(r("url")||r("value"),t,`${n} (${e.action}) needs a url`);break;case"targetOrValue":K(s("target")||r("value"),t,`${n} (${e.action}) needs a target or a value`);break;case"valueOrClear":K(r("value")||e.clearSelection===!0,t,`${n} (${e.action}) needs value`);break;case"valueOrPattern":K(r("value")&&e.value!==""||r("pattern"),t,`${n} (${e.action}) needs a non-empty value or a pattern`);break;default:K(r(o),t,`${n} (${e.action}) needs ${o}`)}for(let o of["target","toTarget"])e[o]!==void 0&&K(s(o),t,`${n}.${o} has no usable locator`);if(e.downloads!==void 0&&K(e.action==="waitForDownload"&&Number.isInteger(e.downloads)&&e.downloads>=2&&e.downloads<=999,t,`${n}.downloads must be a whole number from 2, on a waitForDownload`),e.action==="expectUrl"){let o=e.url??e.value;K(typeof o=="string"&&o.length>0,t,`${n} (expectUrl) needs a non-empty url or value`)}for(let o of["url","saveAs","compareTo","each","pattern","attribute","urlPattern"])e[o]!==void 0&&K(e[o].length>0,t,`${n}.${o} must not be empty`);["press","uploadFile","switchTab","expectText"].includes(e.action)&&K(typeof e.value=="string"&&e.value.length>0,t,`${n} (${e.action}) needs a non-empty value`)}function gw(e,t,n){K(yt(e),t,`${n} must be an object`),K(typeof e.action=="string",t,`${n}.action is missing`),K(cw.has(e.action),t,`${n}.action "${e.action}" is not an action this runner knows. Recorded by a newer saffron-ai? Update, or re-record with --rerecord`);for(let r of dw)K(e[r]===void 0||typeof e[r]=="string",t,`${n}.${r} must be a string`);if(K(e.opensTab===void 0||typeof e.opensTab=="boolean",t,`${n}.opensTab must be true or false`),K(e.clearSelection===void 0||typeof e.clearSelection=="boolean",t,`${n}.clearSelection must be true or false`),K(e.clickCount===void 0||Number.isInteger(e.clickCount)&&e.clickCount>=1,t,`${n}.clickCount must be a whole number from 1`),K(e.button===void 0||["left","right","middle"].includes(e.button),t,`${n}.button must be "left", "right" or "middle"`),K(e.modifiers===void 0||Array.isArray(e.modifiers)&&e.modifiers.every(r=>["Alt","Control","ControlOrMeta","Meta","Shift"].includes(r)),t,`${n}.modifiers must be a list of Alt, Control, ControlOrMeta, Meta or Shift`),e.target!==void 0&&ru(e.target,t,`${n}.target`),e.toTarget!==void 0&&ru(e.toTarget,t,`${n}.toTarget`),pw(e,t,n),e.json!==void 0){K(e.action==="waitForResponse"||e.action==="expectResponse",t,`${n}.json is only supported on response checks`);let r=ir(e.json);K(!r,t,`${n}.json ${r}`)}}function hw(e,t,n){K(yt(e),t,`${n} must be an object`),K(typeof e.gherkin=="string"&&e.gherkin.length>0,t,`${n}.gherkin (the step text) is missing`),K(typeof e.keyword=="string",t,`${n}.keyword is missing`),K(e.kind==="action"||e.kind==="assertion",t,`${n}.kind must be "action" or "assertion"`),K(Array.isArray(e.actions),t,`${n}.actions must be a list (empty for a recorded no-op)`),e.actions.forEach((r,s)=>gw(r,t,`${n}.actions[${s}]`)),e.table!==void 0&&K(Array.isArray(e.table)&&e.table.every(r=>Array.isArray(r)&&r.every(s=>typeof s=="string")),t,`${n}.table must be rows of strings`),K(e.docString===void 0||typeof e.docString=="string",t,`${n}.docString must be a string`),K(e.fromStepSet===void 0||typeof e.fromStepSet=="string",t,`${n}.fromStepSet must be a string`)}function Ma(e,t){if(K(yt(e),t,"is not a JSON object"),K(e.version!==void 0,t,"has no version: not a Saffron recording"),K(Number.isInteger(e.version)&&e.version>=1&&e.version<=Io,t,typeof e.version=="number"&&e.version>Io?`is schema version ${e.version}; this saffron-ai reads versions 1 to ${Io}. Update saffron-ai to the release that wrote it`:`has schema version ${JSON.stringify(e.version)}; this saffron-ai reads versions 1 to ${Io}`),K(typeof e.feature=="string"&&e.feature.length>0,t,"feature (the feature file path) is missing"),K(!nu.isAbsolute(e.feature)&&!nu.win32.isAbsolute(e.feature)&&!e.feature.split(/[\\/]/).includes(".."),t,`names a feature file outside the project: ${JSON.stringify(e.feature)}`),K(typeof e.scenario=="string"&&e.scenario.length>0,t,"scenario (the scenario name) is missing"),K(e.recordedAt===void 0||typeof e.recordedAt=="string",t,"recordedAt must be a string"),K(e.recordedBy===void 0||e.recordedBy==="agent"||e.recordedBy==="manual",t,'recordedBy must be "agent" or "manual"'),K(Array.isArray(e.steps),t,"steps must be a list"),e.steps.forEach((n,r)=>hw(n,t,`steps[${r}]`)),e.data!==void 0&&K(yt(e.data)&&Object.values(e.data).every(n=>typeof n=="string"),t,"data must map references to strings"),e.examples!==void 0&&K(yt(e.examples)&&Object.values(e.examples).every(n=>typeof n=="string"),t,"examples must map columns to strings"),K(e.rowsUseNewDates===void 0||e.rowsUseNewDates===!0,t,"rowsUseNewDates must be true when present"),e.rowBound!==void 0){let n=e.steps.length;K(Array.isArray(e.rowBound)&&e.rowBound.every(r=>yt(r)&&typeof r.column=="string"&&Number.isInteger(r.step)&&r.step>=0&&r.step<n&&(r.reason==="list"||r.reason==="glued"||r.reason==="data"||r.reason==="value"||r.reason==="reads"||r.reason==="container"||r.reason==="session"||r.reason==="unwritten")&&(r.valueSha===void 0||typeof r.valueSha=="string"&&/^(?:[0-9a-f]{64}|s1:[0-9a-f]{32}:[0-9a-f]{64})$/.test(r.valueSha))),t,'rowBound must be a list of { column, step, reason: "list" | "glued" | "data" | "value" | "reads" | "container" | "session" | "unwritten", valueSha? } naming steps of this recording'),K(yt(e.examples),t,"rowBound needs examples, the row it was recorded on")}return e}function su(e,t){K(yt(e),t,"is not a JSON object"),K(yt(e.meta),t,"meta is missing: not a Saffron proposal");let n=e.meta;K(n.mode==="record"||n.mode==="heal",t,'meta.mode must be "record" or "heal"'),K(typeof n.narrative=="string",t,"meta.narrative must be a string"),K(Array.isArray(n.adaptations)&&n.adaptations.every(r=>typeof r=="string"),t,"meta.adaptations must be a list of strings"),K(n.verified===void 0||typeof n.verified=="boolean",t,"meta.verified must be true or false"),K(yt(n.usage),t,"meta.usage is missing"),n.featureEdits!==void 0&&(K(Array.isArray(n.featureEdits)&&n.featureEdits.every(r=>yt(r)&&typeof r.index=="number"&&typeof r.text=="string"),t,"meta.featureEdits must be a list of { index, text }"),n.featureEdits.forEach((r,s)=>K(r.text.trim().length>0,t,`meta.featureEdits[${s}].text is empty: a feature edit must give the step's new text`)),n.featureEdits.forEach((r,s)=>K(!Na.test(r.text),t,`meta.featureEdits[${s}].text holds a line break or another control character`))),n.bound!==void 0&&K(yt(n.bound)&&["scenario","committed","recording"].every(r=>typeof n.bound[r]=="string"),t,"meta.bound must hold the scenario, committed and recording digests"),Ma(e.cache,`${t} (cache)`)}var au=".saffron",cu=e=>iu("sha1").update(e).digest("hex").slice(0,8),Da=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");function lu(e){return Da(e)||`unnamed-${cu(e)}`}var du=e=>Da(e)||"unnamed";function uu(e){let t=Da(e);return t&&/[^\x00-\x7f]/.test(e)?`${t}-${cu(e)}`:lu(e)}function fu(e,t,n,r){let s;try{s=Zt.readFileSync(e,"utf8")}catch{return!0}try{return t(JSON.parse(s))}catch{return r.some(o=>new RegExp(`"${n}"\\s*:\\s*${ue(JSON.stringify(o))}`).test(s))}}function mw(e,t,n){let r=Yt.join(e,`${uu(t)}.json`),s=Yt.join(e,`${du(t)}.json`);return s===r||Zt.existsSync(r)||!Zt.existsSync(s)?r:fu(s,o=>n(o)===t,"scenario",[t])?s:r}var ou=new Map;function pu(e){let t=Yt.join(e,"saffron.config.json"),n=Zt.statSync(t,{throwIfNoEntry:!1}),r=n?`${n.mtimeMs}:${n.ctimeMs}:${n.size}:${n.ino}`:"none",s=ou.get(e);if(s?.stamp===r)return s.top;let o="features";try{let c=JSON.parse(Zt.readFileSync(t,"utf8"));typeof c?.features=="string"&&c.features.trim()&&(o=c.features)}catch{}let a=Yt.relative(e,Yt.resolve(e,o)),i=a.startsWith("..")||Yt.isAbsolute(a)?void 0:a.split(/[\\/]/)[0];return ou.set(e,{stamp:r,top:i}),i}function ys(e,t,n=lu){let r=e.split(/[\\/]/).filter(Boolean),s=r.pop()??"unnamed",o=t===void 0||r[0]===t?r.slice(1):r,a=n([...o,Yt.basename(s,".feature")].join("-"));if(o.length===0)return a;let i=iu("sha1").update(e.replace(/\\/g,"/")).digest("hex").slice(0,6);return`${a}-${i}`}function gu(e,t,n,r,s){let o=d=>mw(Yt.join(e,au,t,d),r,u=>s(u)?.scenario),a=o(ys(n,pu(e))),i=o(ys(n,void 0,du));if(i===a||Zt.existsSync(a)||!Zt.existsSync(i))return a;let c=d=>typeof d=="string"?d.replace(/\\/g,"/"):d;return fu(i,d=>c(s(d)?.feature)===c(n),"feature",[n,c(n)])?i:a}function pe(e,t,n){return gu(e,"cache",t,n,r=>r)}function hu(e,t){let n=new Map;for(let r of t){let s=pe(e,r.featurePath,r.name),o=n.get(s)??new Set;o.add(`${r.featurePath} \u203A ${r.name}${r.line?` (line ${r.line})`:""}`),n.set(s,o)}return[...n.entries()].filter(([,r])=>r.size>1).map(([r,s])=>`${[...s].join(" and ")} both map to ${Yt.relative(e,r)}. Rename one scenario or one file.`)}var ar="owner.json";function vn(e,t,n){return Yt.join(e,au,"artifacts",ys(t,pu(e)),uu(n))}function dt(e,t,n){return gu(e,"proposals",t,n,r=>r?.cache)}function tn(e,t){try{return Ye(e)}catch(n){if(!(n instanceof ke))throw n;t?.(e,n.problem);return}}function Ye(e){if(!Zt.existsSync(e))return;let t;try{t=JSON.parse(Zt.readFileSync(e,"utf8"))}catch(n){throw new ke(e,`is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}return Ma(t,e)}function Dr(e,t){Zt.mkdirSync(Yt.dirname(e),{recursive:!0});let n=(()=>{try{return Zt.statSync(e).mode&511}catch{return}})();Ue(e,`${JSON.stringify({...t,version:ws(t)},null,2)}
|
|
14
|
+
`,n)}function jo(e){let t=[];return{pattern:e.replace(/"((?:[^"\\]|\\.)*)"/g,(r,s)=>(t.push(s),`"\xAB${t.length-1}\xBB"`)),args:t}}function Fa(e,t){let n=r=>JSON.stringify(r.map(({pageFingerprint:s,...o})=>o));return n(e)===n(t)}function ww(e){let t=new Set,n=r=>{if(r)for(let s of r.matchAll(/<([^<>]+)>/g))t.add(s[1])};for(let r of e.actions)Pt(r).forEach(n);return n(e.gherkin),t}var bu=/<[^<>]+>/,Sn=(e,t)=>`${we(e)}
|
|
15
|
+
${t}`;function nn(e){let t=wu.join(e,".saffron","cache"),n=new Map,r=new Map,s=new Map,o=new Map,a=new Set,i=0;if(mu.existsSync(t))for(let d of mu.readdirSync(t,{recursive:!0})){let u=String(d);if(!u.endsWith(".json"))continue;let p=tn(wu.join(t,u));if(!p)continue;i++;let f=tt(p.steps.map(y=>y.gherkin)),g=Mn(p.steps);for(let[y,h]of p.steps.entries()){let S=h.gherkin,v=JSON.stringify(h.actions.map(({pageFingerprint:w,...E})=>E)),x=Sn(f[y],S),b=o.get(x)??new Set;b.add(v),o.set(x,b),b.size>1&&a.add(S);let m=n.get(S),$=Math.max(b.size,m?.variants??0),T={gherkin:h.gherkin,kind:h.kind,...p.examples||p.steps.some(w=>/<[^<>\s]+>/.test(w.gherkin))?{outline:!0}:{},table:h.table,docString:h.docString,actions:h.actions,sourceParams:g,sourceData:p.data,...p.examples?{examples:p.examples}:{},...p.rowBound?.some(w=>w.step===y)?{rowBound:p.rowBound.filter(w=>w.step===y).map(w=>w.column)}:{},...p.rowBound?.some(w=>w.step===y&&w.valueSha)?{rowBoundValues:Object.fromEntries(p.rowBound.filter(w=>w.step===y&&w.valueSha).map(w=>[w.column,w.valueSha]))}:{},feature:p.feature,scenario:p.scenario,recordedAt:p.recordedAt??"",variants:$,...f[y]?{session:f[y]}:{}};!m||T.recordedAt>m.recordedAt?n.set(S,T):m.variants=$;let R=n.get(S),k=me(S),C=s.get(k);if((!C||C.recordedAt<=R.recordedAt)&&s.set(k,R),f[y]?.match(bu))continue;let P=r.get(x);!P||P.recordedAt<=T.recordedAt?r.set(x,{...T,variants:b.size}):P.variants=b.size}}let c=[...a],l=new Map;for(let d of r.values()){let{pattern:u,args:p}=jo(d.gherkin);if(p.length===0)continue;let f=Sn(d.session,u),g=l.get(f);(!g||d.recordedAt>g.recordedAt)&&l.set(f,{...d,args:p})}return{steps:n,seeds:r,bare:s,patterns:l,divergent:c,scannedCaches:i}}function yu(e,t,n){if(t.kind!==void 0&&e.kind!==void 0&&t.kind!==e.kind||!!e.table!=!!t.table)return!1;if(e.table&&t.table){let o=Object.keys(lt(e.table)),a=Object.keys(lt(t.table));if(o.length>0&&a.length>0){if(JSON.stringify(o)!==JSON.stringify(a))return!1}else if(JSON.stringify(e.table)!==JSON.stringify(t.table))return!1}if(e.docString!==void 0!=(t.docString!==void 0)||e.docString!==void 0&&t.docString!==void 0&&e.docString!==t.docString&&(!e.actions.some(o=>[o.value,o.url,o.pattern].some(a=>a?.includes("<docstring>")))||bn(e.actions,e.docString)))return!1;if(e.table&&t.table){let o=lt(e.table),a=lt(t.table);for(let i of Object.keys(o))if(o[i]!==a[i]&&(!wt(e.actions,`<${i}>`)||bn(e.actions,o[i])))return!1}for(let[o,a]of Object.entries(e.sourceParams??{}))if(o in n&&n[o]!==a&&bn(e.actions,a))return!1;if((e.kind!=="assertion"||jr(e.actions))&&Ir(e.gherkin,e.actions,e.examples??{}).some(o=>o in n&&(!e.examples||e.examples[o]!==n[o])))return!1;if(e.sourceData&&e.outline&&Object.keys(n).length>0){let o=e.examples?Object.entries(e.examples).filter(([d,u])=>n[d]!==void 0&&n[d]!==u).map(([,d])=>d):void 0,a=d=>o===void 0||o.some(u=>u!==""&&d.includes(u)),i=[t.text,...t.table?.flat()??[],t.docString??""].join(`
|
|
16
|
+
`).replace(/\{[^{}]*\}|<[^<>]+>/g," "),c=d=>{try{return new RegExp(d).test("")}catch{return!1}},l=e.actions.some(d=>$e.has(d.action)&&(d.value===""||d.pattern!==void 0&&c(d.pattern)));for(let[d,u]of Object.entries(e.sourceData))if(a(d)&&(u.trim()===""?l:!Oe(u).test(i)&&Un(e.actions,u)))return!1}if(e.rowBound&&(!e.examples||ms(e.rowBound,e.examples,n,e.recordedAt,e.sourceData)!==void 0)||e.rowBoundValues&&Object.entries(e.rowBoundValues).some(([o,a])=>!Po(n[o]??"",a)))return!1;if(e.examples){let o=[t.text,...t.table?.flat()??[],t.docString??""].join(`
|
|
17
|
+
`);if(sr(e.actions,o,e.examples,n,e.recordedAt,e.sourceData)||hs(o,e.examples,n,e.actions))return!1}for(let[o,a]of Object.entries(e.sourceData??{})){let i;try{i=Le(o)}catch{continue}if(i!==a&&(Un(e.actions,a)||e.gherkin.includes(`{data:${o}}`)&&!wt(e.actions,`{data:${o}}`)))return!1}let r={...n,...lt(t.resolvedTable??t.table),...tr(t.resolvedDocString??t.docString)},s=ww({gherkin:e.gherkin,keyword:"",kind:"action",actions:e.actions});for(let o of s)if(!(o in r))return!1;return!0}function xu(e,t,n){let r=t.text,[s]=tt([r],t.session),o=s?.match(bu)?t.session:s,a=e.seeds.get(Sn(o,r));if(a)return yu(a,t,n)?a:void 0;let{pattern:i,args:c}=jo(r);if(c.length===0)return;let l=e.patterns.get(Sn(o,i));if(!l)return;let d=new Map;for(let v=0;v<c.length;v++){let x=l.args[v],b=c[v],m=d.get(x);if(m!==void 0&&m!==b)return;d.set(x,b)}let u=new Map([...d].filter(([v,x])=>v!==x)),p=l.actions.flatMap(v=>[v.saveAs,v.compareTo,v.action==="expectDiffers"?v.value:void 0,...v.action==="expectAmount"?[...(v.value??"").matchAll(/"([^"]*)"/g)].map(x=>x[1]):[]]);if([...u.keys()].some(v=>p.includes(v)))return;let f=v=>[v?.name,v?.nameRegex,v?.label,v?.text,v?.placeholder];for(let v of u.keys())if(!l.actions.some(b=>[b.value,b.url,b.pattern,b.urlPattern,b.promptText,b.status,b.method,b.attribute,...f(b.target),...f(b.toTarget)].includes(v)))return;let g=v=>{let x=b=>b?{...b,name:v(b.name),nameRegex:v(b.nameRegex),label:v(b.label),text:v(b.text),placeholder:v(b.placeholder)}:void 0;return l.actions.map(({pageFingerprint:b,...m})=>({...m,value:v(m.value),url:v(m.url),pattern:v(m.pattern),urlPattern:v(m.urlPattern),promptText:v(m.promptText),status:v(m.status),method:v(m.method),attribute:v(m.attribute),target:x(m.target),toTarget:x(m.toTarget)}))},y=g(v=>v!==void 0&&u.has(v)?"":v),h=v=>{if(l.sourceData?.[v]!==void 0)return l.sourceData[v];try{return Le(v)}catch{return}};for(let v of u.keys()){if(bn(y,v))return;let x=v.replace(ve,(b,m)=>h(m)??b);if(x!==v&&bn(y,x))return}for(let v of u.keys())for(let[x]of v.matchAll(/<[^<>]+>|\{(?:data|env):[^{}]+\}/g))if(wt(y,x))return;if(l.examples){let v={...l.examples};for(let[x,b]of u){let m=x.match(/^<([^<>]+)>$/)?.[1];if(m!==void 0&&m in v)v[m]=b;else if(/<[^<>]+>/.test(x))return}if(sr(l.actions,l.gherkin,l.examples,v,l.recordedAt,l.sourceData))return}let S={...l,gherkin:t.text,actions:g(v=>v!==void 0&&u.has(v)?u.get(v):v)};return yu(S,t,n)?S:void 0}function vu(e,t){let n=[];return e.forEach((r,s)=>{if(r.actions.length!==0&&!(t.steps.has(r.gherkin)||t.bare.has(me(r.gherkin)))){for(let o of t.steps.values())if(!(o.variants>1)&&o.actions.length!==0&&Jt(o.gherkin)===Jt(r.gherkin)&&Fa(r.actions,o.actions)){n.push({index:s,from:r.gherkin,to:o.gherkin,feature:o.feature,scenario:o.scenario});break}}}),n}function La(e){return Gt(e,Wt)}function rn(e,t,n,r){let s=No.isAbsolute(t)?t:No.join(e,t),o=La(s),a=n??Vt(o.filter(y=>y.endsWith(".saffron")),e),i=new Map,c=new Map;for(let y of o)for(let h of r?.get(y)??nt(y,e,a)){let S=`${h.featurePath}::${h.name}`;for(let v of h.steps){let x=me(v.text),b=i.get(x);if(b||(b={text:x,prefixed:new Set,keywords:new Map,kind:v.kind,scenarios:new Set,files:new Set,fromStepSet:v.source?.fromStepSet},i.set(x,b)),v.text!==x&&b.prefixed.add(v.text),b.keywords.set(v.keyword,(b.keywords.get(v.keyword)??0)+1),b.scenarios.add(S),v.source&&b.files.add(v.source.file),v.source?.fromStepSet){let m=c.get(v.source.fromStepSet);m||c.set(v.source.fromStepSet,m=new Set),m.add(S)}}}let l=nn(e),d=new Map;for(let[y,h]of l.seeds){let S=me(h.gherkin),v=d.get(S)??{};v[y]=h.variants>1?"divergent":"recorded",d.set(S,v)}for(let[y,h]of yw(e)){let S=me(y.slice(y.indexOf(`
|
|
18
|
+
`)+1));d.set(S,{...d.get(S),[y]:h})}let u=y=>d.get(me(y))?.[Sn(tt([y])[0],y)]??"unrecorded",p=y=>{let h=Object.values(d.get(y)??{});return h.includes("divergent")?"divergent":h.length?"recorded":"unrecorded"},f=[...i.values()].map(y=>({text:y.text,keyword:[...y.keywords.entries()].sort((h,S)=>S[1]-h[1])[0][0],kind:y.kind,status:p(y.text),recordings:d.get(y.text)??{},...y.prefixed.size?{sessions:Object.fromEntries([...y.prefixed].sort().map(h=>[h,u(h)]))}:{},usage:y.scenarios.size,files:[...y.files].sort(),fromStepSet:y.fromStepSet})).sort((y,h)=>h.usage-y.usage||y.text.localeCompare(h.text)),g=[...a.values()].map(y=>({name:y.name,file:y.file,line:y.line,steps:y.steps.map(h=>h.text),usage:c.get(y.name)?.size??0})).sort((y,h)=>h.usage-y.usage||y.name.localeCompare(h.name));return{steps:f,stepSets:g,scannedFiles:o.length,scannedCaches:l.scannedCaches}}function yw(e){let t=No.join(e,".saffron","cache"),n=new Map;if(!Su.existsSync(t))return new Map;for(let r of Su.readdirSync(t,{recursive:!0})){if(!String(r).endsWith(".json"))continue;let s=tn(No.join(t,String(r)));if(!s)continue;let o=tt(s.steps.map(a=>a.gherkin));s.steps.forEach((a,i)=>{if(!o[i]?.match(/<[^<>]+>/))return;let c=Sn(o[i],a.gherkin),l=n.get(c)??new Set;l.add(JSON.stringify(a.actions.map(({pageFingerprint:d,...u})=>u))),n.set(c,l)})}return new Map([...n].map(([r,s])=>[r,s.size>1?"divergent":"recorded"]))}function Mo(e,t){let n=t.toLowerCase();return{...e,steps:e.steps.filter(r=>r.text.toLowerCase().includes(n)),stepSets:e.stepSets.filter(r=>r.name.toLowerCase().includes(n)||r.steps.some(s=>s.toLowerCase().includes(n)))}}function $u(e){let t={},n="saffron,feature,gherkin,cucumber";for(let r of e.steps)t[`step: ${r.text}`]={scope:n,prefix:r.text,body:[r.text.replace(/\$/g,"\\$")],description:`${r.status} \xB7 used in ${r.usage} scenario(s)`};for(let r of e.stepSets)t[`StepSet: ${r.name}`]={scope:n,prefix:`StepSet ${r.name}`,body:[`StepSet ${r.name}`],description:`step set (${r.steps.length} steps) in ${r.file}`};return JSON.stringify(t,null,2)+`
|
|
19
|
+
`}import{Server as mx}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as wx}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as yx,ListToolsRequestSchema as bx}from"@modelcontextprotocol/sdk/types.js";import dn from"node:fs";import $t from"node:path";import ku from"node:fs";import bw from"node:path";function _e(e){bd(e);let t=bw.join(e,"saffron.config.json"),n=ku.existsSync(t)?JSON.parse(ku.readFileSync(t,"utf8")):{};return typeof n.features=="string"&&!n.features.trim()&&(n.features=Fr.features),Ut(e,n.dataDir,process.env.SAFFRON_ENV??n.env),Id(n.dateLocale,n.timezone),n}var Fr={provider:"claude",features:"features",dataDir:"data",actionTimeoutMs:5e3,pollIntervalMs:100,retries:1,screenshot:"viewport",maxTurns:100,strict:!1,verifyProposals:!0,snapshotMode:"none",reuseSteps:!0,browser:"chromium",workers:1,agentWorkers:1,assertionPolicy:"strict",hookTimeoutMs:3e5,trace:"off"};function Ru(e){return{...Fr,...Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}}import Do from"node:fs";import Lr from"node:path";import{fileURLToPath as Tu}from"node:url";function Au(e,t){for(let n=0;n<6;n++){let r=Lr.join(e,"package.json");if(Do.existsSync(r))try{if(JSON.parse(Do.readFileSync(r,"utf8")).name===t)return e}catch{}e=Lr.dirname(e)}}function bs(){return Au(Lr.dirname(Tu(import.meta.url)),"saffron-ai")}function Eu(e){try{let t=Au(Lr.dirname(Tu(import.meta.resolve(e))),e),n=t&&JSON.parse(Do.readFileSync(Lr.join(t,"package.json"),"utf8")).version;return typeof n=="string"?n:void 0}catch{return}}function ut(){let e=bs();if(!e)return"unknown";try{return JSON.parse(Do.readFileSync(Lr.join(e,"package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}import bt from"node:fs";import Qe from"node:path";import Ze from"node:fs";import{createHash as xw}from"node:crypto";import Ou from"node:os";import Br from"node:path";function _u(e,t){Ze.mkdirSync(Br.dirname(e),{recursive:!0});let n=Buffer.from(`${JSON.stringify(t,null,2)}
|
|
20
|
+
`);return Ur(e,()=>Ue(e,n)),za(n)}var vw=6e4,Sw=5e3,$w=60*6e4,kw=new Int32Array(new SharedArrayBuffer(4)),cr=class extends Error{};function Ur(e,t,n=1e4){let r=`${e}.lock`,s=Date.now()+n,o;for(;;){o=JSON.stringify({pid:process.pid,host:Ou.hostname(),at:new Date().toISOString()});try{Ze.writeFileSync(r,o,{flag:"wx"});break}catch(a){let i=a.code,c=i==="EPERM"&&process.platform==="win32";if(i!=="EEXIST"&&!c)throw a;if(Date.now()>=s)throw c?a:new cr(`${e} is being decided by another process. Try again.`);Rw(r)||Atomics.wait(kw,0,0,25)}}try{return t()}finally{Ba(r)===o&&Ze.rmSync(r,{force:!0})}}function Ba(e){try{return Ze.readFileSync(e,"utf8")}catch{return}}function Rw(e){let t=Ba(e);if(t===void 0)return!1;let n={};try{n=JSON.parse(t)||{}}catch{}let r=Date.parse(n.at??""),s=vw;if(Number.isNaN(r)){try{r=Ze.statSync(e).mtimeMs}catch{return!1}s=Sw}let o=n.host===Ou.hostname()&&typeof n.pid=="number";return o&&Tw(n.pid)&&Date.now()-r<$w||!o&&Date.now()-r<s||Ba(e)!==t?!1:(Ze.rmSync(e,{force:!0}),!0)}function Tw(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function Fo(e,t,n){return Ze.existsSync(e)?Ur(e,()=>Ze.existsSync(e)?t():n()):n()}function Ua(e){let t=/^(.+)#([0-9a-f]{64})$/i.exec(e);return t?{file:t[1],revision:t[2].toLowerCase()}:{file:e}}function jt(e){return za(Ze.readFileSync(e))}var za=e=>xw("sha256").update(e.includes(13)?Buffer.from(e.toString("utf8").replace(/\r\n/g,`
|
|
21
|
+
`)):e).digest("hex"),Cu=e=>Br.join(e,".saffron","reports","filed.json");function Pu(e){let t;try{t=JSON.parse(Ze.readFileSync(Cu(e),"utf8"))}catch{return{}}return!t||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,n])=>typeof n=="string"))}function Iu(e,t,n){return Pu(e)[He(e,t)]===n}function ju(e,t,n){let r=Pu(e);r[He(e,t)]=n;for(let[s,o]of Object.entries(r)){try{if(jt(Br.join(e,s))===o)continue}catch{}delete r[s]}Ue(Cu(e),`${JSON.stringify(r,null,2)}
|
|
22
|
+
`)}function zr(e){return Lo(e).proposal}function Lo(e){return qa(Ze.readFileSync(e),e)}function qa(e,t){let n;try{n=JSON.parse(e.toString("utf8"))}catch(r){throw new ke(t,`is not valid JSON: ${r instanceof Error?r.message:String(r)}`)}return su(n,t),{proposal:n,revision:za(e),bytes:e}}function sn(e,t){let n=Br.join(e,".saffron","proposals");if(!Ze.existsSync(n))return[];let r=[];for(let s of Ze.readdirSync(n)){let o=Br.join(n,s);if(Ze.statSync(o).isDirectory())for(let a of Ze.readdirSync(o)){if(!a.endsWith(".json"))continue;let i=Br.join(o,a);try{r.push({file:i,...Lo(i)})}catch(c){if(!t||!(c instanceof ke))throw c;t(i,c.problem)}}}return r}function Bo(e,t){let n=zr(t),r=pe(e,n.cache.feature,n.cache.scenario);return Dr(r,n.cache),Ze.rmSync(t),r}function Uo(e){Ze.rmSync(e)}var Ha=(e,t)=>Qe.relative(e,t).split(Qe.sep).join("/");function Nu(e){return bt.existsSync(e)?[...bt.readdirSync(e,{recursive:!0})].map(String).filter(t=>t.endsWith(".json")).map(t=>Qe.join(e,t)).sort():[]}function Mu(e){try{let t=JSON.parse(bt.readFileSync(e,"utf8")),n="cache"in t&&t.cache?t.cache:t;return{feature:n.feature,scenario:n.scenario}}catch{return{}}}function Du(e){try{let t=JSON.parse(bt.readFileSync(Qe.join(e,ar),"utf8"));return{feature:typeof t.feature=="string"?t.feature:void 0,scenario:typeof t.scenario=="string"?t.scenario:void 0}}catch{return{}}}function qo(e,t,n){let r=Qe.isAbsolute(t)?t:Qe.join(e,t),s=new Set(Gt(r,Wt));for(let l of["cache","proposals"])for(let d of Nu(Qe.join(e,".saffron",l))){let{feature:u}=Mu(d);if(typeof u=="string"){let p=Qe.resolve(e,u);bt.existsSync(p)&&s.add(p)}}for(let l of zo(Qe.join(e,".saffron","artifacts")))for(let d of zo(l)){let u=Du(d).feature;if(u){let p=Qe.resolve(e,u);bt.existsSync(p)&&s.add(p)}}let o=[...n?.unreadable??[]],a=[...s].filter(l=>!n?.parsedFiles.has(l)),i=new Map;if(a.length>0)try{i=Vt([...new Set([...yn(r),...s].filter(l=>l.endsWith(".saffron")))],e)}catch(l){o.push(l instanceof Error?l.message:String(l))}let c=new Set(n?.owned??[]);for(let l of a){let d;try{d=nt(l,e,i)}catch(u){o.push(`${Ha(e,l)}: ${u instanceof Error?u.message:String(u)}`);continue}for(let u of d)c.add(pe(e,u.featurePath,u.name)),c.add(dt(e,u.featurePath,u.name)),c.add(vn(e,u.featurePath,u.displayName))}return{...Aw(e,c),unreadable:o}}function Aw(e,t){let n=[],r=0;for(let o of["cache","proposal"]){let a=Qe.join(e,".saffron",o==="cache"?"cache":"proposals");for(let i of Nu(a)){if(t.has(i)){r++;continue}let{feature:c,scenario:l}=Mu(i),d=c?Qe.join(e,c):void 0;n.push({file:Ha(e,i),kind:o,feature:c,scenario:l,reason:c?bt.existsSync(d)?"scenario-gone":"feature-gone":"unknown"})}}let s=Qe.join(e,".saffron","artifacts");for(let o of zo(s))for(let a of zo(o)){let{feature:i,scenario:c}=Du(a),l=i&&c?vn(e,i,c):void 0;if(t.has(a)||l&&t.has(l)&&l!==a&&!bt.existsSync(l)){r++;continue}n.push({file:Ha(e,a),kind:"artifact",feature:i,scenario:c,reason:i?bt.existsSync(Qe.join(e,i))?"scenario-gone":"feature-gone":"unknown"})}return{orphans:n,kept:r}}function zo(e){try{return bt.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>Qe.join(e,t.name)).sort()}catch{return[]}}function Fu(e,t){let n=[],r=new Set;for(let s of t){let o=Qe.join(e,s.file);try{s.kind==="proposal"?Ur(o,()=>bt.rmSync(o)):bt.rmSync(o,{recursive:s.kind==="artifact"}),n.push(s.file),r.add(Qe.dirname(o))}catch{}}for(let s of r)try{bt.readdirSync(s).length===0&&bt.rmdirSync(s)}catch{}return n}function Lu(e){if(e.kind==="artifact")return`${e.file}/
|
|
23
23
|
failure screenshots of a scenario that no longer exists`;let t=e.feature&&e.scenario?`${e.feature} \u203A ${e.scenario}`:"an unreadable recording",n=e.reason==="feature-gone"?"the feature file is gone":e.reason==="scenario-gone"?"the scenario is gone from that file":"it names no scenario";return`${e.file}
|
|
24
|
-
${e.kind==="proposal"?"pending proposal for ":""}${t}: ${n}`}import
|
|
24
|
+
${e.kind==="proposal"?"pending proposal for ":""}${t}: ${n}`}import wc from"node:fs";import js from"node:path";import{createHash as Ew,randomBytes as Ow}from"node:crypto";var Ho=/\{unique:([A-Za-z0-9_-]+)(?::(digits))?\}/g,Nt="__saffron_unique_seed",$n=()=>`${Date.now().toString(36)}${Ow(4).toString("hex")}`;function Bu(e,t,n=!1){let r=Ew("sha1").update(`${e}:${t}`).digest();if(n){let o=r.readUInt32BE(0)*65536+r.readUInt16BE(4);return String(1e8+o%9e8)}let s=BigInt(`0x${r.subarray(0,8).toString("hex")}`).toString(36).padStart(9,"0").slice(-9);return`${"abcdefghijklmnopqrstuvwxyz"[r[8]%26]}${s}`}function on(e,t){return e.replace(Ho,(n,r,s)=>Bu(t,r,s==="digits"))}function qr(e,t){let n=new Map;for(let r of e)if(r)for(let s of r.matchAll(Ho))n.set(s[0],Bu(t,s[1],s[2]==="digits"));return n}function Uu(e,t){let n=e;for(let[r,s]of t)n=n.split(s).join(r);return n}import{createHash as _w}from"node:crypto";async function Jo(e){let t;try{t=await e.locator("body").ariaSnapshot({timeout:3e3})}catch{return"sha256:unavailable"}let n=t.replace(/\d+/g,"#").replace(/\s+/g," ").trim();return`sha256:${_w("sha256").update(n).digest("hex")}`}var Cw=/^[a-z][a-z\d+.-]*:|^\/\//i,zu=e=>e.pathname.replace(/\/+$/,"");function xs(e,t){if(!t)return e;let n,r;try{n=new URL(e),r=new URL(t)}catch{return e}if(n.origin!==r.origin)return e;let s=zu(r),o=n.pathname,a;if(o===r.pathname||o===s||o===`${s}/`)a="/";else if(o.startsWith(`${s}/`))a=o.slice(s.length);else return e;let i=n.search===r.search?"":n.search||"?",c=a!=="/"?n.hash:n.hash===r.hash?"":n.hash||(r.hash?"#":"");return`${a}${i}${c}`}function Ja(e,t){if(Cw.test(e))return e;if(!t)throw new Error(`relative navigation "${e}" needs a base URL (set baseURL or pass --base-url)`);let n=new URL(t),r=e.indexOf("#"),s=r>=0?e.slice(r):void 0,o=r>=0?e.slice(0,r):e,a=o.indexOf("?"),i=a>=0?o.slice(a):void 0,c=a>=0?o.slice(0,a):o,l=c===""||c==="/",d=new URL(n.href);return d.pathname=l?n.pathname:`${zu(n)}${c.startsWith("/")?c:`/${c}`}`,d.search=i===void 0?n.search:i==="?"?"":i,d.hash=s==="#"?"":s!==void 0?s:l?n.hash:"",d.toString()}import Va from"node:fs";import Pw from"node:os";import xt from"node:path";import{Client as Iw}from"@modelcontextprotocol/sdk/client/index.js";import{AjvJsonSchemaValidator as jw}from"@modelcontextprotocol/sdk/validation/ajv";import{StdioClientTransport as Nw}from"@modelcontextprotocol/sdk/client/stdio.js";import{McpServer as Mw}from"@modelcontextprotocol/sdk/server/mcp.js";import{CallToolRequestSchema as Dw,ListToolsRequestSchema as Fw}from"@modelcontextprotocol/sdk/types.js";var Ga=6e4;function Ju(){return Va.mkdtempSync(xt.join(Pw.tmpdir(),"saffron-mcp-"))}var Ka=1e8,Vu=new Set(["browser_navigate","browser_click","browser_type","browser_press_sequentially","browser_fill_form","browser_select_option","browser_check","browser_uncheck","browser_press_key","browser_hover","browser_drag","browser_file_upload","browser_handle_dialog","browser_tabs","browser_snapshot","browser_find","browser_wait_for","browser_take_screenshot","browser_console_messages","browser_network_requests","browser_network_request","browser_evaluate"]);function Lw(e){return{...e,tools:e.tools.filter(t=>Vu.has(t.name))}}function Bw(e){return Vu.has(e)?void 0:{isError:!0,content:[{type:"text",text:`${e} is not available in a Saffron session.`}]}}var vs=e=>({isError:!0,content:[{type:"text",text:e}]}),Uw=new Set(["http:","https:"]);function Ss(e){if(typeof e!="string"||/^localhost(:\d+)?(\/|$)/i.test(e))return;let t=`${e} is not a web page; a Saffron session only opens http(s) URLs.`,n;try{n=new URL(e)}catch{return/^[a-z][a-z\d+.-]*:/i.test(e.replace(/^[\u0000- ]+/,"").replace(/[\t\n\r]/g,""))?t:void 0}return Uw.has(n.protocol)||n.href==="about:blank"?void 0:t}function Ya(e,t){if(!Array.isArray(e))return;let n=a=>{try{return Va.realpathSync(a)}catch{return}},r=n(t)??xt.resolve(t),s=a=>{let i=xt.relative(r,a);return i.startsWith("..")||xt.isAbsolute(i)?void 0:i},o=a=>a.split(xt.sep).some(i=>i.startsWith(".")&&i!=="..");for(let a of e){if(typeof a!="string")continue;let i=xt.resolve(a),c=n(i),l=n(xt.dirname(i)),d=s(c??(l?xt.join(l,xt.basename(i)):i));if(d===void 0&&!c&&!l){let u=xt.relative(xt.resolve(t),i);!u.startsWith("..")&&!xt.isAbsolute(u)&&(d=u)}if(d===void 0)return`${a} is outside the project; uploads come from files inside it.`;if(o(d)||o(xt.relative(xt.resolve(t),i)))return`${a} is a hidden file; a Saffron session does not upload dotfiles.`;if(!c)return`${a} does not exist; uploads come from files inside the project.`;if(Va.statSync(c).isDirectory())return`${a} is a folder; a Saffron session uploads single files only.`}}function qu(e,t,n=process.cwd()){if(!t)return{args:t};let r=e==="browser_navigate"||e==="browser_tabs"?Ss(t.url):e==="browser_file_upload"?Ya(t.paths,n):void 0;if(r)return{args:t,refused:vs(r)};if(e==="browser_tabs"&&t.isolatedContext!==void 0)return{args:t,refused:vs(`isolatedContext is not available in a Saffron session: open the tab in the scenario's own context. Another person's browser is an As "name" step.`)};if("filename"in t){let{filename:s,...o}=t;return{args:o}}return{args:t}}var zw=/^### (?:Ran Playwright code|Open tabs|Events)\r?$/;function qw(e,t=Ga){if(!Array.isArray(e.content)||e.content.reduce((o,a)=>o+(a.type==="text"&&typeof a.text=="string"?a.text.length:0),0)<=t)return e;let r=t,s=e.content.map(o=>{if(o.type!=="text"||typeof o.text!="string")return o;let a=o.text;if(a.length<=r)return r-=a.length,o;let i=[...a.matchAll(/^### .*$/gm)],c=i.map((p,f)=>({start:p.index,stop:i[f+1]?.index??a.length,recorded:zw.test(p[0])})),l=r;for(let p of c)p.recorded&&p.start<l&&p.stop>l&&(l=p.start);l>0&&/[\uD800-\uDBFF]/.test(a[l-1])&&(l-=1),r-=l;let d=c.filter(p=>p.recorded&&p.start>=l).map(p=>a.slice(p.start,p.stop).trimEnd()),u=`
|
|
25
25
|
|
|
26
|
-
[Saffron cut this result at ${l} of ${a.length} characters: whole, it would not fit the agent's context. Ask for less: a snapshot of one region, a filtered request list, or a saffron_assert on the field you need instead of the whole body.]`;return{...o,text:a.slice(0,l)+
|
|
26
|
+
[Saffron cut this result at ${l} of ${a.length} characters: whole, it would not fit the agent's context. Ask for less: a snapshot of one region, a filtered request list, or a saffron_assert on the field you need instead of the whole body.]`;return{...o,text:a.slice(0,l)+u+d.map(p=>`
|
|
27
27
|
|
|
28
|
-
${p}`).join("")}});return{...e,content:s}}function
|
|
29
|
-
`).filter(l=>l.trim()!==""&&!/^(?:Error: )?download\.saveAs: /.test(l)&&!/^\s+at /.test(l)).length>0?o:(t=!0,{...o,text:o.text.slice(0,i.index)+o.text.slice(i.index+i[0].length)})});if(!t)return e;let{isError:r,...s}=e;return{...s,content:n}}async function fu(e,t,n={}){let r=new Lm({name:"saffron-cap",version:"1"}),s=Object.fromEntries(Object.entries(process.env).filter(a=>a[1]!==void 0));await r.connect(new Um({...e,env:s,stderr:"ignore"}));let o=Aa(r,void 0,t,n);return{config:{type:"sdk",name:"playwright",instance:o},close:async()=>{await Promise.allSettled([r.close(),o.close()])}}}function Aa(e,t=(s,o,a)=>a(),n,r={}){let s=new zm({name:"playwright",version:"1"},{capabilities:{tools:{}}});return s.server.setRequestHandler(qm,async()=>Vm(await e.listTools())),s.server.setRequestHandler(Hm,async(o,a)=>{let i=Jm(o.params.name);if(i)return i;let c=Gm(o.params.name,o.params.arguments,n);if(c.refused)return c.refused;let l={...o.params,arguments:c.args};return Ym(await t(l.name,l.arguments,async()=>{let d=async w=>Zm(await e.callTool(w,void 0,{timeout:Ra,signal:a.signal})),f=l.arguments?.fields,p=l.name==="browser_fill_form"&&Array.isArray(f)&&f.length>1,u=(l.name==="browser_type"||l.name==="browser_press_sequentially")&&l.arguments?.submit===!0;if(!p&&!u)return d(l);let h=(await e.listTools()).tools.find(w=>w.name===l.name);if(!h)return Oo(`${l.name} is not available in this browser session.`);let b=new Bm().getValidator(h.inputSchema)(l.arguments);if(!b.valid)return Oo(`Invalid ${l.name} arguments: ${b.errorMessage}`);let g=p?f.map(w=>({...l,arguments:{...l.arguments,fields:[w]}})):[{...l,arguments:{...l.arguments,submit:!1}},l.name==="browser_type"?{...l,arguments:{...l.arguments,text:"",slowly:!0,submit:!0}}:{name:"browser_press_key",arguments:{key:"Enter"}}],S=[],y=!1;try{for(let w of g){a.signal.throwIfAborted(),r.beforeAction?.();let v=await d(w);if(v.isError)return v;S.push(v)}return y=!0,{...S.at(-1),content:S.flatMap(w=>Array.isArray(w.content)?w.content:[])}}finally{if(!y)for(let w of S)r.onPartialResult?.(w)}}))}),s}import us from"node:fs";import rw from"node:os";import Ea from"node:path";import wt from"node:fs";import Qm from"node:path";import{createHash as Xm,randomBytes as ew}from"node:crypto";import Po from"node:zlib";var In=4294967295,gu=67324752,hu=33639248,mu=101010256;function wu(e){return ds(e).map(t=>({name:t.name,data:t.read()}))}function yu(e,t){let n=Math.max(0,t-22-65535),r=e(n,t-n),s=-1;for(let l=r.length-22;l>=0;l--)if(r.readUInt32LE(l)===mu){s=l;break}if(s<0)throw new Error("not a zip file: no central directory");let o=r.readUInt16LE(s+10),a=e(r.readUInt32LE(s+16),r.readUInt32LE(s+12)),i=0,c=[];for(let l=0;l<o;l++){if(a.readUInt32LE(i)!==hu)throw new Error("not a zip file: bad central directory entry");let d=a.readUInt16LE(i+10),f=a.readUInt32LE(i+16),p=a.readUInt32LE(i+20),u=a.readUInt32LE(i+24),h=a.readUInt16LE(i+28),b=a.readUInt16LE(i+30),g=a.readUInt16LE(i+32),S=a.readUInt32LE(i+42),y=a.subarray(i+46,i+46+h).toString("utf8");i+=46+h+b+g;let w=e(S,30);if(w.length<30||w.readUInt32LE(0)!==gu)throw new Error(`not a zip file: bad local header for ${y}`);let v=S+30+w.readUInt16LE(26)+w.readUInt16LE(28);if(!y.endsWith("/")){if(d!==0&&d!==8)throw new Error(`zip entry ${y} uses compression method ${d}, which is not supported`);c.push({name:y,method:d,crc:f,size:u,compressedSize:p,start:v})}}return c}function ds(e){return yu((t,n)=>e.subarray(t,t+n),e.length).map(({name:t,method:n,crc:r,size:s,compressedSize:o,start:a})=>{let i=e.subarray(a,a+o);return{name:t,method:n,crc:r,size:s,raw:i,read:()=>n===0?Buffer.from(i):Po.inflateRawSync(i)}})}function tw(e,t,n){let r=wt.openSync(e,"r");try{let s=Buffer.alloc(n),o=0;for(;o<n;){let a=wt.readSync(r,s,o,n-o,t+o);if(a===0)break;o+=a}return s.subarray(0,o)}finally{wt.closeSync(r)}}function bu(e){let t=wt.statSync(e).size,n=(r,s)=>tw(e,r,Math.max(0,Math.min(s,t-r)));return yu(n,t).map(r=>({...r,raw:()=>n(r.start,r.compressedSize)}))}var nw=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n>>>0}return e})();function Co(e,t=0){let n=Po.crc32;if(n)return n(e,t)>>>0;let r=(t^4294967295)>>>0;for(let s of e)r=nw[(r^s)&255]^r>>>8;return(r^4294967295)>>>0}var pu=1024*1024;function vu(e,t){let n=wt.openSync(e,"r");try{let r=Buffer.alloc(pu);for(let s;(s=wt.readSync(n,r,0,pu,null))>0;)t(r.subarray(0,s))}finally{wt.closeSync(n)}}function Io(e){let t=Xm("sha256"),n=0,r=0;return vu(e,s=>{n=Co(s,n),r+=s.length,t.update(s)}),{crc:n,size:r,sha256:t.digest("hex")}}function xu(e,t,n,r,s,o){let a=Buffer.alloc(30);a.writeUInt32LE(gu,0),a.writeUInt16LE(20,4),a.writeUInt16LE(2048,6),a.writeUInt16LE(t,8),a.writeUInt32LE(0,10),a.writeUInt32LE(n,14),a.writeUInt32LE(r,18),a.writeUInt32LE(s,22),a.writeUInt16LE(e.length,26),a.writeUInt16LE(0,28);let i=Buffer.alloc(46);return i.writeUInt32LE(hu,0),i.writeUInt16LE(20,4),i.writeUInt16LE(20,6),i.writeUInt16LE(2048,8),i.writeUInt16LE(t,10),i.writeUInt32LE(0,12),i.writeUInt32LE(n,16),i.writeUInt32LE(r,20),i.writeUInt32LE(s,24),i.writeUInt16LE(e.length,28),i.writeUInt16LE(0,30),i.writeUInt16LE(0,32),i.writeUInt16LE(0,34),i.writeUInt16LE(0,36),i.writeUInt32LE(0,38),i.writeUInt32LE(o,42),{local:a,central:i}}function Su(e,t,n){let r=Buffer.alloc(22);return r.writeUInt32LE(mu,0),r.writeUInt16LE(0,4),r.writeUInt16LE(0,6),r.writeUInt16LE(e,8),r.writeUInt16LE(e,10),r.writeUInt32LE(t,12),r.writeUInt32LE(n,16),r.writeUInt16LE(0,20),r}var $u=e=>new Error(`cannot write a zip of ${e} files: one holds at most 65,535`),ku=e=>new Error(`cannot write ${e} into a zip: a zip holds at most 4 GB, and this one would be larger`),Ru=()=>new Error("cannot write the zip: a zip holds at most 4 GB, and this one would be larger");function Tu(e){if(e.length>65535)throw $u(e.length);let t=[],n=[],r=0;for(let o of e){let a="raw"in o,i=a?o.raw:Po.deflateRawSync(o.data),c=a?o.size:o.data.length,l=Buffer.from(o.name,"utf8");if(c>In||r+30+l.length+i.length>In)throw ku(o.name);let{local:d,central:f}=xu(l,a?o.method:8,a?o.crc:Co(o.data),i.length,c,r);t.push(d,l,i),n.push(f,l),r+=d.length+l.length+i.length}let s=n.reduce((o,a)=>o+a.length,0);if(r+s>In)throw Ru();return Buffer.concat([...t,...n,Su(e.length,s,r)])}function Nr(e,t){for(let n=0;n<t.length;)n+=wt.writeSync(e,t,n,t.length-n)}function Au(e,t){if(t.length>65535)throw $u(t.length);wt.mkdirSync(Qm.dirname(e),{recursive:!0});let n=`${e}.${process.pid}-${ew(4).toString("hex")}.partial`,r=wt.openSync(n,"w");try{let s=[],o=0;for(let i of t){let c=Buffer.from(i.name,"utf8"),l="file"in i,d=l&&(i.crc===void 0||i.size===void 0)?Io(i.file):void 0,f=l?void 0:Po.deflateRawSync(i.data),p=l?d?.crc??i.crc:Co(i.data),u=l?d?.size??i.size:i.data.length,h=f?.length??u;if(u>In||o+30+c.length+h>In)throw ku(i.name);let{local:b,central:g}=xu(c,l?0:8,p,h,u,o);if(Nr(r,b),Nr(r,c),f)Nr(r,f);else{let S=0,y=0;if(vu(i.file,w=>{S+w.length>u||(Nr(r,w),S+=w.length,y=Co(w,y))}),S!==u||y!==p)throw new Error(`${i.name} changed while it was being packed`)}s.push(g,c),o+=b.length+c.length+h}let a=s.reduce((i,c)=>i+c.length,0);if(o+a>In)throw Ru();for(let i of s)Nr(r,i);Nr(r,Su(t.length,a,o)),wt.closeSync(r),wt.renameSync(n,e)}catch(s){try{wt.closeSync(r)}catch{}throw wt.rmSync(n,{force:!0}),s}}var _a=["off","on","retain-on-failure"],Oa="trace.zip";async function _u(e,t){await e.tracing.start({screenshots:!0,snapshots:!0,sources:!1,title:t})}async function No(e,t){t&&us.mkdirSync(Ea.dirname(t),{recursive:!0}),await e.tracing.stop(t?{path:t}:void 0)}async function jo(e,t,n){let r;try{r=us.mkdtempSync(Ea.join(rw.tmpdir(),"saffron-trace-"));let s=Ea.join(r,Oa);await e.tracing.stop({path:s});let o=hw(us.readFileSync(s),n);return Je(t,o),zt(o)}catch{try{us.rmSync(t,{force:!0})}catch{console.warn("Could not remove the execution trace artifact.")}console.warn("Could not save the execution trace; no trace was attached to this run.");return}finally{if(r)try{us.rmSync(r,{recursive:!0,force:!0})}catch{console.warn("Could not remove the private temporary trace directory.")}}}async function Ou(e,t,n,r){if(!t)return r();let s=e.context().tracing;await s.group(n).catch(()=>{});try{return await r()}finally{await s.groupEnd().catch(()=>{})}}var sw=new Set(["callId","parentId","pageId","frameId","contextId","pageref","_frameref","snapshotName","beforeSnapshot","afterSnapshot","inputSnapshot","sha1","_sha1"]),ow=new Set(["before","action","after"]),iw=/^\[saffron:(?:agent|replay|pending|action):-?\d+\] /,aw=new Set(["type","class","method"]),cw=new Set(["__playwright_bounding_rect__","__playwright_scroll_top_","__playwright_scroll_left_","__playwright_target__","__playwright_checked_","__playwright_selected_","__playwright_popover_open_","__playwright_dialog_open_","__playwright_shadow_root_","__playwright_custom_elements__"]),lw=new Set(["style","__playwright_style_sheet_"]),dw=new Set(["srcset","imagesrcset"]),uw=/^(?:image\/(?!svg)|font\/|audio\/|video\/)/i,fw=/\.(?:jpe?g|png|gif|webp|avif|bmp|ico|woff2?|ttf|otf|eot|mp3|mp4|m4a|wav|ogg|webm)$/i,pw=/^text\/css\b/i,gw=/\.css$/i;function hw(e,t){let n=Rn(t,{encodings:!0});if(n.empty)return e;let r=Rn(t,{encodings:!0,bytes:!0}),s=ds(e),o=new Set(s.filter(u=>u.name.includes("/")).map(u=>u.name));for(let u of s)u.name.startsWith("resources/")&&o.add(u.name.slice(10));let a={names:o,pieces:Tw(t)},i=new Set,c=new Set,l=u=>{for(let h of[u.snapshot?.response?.content,u.snapshot?.request?.postData]){if(!h)continue;let b=h._file??(h._sha1&&`resources/${h._sha1}`);if(!b)continue;let g=String(h.mimeType??"");uw.test(g)?i.add(b):pw.test(g)&&c.add(b)}},d=[...s],f=!1,p=(u,h)=>{h&&(d[u]={name:s[u].name,data:h},f=!0)};return s.forEach((u,h)=>{/\.(?:trace|network)$/.test(u.name)?p(h,mw(u.read(),n,a,u.name.endsWith(".network")?l:void 0)):u.name.endsWith(".stacks")&&p(h,ww(u.read(),n,a))}),s.forEach((u,h)=>{/\.(?:trace|network|stacks)$/.test(u.name)||i.has(u.name)||fw.test(u.name)||p(h,yw(u.read(),n,r,c.has(u.name)||gw.test(u.name)))}),f?Tu(d):e}function mw(e,t,n,r){let s=e.toString("utf8").split(`
|
|
30
|
-
`),
|
|
31
|
-
`),"
|
|
32
|
-
`)
|
|
33
|
-
`),r=[];for(let s of n){if(!s.
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
`)
|
|
37
|
-
`)}var Ua=e=>new Promise(t=>setTimeout(t,e)),Da=class{entries=[];lastMatch;seq=0;prevStepSeq=0;curStepSeq=0;requestSeq=0;actionSeq=0;requests=new WeakMap;onRequest=t=>{let n=t.redirectedFrom();this.requests.set(t,n?this.requests.get(n)??0:++this.requestSeq);let r=t.resourceType?.();(r==="fetch"||r==="xhr")&&this.inFlight.add(t)};inFlight=new Set;onDone=t=>{this.inFlight.delete(t)};async quiet(t){let n=Date.now()+t;for(await new Promise(r=>setTimeout(r,Math.min(150,t)));this.inFlight.size>0&&Date.now()<n;)await new Promise(r=>setTimeout(r,25))}listener;context;attach(t,n){this.context=t,this.listener=r=>{let s={seq:++this.seq,requestSeq:this.requests.get(r.request())??0,url:r.url(),method:r.request().method(),status:r.status()};if(this.entries.push(s),n){let o=r.headers()["content-type"]??"";/json|text|xml/i.test(o)&&r.text().then(a=>{s.body=a}).catch(()=>{})}},t.on("request",this.onRequest),t.on("response",this.listener),t.on("requestfinished",this.onDone),t.on("requestfailed",this.onDone)}detach(){this.context&&this.listener&&(this.context.off("response",this.listener),this.context.off("request",this.onRequest),this.context.off("requestfinished",this.onDone),this.context.off("requestfailed",this.onDone))}markStep(){this.prevStepSeq=this.curStepSeq,this.curStepSeq=this.seq}sincePreviousStep(){return this.entries.filter(t=>t.seq>this.prevStepSeq)}markAction(){this.actionSeq=this.requestSeq}sinceAction(){return this.entries.filter(t=>t.requestSeq>this.actionSeq)}all(){return this.entries}};function Cw(e,t){if(!t)return e>=200&&e<300;let n=/^([1-5])xx$/i.exec(t.trim());if(n){let r=Number(n[1])*100;return e>=r&&e<r+100}return e===Number(t.trim())}function Bu(e,t,n,r,s){return!(!t.test(e.url)&&!t.test(La(e.url))||n&&e.method.toUpperCase()!==n.toUpperCase()||!Cw(e.status,r)||s&&(e.body===void 0||!s.test(e.body)))}var Pw=(e,t)=>`response matching ${e.method??"any-method"} /${t}/ status ${e.status??"2xx"}${e.pattern?` body /${e.pattern}/`:""}`,Do=new Set(["click","fill","press","selectOption","check","uncheck","hover","dragTo","uploadFile"]),za=/(?<=(?:^|[^\\])(?:\\\\)*)(\\?)(<[^<>]+>|\{(?:env|data|date)[^{}]*\})/g;function Gu(e,t){return e===void 0?!1:[...e.matchAll(za)].some(({2:n,index:r})=>{let s=e.slice(Math.max(0,r-2),r);return!(n.startsWith("<")&&(s==="(?"||s==="\\k"))&&t(n).trim()===""})}function Uu(e){let t=[...e.matchAll(/(?:has-text\(\s*|(?:internal:)?(?:has-)?text=)"((?:[^"\\]|\\.)*)"(?!s)/g)].map(s=>s[1]),n=[...e.matchAll(/contains\(\s*(?:\.|text\(\))\s*,\s*(?:'((?:[^'\\]|\\.)*)'|"((?:[^"\\]|\\.)*)")\s*\)/g)].map(s=>s[1]??s[2]),r=e.split(">>").flatMap(s=>s.trim().match(/^(?:internal:)?text=(?!["/])(.*)$/s)?.[1]??[]);return[...t,...n,...r]}var Fa=(e,t)=>new Error(`${e} "${t}" holds an empty row or data value, so it would match more than it means. Give that cell or data value a value, or give the blank case its own Scenario.`);function St(e,t,n,r){return e===void 0||e.trim()===""?!1:t.trim()===""?!0:r!==void 0&&r.test("")&&r.test("\u2063zq9")&&[...e.matchAll(za)].some(({2:s,index:o})=>{let a=e.slice(Math.max(0,o-2),o);return!(s.startsWith("<")&&(a==="(?"||a==="\\k"))&&n(s).trim()===""})}var Mn=String.raw`(?:<[^<>]+>|\{(?:data|env|unique|date)[^{}]*\})`;function jr(e,t,n){if(!e.includes(t))return!1;let r=n!==void 0&&new RegExp(`^\\s*${Mn}`).test(n)&&/^[\p{L}\p{N}\p{M}]/u.test(t),s=n!==void 0&&new RegExp(`${Mn}\\s*$`).test(n)&&/[\p{L}\p{N}\p{M}]$/u.test(t);return!r&&!s?!0:new RegExp(`${r?"(?<![\\p{L}\\p{N}\\p{M}])":""}${be(t)}${s?"(?![\\p{L}\\p{N}\\p{M}])":""}`,"u").test(e)}function ja(e,t){let n=new RegExp(`^\\s*${Mn}`).test(e)&&/^[\p{L}\p{N}\p{M}]/u.test(t),r=new RegExp(`${Mn}\\s*$`).test(e)&&/[\p{L}\p{N}\p{M}]$/u.test(t);return!n&&!r?t:new RegExp(`${n?"(?<![\\p{L}\\p{N}\\p{M}])":""}${be(t.trim())}${r?"(?![\\p{L}\\p{N}\\p{M}])":""}`,"iu")}var La=e=>{try{return decodeURIComponent(e)}catch{return e}},Pt=(e,t)=>new Error(`${e} "${t}" is empty for this row, so it would hold for anything. Give that cell or data value a value, or give the check its own Scenario.`);function pn(e,t,n,r,s){let o=(c,l,d)=>c.replace(l,f=>{let p=d(f);return p.trim()===""&&r?.(),p}),a=o(e,/<[^<>]+>/g,c=>Vn(c,t)),i=Ve(o(a,Ae,Dt),s);return Bl(o(i,Ce,c=>oo(c,n)))}function Dn(e,t,n,r=!1,s=!1){return e.replace(za,(o,a,i,c)=>{let l=e.slice(Math.max(0,c-2),c);if(i.startsWith("<")&&(l==="(?"||l==="\\k"))return o;let d=t(i);if(d===i)return o;if(!r)return a+n(d);let f=!1,p=-1;for(let w=0;w<c;w++){if(e[w]==="\\"){w++;continue}e[w]==="["&&(f=!0),e[w]==="]"&&(f=!1),!f&&e[w]==="{"&&(p=w),!f&&e[w]==="}"&&(p=-1)}if(f)return n(d).replace(/-/g,"\\x2d");if(p>=0&&e.indexOf("}",c+o.length)>=0)throw new Error("A regex quantifier cannot contain a row or data token. Use a separate Scenario with a literal repeat count.");if(!s)return n(d);let u=e.slice(0,c),h=e.slice(c+o.length),b=/[\p{L}\p{N}\p{M}]$/u.test(u)||/(?:\\[dDwWsSpP]|(?<!\\)[.\])}*+?])$/.test(u),g=Ku(h),S=/^[\p{L}\p{N}\p{M}]/u.test(d)&&!b?String.raw`(?<![\p{L}\p{N}\p{M}])`:"",y=/[\p{L}\p{N}\p{M}]$/u.test(d)&&!g?String.raw`(?![\p{L}\p{N}\p{M}])`:"";return S+n(d)+y})}function Ku(e){if(/^[\p{L}\p{N}\p{M}]/u.test(e)||/^(?:\\[dDwWsSpP]|[.*+?{])/.test(e))return!0;let t=/^\((?:\?:|\?<[A-Za-z_]\w*>)?/.exec(e);if(t)return Ku(e.slice(t[0].length));let n=/^\[((?:\\.|[^\]\\])*)\]/.exec(e);return n!==null&&(/[\p{L}\p{N}]/u.test(n[1].replace(/\\./g,""))||/\\[dDwWpP]/.test(n[1])||n[1].startsWith("^"))}function Ht(e,t=""){return(/[uv]/.test(t)||e.includes(String.raw`[\p{L}\p{N}\p{M}]`))&&(e=e.replace(/\\.|[\s\S]/g,n=>/^\\['"`>\-]$/.test(n)?`\\x${n.charCodeAt(1).toString(16)}`:n),/[uv]/.test(t)||(t+="u")),new RegExp(e,t)}function Ba(e,t){return Wn(e,(r,s)=>Dn(r,t,ue[s],s==="regex",!0),t,!0).replace(/"((?:[^"\\]|\\.)*)"|=\/((?:[^/\\]|\\.)*)\/([a-z]*)/g,(r,s,o,a)=>s!==void 0?r:`=${Ht(o,a).toString()}`)}function zu(e,t,n,r=!1,s=!0,o=new Set,a){let i=p=>pn(p,n,o,void 0,a);for(let p of["name","text","label","placeholder","testId"]){if(St(t[p],i(t[p]??""),i))throw Pt(`The target's ${p}`,t[p]);if((p==="text"||p==="label"||p==="placeholder")&&Gu(t[p],i))throw Fa(`The target's ${p}`,t[p])}if(t.role&&t.nameRegex!==void 0){let p=Dn(t.nameRegex,i,ue.pattern,!0,!0);if(St(t.nameRegex,p,i,Ht(p,"i")))throw Pt("The target's name",t.nameRegex)}let c=p=>p.split(">>").map(u=>u.trim().startsWith("internal:")?u:u.replace(/(\[\s*[\w-]+\s*=\s*)(["'])((?:(?!\2)[^\\]|\\.)*)\2(\s*[is]?\s*\])/g,"$1$2$2$4")).join(">>");for(let p of[...t.fallbackSelectors??[],...t.frame?[t.frame]:[]]){let u=c(p);Wn(u,(S,y)=>{let w=Dn(S,i,ue[y],y==="regex",!0),v;try{v=y==="regex"?Ht(w):void 0}catch{}if(St(S,w,i,v))throw Pt("The text in selector",p);return S},S=>S,!0);let h=[...u.matchAll(/'((?:[^'\\]|\\.)*)'/g)].map(S=>S[1]),b=u.split(">>").flatMap(S=>S.trim().match(/^(?:internal:)?text=(?!["/])(.*)$/s)?.[1]??[]);for(let S of[...h,...b])if(St(S,i(S),i))throw Pt("The text in selector",p);let g=new RegExp(`^\\s*(${Mn})|(${Mn})\\s*$`,"g");for(let S of Uu(p))if([...S.matchAll(g)].some(w=>i(w[1]??w[2]).trim()==="")&&i(S).trim()!=="")throw Fa("The text in selector",p)}let l=[],d=p=>Ba(p,i),f=p=>{if(t.role){let u=t.nameRegex?Ht(Dn(t.nameRegex,i,ue.pattern,!0,!0),"i"):t.name?i(t.name):void 0,h=t.role;u===void 0&&!!(t.label||t.placeholder||t.text||t.testId||t.fallbackSelectors?.length)?t.text&&l.push(p.getByRole(h).filter({hasText:ja(t.text,i(t.text))})):typeof u=="string"?(l.push(p.getByRole(h,{name:u,exact:!0})),s&&l.push(p.getByRole(h,{name:u,exact:!1}))):l.push(p.getByRole(h,{name:u,exact:!1}))}t.label&&l.push(p.getByLabel(i(t.label))),t.placeholder&&l.push(p.getByPlaceholder(i(t.placeholder))),t.text&&!t.role&&l.push(p.getByText(ja(t.text,i(t.text)))),t.testId&&l.push(p.getByTestId(i(t.testId)));for(let u of t.fallbackSelectors??[]){let h=u.split(">>").pop()??u,b=p.locator(d(u)),g=typeof b.filter!="function"?b:Uu(h).reduce((S,y)=>new RegExp(`^\\s*${Mn}|${Mn}\\s*$`).test(y)?S.filter({hasText:ja(y,i(y))}):S,b);l.push(g)}};if(t.frame)f(e.frameLocator(d(t.frame)));else if(f(e),r)for(let p of e.frames())p!==e.mainFrame()&&f(p);if(l.length===0)throw new Error("Action target has neither role nor fallback selectors");return l}var Yu=100,Iw=500;async function Nw(e,t,n,r){let s=Date.now()+t,o;for(;Date.now()<s;){try{if(await e())return}catch(a){o=a}await Ua(r)}throw new Error(`Timed out waiting for ${n}${o?` (${String(o)})`:""}`)}async function Zt(e,t,n=!1){let r;for(let s of e)try{await t(s.first());return}catch(o){if(r=o,n&&await s.first().count().catch(()=>0)>0)throw o}throw r}var jw=20,Ze=e=>e.replace(/\s+/g," ").trim(),jn=new WeakMap,hs=new WeakMap;async function Hu(e,t){let n={element:t};if(await e.count()!==1)return n;let r=await t.ownerFrame();if(!r)return n;let s=await t.getAttribute("id"),o=await t.getAttribute("data-testid"),a=[o?r.getByTestId(o):void 0,s?r.locator(`#${await t.evaluate(i=>i.ownerDocument.defaultView.CSS.escape(i.id))}`):void 0];for(let i of a)if(i&&await i.count()===1){n.stable=i;break}return n}async function Mw(e){if(!await e.element.evaluate(n=>n.isConnected).catch(()=>!1)&&e.stable&&await e.stable.count()===1){let n=await e.stable.elementHandle({timeout:100});n&&(await e.element.dispose().catch(()=>{}),e.element=n)}return Ze((await e.element.evaluate(tr,!1)).text)}var ms=new WeakMap,gs=new WeakMap,qu="__saffron_download",Vu=5*1024*1024;async function Ha(e,t,n){let r=e.suggestedFilename(),s,o=new Promise(l=>{s=setTimeout(()=>l(`it did not finish within ${n} ms`),n)}),a=await Promise.race([e.failure(),o]).finally(()=>clearTimeout(s));if(a)throw e.cancel().catch(()=>{}),new Error(`waitForDownload failed: the download of ${r} failed (${a})`);if(!t)return e.path();let i=ws.basename(r).replace(/[\u0000-\u001f<>:"/\\|?*]/g,"_"),c=ws.join(t,i===""||i==="."||i===".."?"download":i);return await Ma.promises.mkdir(t,{recursive:!0}),await e.saveAs(c),c}async function qa(e){let t=ws.basename(e),{size:n}=await Ma.promises.stat(e);if(n>Vu)throw new Error(`the downloaded file ${t} is ${n} bytes; a content check reads text files up to ${Vu} bytes`);let r=await Ma.promises.readFile(e),s;try{if(r.includes(0))throw new Error("NUL byte");s=new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{throw new Error(`the downloaded file ${t} is not a UTF-8 text file, so its content cannot be checked`)}return s=s.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
|
|
38
|
-
`)
|
|
39
|
-
|
|
40
|
-
${_
|
|
41
|
-
|
|
42
|
-
`)
|
|
43
|
-
`)))),
|
|
44
|
-
`)
|
|
45
|
-
`))c(a(S));return{text:b,pieces:[...i],kept:d}}function Dw(e,[t,n]){let r=(0,eval)("("+n+")"),s=i=>{for(let c=i;c;c=c.parentElement??c.getRootNode().host)if(c.hidden||c.ownerDocument.defaultView.getComputedStyle(c).display==="none")return!0;return!1},o=i=>String(i.textContent??"").replace(/\s+/g," ").trim(),a=i=>s(i)||o(i)!==""&&!/\S/.test(r(i).text);if(e.length===0||!a(e[0]))return 0;for(let i=1;i<Math.min(e.length,t);i++)if(!a(e[i]))return o(e[i])===o(e[0])?i:0;return 0}async function Ju(e,t){let{text:n,kept:r}=await e.evaluate(tr,!1,t);if(/\S/.test(n)||await e.isVisible())return{text:n,kept:r}}async function ys(e,t,n,r,s,o=new Map,a,i=Yu,c=new Set,l){let d=(m,A,O)=>Nw(m,A,O,i),f=gs.get(e);if(f!==void 0&&(Do.has(t.action)&&!(t.action==="uploadFile"&&!t.target)||t.action==="goto"||t.action==="newTab")){gs.delete(e);let m=jn.get(e),A=e.context(),O=[],T=()=>{},_=F=>{O.push(F),O.length>=f&&T()},N=F=>{F.on("download",_)};A.pages().forEach(N),A.on("page",N);try{let F;try{F=await ys(e,t,n,r,s,o,a,i,c,l)}catch(I){if(!/Download is starting/.test(I instanceof Error?I.message:String(I)))throw I}if(O.length<f&&await new Promise(I=>{let L=setTimeout(I,r);T=()=>{clearTimeout(L),I()}}),O.length===0)throw new Error(`waitForDownload failed: the ${t.action} after it started no download within ${r} ms`);if(O.length<f)throw new Error(`waitForDownload failed: the ${t.action} after it started ${O.length} of the ${f} downloads it started when recorded, within ${r} ms`);return o.set(qu,await Ha(O[O.length-1],l,r)),F}catch(F){throw gs.set(e,f),m&&!jn.has(e)&&jn.set(e,m),F}finally{A.off("page",N);for(let F of A.pages())F.off("download",_)}}let p=jn.get(e);if(p&&Do.has(t.action)&&t.action!=="uploadFile"){jn.delete(e);let m,A=T=>{m??=T};e.on("filechooser",A);let O;try{if(O=await ys(e,t,n,r,s,o,a,i,c,l),m||await e.waitForEvent("filechooser",{timeout:r}).then(A,()=>{}),!m)throw new Error(`uploadFile failed: the ${t.action} after it opened no file chooser within ${r} ms`);try{await m.setFiles(p,{timeout:r})}catch(T){throw new Error(`uploadFile failed: ${T instanceof Error?T.message:String(T)}`)}}catch(T){throw jn.set(e,p),T}finally{e.off("filechooser",A)}return O}o.has(Ct)||o.set(Ct,fn()),(Do.has(t.action)||t.action==="goto"||t.action==="newTab"||t.action==="closeTab")&&a?.markAction();let u=o.get(Ct),h=m=>typeof m=="string"?Yt(m,u):Array.isArray(m)?m.map(h):m&&typeof m=="object"?Object.fromEntries(Object.entries(m).map(([A,O])=>[A,h(O)])):m;t=h(t),n=h(n),o.has(uo)||o.set(uo,String(Date.now()));let b=new Date(Number(o.get(uo))),g=m=>pn(m,n,c,void 0,b),S=()=>JSON.stringify(Object.fromEntries(Object.entries(t.target??{}).sort(([m],[A])=>m.localeCompare(A)).map(([m,A])=>Array.isArray(A)?[m,A.map(O=>Ba(O,g))]:A===void 0||m==="role"?[m,A]:m==="nameRegex"?[m,Dn(A,g,ue.pattern,!0,!0)]:m==="frame"?[m,Ba(A,g)]:[m,g(A)]))),y=(m,A)=>Dn(m,O=>pn(O,n,c,A,b),ue.pattern,!0,!0),w=!1,v=t.value!==void 0&&t.action!=="expectAmount"?pn(t.value,n,c,()=>{w=!0},b):void 0,x=t.url!==void 0?g(t.url):void 0,$=t.action==="expectVisible"||t.action==="expectText"||t.action==="expectValue"||t.action==="expectMatches"||t.action==="expectAttribute"||t.action==="expectEach"||t.action==="expectDiffers"||t.action==="expectAmount"||t.action==="captureText",E=t.target?zu(e,t.target,n,$,!Do.has(t.action)&&!Se.has(t.action),c,b):[],R={timeout:r},k={timeout:Math.min(1e3,r)},C=async m=>{let A=await m.evaluateAll(Dw,[jw,tr.toString()]);return A>0?m.nth(A):m.first()},P=m=>async()=>{for(let A of E)try{if(await m(await C(A)))return!0}catch{}return!1};switch(t.action){case"goto":{if(!x)throw new Error("goto requires url");let m=ls(x);if(m)throw new Error(m);await e.goto(Sa(x,s),R);return}case"click":{let{clickCount:m,button:A,modifiers:O}=t,T={...R,clickCount:m,button:A,modifiers:O};return Zt(E,_=>_.click(T),!0)}case"fill":return Zt(E,m=>m.fill(v??"",R),!0);case"press":return E.length>0?Zt(E,m=>m.press(v??"",R),!0):e.keyboard.press(v??"");case"selectOption":return Zt(E,async m=>{if(t.clearSelection){await m.selectOption([],R);return}let A=(v??"").split(`
|
|
46
|
-
`)
|
|
47
|
-
`)
|
|
48
|
-
`).filter(Boolean).map(T=>ws.resolve(m,T));if(A.length===0)throw new Error("uploadFile requires a path");let O=Ta(A,m);if(O)throw new Error(O);if(E.length>0)return Zt(E,T=>T.setInputFiles(A,R),!0);jn.set(e,A);return}case"waitForDownload":gs.set(e,t.downloads??1);return;case"expectDownload":{let m=o.get(qu);if(!m)throw new Error("expectDownload: no file was downloaded in this scenario before this check");let A=Va(t,n,c,b);if(A)throw new Error(A);let O=Lo(t,n,c,b),T=Ja(await qa(m),ws.basename(m),O.value,O.pattern,t.value);if(T)throw new Error(T);return}case"dragTo":{if(!t.toTarget)throw new Error("dragTo requires toTarget");let m=zu(e,t.toTarget,n,!1,!1,c,b);return Zt(E,A=>A.dragTo(m[0].first(),R),!0)}case"captureText":{if(!t.saveAs)throw new Error("captureText requires saveAs");await a?.quiet(Math.min(r/2,3e3));let m=Math.min(Iw,r/4),A=Date.now()+r-m,O;return d(async()=>{for(let T of E){let _;try{if(_=await(await C(T)).elementHandle(k)??void 0,!_)continue;let N=Ze((await _.evaluate(tr,!1)).text);if(N==="")continue;let F=Date.now();if(O?.text!==N&&(O={text:N,since:F}),F-O.since<m&&F<A)return!1;let I=await Hu(T,_),L=hs.get(o);return L||hs.set(o,L=new Map),await L.get(t.saveAs)?.tracked.element.dispose().catch(()=>{}),L.set(t.saveAs,{page:e,key:S(),value:N,tracked:I}),_=void 0,o.set(t.saveAs,N),!0}catch{}finally{await _?.dispose().catch(()=>{})}}return!1},r,`non-empty text to capture as "${t.saveAs}"`)}case"expectAmount":{let m=Yn(t.value??"",T=>pn(T,n,c,void 0,b)),A=po(m,T=>o.get(T));if("problem"in A)throw new Error(`expectAmount: ${A.problem}`);let O;try{return await d(P(async T=>{O=Ze((await T.evaluate(tr,!1,k)).text);let _=vt(O);return _!==void 0&&En(_,A.amount)}),r,/\{env:/.test(t.value??"")?`the amount ${t.value}`:`the amount ${cd(A.amount)} (${m})`)}catch(T){throw new Error(`${T instanceof Error?T.message:String(T)}${O===void 0?"":`; the target shows "${O}"`}`)}}case"expectDiffers":{if(!t.compareTo)throw new Error("expectDiffers requires compareTo");let m=o.get(t.compareTo);if(m===void 0)throw new Error(`expectDiffers: no captured value named "${t.compareTo}"`);if(E.length>0){let T=hs.get(o)?.get(t.compareTo),_=T?.page===e&&T.value===m&&T.key===S()?T.tracked:void 0,N=_;try{return await d(async()=>{if(N){let F=await Mw(N);if(F===""||F===m)return!1;for(let I of E)try{if(await I.evaluateAll((L,j)=>L.includes(j),N.element))return!0}catch{}return!1}for(let F of E){let I;try{if(I=await(await C(F)).elementHandle(k)??void 0,!I)continue;let L=Ze((await I.evaluate(tr,!1)).text);if(L==="")continue;return N=await Hu(F,I),L!==m}catch{}finally{I&&I!==N?.element&&await I.dispose().catch(()=>{})}}return!1},r,`target text to differ from "${t.compareTo}" (${m})`)}finally{N&&N!==_&&await N.element.dispose().catch(()=>{})}}let A=v??"",O=o.get(A);if(O===void 0)throw new Error(`expectDiffers: no captured value named "${A}"`);if(O===m)throw new Error(`expectDiffers: "${A}" (${O}) equals "${t.compareTo}" (${m})`);return}case"expectAttribute":{if(!t.attribute)throw new Error("expectAttribute requires attribute");if(!t.pattern)throw new Error("expectAttribute requires pattern");let m=!1,A=y(t.pattern,()=>{m=!0}),O=Ht(A);if(m&&A!==""&&!O.test(""))throw new Error("The attribute pattern contains an empty row or data value. Give it a value, or give the blank case its own Scenario with an explicit pattern.");let T=g(t.attribute);if(St(t.attribute,T,g))throw Pt("The attribute name",t.attribute);let _=St(t.pattern,A,g,O),N=O.test("")&&O.test("false")&&!O.test("true");return d(P(async F=>{let I=await F.getAttribute(T,k);return _?(I??"").trim()==="":I===null?N:O.test(I)}),r,`attribute ${T} to match /${t.pattern}/`)}case"expectMatches":{if(!t.pattern)throw new Error("expectMatches requires pattern");let m=!1,A=y(t.pattern,()=>{m=!0}),O=Ht(A,"i");if(m&&Ze(A)!==""&&!O.test(""))throw new Error("The expected text pattern contains an empty row or data value. Give it a value, or give the blank case its own Scenario with an explicit pattern.");let T=Ze(A)===""||St(t.pattern,A,g,O);return d(P(async _=>{let N=await Ju(_,k);return N===void 0?T:T?Ze(N.text)==="":O.test(Ze(N.text))||N.kept&&O.test(N.text)}),r,`target text to match /${t.pattern}/i`)}case"switchTab":{let m=Number.parseInt(v??"",10),A=()=>e.context().pages().filter(T=>!T.isClosed());await d(async()=>A().length>m,r,`tab ${v} to exist (${A().length} open: ${A().map(T=>T.url()).join(", ")})`);let O=A()[m];return await O.bringToFront(),O}case"closeTab":{let m=e.context().pages().filter(T=>!T.isClosed()),A=v===void 0?e:m[Number.parseInt(v,10)];if(!A)throw new Error(`tab ${v} does not exist (${m.length} open)`);await A.close();let O=e.context().pages().filter(T=>!T.isClosed());if(O.length===0)throw new Error("closed the last tab; nothing left to drive");return O[O.length-1]}case"newTab":{let m=x?ls(x):void 0;if(m)throw new Error(m);let A=await e.context().newPage();return x&&await A.goto(Sa(x,s),R),A}case"waitForResponse":case"expectResponse":{if(!t.urlPattern)throw new Error(`${t.action} requires urlPattern`);let m=y(t.urlPattern),A=Ht(m),O=t.status!==void 0?g(t.status):void 0,T=t.method!==void 0?g(t.method):void 0,_=!1,N=t.pattern?y(t.pattern,()=>{_=!0}):void 0,F=N!==void 0?Ht(N):void 0;if(_&&N!==""&&F&&!F.test(""))throw new Error("The response body pattern contains an empty row or data value. Give it a value, or give the blank case its own Scenario with an explicit pattern.");if(St(t.urlPattern,m,g,A))throw Pt("The response URL pattern",t.urlPattern);if(St(t.status,O??"",g))throw Pt("The response status",t.status);if(St(t.method,T??"",g))throw Pt("The response method",t.method);if(F&&St(t.pattern,N,g,F))throw Pt("The response body pattern",t.pattern);if(!a){await e.waitForResponse(async L=>{let j={seq:0,url:L.url(),method:L.request().method(),status:L.status()};if(!Bu(j,A,T,O,void 0))return!1;if(!F)return!0;let H=await L.text().catch(()=>{});return H!==void 0&&F.test(H)},R);return}let I=()=>t.action==="expectResponse"?a.sinceAction():a.sincePreviousStep();return d(async()=>{let L=I().find(j=>Bu(j,A,T,O,F));return L&&(a.lastMatch=L),L!==void 0},r,Pw({...t,status:O,method:T},t.urlPattern))}default:throw new Error(`Unknown action type: ${t.action}`)}}var Fo=(e,t)=>pt(e.actions,t);function Fw(e,t){let n=e.examples;return n?e.steps.some(r=>r.actions.some(s=>Et(s).some(o=>o!==void 0&&[...o.matchAll(/\{data:([^{}]*<[^<>{}]+>[^{}]*)\}/g)].some(([,a])=>a.replace(/<([^<>]+)>/g,(i,c)=>n[c]??"\0")===t)))):!1}var Wu=(e,t)=>cn(e.actions,t);function Fn(e,t){if(!t.rowBound?.length||!t.examples||t.steps.length!==e.steps.length||t.steps.some((g,S)=>g.gherkin!==e.steps[S].text||g.kind!==e.steps[S].kind)||t.steps.some((g,S)=>JSON.stringify(g.table??null)!==JSON.stringify(e.steps[S].table??null)||(g.docString??null)!==(e.steps[S].docString??null))&&!Mr(e,t))return;let r=t.rowBound.filter(g=>g.column in e.params),s=is([...new Set(r.map(g=>g.column))],t.examples,e.params,t.recordedAt,t.data);if(s===void 0){let g=r.find(w=>w.valueSha!==void 0&&!mo(e.params[w.column]??"",w.valueSha));if(!g)return;let{keyword:S,gherkin:y}=t.steps[g.step];return`This Outline was recorded with ${g.column} as ${t.examples[g.column]}, which resolves to another value now (or is not set), and step ${g.step+1} ("${S?`${S.trim()} `:""}${y}") still holds the value it had, so the recording cannot check this row. Record the Outline again with saffron run --rerecord.`}let{step:o,reason:a}=r.find(g=>g.column===s),i=t.examples[s],c=`this row, where ${s} is "${e.params[s]}"`,{keyword:l,gherkin:d}=t.steps[o],f=`step ${o+1} ("${l?`${l.trim()} `:""}${d}")`,p=d.includes(`<${s}>`),u=[...new Set(r.map(g=>g.column))],b=(e.exampleRows??[]).every(g=>is(u,t.examples,g,t.recordedAt,t.data)!==void 0)?` No Examples row has ${s} "${i}" any more: record the Outline again with saffron run --rerecord.`:" Or record the Outline again on another row with saffron run --rerecord.";return(a==="unwritten"&&t.steps[o].kind==="assertion"?`This Outline was recorded on the row where ${s} is "${i}", and ${f} names <${s}> but only checks that something is shown or in a state, which reads the same whoever <${s}> is, so it cannot prove ${c}. Make the check show the value: write <${s}> in the text the step expects (\`Then the dashboard greets "<${s}>"\`), then record again with saffron run --rerecord. Or give each value its own Scenario.`:a==="unwritten"?`This Outline was recorded on the row where ${s} is "${i}", and ${f} names <${s}> but recorded no action that writes it (on that row the page already was that way, or the action holds no row value, like ticking a box), so on ${c} it would do what it did for "${i}". Give each value its own Scenario, or, where the value is what the step picks (an option or radio labelled with it), record the step picking it even when it already is.`:a==="session"?`This Outline was recorded on the row where ${s} is "${i}", and ${f} runs in the browser session <${s}> names and types a value the step does not write, which was that person's: on ${c} the other person would type it too. Write that value in the step, or give it an Examples column and write <column> there, or give each person's flow its own Scenario.`:a==="container"?`This Outline was recorded on the row where ${s} is "${i}", and ${f} acts in the section <${s}> names without being scoped to it, so on ${c} it would act in whichever such section comes first. Record the Outline again so that step's target names its section, or the dialog its action opened (saffron run --rerecord), or give each section its own Scenario.`:a==="list"?`This Outline was recorded on the row where ${s} is "${i}", and ${f} holds other rows' ${s} values too, so one recording cannot check ${c}. Give that check its own Scenario, or give the text it holds an Examples column of its own and write that column in the step.`:a==="reads"?`This Outline was recorded on the row where ${s} is "${i}", and ${f} checks a response status, method or attribute against what a {data:...} reference keyed by <${s}> reads on that row, so one recording cannot check ${c}. Give the expected value an Examples column of its own and name it in that step, or give that check its own Scenario.`:a==="value"?`This Outline was recorded on the row where ${s} is "${i}", and ${f} checks "${i}" as a response status, method or attribute without naming <${s}>, so one recording cannot check ${c}. If that check follows the row, name <${s}> in that step; if the value only coincides, give the check its own Scenario.`:a==="data"?`This Outline was recorded on the row where ${s} is "${i}", and ${f} reads a {data:...} entry that more than one of the Outline's {data:...} references chose on that row, so one recording cannot check ${c}. Write the {data:...} reference that step needs in its own text, or give that check its own Scenario.`:p?`This Outline was recorded on the row where ${s} is "${i}", and ${f} holds "${i}" spelled otherwise or inside other text (an attribute's name, a {data:...} path), where <${s}> cannot follow the row, so one recording cannot check ${c}. Spell the value as the cell does, give it an Examples column of its own, or give that check its own Scenario.`:`This Outline was recorded on the row where ${s} is "${i}", and ${f} writes "${i}" inside other text without naming <${s}>, so one recording cannot check ${c}. Put <${s}> in that step, or give that check its own Scenario.`)+b}function Lw(e){let t=JSON.stringify([e.params,e.exampleRows??[],e.steps.map(n=>[n.text,n.table??[],n.docString??""])]);if(Kn(t))return!0;try{let n=Dt(t);return(n.match(/\{date/g)??[]).length>(t.match(/\{date/g)??[]).length?!0:Kn(n)}catch{return!1}}function Mr(e,t){if(t.steps.length!==e.steps.length||t.version<3&&Lw(e))return!1;let n=t.examples?[t.examples]:Object.keys(e.params).length>0?e.exampleRows??[]:[];for(let[r,s]of Object.entries(t.data??{})){let o;try{o=qe(r)}catch{continue}if(o===s)continue;let a=t.steps.some(c=>Fo(c,`{data:${r}}`))||Fw(t,r),i=t.steps.some(c=>On(c.actions,s));if(!a||i)return!1}return t.steps.every((r,s)=>{let o=e.steps[s];if(r.gherkin!==o.text||r.kind!==o.kind)return!1;if(n.length>0){let c=[o.text,...o.table?.flat()??[],o.docString??""].join(`
|
|
49
|
-
`);if(
|
|
28
|
+
${p}`).join("")}});return{...e,content:s}}function Hw(e){if(!e.isError||!Array.isArray(e.content))return e;let t=!1,n=e.content.map(o=>{if(o.type!=="text"||typeof o.text!="string")return o;let a=o.text.split(/^### Events\r?$/m)[1]?.split(/^### /m)[0]??"",i=/^### Error\r?\n([\s\S]*?)(?=^### |(?![\s\S]))/m.exec(o.text);return!i||!/^- Downloading file .* \.\.\.\r?$/m.test(a)||i[1].split(`
|
|
29
|
+
`).filter(l=>l.trim()!==""&&!/^(?:Error: )?download\.saveAs: /.test(l)&&!/^\s+at /.test(l)).length>0?o:(t=!0,{...o,text:o.text.slice(0,i.index)+o.text.slice(i.index+i[0].length)})});if(!t)return e;let{isError:r,...s}=e;return{...s,content:n}}async function Wu(e,t,n={}){let r=new Iw({name:"saffron-cap",version:"1"}),s=Object.fromEntries(Object.entries(process.env).filter(a=>a[1]!==void 0));await r.connect(new Nw({...e,env:s,stderr:"ignore"}));let o=Za(r,void 0,t,n);return{config:{type:"sdk",name:"playwright",instance:o},close:async()=>{await Promise.allSettled([r.close(),o.close()])}}}function Wa(e,t){return typeof e=="string"?t(e):Array.isArray(e)?e.map(n=>Wa(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Wa(r,t)])):e}function Hu(e,t,n){return t.size===0?e:Wa(e,r=>{let s=!1,o=r.replace(Se,(a,i)=>{let c=t.get(i);return c!==void 0&&c.length<6&&r!==a&&(s=!0),c??a});return s&&n?.(o,r),o})}var Jw={browser_type:["text"],browser_press_sequentially:["text"],browser_fill_form:["fields"],browser_select_option:["values"],browser_navigate:["url"],browser_tabs:["url"],browser_file_upload:["paths"],browser_wait_for:["text","textGone"],browser_handle_dialog:["promptText"]};function Vw(e,t,n,r){let s=Jw[e];return!t||!s||n.size===0?t:Object.fromEntries(Object.entries(t).map(([o,a])=>[o,s.includes(o)?o==="fields"&&Array.isArray(a)?a.map(i=>i&&typeof i=="object"?{...i,value:Hu(i.value,n,r)}:i):Hu(a,n,r):a]))}var Ww=e=>!!e&&typeof e=="object"&&["image","audio"].includes(e.type??"");function Gw(e,t,n=r=>r){if(t.size===0)return e;let r=s=>typeof s=="string"?ha(n(s),t):Array.isArray(s)?s.map(o=>Ww(o)?o:r(o)):s&&typeof s=="object"?Object.fromEntries(Object.entries(s).map(([o,a])=>[o,o==="blob"?a:r(a)])):s;return r(e)}function Za(e,t=(s,o,a)=>a(),n,r={}){let s=new Mw({name:"playwright",version:"1"},{capabilities:{tools:{}}}),o=r.secrets?.()??new Map,a=new Map,i=(u,p)=>{u.length>=3&&a.set(u,p)},c=Pr(r.texts?.()??[],o),l=u=>{let p=[...a].sort((f,g)=>g[0].length-f[0].length);return Gw(u,o,f=>c(p.reduce((g,[y,h])=>g.split(y).join(h),f)))};s.server.setRequestHandler(Fw,async()=>Lw(await e.listTools())),s.server.setRequestHandler(Dw,async(u,p)=>{let f=Bw(u.params.name);if(f)return f;if(o.size>0&&u.params.name==="browser_evaluate"&&JSON.stringify(u.params.arguments??{}).includes("{env:"))return vs("browser_evaluate cannot use an {env:...} token: a secret reaches the page only by typing, filling, selecting, navigating or uploading it.");try{let g=qu(u.params.name,Vw(u.params.name,u.params.arguments,o,i),n);if(g.refused)return l(g.refused);let y={...u.params,arguments:g.args},h=qu(u.params.name,u.params.arguments,n).args,S=await t(y.name,h,()=>d(y,p.signal)),v=qw(l(S));return o.size>0&&r.onResult?.(v,S),v}catch(g){throw new Error(l(g instanceof Error?g.message:String(g)))}});let d=async(u,p)=>{let f=async $=>Hw(await e.callTool($,void 0,{timeout:Ka,signal:p})),g=u.arguments?.fields,y=u.name==="browser_fill_form"&&Array.isArray(g)&&g.length>1,h=(u.name==="browser_type"||u.name==="browser_press_sequentially")&&u.arguments?.submit===!0;if(!y&&!h)return f(u);let S=(await e.listTools()).tools.find($=>$.name===u.name);if(!S)return vs(`${u.name} is not available in this browser session.`);let v=new jw().getValidator(S.inputSchema)(u.arguments);if(!v.valid)return vs(`Invalid ${u.name} arguments: ${v.errorMessage}`);let x=y?g.map($=>({...u,arguments:{...u.arguments,fields:[$]}})):[{...u,arguments:{...u.arguments,submit:!1}},u.name==="browser_type"?{...u,arguments:{...u.arguments,text:"",slowly:!0,submit:!0}}:{name:"browser_press_key",arguments:{key:"Enter"}}],b=[],m=!1;try{for(let $ of x){p.throwIfAborted(),r.beforeAction?.();let T=await f($);if(T.isError)return T;b.push(T)}return m=!0,{...b.at(-1),content:b.flatMap($=>Array.isArray($.content)?$.content:[])}}finally{if(!m)for(let $ of b)r.onPartialResult?.($)}};return s}import Xw from"node:path";import{createHash as ey}from"node:crypto";function le(e,t=200){let n=e.replace(/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?|\x1b[@-_]?/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"");return n.length>t?`${n.slice(0,t-3)}...`:n}function ks(e){return Array.isArray(e)?e.map(ks):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([t,n])=>n!==void 0&&t!=="pageFingerprint").sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,ks(n)])):e}var Qa=e=>JSON.stringify(ks(e));function Vo(e,t="",n={}){if(Array.isArray(e))e.some(r=>r!==null&&typeof r=="object")?e.forEach((r,s)=>Vo(r,`${t}[${s}]`,n)):n[t]=e.map(r=>String(r)).join(", ");else if(e&&typeof e=="object")for(let[r,s]of Object.entries(e))Vo(s,t?`${t}.${r}`:r,n);else t&&(n[t]=String(e));return n}function Kw(e,t){let n=Vo(ks(e)),r=Vo(ks(t)),s=[...new Set([...Object.keys(n),...Object.keys(r)])].sort(),o=[];for(let a of s){if(a==="action"||n[a]===r[a])continue;let i=a.replace(/^target\./,"").replace(/^toTarget\./,"destination ");n[a]===void 0?o.push(`${i}: added "${r[a]}"`):r[a]===void 0?o.push(`${i}: removed "${n[a]}"`):o.push(`${i}: "${n[a]}" \u2192 "${r[a]}"`)}return o}function Zu(e,t,n){let r=e.map(n),s=t.map(n),o=Array.from({length:r.length+1},()=>new Array(s.length+1).fill(0));for(let l=r.length-1;l>=0;l--)for(let d=s.length-1;d>=0;d--)o[l][d]=r[l]===s[d]?o[l+1][d+1]+1:Math.max(o[l+1][d],o[l][d+1]);let a=[],i=0,c=0;for(;i<r.length&&c<s.length;)r[i]===s[c]?(a.push({before:e[i],after:t[c]}),i++,c++):o[i+1][c]>=o[i][c+1]?(a.push({before:e[i]}),i++):(a.push({after:t[c]}),c++);for(;i<r.length;i++)a.push({before:e[i]});for(;c<s.length;c++)a.push({after:t[c]});return a}function Gu(e){if(!e)return"";let t=[];if(e.role){let n=e.name?` "${e.name}"`:e.nameRegex?` matching /${e.nameRegex}/`:"";t.push(`${e.role}${n}`)}else e.label?t.push(`label "${e.label}"`):e.text?t.push(`text "${e.text}"`):e.placeholder?t.push(`placeholder "${e.placeholder}"`):e.testId&&t.push(`test id ${e.testId}`);return e.fallbackSelectors?.length&&t.push(`[${e.fallbackSelectors.join(", ")}]`),e.frame&&t.push(`inside frame ${e.frame}`),t.join(" ")}var Ku=e=>`${e.method??"any"} /${e.urlPattern}/ ${e.status??"2xx"}`+(e.pattern?` with a body matching /${e.pattern}/`:"")+(e.json?` with JSON ${e.json.map(t=>`${JSON.stringify(t.path)} ${t.exists!==void 0?t.exists?"present":"absent":`equals ${t.type??"string"} ${JSON.stringify(t.equals)}`}`).join(", ")}`:"");function ft(e){let t=Gu(e.target),n=e.value??"",r=(()=>{switch(e.action){case"goto":return`go to ${e.url}`;case"click":{let s=[e.clickCount===2?"double ":e.clickCount&&e.clickCount>2?`${e.clickCount}x `:"",e.button&&e.button!=="left"?`${e.button}-`:""].join("");return`${e.modifiers?.length?`${e.modifiers.join("+")}+`:""}${s}click ${t}`}case"fill":return`fill ${t} with "${n}"`;case"press":return t?`press ${n} on ${t}`:`press ${n}`;case"selectOption":return e.clearSelection?`clear the selection in ${t}`:`select ${n.split(`
|
|
30
|
+
`).map(s=>`"${s}"`).join(", ")} in ${t}`;case"check":return`check ${t}`;case"uncheck":return`uncheck ${t}`;case"hover":return`hover ${t}`;case"waitFor":return t?`wait for ${t}`:`wait ${n}ms`;case"captureText":return`remember ${t} as "${e.saveAs}"`;case"handleDialog":return`${n} the dialog${e.promptText?` with "${e.promptText}"`:""}`;case"uploadFile":return`upload ${n}`;case"dragTo":return`drag ${t} onto ${Gu(e.toTarget)}`;case"waitForResponse":return`wait for ${Ku(e)}`;case"switchTab":return`switch to tab ${n}`;case"closeTab":return`close tab ${n||"(the current one)"}`;case"newTab":return`open a new tab${e.url?` at ${e.url}`:""}`;case"waitForDownload":return e.downloads&&e.downloads>1?`expect the next action to download ${e.downloads} files (the latest is checked)`:"expect the next action to download a file";case"expectAmount":return`expect ${t} to show the amount ${n}`;case"expectVisible":return`expect ${t} to be visible`;case"expectNotVisible":return`expect ${t} to be gone`;case"expectText":return`expect ${t} to contain "${n}"`;case"expectUrl":return`expect the URL to contain "${e.url??n}"`;case"expectValue":return`expect ${t} to hold "${n}"`;case"expectDiffers":return`expect ${t||`"${n}"`} to differ from "${e.compareTo}"`;case"expectMatches":return`expect ${t} to match /${e.pattern}/`;case"expectAttribute":return`expect ${t} ${e.attribute} to match /${e.pattern}/`;case"expectResponse":return`expect a response ${Ku(e)}`;case"expectEach":return`expect ${t} to show every value of ${e.each}`;case"expectDownload":return`expect the downloaded file to ${[e.value?`contain "${n}"`:"",e.pattern?`match /${e.pattern}/`:""].filter(Boolean).join(" and ")}`;default:return e.action}})();return e.opensTab?`${r}, opening a tab`:r}var $s=e=>$e.has(e.action);function Yw(e,t){let n=Zu(e,t,Qa),r=[];for(let s=0;s<n.length;s++){let o=n[s];if(o.before&&o.after){r.push({change:"same",before:ft(o.before),after:ft(o.after),assertion:$s(o.after)});continue}let a=n[s+1];if(o.before&&a?.after&&!a.before){r.push({change:"changed",before:ft(o.before),after:ft(a.after),details:Kw(o.before,a.after),assertion:$s(o.before)||$s(a.after)}),s++;continue}o.before&&r.push({change:"removed",before:ft(o.before),assertion:$s(o.before)}),o.after&&r.push({change:"added",after:ft(o.after),assertion:$s(o.after)})}return r}var Zw=e=>`${e.kind}\0${e.gherkin}`;function Hn(e,t,n=[]){let r=Zu(e?.steps??[],t.steps,Zw),s=[],o={added:0,removed:0,changed:0,assertions:0};for(let i of r){let c=i.after??i.before,l=Yw(i.before?.actions??[],i.after?.actions??[]);for(let u of l)u.change==="added"?o.added++:u.change==="removed"?o.removed++:u.change==="changed"&&o.changed++,u.change!=="same"&&u.assertion&&o.assertions++;let d=e&&i.before?i.after?l.some(u=>u.change!=="same")?"changed":"same":"removed":"added";s.push({gherkin:c.gherkin,kind:c.kind,fromStepSet:c.fromStepSet,change:d,actions:l})}let a=Qw(e,t);return{feature:t.feature,scenario:t.scenario,hasCommitted:e!==void 0,steps:s,summary:o,...a.length>0?{recording:a}:{},...n.length>0?{featureEdits:n.map(i=>{let c=t.steps[i.index]?.gherkin??`step ${i.index+1}`;return{index:i.index,from:c,to:i.text,fromStepSet:t.steps[i.index]?.fromStepSet,...Jt(c)!==Jt(i.text)?{skipped:'it changes which browser session the step runs in (its As "...")'}:{}}})}:{}}}function Qw(e,t){let n=[],r=a=>`<${a.column}> at step ${a.step+1} (${a.reason})`,s=new Set((e?.rowBound??[]).map(r)),o=new Set((t.rowBound??[]).map(r));for(let a of s)o.has(a)||n.push(`row binding dropped: ${a}. Other Examples rows are no longer refused there; check they cannot pass on this row's data.`);for(let a of o)s.has(a)||n.push(`row binding${e?" added":""}: ${a}. Rows typing that column differently are refused.`);e&&JSON.stringify(e.examples??null)!==JSON.stringify(t.examples??null)&&n.push(`recorded on another Examples row: ${JSON.stringify(e.examples??{})} \u2192 ${JSON.stringify(t.examples??{})}`);for(let a of new Set([...Object.keys(e?.data??{}),...Object.keys(t.data??{})])){let i=e?.data?.[a],c=t.data?.[a];e&&i!==c&&n.push(`{data:${a}} recorded as ${c===void 0?"nothing":JSON.stringify(c)}, was ${i===void 0?"nothing":JSON.stringify(i)}`)}return!!e?.rowsUseNewDates!=!!t.rowsUseNewDates&&e&&n.push(t.rowsUseNewDates?"marked as using new date syntax in another row (written as version 3)":"no longer marked as using new date syntax in another row: it may be written as an older version"),n}var Yu=new Set(["goto","click","press","newTab","switchTab","closeTab"]);function Qu(e,t){let n=[],r=s=>`${s} navigation action${s===1?"":"s"}`;for(let s=0;s<Math.min(e.length,t.length);s++){let o=e[s].actions.filter(u=>Yu.has(u.action)),i=[...t[s].actions.filter(u=>Yu.has(u.action))],c=[];for(let u of o){let p=i.findIndex(f=>Qa(f)===Qa(u));p>=0?i.splice(p,1):c.push(u)}let l=i;for(let u=c.length-1;u>=0;u--){let p=l.findIndex(f=>f.action===c[u].action);p>=0&&(l.splice(p,1),c.splice(u,1))}let d=`step ${s+1} ("${e[s].gherkin}")`;c.length>0&&n.push(`flow change: ${d} no longer performs ${r(c.length)} from the committed recording: ${c.map(ft).join("; ")}. A page or navigation step may have been removed or merged.`),l.length>0&&n.push(`flow change: ${d} now performs ${r(l.length)} the committed recording did not: ${l.map(ft).join("; ")}. A page or navigation step may have been added or reordered.`)}return n}function Wo(e){let t=[];t.push(`${e.feature} \u203A ${e.scenario}`),t.push(e.hasCommitted?"Comparing the committed recording with the proposed one.":"First recording for this scenario: there is nothing to compare against."),t.push("");for(let a of e.steps){let i=a.change==="removed"?"- ":a.change==="added"&&e.hasCommitted?"+ ":" ";t.push(`${i}${a.kind==="assertion"?"[assertion] ":""}${a.gherkin}`+(a.fromStepSet?` (from step set "${a.fromStepSet}")`:""));for(let c of a.actions)if(c.change==="same")t.push(` ${c.before}`);else if(c.change==="added")t.push(` + ${c.after}`);else if(c.change==="removed")t.push(` - ${c.before}`);else{t.push(` - ${c.before}`),t.push(` + ${c.after}`);for(let l of c.details??[])t.push(` ${l}`)}t.push("")}if(e.featureEdits?.length){t.push("Feature file edits, applied only by saffron accept --with-feature-edit:");for(let a of e.featureEdits){let i=a.fromStepSet?` (step set "${a.fromStepSet}": every scenario that uses it)`:"";t.push(` - ${a.from}${i}`,` + ${a.to}`),a.skipped&&t.push(` (accept skips this edit: ${a.skipped})`)}t.push("")}if(e.recording?.length){t.push("Beside the steps:");for(let a of e.recording)t.push(` ! ${a}`);t.push("")}let{added:n,removed:r,changed:s,assertions:o}=e.summary;return t.push(n+r+s===0?e.recording?.length?"No action changed, but the recording did (above): read that first.":"No action changed.":`${s} changed, ${n} added, ${r} removed.`+(o>0?` ${o} of them ${o===1?"is an assertion":"are assertions"}: read those first.`:"")),t.map(a=>le(a,1/0)).join(`
|
|
31
|
+
`)}var Xu=5e3,ty=new Set(["click","press","selectOption","check","uncheck","hover","dragTo"]);function of(e){return e.mode==="heal"||e.mode==="refine"}function ic(e){return e.mode==="heal"||e.mode==="refine"?e.failedStep?.stepIndex??e.completedSteps?.length??0:e.recordOnly?e.recordOnly.from:e.completedSteps?.length??0}var ef=/^\s*(?:[\w-]+\s+)?(?:section|form|card|dialog|modal|panel|row|table|list|region|area|tab|popup|menu|group|box|column|drawer|sidebar|block)s?\b/i,ny=/\b(?:field|input|selector|select|dropdown|picker|checkbox|radio|button|link|option|flag|toggle|switch|label|error|message|price|total|amount|heading|title|badge)s?\s*$/i;function Rs(e,t=!1){let n=[];for(let r of e.matchAll(/\b(in|inside|within|under)\s+(?:the\s+)?"([^"]+)"/gi)){let s=e.slice(0,r.index),o=e.slice(r.index+r[0].length),a=r[1].toLowerCase();(a==="inside"||a==="within"||ef.test(o)||!t&&(/"[^"]*"/.test(s)&&!/\b(?:fill|type|log|sign)\s*$/i.test(s)||ny.test(s)))&&n.push(r[2])}for(let r of e.matchAll(/\bthe\s+"([^"]+)"/gi))ef.test(e.slice(r.index+r[0].length))&&!n.includes(r[1])&&n.push(r[1]);return n}var ry=e=>e?sc([e.name,e.nameRegex,e.label,e.text,e.placeholder,e.testId,e.frame,...e.fallbackSelectors??[]].join(`
|
|
32
|
+
`).replace(/\\/g,"")):"",sc=e=>e.toLowerCase().replace(/[-_ ]+/g," "),sy=/^(?:option|menuitem|menuitemradio|menuitemcheckbox|treeitem|dialog|alertdialog)$/,oy=/role=(?:option|menuitem\w*|treeitem|(?:alert)?dialog)\b|\[role=["']?(?:option|menuitem\w*|treeitem|(?:alert)?dialog)\b/;function ac(e,t,n=!1,r=!1){let s=sc(t);if(!r&&e.some(i=>i.value!==void 0&&sc(i.value).includes(s)))return[];let o=!1,a=i=>i.target!==void 0&&$e.has(i.action)&&(r||[i.target.name,i.target.nameRegex,i.target.label,i.target.text,i.target.placeholder,i.target.testId,...i.target.fallbackSelectors??[]].some(c=>c!==void 0&&c!==""));return e.filter(i=>Jr(i)&&i.action!=="waitFor"||Qo(i)||n&&a(i)).filter(i=>{if(ry(i.target).includes(s))return o=!0,!1;let c=sy.test(i.target?.role??"")||oy.test((i.target?.fallbackSelectors??[]).join(`
|
|
33
|
+
`));return!(o&&c)})}function Xa(e){let t=e.target;if(!t)return;let n=[...(t.fallbackSelectors?.[0]??"").split(">>").pop().matchAll(/(?:name|data-testid|label|text)=\\?"((?:[^"\\]|\\.)*)\\?"/g)].pop()?.[1],r=t.name??t.label??t.text??t.placeholder??t.testId??n;return r===void 0||r===""?void 0:r.toLowerCase()}var tf=new Set(["waitForDownload","handleDialog","uploadFile"]),Jr=e=>e.target!==void 0&&!$e.has(e.action)&&e.action!=="captureText",Qo=e=>e.action==="captureText"&&e.target!==void 0,ec=e=>`${e} action${e===1?"":"s"}`,tc=e=>e.map(ft).join("; "),Go=class{firstStep;lastStep;discardBeforeAnnounce;preAnnounce=[];discarded=[];carried;pendingTabOpen=!1;pendingTabFallback;lastOpener;lastOpenerAt=0;lastOpenerSession="";sessionKeys;inFlight=new Set;redoing=new Map;redoBase=new Map;replaced=[];lastFiled;setupSteps;steps;resolvedTexts;currentStepIndex=-1;done=!1;success=!1;narrative="";adaptations=[];suggestedFeatureEdit;featureEdits=[];announced=new Set;pendingFingerprint;lastDownload;downloadUnarmed=!1;params;envNames;writtenTexts;startedAt;uniqueSeed;constructor(t,n={}){this.setupSteps=t.steps.map(r=>r.setup),this.params=t.params,this.envNames=ct(t),this.writtenTexts=Or(t),this.startedAt=n.startedAt??new Date,this.uniqueSeed=n.uniqueSeed??"",this.firstStep=Math.max(n.firstStep??0,0),this.lastStep=n.lastStep,this.discardBeforeAnnounce=n.discardBeforeAnnounce??!1,this.sessionKeys=t.steps.map(r=>we(r.session)),this.steps=t.steps.map(r=>({gherkin:r.text,keyword:r.keyword,kind:r.kind,table:r.table,docString:r.docString,fromStepSet:r.source?.fromStepSet,actions:[]})),this.resolvedTexts=t.steps.map(r=>r.resolvedText??r.text)}redo(t){for(let{index:n,actions:r}of t){let s=this.steps[n]?.actions??[];this.redoBase.set(n,new Set(s));let o=[];for(let a of[...r].sort((i,c)=>s.indexOf(i)-s.indexOf(c))){let i=s.indexOf(a);if(i<0)continue;let c=[a];for(;i>0&&tf.has(s[i-1].action)&&!(s[i-1].action==="uploadFile"&&s[i-1].target);)c.unshift(s[--i]);o.push(c)}this.redoing.set(n,o)}}addArmedAction(t){if(this.done)return;let n=this.destination();if(this.lastFiled&&!n?.includes(this.lastFiled)){let i=this.steps.findIndex((c,l)=>l>=this.firstStep&&c.actions.includes(this.lastFiled));i>=0&&(n=this.steps[i].actions)}if(!n){this.discard([t],this.refusalReason());return}let r=this.lastFiled?n.indexOf(this.lastFiled):-1,s=r>=0?r:Math.max(n.length-1,0),o=n[s-1];if(t.action==="waitForDownload"&&o?.action==="waitForDownload"){o.downloads=(o.downloads??1)+(t.downloads??1);return}o!==void 0&&o.action===t.action&&o.value===t.value&&o.promptText===t.promptText||n.splice(s,0,t)}destination(){if(this.currentStepIndex<0)return this.discardBeforeAnnounce?void 0:this.firstStep===0?this.steps[0]?.actions:this.preAnnounce;if(!(this.currentStepIndex<this.firstStep))return this.steps[this.currentStepIndex]?.actions}refusalReason(){let t=this.currentStepIndex;return t<0?`before announcing the failed step (step ${this.firstStep+1}); a heal records nothing until it announces that step, so this exploration was not filed under any step`:`under step ${t+1} ("${this.steps[t]?.gherkin??""}"), which had already run before the agent took over, so its recording was kept`}discard(t,n){if(t.length===0)return;let r=this.discarded.find(s=>s.why===n);r?r.actions.push(...t):this.discarded.push({actions:[...t],why:n})}announce(t,n,r){if(this.currentStepIndex=t,this.announced.add(t),r){let o=`Step ${t+1} (`;this.adaptations=this.adaptations.filter(a=>!a.startsWith(o)),this.adaptations.push(`${o}"${n}"): ${r}`)}let s=this.steps[t];this.preAnnounce.length>0&&t>=this.firstStep&&s&&(s.actions.unshift(...this.preAnnounce),this.carried={index:t,actions:this.preAnnounce},this.preAnnounce=[])}attributionNotes(){let t=[];if(this.carried){let{index:r,actions:s}=this.carried;t.push(`recording: ${ec(s.length)} the agent performed before announcing a step ${s.length===1?"was":"were"} filed under step ${r+1} ("${this.steps[r]?.gherkin??""}"), the first step it recorded: ${tc(s)}.`)}let n=this.preAnnounce.length>0?[{actions:this.preAnnounce,why:"before announcing a step this session records"}]:[];for(let{actions:r,why:s}of[...this.discarded,...n])t.push(`recording: discarded ${ec(r.length)} the agent performed ${s}: ${tc(r)}.`);for(let{index:r,actions:s}of this.replaced)t.push(`recording: step ${r+1} ("${this.steps[r]?.gherkin??""}") was performed again when Saffron asked, replacing ${ec(s.length)}: ${tc(s)}.`);return t}beginToolCall(t){this.inFlight.add(t)}endToolCall(t,n){this.inFlight.delete(t)&&(this.pendingTabOpen&&n&&(this.pendingTabFallback=void 0),this.inFlight.size===0&&this.pendingTabOpen&&(this.pendingTabFallback&&(this.pendingTabFallback.opensTab=!0),this.pendingTabOpen=!1,this.pendingTabFallback=void 0))}markTabOpened(t){let r=Date.now()-this.lastOpenerAt<=Xu&&(t===void 0||t===this.lastOpenerSession)?this.lastOpener:void 0,s=t!==void 0&&t!==this.sessionOf(this.currentStepIndex);if(this.inFlight.size===0||s){r&&(r.opensTab=!0);return}this.pendingTabOpen=!0,this.pendingTabFallback=r}creditLateDownload(){let t=Date.now()-this.lastOpenerAt<=Xu?this.lastOpener:void 0;if(!t)return!1;for(let n of this.steps){let r=n.actions.indexOf(t);if(r<0)continue;let s=n.actions[r-1];return s?.action==="waitForDownload"?s.downloads=(s.downloads??1)+1:n.actions.splice(r,0,{action:"waitForDownload"}),!0}return!1}sessionOf(t){return this.sessionKeys[t>=0?t:this.firstStep]??""}addActions(t){if(this.done||t.length===0)return;if(this.currentStepIndex<0&&this.firstStep>0&&!this.discardBeforeAnnounce){let i=t.filter(c=>c.action==="switchTab");if(this.discard(i,"before announcing its first step (replay is already on the live page when the agent takes over)"),t=t.filter(c=>c.action!=="switchTab"),t.length===0)return}let n=this.destination();if(!n){this.pendingFingerprint=void 0,this.discard(t,this.refusalReason());return}this.pendingFingerprint&&t[0]&&(t[0].pageFingerprint=this.pendingFingerprint,this.pendingFingerprint=void 0);let r=this.redoing.get(this.currentStepIndex),s=i=>Qo(i)?"capture":Jr(i)&&i.action!=="waitFor"?"interaction":i.target!==void 0&&$e.has(i.action)?"check":void 0,o=(r??[]).map(i=>({flagged:i[i.length-1],actions:i.filter(c=>n.includes(c))})).filter(i=>i.actions.length>0);if(o.length>0){let i=new Map,c=[];for(let f of t){let g=s(f);if(g===void 0)continue;let y=Xa(f),h=o.findIndex(x=>s(x.flagged)===g&&(y===void 0||Xa(x.flagged)===void 0||Xa(x.flagged)===y));if(h<0)continue;let[S]=o.splice(h,1),v={action:"waitFor"};n.splice(n.indexOf(S.actions[0]),0,v);for(let x of S.actions)n.splice(n.indexOf(x),1);i.set(f,v),c.push(...S.actions)}let l=(f,g)=>JSON.stringify({...f,pageFingerprint:void 0})===JSON.stringify({...g,pageFingerprint:void 0}),d=(f,g,y=0)=>{let h=f-1;for(;h>=0&&s(n[h])!=="interaction";)h--;let S=g.findIndex(m=>s(m)!==void 0),v=g[S],x=m=>JSON.stringify([m.action,m.target,m.toTarget,m.clickCount,m.button,m.modifiers,m.value]);if(h>=0&&v!==void 0&&s(v)==="interaction"&&!i.has(v)&&this.redoBase.get(this.currentStepIndex)?.has(n[h])&&x(v)===x(n[h])){let m=h;for(;m>0&&tf.has(n[m-1].action)&&!(n[m-1].action==="uploadFile"&&n[m-1].target);)m--;c.push(...n.slice(m,h+1)),n.splice(m,h+1-m,...g.slice(0,S+1)),f+=S-(h-m),g=g.slice(S+1)}let b=n.slice(h+1,f);g=g.filter(m=>i.has(m)||s(m)==="interaction"||!b.some($=>l(m,$))),n.splice(f,y,...g)},u=[];for(let f of t){u.push(f);let g=i.get(f);g&&(d(n.indexOf(g),u,1),u=[])}let p=o[0]?.actions[0];if(u.length>0&&d(p?n.indexOf(p):n.length,u),c.length>0){let f=this.replaced[this.replaced.length-1];f?.index===this.currentStepIndex?f.actions.push(...c):this.replaced.push({index:this.currentStepIndex,actions:c})}o.length>0?this.redoing.set(this.currentStepIndex,o.map(f=>f.actions)):this.redoing.delete(this.currentStepIndex)}else this.redoing.delete(this.currentStepIndex),n.push(...t);this.lastFiled=[...t].reverse().find(i=>Jr(i)&&i.action!=="waitFor"&&n.includes(i))??t[t.length-1];let a=[...t].reverse().find(i=>ty.has(i.action));a&&(this.lastOpener=a,this.lastOpenerAt=Date.now(),this.lastOpenerSession=this.sessionOf(this.currentStepIndex),this.pendingTabOpen&&(a.opensTab=!0,this.pendingTabOpen=!1,this.pendingTabFallback=void 0))}},iy={n:`
|
|
34
|
+
`,r:"\r",t:" ",b:"\b",f:"\f",v:"\v",0:"\0"},Mt=e=>e.replace(/\\(?:x([0-9a-fA-F]{2})|u\{([0-9a-fA-F]+)\}|u([0-9a-fA-F]{4})|([\s\S]))/g,(t,n,r,s,o)=>r!==void 0?String.fromCodePoint(parseInt(r,16)):n!==void 0||s!==void 0?String.fromCharCode(parseInt(n??s,16)):iy[o]??o);function ay(e){let t=e.match(/'((?:[^'\\]|\\.)*)'/);return t?Mt(t[1]):void 0}function af(e){let t=[],n=0;for(;n<e.length;){let r=/^\.?([A-Za-z]+)\(/.exec(e.slice(n));if(!r)return;let s=n+r[0].length,o=s,a=1,i;for(;s<e.length&&a>0;s++){let c=e[s];if(i)c==="\\"?s++:c===i&&(i=void 0);else if(c==="'"||c==='"'||c==="`")i=c;else if(c==="/"&&/[(,:]\s*$/.test(e.slice(o-1,s)))for(s++;s<e.length&&e[s]!=="/";s++)e[s]==="\\"&&s++;else c==="("||c==="{"||c==="["?a++:(c===")"||c==="}"||c==="]")&&a--}if(a!==0)return;t.push({method:r[1],args:e.slice(o,s-1)}),n=s}return t}function nc(e,t){let n=/^'((?:[^'\\]|\\.)*)'$/.exec(e.trim());if(n)return`${JSON.stringify(Mt(n[1]))}${t?"s":"i"}`;let r=/^\/((?:[^/\\]|\\.)*)\/([a-z]*)$/.exec(e.trim());if(!r)return;let s=wa(r[1]);return s!==r[1]&&/[uv]/.test(r[2])?void 0:`/${s}/${r[2]}`}var cy=new Set(["checked","disabled","selected","expanded","includeHidden","level","pressed","busy"]);function nf(e,t){let n=/exact:\s*true/.test(t),r=/^\s*('(?:[^'\\]|\\.)*'|\/(?:[^/\\]|\\.)*\/[a-z]*)/.exec(t)?.[1];switch(e){case"locator":{let s=/^\s*'((?:[^'\\]|\\.)*)'\s*$/.exec(t);return s?Mt(s[1]):void 0}case"getByRole":{let s=/^\s*'([^']+)'/.exec(t)?.[1];if(!s)return;let o="";for(let[,a,i]of t.matchAll(/(\w+):\s*('(?:[^'\\]|\\.)*'|\/(?:[^/\\]|\\.)*\/[a-z]*|[^,}\s]+)/g))if(a==="name"||a==="description"){let c=nc(i,n);if(c===void 0)return;o+=`[${a}=${c}]`}else if(cy.has(a))o+=`[${a==="includeHidden"?"include-hidden":a}=${i.replace(/^'(.*)'$/,"$1")}]`;else if(a!=="exact")return;return`internal:role=${s}${o}`}case"getByText":case"getByLabel":case"getByPlaceholder":case"getByAltText":case"getByTitle":{let s=r===void 0?void 0:nc(r,n);return s===void 0?void 0:e==="getByText"?`internal:text=${s}`:e==="getByLabel"?`internal:label=${s}`:`internal:attr=[${{getByPlaceholder:"placeholder",getByAltText:"alt",getByTitle:"title"}[e]}=${s}]`}case"getByTestId":{let s=r&&/^'/.test(r)?Mt(r.slice(1,-1)):void 0;return s===void 0?void 0:`internal:testid=[data-testid=${JSON.stringify(s)}s]`}case"first":return"nth=0";case"last":return"nth=-1";case"nth":return/^\s*-?\d+\s*$/.test(t)?`nth=${t.trim()}`:void 0;case"filter":{let s=/hasText:\s*('(?:[^'\\]|\\.)*'|\/(?:[^/\\]|\\.)*\/[a-z]*)/.exec(t);if(!s||!/^\s*\{\s*\}\s*$/.test(t.replace(s[0],"")))return;let o=nc(s[1],!1);return o===void 0?void 0:`internal:has-text=${o}`}default:return}}function ly({method:e,args:t}){let n=String.raw`'(?:[^'\\]|\\.)*'`;return e==="getByRole"?new RegExp(String.raw`^\s*'[^']+'\s*(?:,\s*\{\s*(?:name:\s*${n}\s*(?:,\s*exact:\s*true\s*)?)?\}\s*)?$`).test(t):["getByText","getByLabel","getByPlaceholder","getByTestId","locator"].includes(e)&&new RegExp(String.raw`^\s*${n}\s*$`).test(t)}function rc(e){let t={},n=e.match(/(?:frameLocator\('((?:[^'\\]|\\.)*)'\)|locator\('((?:[^'\\]|\\.)*)'\)\.contentFrame\(\))/);n&&(t.frame=Mt(n[1]??n[2]),e=e.slice((n.index??0)+n[0].length));let r=af(e.replace(/^\./,"")),s=r?.filter((c,l)=>!(c.method==="first"&&l===r.length-1));if(s&&s.length>1){let c=s.map(l=>nf(l.method,l.args));return c.some(l=>l===void 0)?void 0:{...t,fallbackSelectors:[c.join(" >> ")]}}if(s?.length===1&&!ly(s[0])){let c=nf(s[0].method,s[0].args);return c===void 0?void 0:{...t,fallbackSelectors:[c]}}let o=e.match(/getByRole\('([^']+)'(?:,\s*\{([^}]*)\})?\)/);if(o){t.role=o[1];let c=(o[2]??"").match(/name:\s*'((?:[^'\\]|\\.)*)'/);c&&(t.name=Mt(c[1]))}let a=[[/getByLabel\('((?:[^'\\]|\\.)*)'\)/,"label"],[/getByText\('((?:[^'\\]|\\.)*)'\)/,"text"],[/getByTestId\('((?:[^'\\]|\\.)*)'\)/,"testId"],[/getByPlaceholder\('((?:[^'\\]|\\.)*)'\)/,"placeholder"]];for(let[c,l]of a){let d=e.match(c);d&&(t[l]=Mt(d[1]))}let i=e.match(/(?:^|\.)locator\('((?:[^'\\]|\\.)*)'\)/);return i&&(t.fallbackSelectors=[Mt(i[1])]),Object.keys(t).length>0?t:void 0}var rf={click:"click",dblclick:"click",fill:"fill",pressSequentially:"fill",type:"fill",press:"press",check:"check",uncheck:"uncheck",hover:"hover",selectOption:"selectOption"};function dy(e,t){let n=e.match(/page\.goto\('((?:[^'\\]|\\.)*)'\)/);if(n)return{action:"goto",url:xs(Mt(n[1]),t)};let r=e.match(/page\.keyboard\.press\('((?:[^'\\]|\\.)*)'\)/);if(r)return{action:"press",value:Mt(r[1])};let s=e.match(/await\s+page\.(.+)\.dragTo\(page\.(.+?)\);?\s*$/);if(s){let y=rc(s[1]),h=rc(s[2]);if(y&&h)return{action:"dragTo",target:y,toTarget:h}}let o=/await\s+page\.(.*\))\s*;?\s*$/.exec(e)?.[1],a=o===void 0?void 0:af(o),i=a?.[a.length-1];if(!a||!i||a.length<2||!Object.hasOwn(rf,i.method))return;let{method:c,args:l}=i,d=a.slice(0,-1).map(y=>`${y.method}(${y.args})`).join("."),u=rc(d);if(!u||c==="pressSequentially"&&/^\s*''\s*\)?\s*;?\s*$/.test(l))return;let p={action:rf[c],target:u};if(c==="click"||c==="dblclick"){let y=/clickCount:\s*(\d+)/.exec(l)?.[1];c==="dblclick"?p.clickCount=2:y&&y!=="1"&&(p.clickCount=Number(y));let h=/button:\s*'(left|right|middle)'/.exec(l)?.[1];h&&h!=="left"&&(p.button=h);let S=/modifiers:\s*\[([^\]]*)\]/.exec(l)?.[1],v=S?[...S.matchAll(/'((?:[^'\\]|\\.)*)'/g)].map(x=>Mt(x[1])):[];return v.length>0&&(p.modifiers=v),p}let f=c==="selectOption"?/^\s*\[((?:'(?:[^'\\]|\\.)*'|[^\]'])*)\]/.exec(l)?.[1]:void 0;if(f!==void 0&&!f.trim())return{...p,clearSelection:!0};let g=f?.trim()?[...f.matchAll(/'((?:[^'\\]|\\.)*)'/g)].map(y=>Mt(y[1])).join(`
|
|
35
|
+
`):ay(l);return g!==void 0&&(p.value=g),p}function cf(e){let t=Array.isArray(e)?e:e?.content,n=typeof e=="string"?[e]:Array.isArray(t)?t.flatMap(r=>typeof r?.text=="string"?[r.text]:[]):[];for(let r of n){let s=r.split(/^### Open tabs\r?$/m)[1]?.split(/^### /m)[0];if(!s)continue;let o=/^- (\d+): \(current\) /m.exec(s)?.[1];if(o!==void 0)return Number(o)}}function lf(e){let t=Array.isArray(e)?e:e?.content;return(typeof e=="string"?[e]:Array.isArray(t)?t.flatMap(r=>typeof r?.text=="string"?[r.text]:[]):[]).reduce((r,s)=>r+[...(s.split(/^### Events\r?$/m)[1]?.split(/^### /m)[0]??"").matchAll(/^- Downloading file .* \.\.\.\r?$/gm)].length,0)}function cc(e){if(typeof e=="string")return[e];let t=Array.isArray(e)?e:e?.content;return Array.isArray(t)?t.flatMap(n=>typeof n?.text=="string"?[n.text]:[]):[]}function df(e){let t=new Map;for(let n of cc(e).flatMap(r=>r.split(/^### Snapshot[ \t\r]*$/m).slice(1).map(s=>s.split(/^### /m)[0])))for(let r of n.matchAll(/^\s*-\s+([a-z]+)\s+"((?:[^"\\\n]|\\.)*)"((?:[ \t]+\[[^\]\n]*\])+)/gm)){let s=/\[ref=([^\]]+)\]/.exec(r[3])?.[1];if(!s)continue;let o=r[2];try{o=JSON.parse(`"${r[2]}"`)}catch{}t.set(s,{role:r[1],name:o})}return t}function uf(e){let t=s=>{let o=s?.ref??s?.target;return typeof o=="string"&&/^(?:f\d+)?e\d+$/.test(o)?o:void 0},n=e?.fields;if(Array.isArray(n))return n.map(t);let r=t(e)??t({ref:e?.startRef});return r?[r]:[]}function ff(e,t,n){let r=s=>s.toLowerCase().replace(/\s+/g," ").trim();e.filter(Jr).forEach((s,o)=>{let a=t.length===1?t[0]:t[o],i=a===void 0?void 0:n.get(a),c=s.target;!i||c.role!==i.role||c.name===void 0||c.name===i.name||c.name.trim()===""||r(i.name).includes(r(c.name))&&(c.name=i.name)})}function pf(e,t){let n=[],r=Array.isArray(e)?e:e?.content;if(Array.isArray(r))for(let o of r){let a=o?.text;typeof a=="string"&&n.push(a)}else typeof e=="string"&&n.push(e);let s=[];for(let o of n){let a=o.split(/^### Ran Playwright code[ \t\r]*$/m).slice(1).map(i=>i.split(/^### /m)[0]).join(`
|
|
36
|
+
`);for(let i of a.split(`
|
|
37
|
+
`)){let c=dy(i.trim(),t);c&&s.push(c)}}return uy(s)}function uy(e){return e.filter((t,n)=>{let r=e[n+1];return!(t.action==="fill"&&(t.value??"")===""&&r?.action==="fill"&&JSON.stringify(r.target)===JSON.stringify(t.target))})}function gf(e){let t=[];for(let n of e){if(n.kind==="assertion"&&n.actions.length===0){t.push(`Step "${n.gherkin}" is an assertion but recorded no check, so nothing would be verified. Re-record with: saffron run --rerecord`);continue}let r=me(n.gherkin),s=r.replace(/"[^"]*"|<[^<>]+>/g," "),o=/\b(?:clear|clears|clearing|erase|erases|wipe|wipes)\b/i.test(s)||/(?<!\b(?:the|is|are)\s+)\b(?:empty|empties|blank)\b/i.test(s);if(!/"[^"]+"|<[^<>]+>/.test(r)||o)continue;n.actions.filter(i=>i.action==="fill"&&(i.value??"")==="").length>(r.match(/""/g)??[]).length&&t.push(`Step "${n.gherkin}" recorded a fill with an empty value although the step passes one; the typed value was lost. Re-record with: saffron run --rerecord`)}return t}function hf(e,t,n=fe.pattern){for(let[r,s]of t){let o=Qd(e,n(s));if(o)return o==="bare"?`<${r}>`:`^<${r}>$`}}function Hr(e,t,n=o=>o,r=!1,s=Object.keys(t)){let o=Object.entries(t).filter(([,i])=>i.length>=3);if(!r)return Ko(e,o,i=>new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),n,s);let a=o.find(([,i])=>!Pa(i)&&e===n(i));return a?`<${a[0]}>`:Ko(e,o.filter(([,i])=>Pa(i)),i=>Oe(i,"gu"),n,s)}function Ko(e,t,n,r=o=>o,s=t.map(([o])=>o)){let o=new RegExp(`(${or(s).source}|\\{(?:env|data|unique|date)[^{}<]*<[^{}]*\\})`);return[...t].sort((a,i)=>i[1].length-a[1].length).reduce((a,[i,c])=>a.split(o).map((l,d)=>{if(d%2)return l;let u=l.normalize("NFC"),p=u.replace(n(r(c).normalize("NFC"),c),()=>`<${i}>`);return p===u?l:p}).join(""),e)}function fy(e,t,n){if(/^\s*(?:xpath=|\/\/)/.test(e))return e.replace(/'([^']*)'|"([^"]*)"/g,(o,a,i)=>a!==void 0?`'${n(a)}'`:`"${n(i)}"`);let r,s=!0;return wn(e,t,o=>o.split(/(>>)/).map((a,i)=>i%2?a:((s||i>0)&&(r=a.match(/^\s*([a-z_-]+(?::[a-z_-]+)?)=/i)?.[1]?.toLowerCase()),s=!1,r===void 0?a.replace(/([#.])((?:[\p{L}\p{N}\p{M}_-]|\\.)+)/gu,(c,l,d)=>l+n(d)):/^(?:id|data-testid|data-test-id|data-test)$/.test(r)?a.replace(/=(.*)$/s,(c,l)=>`=${n(l)}`):a)).join(""))}function Xo(e,t){let n=[me(e??""),me(t?.text??""),...t?.table?.flat()??[],t?.docString??""].join(`
|
|
38
|
+
`);return new Set([...n.matchAll(/<([^<>]+)>/g)].map(r=>r[1]))}function Ts(e,t){let n=[e?.text??"",...e?.table?.flat()??[],e?.docString??""].join(`
|
|
39
|
+
`).replace(/<[^<>]+>/g," ");try{return t(n)}catch{return n}}function lc(e,t,n=e,r="",s=o=>[n[o]??e[o]]){let o=new Map;for(let a of Object.keys(e))o.set(n[a]??e[a],[...o.get(n[a]??e[a])??[],a]);return Object.fromEntries(Object.entries(e).filter(([a,i])=>{let c=n[a]??i;if(c!==""&&Oe(c).test(r)&&(!t.has(a)||!s(a).every(d=>Oe(d).test(r))))return!1;let l=o.get(c);return l.length>1&&l.some(d=>/\{env:/.test(e[d]))?!1:(l.find(d=>t.has(d))??l[0])===a}))}function Yo(e,t,n){let r=e.flatMap(s=>{let o=s[t];if(o===void 0)return[];try{return[n(o)]}catch{return[o]}});return[...new Set(r)].filter(s=>s.trim()!=="")}function mf(e,t,n,r){return e(t).filter(s=>s!==n&&!/\{(?:env|data|unique|date)/.test(s)&&(s.length>=3||r.has(t)))}function oc(e,t){return new RegExp(`(^|[-_:.])${ue(e)}(?=$|[-_:.])`,t)}function ei(e,t){let n=Object.keys(t.params);if(n.length===0)return[];let r=tt(e.map(x=>x.gherkin)),s=new Date().toISOString(),o=t.exampleRows??[t.params],a=Er(o.flatMap(x=>Object.values(x))),i=x=>x.replace(ve,(b,m)=>a.get(m)??b).replace(Se,(b,m)=>process.env[m]??b),c=Object.fromEntries(Object.entries(t.params).map(([x,b])=>[x,i(b)])),l=x=>!/\{(?:env|data|unique|date)/.test(x),d=x=>Yo(o,x,i),u=(x,b,m)=>{let $=x.trim(),T=`${b}
|
|
40
|
+
${b.replace(ve,(k,C)=>m.get(C)??k)}`.toLowerCase(),R=k=>b.includes(k)&&($===k||$.startsWith(k)&&/^[/?#]/.test($.slice(k.length))||T.includes($.toLowerCase()));return x.replace(or(n)," ").replace(ve,(k,C)=>R(k)?k:a.get(C)??m.get(C)??k).replace(Se,(k,C)=>R(k)?k:process.env[C]??k).replace(/\{(?:env|data|unique|date)[^{}]*\}/g," ")},p=[],f=[...new Set(t.steps.flatMap(x=>[x.text,...x.table?.flat()??[],x.docString??""]).flatMap(x=>[...x.matchAll(/\{data:([^{}]*<[^<>{}]+>[^{}]*)\}/g)].map(b=>b[1])))].flatMap(x=>{let b=[...x.matchAll(/<([^<>]+)>/g)].map(T=>T[1]).filter(T=>T in t.params),$=(T=>{if(!b.some(R=>/[{}<>]/.test(T[R]??"{")))try{return Le(x.replace(/<([^<>]+)>/g,(R,k)=>T[k]??R))}catch{return}})(t.params);return b.length===0||$===void 0||$.trim()===""?[]:[{used:b,value:$.trim().toLowerCase()}]}),g=[...As(t).all].filter(([,x])=>x.size>1);g.length>0&&e.forEach((x,b)=>{let m=x.actions.flatMap($=>Pt($)).filter($=>$!==void 0);for(let[$,T]of g){if(!m.some(k=>k.includes($)))continue;let R=new Set([...T].flatMap(k=>[...k.matchAll(/<([^<>]+)>/g)].map(C=>C[1])));for(let k of R)k in t.params&&p.push({column:k,step:b,reason:"data"})}});let{own:y,all:h}=As(t),S=[...Zo(h)];S.length>0&&e.forEach((x,b)=>{let m=Zo(y[b]??new Map),$=Ts(t.steps[b],R=>R).replace(/\{[^{}]*\}/g," "),T=x.actions.flatMap(R=>Pt(R)).filter(R=>R!==void 0);for(let[R,k]of S){let C=m.get(R),P=R.trim()!==""&&(Oe(R).test($)||R.length>=4&&$.includes(R));if(!C&&P)continue;let w=C??k,E=Mr(R).exact,_=I=>R.trim()===""?I.trim()==="":E.some(U=>R.length>=3?I.includes(U):Oe(U).test(I)),A=[t.steps[b]?.text??x.gherkin,...t.steps[b]?.table?.flat()??[],t.steps[b]?.docString??""].join(`
|
|
41
|
+
`),O=[...w].some(I=>JSON.stringify(x.actions).split(I).length>A.split(I).length);if(!(C===void 0?_a(x.actions,R):w.size>1&&T.some(_)||P&&(T.some(_)||O)||Un(x.actions,R)))continue;let L=new Set([...w].flatMap(I=>[...I.matchAll(/<([^<>]+)>/g)].map(U=>U[1])));for(let I of L)I in t.params&&!p.some(U=>U.column===I&&U.step===b)&&p.push({column:I,step:b,reason:"data"})}});let v=x=>{let b=Xd(t.params[x]);return b?{valueSha:b}:{}};return e.forEach((x,b)=>{let m=Xo(x.gherkin,t.steps[b]),$=lc(c,m,c,Ts(t.steps[b],N=>N),d),T=Object.entries($).filter(([N,M])=>l(M)&&M.trim()!==""&&(M.length>=3||m.has(N))),R=new Set(T.filter(([N])=>m.has(N)).map(([,N])=>N)),k=t.steps[b],C=[k?.text??x.gherkin,...k?.table?.flat()??[],k?.docString??""].join(`
|
|
42
|
+
`),P=Er([C]),w=[C,...P.values()].join(`
|
|
43
|
+
`),E=x.actions.flatMap(N=>Bn(N)).flatMap(N=>N===void 0?[]:[u(N,w,P).normalize("NFC")]),A=x.actions.flatMap(N=>N.each!==void 0&&!C.includes(N.each)?N.each.match(/^\{data:([^{}]+)\}$/)?.slice(1)??[]:[]).map(N=>N.toLowerCase()),O=x.actions.flatMap(N=>N.attribute!==void 0?[N.attribute]:[]),j=N=>[N,N.replace(/\s+/g,"-"),N.replace(/\s+/g,"_")].some(M=>A.some(B=>B.includes(M))||O.some(B=>oc(M,"i").test(B))),L=x.actions.flatMap(N=>[N.status,N.method,N.attribute]).flatMap(N=>N===void 0?[]:[u(N,w,P).trim().toLowerCase()]),I=new Set;for(let[N,M]of Object.entries(c)){let B=M.trim().toLowerCase();m.has(N)||/\{(?:date|unique)/.test(t.params[N]??"")||B===""||!L.includes(B)||(p.push({column:N,step:b,reason:"value",...v(N)}),I.add(N))}for(let[N,M]of Object.entries(c)){if(I.has(N)||/\{(?:date|unique)/.test(t.params[N]??""))continue;let B=M.trim().toLowerCase();B.length<3||!j(B)||(p.push({column:N,step:b,reason:"glued",...v(N)}),I.add(N))}for(let{used:N,value:M}of f)if(L.includes(M))for(let B of N)I.has(B)||(p.push({column:B,step:b,reason:"reads",...v(B)}),I.add(B));for(let[N,M]of T){if(I.has(N))continue;let B=mf(d,N,M,m);B.length>0&&E.some(J=>Nr(J,M,R.has(M))&&B.some(ne=>Nr(J,ne,R.has(M))))?p.push({column:N,step:b,reason:"list",...v(N)}):!m.has(N)&&M.length>=3&&E.some(J=>Oa(M.normalize("NFC")).test(J))&&p.push({column:N,step:b,reason:"glued",...v(N)})}let U=N=>p.some(M=>M.column===N&&M.step===b);for(let N of Object.keys(t.params)){let M=c[N]??"";if(U(N)||M.trim()==="")continue;let B=Object.keys(c).filter(ne=>c[ne]===M);if(B.length>1&&o.some(ne=>new Set(B.map(Me=>i(ne[Me]??""))).size>1))continue;let J={...t.params,...Object.fromEntries(B.map(ne=>[ne,"\u2063another row\u2063"]))};sr(x.actions,C,t.params,J,s)&&p.push({column:N,step:b,reason:"glued",...v(N)})}if(x.actions.some(N=>N.target!==void 0)){let N=new Set(Rs(x.gherkin,!0));for(let M of Rs(x.gherkin))for(let[,B]of M.matchAll(/<([^<>]+)>/g))!(B in t.params)||U(B)||ac(x.actions,`<${B}>`,x.kind==="assertion",N.has(M)).length===0||p.push({column:B,step:b,reason:"container",...v(B)})}let D=N=>x.kind==="assertion"&&!jr(x.actions)&&!(t.params[N]??"").includes("{date"),q=[t.steps[b]?.text??x.gherkin,...t.steps[b]?.table?.flat()??[],t.steps[b]?.docString??""].join(`
|
|
44
|
+
`),Y=N=>_o(q,N,c);for(let N of Ir(x.gherkin,x.actions,t.params).filter(M=>!D(M)&&!Y(M)))N in t.params&&!U(N)&&(c[N]??"").trim()!==""&&p.push({column:N,step:b,reason:"unwritten",...v(N)});let Q=r[b];if(Q!==void 0&&/<[^<>]+>/.test(Q)){let N=`${C}
|
|
45
|
+
${C.replace(ve,(J,ne)=>P.get(ne)??J).replace(Se,(J,ne)=>process.env[ne]??J)}`,M=J=>new RegExp(or(n).source).test(J)||/\{(?:date[^{}]*|unique:[^{}]+)\}/.test(J);if(x.actions.some(J=>(J.action==="fill"||J.action==="selectOption")&&(J.value??"").trim()!==""&&!M(J.value)&&!Oe(J.value).test(N)))for(let[,J]of Q.matchAll(/<([^<>]+)>/g))J in t.params&&!U(J)&&p.push({column:J,step:b,reason:"session",...v(J)})}if(x.kind==="assertion")for(let[N,M]of Object.entries(t.params)){let B=(c[N]??"").trim();U(N)||m.has(N)||B===""||B.length>2||/\{(?:date|unique)/.test(M)||Oe(B,"u").test(C)||x.actions.some(J=>Bn(J).some(ne=>ne!==void 0&&Nr(u(ne,w,P),B,!1)))&&p.push({column:N,step:b,reason:"glued",...v(N)})}}),p}function py(e,t,n=[],r=t,s=a=>a,o=[]){let a=d=>Yo(o.length>0?o:[t],d,s),i=new Map,c=d=>i.get(d)??i.set(d,Yo(o.length>0?o:[t],d,u=>u)).get(d),l=Object.keys(t);return e.map((d,u)=>{let p=Xo(d.gherkin,n[u]),f=[...p].filter(w=>w in t&&(r[w]??t[w])===""),g=f.length===1?`<${f[0]}>`:void 0,y=lc(t,p,r,Ts(n[u],s),a),h=Object.entries(y).map(([w,E])=>[w,E.includes("{date")?E:r[w]??E]).filter(([w,E])=>E.length>=3||E!==""&&p.has(w));if(h.length===0&&!g)return d;let S=new Set(h.filter(([w])=>p.has(w)).map(([,w])=>w)),v=(w,E)=>Co(E,w,"gu",S.has(E)),x=(w,E,_)=>hf(w,E,_)??Ko(w,E,v,_,l),b=[...p].flatMap(w=>{let E=w in y?Rt(r[w]??t[w]):void 0;return E===void 0?[]:[[w,E]]}),$=[...h.filter(([w])=>p.has(w))].sort((w,E)=>E[1].length-w[1].length),T=w=>w===void 0?w:$.reduce((E,[_,A])=>E.replace(oc(A,"gi"),(O,j)=>`${j}<${_}>`),w),R=(w,E=_=>_)=>{if(w===void 0)return;let _=x(w,h,E),A=_.replace(or(l)," "),O=h.filter(([j,L])=>!/\{(?:env|data|unique|date)/.test(t[j])&&Nr(w,L,S.has(L),E(L))&&mf(c,j,L,p).some(I=>Nr(A,I,S.has(L),E(I))));return O.length===0?_:x(w,h.filter(j=>!O.includes(j)),E)},k=w=>R(w,fe.pattern),C=w=>w===void 0?void 0:fy(w,(E,_)=>R(E,fe[_]),E=>Ko(E,h,v,void 0,l)),P=w=>w?{...w,name:R(w.name),nameRegex:k(w.nameRegex),label:R(w.label),text:R(w.text),placeholder:R(w.placeholder),testId:R(w.testId),frame:C(w.frame),fallbackSelectors:w.fallbackSelectors?.map(E=>C(E))}:void 0;return{...d,actions:d.actions.map(w=>({...w,value:w.action==="expectDiffers"?w.value:w.action==="expectAmount"&&w.value!==void 0?rr(w.value,E=>zd(R(E)??E,b)):(w.action==="fill"||$e.has(w.action))&&w.value===""&&g?g:R(w.value),url:R(w.url),pattern:k(w.pattern),urlPattern:k(w.urlPattern),promptText:R(w.promptText),each:w.each!==void 0&&!d.gherkin.includes(w.each)?w.each.replace(/^\{data:([^{}]+)\}$/,(E,_)=>`{data:${$.reduce((A,[O,j])=>A.replace(oc(j,"g"),(L,I)=>`${I}<${O}>`),_)}}`):w.each,status:T(w.status),...w.json?{json:w.json.map(E=>({...E,...E.equals!==void 0?{equals:R(E.equals)}:{}}))}:{},method:T(w.method),attribute:T(w.attribute),target:P(w.target),toTarget:P(w.toTarget)}))}})}function gy(e,t,n=r=>r){let r=Mn(t.steps);return e.map((s,o)=>{let a=t.steps[o],i=a?.resolvedTable??a?.table,c=a?.resolvedDocString??a?.docString,l={...lt(i),...tr(c)},d=new Set,u=Object.entries({...r,...l}).map(([h,S])=>{let v=n(S);return S.includes("{date")&&d.add(h),[h,v]}).filter(([h,S])=>S.length>=3&&(!d.has(h)||h in l||wf(S))).filter(([h,S])=>h in l||!(a?.resolvedText??a?.text??"").includes(S)),p=new Set(u.map(([,h])=>h).filter((h,S,v)=>v.indexOf(h)!==S)),f=u.filter(([,h])=>!p.has(h)).sort((h,S)=>S[1].length-h[1].length);if(f.length===0)return s;let g=(h,S=x=>x,v=!1)=>h===void 0?void 0:f.reduce((x,[b,m])=>Hr(x,{[b]:m},S,v||d.has(b)),h),y=h=>h?{...h,name:g(h.name),nameRegex:g(h.nameRegex,fe.pattern),label:g(h.label),text:g(h.text),placeholder:g(h.placeholder),testId:g(h.testId,void 0,!0),frame:g(h.frame,void 0,!0),fallbackSelectors:h.fallbackSelectors?.map(S=>wn(S,(v,x)=>g(v,fe[x])??v))}:void 0;return{...s,actions:s.actions.map(h=>({...h,value:h.action==="expectDiffers"?h.value:h.action==="expectAmount"&&h.value!==void 0?rr(h.value,S=>g(S)):g(h.value),url:g(h.url),pattern:g(h.pattern,fe.pattern),urlPattern:g(h.urlPattern,fe.pattern),promptText:g(h.promptText),...h.json?{json:h.json.map(S=>({...S,...S.equals!==void 0?{equals:g(S.equals)}:{}}))}:{},target:y(h.target),toTarget:y(h.toTarget)}))}})}var wf=e=>/(?<!\d)\d{4}(?!\d)/.test(e);function hy(e,t){for(let n=1;n<=400;n++){let r=new Date(t.getTime()+n*864e5),s=Ke(e[0],r);if(e.some(o=>Ke(o,r)!==s))return!1}return!0}function my(e){let t=new RegExp(`^${Fn.source}$`).exec(e)?.[4],n=t===void 0?"YYYY-MM-DD":t.replace(/:[a-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$/,"");return/Y/.test(n)&&/[MD]/.test(n)}var wy=["DD/MM/YYYY","MM/DD/YYYY","DD.MM.YYYY","D MMM YYYY","MMM D, YYYY","D MMMM YYYY","MMMM D, YYYY"];function yy(e,t,n,r=[],s=[]){let o=t.steps.map(c=>[c.text,...c.table?.flat()??[],c.docString??""].flatMap(l=>l.match(Fn)??[])),a=(c,l)=>c.map(d=>[d,Ke(d,n)]).filter(([,d])=>!r.some(u=>u.includes(d))&&!(s[l]??[]).includes(d)),i=o.flat().filter(my).flatMap(c=>[c,.../^\{date(?:[+-]\d+)?\}$/.test(c)?wy.map(l=>`${c.slice(0,-1)}:${l}}`):[]]);return e.map((c,l)=>{let d=[...new Map([...a(o[l]??[],l),...a(i,l)])],u=new Map;for(let[g,y]of d)u.set(y,[...u.get(y)??[],g]);let p=d.filter(([g,y])=>{let h=u.get(y);return h.length===1||h[0]===g&&hy(h,n)}).sort((g,y)=>y[1].length-g[1].length);if(p.length===0)return c;let f=(g,y=h=>h)=>p.find(([,h])=>g===y(h))?.[0]??p.filter(([,h])=>h.length>=3).reduce((h,[S,v])=>h.split(/(\{(?:env|data|unique|date)[^{}]*\}|<[^<>{}]+>)/).map((x,b)=>b%2?x:x.replace(Oe(y(v),"gu"),()=>S)).join(""),g);return{...c,actions:c.actions.map(g=>kn(g,y=>f(y),(y,h)=>f(y,fe[h])))}})}function by(e,t=new Date,n=[]){return e.map(r=>({...r,actions:r.actions.map(s=>kn(s,o=>Fd(o,t,n)))}))}function kn(e,t,n,r=t,s=t,o=!0){let a=(u,p,f=t)=>{let g={...u};for(let y of p)typeof u[y]=="string"&&(g[y]=f(u[y]));return g},i=u=>n?n(u,"pattern"):t(u),c=u=>{let p=a(a(u,["name","label","text","placeholder","testId","frame"]),["nameRegex"],i);return u.fallbackSelectors&&(p.fallbackSelectors=u.fallbackSelectors.map(f=>n?wn(f,n,s):t(f))),p},l=e.action==="expectDiffers"?["url","promptText"]:["value","url","promptText"],d=a(a(a(e,l),["status","method","attribute","each"],r),["pattern","urlPattern"],i);return e.action==="expectAmount"&&e.value!==void 0&&(d.value=rr(e.value,t)),e.target&&(d.target=c(e.target)),e.toTarget&&(d.toTarget=c(e.toTarget)),e.json&&(d.json=e.json.map(u=>({...u,path:o?t(u.path):u.path,...u.equals!==void 0?{equals:t(u.equals)}:{}}))),d}function xy(e,t){if(t.length===0)return e;let n=new Map(t.map(([o,a])=>[a,o])),r=[...n.keys()].sort((o,a)=>a.length-o.length).map(ue).join("|"),s=new RegExp(String.raw`(?<=^|[^A-Za-z0-9\\]|\\[A-Za-z])(?:${r})(?![A-Za-z0-9])`,"g");return e.split(/(\{(?:env|data|unique|date)[^{}]*\})/).map((o,a)=>a%2?o:o.replace(s,i=>`{env:${n.get(i)}}`)).join("")}function vy(e,t){let n=ct(t),r=hn(at(t)),s=new RegExp(`${Se.source}|${ve.source}`,"g"),o=a=>a.replace(s,(i,c,l)=>(c!==void 0?n.has(c):r.has(l))?i:wd(i));return e.map(a=>({...a,actions:a.actions.map(i=>({...kn(i,o),...i.each!==void 0?{each:i.each}:{}}))}))}function sf(e,t,n=[]){if(t.size===0)return e;let r=Pr(n,t),s=mn(t,{standaloneBelow:6}),o=b=>{let m=encodeURIComponent(b),$=m.replace(/[!'()*]/g,T=>`%${T.charCodeAt(0).toString(16).toUpperCase()}`);return[...new Set([m,$,m.replace(/%20/g,"+"),$.replace(/%20/g,"+"),encodeURI(b)])].filter(T=>T!==b)},a=b=>b.length>=6&&b.toLowerCase()!==b.toUpperCase(),i=[...t].filter(([,b])=>b.length>=Nn).flatMap(([b,m])=>o(m).map($=>[b,$,a(m)])).sort((b,m)=>m[1].length-b[1].length),c=(b,m=$=>$)=>i.reduce(($,[T,R,k])=>{let C=ga(m(R));return $.replace(new RegExp(C,k?"gi":"g"),()=>`{env:${T}}`)},b),l=[...t].filter(([,b])=>a(b)).sort((b,m)=>m[1].length-b[1].length).map(([b,m])=>[b,new RegExp(ue(m),"gi")]),d=b=>l.reduce((m,[$,T])=>m.split(/(\{[^{}]*\})/).map((R,k)=>k%2?R:R.replace(T,`{env:${$}}`)).join(""),b),u=b=>d(s.mask(r(c(b)))),p=[...t].filter(([,b])=>b.length>=Nn),f=b=>{let m=Pr(n,t,fe[b]),$=mn(new Map(p.filter(([,R])=>R.length>=6).map(([R,k])=>[R,fe[b](k)]))),T=p.filter(([,R])=>R.length<6).map(([R,k])=>[R,fe[b](k)]);return R=>u(xy($.mask(m(c(R,fe[b]))),T))},g={quoted:f("quoted"),regex:f("regex"),pattern:f("pattern")},y=new Set(e.flatMap(b=>b.actions.flatMap(m=>[m.saveAs,m.compareTo,m.action==="expectDiffers"?m.value:void 0,...m.action==="expectAmount"?[...(m.value??"").matchAll(/"([^"]*)"/g)].map($=>$[1]):[]].filter($=>$!==void 0)))),h=mn(t,{encodings:!0}),S=new Map,v=new Set(y);for(let b of y){let m=h.mask(b);if(m===b)continue;let $=`capture-${ey("sha256").update(m).digest("hex")}`;if(v.has($)||h.mask($)!==$)throw new Error("Secret-bearing capture names cannot be safely distinguished. Record again with distinct capture names that contain no secrets.");v.add($),S.set(b,$)}let x=b=>b===void 0?void 0:S.get(b)??b;return e.map(b=>({...b,actions:b.actions.map(m=>{let $=kn(m,u,(T,R)=>g[R](T));return{...$,...m.saveAs!==void 0?{saveAs:x(m.saveAs)}:{},...m.compareTo!==void 0?{compareTo:x(m.compareTo)}:{},...m.action==="expectDiffers"&&m.value!==void 0?{value:x(m.value)}:{},...m.action==="expectAmount"&&$.value!==void 0?{value:rr($.value,T=>T,T=>x(T))}:{}}})}))}function yf(e,t,n="",r=new Date){let s=at(t),o=Te(t),a=r,i=T=>Ke(zt(on(T,n)),a).replace(Se,(R,k)=>o.get(k)??R),c=Object.fromEntries(Object.entries(t.params).map(([T,R])=>{try{return[T,i(R)]}catch{return[T,R]}})),l=e.map((T,R)=>Xo(T.gherkin,t.steps[R])),d=l.map((T,R)=>lc(t.params,T,c,Ts(t.steps[R],i),k=>Yo(t.exampleRows??[t.params],k,i))),u=Object.entries(t.params).filter(([,T])=>T.includes("{date")).map(([T,R])=>[T,R,c[T]]),p=(T,R)=>wf(R)||/\{date[^{}]*:[^{}]*(?:MMM|ddd)/.test(T),f=T=>u.filter(([R,k,C])=>R in(d[T]??{})&&(l[T]?.has(R)||p(k,C))),y=py(gy(vy(Sy(ky(sf(e,o,s),t,c,o),t),t),t,T=>Ke(zt(on(T,n)),a)),t.params,t.steps,c,i,t.exampleRows).map((T,R)=>{let k=[...l[R]].flatMap(C=>{let P=c[C];if(P===void 0||P.length<3)return[];let w=encodeURIComponent(P);return w===P?[]:[...new Set([w,w.replace(/%20/g,"+")])].map(E=>[E,`<${C}>`])});return k.length===0?T:{...T,actions:T.actions.map(C=>C.url===void 0?C:{...C,url:k.reduce((P,[w,E])=>P.split(w).join(E),C.url)})}}),h=[...s,..._r(s),...o.values()],S=e.map((T,R)=>u.filter(([k])=>l[R]?.has(k)).map(([,,k])=>k)),v=yy(y,t,a,h,S).map((T,R)=>{let k=u.filter(([C,P,w])=>l[R]?.has(C)||p(P,w)).map(([,,C])=>C);return by([T],a,[...h,...k])[0]}),x=sf(Ry(Ty(v,new Map([...Er(s)].map(([T,R])=>[T,R.includes("{date")?Ke(R,a):R]))),qr(s,n)),o,s),b=Object.fromEntries(Object.entries(t.params).filter(([,T])=>!T.includes("{date")&&/\{(?:env|data|unique):/.test(T))),m=Object.keys(t.params),$=$y(x,t);return Object.keys(b).length===0&&u.length===0?$:$.map((T,R)=>{let k=f(R),C={...Object.fromEntries(Object.entries(b).filter(([O])=>O in(d[R]??{}))),...Object.fromEntries(k.map(([O,j])=>[O,j]))},P=Object.fromEntries(k.filter(([,,O])=>!O.includes("{date")).map(([O,,j])=>[O,j])),w=Object.entries(P).filter(([,O])=>O.length<3),E=(O,j)=>{let L=w.find(([,I])=>O===(j?j(I):I));return L?`<${L[0]}>`:Hr(O,P,j,!0,m)},_=O=>E(Hr(O,C,void 0,!1,m)),A=(O,j)=>{let L=Hr(O,C,void 0,!1,m);return(j==="pattern"?hf(L,w):void 0)??E(L,fe[j])};return{...T,actions:T.actions.map(O=>kn(O,_,A,_,_,!1))}})}function As(e){let t=e.steps.map(o=>[o.text,...o.table?.flat()??[],o.docString??""]),n=t.flat(),r=t.map(()=>new Map),s=new Map;return t.forEach((o,a)=>{for(let i of o)for(let[c,l]of i.matchAll(/\{data:([^{}]*<[^<>{}]+>[^{}]*)\}/g)){let d=!0,u=`{data:${l.replace(/<([^<>]+)>/g,(p,f)=>{let g=e.params[f];return(g===void 0||/[{}<>]/.test(g))&&(d=!1),g??""})}}`;if(!(!d||n.some(p=>p.includes(u))))for(let p of[r[a],s])(p.get(u)??p.set(u,new Set).get(u)).add(c)}}),{own:r,all:s}}function Zo(e){let t=new Map;for(let[n,r]of e){let s;try{s=Le(n.slice(6,-1))}catch{continue}let o=Ke(s.replace(Se,(a,i)=>process.env[i]??a));for(let a of new Set([s,o]))for(let i of r)(t.get(a)??t.set(a,new Set).get(a)).add(i)}return t}function Sy(e,t){let{own:n}=As(t),r=s=>[...Zo(s)].flatMap(([o,a])=>a.size===1&&o.trim()!==""?[[o,[...a][0]]]:[]);return e.map((s,o)=>{let a=Ts(t.steps[o],l=>l).replace(/\{[^{}]*\}/g," "),i=new Map(r(n[o]??new Map).filter(([l])=>!Oe(l).test(a)));if(i.size===0)return s;let c=l=>{let d=i.get(l);if(d!==void 0)return d;let u=l;for(let[p,f]of i)u=u.split(/(\{[^{}]*\}|<[^<>\s]+>)/).map((g,y)=>y%2?g:g.replace(Oe(p,"gu"),f)).join("");return u};return{...s,actions:s.actions.map(l=>kn(l,c,d=>d,c,d=>bf(d,c),!1))}})}function $y(e,t){let{own:n,all:r}=As(t),s=a=>[...a].filter(([,i])=>i.size===1).map(([i,c])=>[i,[...c][0]]),o=s(r);return o.length===0&&n.every(a=>a.size===0)?e:e.map((a,i)=>{let c=new Map([...o,...s(n[i]??new Map)]);if(c.size===0)return a;let l=d=>{let u=d;for(let[p,f]of c)u=u.split(p).join(f);return u};return{...a,actions:a.actions.map(d=>kn(d,l,u=>l(u),l,l,!1))}})}function bf(e,t){let n=[],r=e.replace(/(^|[\s>+~,(])([A-Za-z][\w-]*)(?=$|[.#[:\s>+~,)])/g,(s,o,a)=>`${o}\0${n.push(a)-1}\0`);return t(r).replace(/\u0000(\d+)\u0000/g,(s,o)=>n[Number(o)])}function ky(e,t,n,r){if(r.size===0)return e;let{own:s}=As(t),o=[...r].sort((c,l)=>l[1].length-c[1].length),a=c=>c.replace(/\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g,(l,d)=>r.get(d)??l),i=c=>c.split(/(<[^<>\s]+>|\{[^{}]*\})/).map((l,d)=>d%2?l:o.reduce((u,[p,f])=>f===""?u:u.split(f).join(`{env:${p}}`),l)).join("");return e.map((c,l)=>{let d=Xo(c.gherkin,t.steps[l]),u=[c.gherkin,...c.table?.flat()??[],c.docString??""].join(`
|
|
46
|
+
`),p=Zo(s[l]??new Map),f=[...d].flatMap(h=>{let S=n[h],v=!me(u.replace(/\{data:[^{}]*\}/g," ")).includes(`<${h}>`);return S===void 0||S.length<3||v||/\{env:/.test(t.params[h]??"")||p.has(S)?[]:[...r].filter(([b,m])=>m!==""&&S.includes(m)&&!u.includes(`{env:${b}}`)).length===0?[]:Object.entries(t.params).some(([b,m])=>/\{env:/.test(m)&&n[b]===S)?[]:[[h,S]]}),g=new Map([...p].filter(([h,S])=>S.size===1&&h.trim()!=="").map(([h,S])=>[h,[...S][0]]));if(f.length===0&&g.size===0)return c;let y=h=>{let S=a(h),v=g.get(S);if(v!==void 0&&S!==h)return v;let x=S===h?S:[...g].filter(([m])=>m.length>=4).reduce((m,[$,T])=>m.split($).join(T),S),b=f.reduce((m,[$,T])=>m.split(T).join(`<${$}>`),x);return b===S?h:i(b)};return{...c,actions:c.actions.map(h=>kn(h,y,S=>y(S),y,y,!1))}})}function Ry(e,t){if(t.size===0)return e;let n=r=>typeof r=="string"?Uu(r,t):Array.isArray(r)?r.map(n):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([s,o])=>[s,s==="pageFingerprint"?o:n(o)])):r;return e.map(r=>({...r,actions:r.actions.map(s=>n(s))}))}function Ty(e,t){return t.size===0?e:e.map(n=>{let r=new Set([...n.gherkin.matchAll(ve)].map(y=>y[1])),s=[n.gherkin,...n.table?.flat()??[],n.docString??""].join(`
|
|
47
|
+
`).replace(/\{[^{}]*\}|<[^<>]+>/g," "),a=!/\{data:/.test(n.gherkin)?new Map([...t].filter(([,y])=>y===""||!Oe(y).test(s))):t,i=[...new Set((s.match(/[\p{L}\p{N}]+(?:[-'][\p{L}\p{N}]+)*/gu)??[]).filter(y=>[...a.values()].some(h=>h.length>=4&&y!==h&&y.includes(h))))],c=i.length>0?new RegExp(`(${i.sort((y,h)=>h.length-y.length).map(ue).join("|")})`):void 0,l=y=>c?y.split(c).map((h,S)=>S%2?h:bo(h,a,r)).join(""):bo(y,a,r),d=y=>new Map([...a].filter(([,h])=>h.length>=4).map(([h,S])=>[h,fe[y](S)])),u={quoted:d("quoted"),regex:d("regex"),pattern:d("pattern")},p=y=>y.split(/(\{(?:env|data|unique|date)[^{}]*\})/).map((h,S)=>S%2?h:l(h)).join(""),f=(y,h)=>p(bo(y,u[h],r)),g=y=>{let h=[...a].filter(([S,v])=>r.has(S)&&v===y);return h.length===1?`{data:${h[0][0]}}`:y};return{...n,actions:n.actions.map(y=>kn(y,l,f,g,h=>bf(h,p)))}})}function dc(e,t,n){if(e!=="mcp__playwright__browser_tabs")return;let r=t??{},s=typeof r.index=="number"?String(r.index):void 0;switch(r.action){case"select":return s===void 0?void 0:{action:"switchTab",value:s};case"close":return s===void 0?{action:"closeTab"}:{action:"closeTab",value:s};case"new":return typeof r.url=="string"&&r.url?{action:"newTab",url:xs(r.url,n)}:{action:"newTab"};default:return}}function xf(e,t){let n=t??{};if(e==="mcp__playwright__browser_handle_dialog"){let r={action:"handleDialog",value:n.accept?"accept":"dismiss"};return typeof n.promptText=="string"&&n.promptText&&(r.promptText=n.promptText),r}if(e==="mcp__playwright__browser_file_upload"){let r=Array.isArray(n.paths)?n.paths:[];if(r.length===0)return;let s=it().root+Xw.sep;return{action:"uploadFile",value:r.map(a=>typeof a=="string"&&a.startsWith(s)?a.slice(s.length):a).join(`
|
|
48
|
+
`)}}}import Os from"node:fs";import Py from"node:os";import uc from"node:path";import vt from"node:fs";import Ay from"node:path";import{createHash as Ey,randomBytes as Oy}from"node:crypto";import ni from"node:zlib";var Jn=4294967295,Sf=67324752,$f=33639248,kf=101010256;function Rf(e){return Es(e).map(t=>({name:t.name,data:t.read()}))}function Tf(e,t){let n=Math.max(0,t-22-65535),r=e(n,t-n),s=-1;for(let l=r.length-22;l>=0;l--)if(r.readUInt32LE(l)===kf){s=l;break}if(s<0)throw new Error("not a zip file: no central directory");let o=r.readUInt16LE(s+10),a=e(r.readUInt32LE(s+16),r.readUInt32LE(s+12)),i=0,c=[];for(let l=0;l<o;l++){if(a.readUInt32LE(i)!==$f)throw new Error("not a zip file: bad central directory entry");let d=a.readUInt16LE(i+10),u=a.readUInt32LE(i+16),p=a.readUInt32LE(i+20),f=a.readUInt32LE(i+24),g=a.readUInt16LE(i+28),y=a.readUInt16LE(i+30),h=a.readUInt16LE(i+32),S=a.readUInt32LE(i+42),v=a.subarray(i+46,i+46+g).toString("utf8");i+=46+g+y+h;let x=e(S,30);if(x.length<30||x.readUInt32LE(0)!==Sf)throw new Error(`not a zip file: bad local header for ${v}`);let b=S+30+x.readUInt16LE(26)+x.readUInt16LE(28);if(!v.endsWith("/")){if(d!==0&&d!==8)throw new Error(`zip entry ${v} uses compression method ${d}, which is not supported`);c.push({name:v,method:d,crc:u,size:f,compressedSize:p,start:b})}}return c}function Es(e){return Tf((t,n)=>e.subarray(t,t+n),e.length).map(({name:t,method:n,crc:r,size:s,compressedSize:o,start:a})=>{let i=e.subarray(a,a+o);return{name:t,method:n,crc:r,size:s,raw:i,read:()=>n===0?Buffer.from(i):ni.inflateRawSync(i)}})}function _y(e,t,n){let r=vt.openSync(e,"r");try{let s=Buffer.alloc(n),o=0;for(;o<n;){let a=vt.readSync(r,s,o,n-o,t+o);if(a===0)break;o+=a}return s.subarray(0,o)}finally{vt.closeSync(r)}}function Af(e){let t=vt.statSync(e).size,n=(r,s)=>_y(e,r,Math.max(0,Math.min(s,t-r)));return Tf(n,t).map(r=>({...r,raw:()=>n(r.start,r.compressedSize)}))}var Cy=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n>>>0}return e})();function ti(e,t=0){let n=ni.crc32;if(n)return n(e,t)>>>0;let r=(t^4294967295)>>>0;for(let s of e)r=Cy[(r^s)&255]^r>>>8;return(r^4294967295)>>>0}var vf=1024*1024;function Ef(e,t){let n=vt.openSync(e,"r");try{let r=Buffer.alloc(vf);for(let s;(s=vt.readSync(n,r,0,vf,null))>0;)t(r.subarray(0,s))}finally{vt.closeSync(n)}}function ri(e){let t=Ey("sha256"),n=0,r=0;return Ef(e,s=>{n=ti(s,n),r+=s.length,t.update(s)}),{crc:n,size:r,sha256:t.digest("hex")}}function Of(e,t,n,r,s,o){let a=Buffer.alloc(30);a.writeUInt32LE(Sf,0),a.writeUInt16LE(20,4),a.writeUInt16LE(2048,6),a.writeUInt16LE(t,8),a.writeUInt32LE(0,10),a.writeUInt32LE(n,14),a.writeUInt32LE(r,18),a.writeUInt32LE(s,22),a.writeUInt16LE(e.length,26),a.writeUInt16LE(0,28);let i=Buffer.alloc(46);return i.writeUInt32LE($f,0),i.writeUInt16LE(20,4),i.writeUInt16LE(20,6),i.writeUInt16LE(2048,8),i.writeUInt16LE(t,10),i.writeUInt32LE(0,12),i.writeUInt32LE(n,16),i.writeUInt32LE(r,20),i.writeUInt32LE(s,24),i.writeUInt16LE(e.length,28),i.writeUInt16LE(0,30),i.writeUInt16LE(0,32),i.writeUInt16LE(0,34),i.writeUInt16LE(0,36),i.writeUInt32LE(0,38),i.writeUInt32LE(o,42),{local:a,central:i}}function _f(e,t,n){let r=Buffer.alloc(22);return r.writeUInt32LE(kf,0),r.writeUInt16LE(0,4),r.writeUInt16LE(0,6),r.writeUInt16LE(e,8),r.writeUInt16LE(e,10),r.writeUInt32LE(t,12),r.writeUInt32LE(n,16),r.writeUInt16LE(0,20),r}var Cf=e=>new Error(`cannot write a zip of ${e} files: one holds at most 65,535`),Pf=e=>new Error(`cannot write ${e} into a zip: a zip holds at most 4 GB, and this one would be larger`),If=()=>new Error("cannot write the zip: a zip holds at most 4 GB, and this one would be larger");function jf(e){if(e.length>65535)throw Cf(e.length);let t=[],n=[],r=0;for(let o of e){let a="raw"in o,i=a?o.raw:ni.deflateRawSync(o.data),c=a?o.size:o.data.length,l=Buffer.from(o.name,"utf8");if(c>Jn||r+30+l.length+i.length>Jn)throw Pf(o.name);let{local:d,central:u}=Of(l,a?o.method:8,a?o.crc:ti(o.data),i.length,c,r);t.push(d,l,i),n.push(u,l),r+=d.length+l.length+i.length}let s=n.reduce((o,a)=>o+a.length,0);if(r+s>Jn)throw If();return Buffer.concat([...t,...n,_f(e.length,s,r)])}function Vr(e,t){for(let n=0;n<t.length;)n+=vt.writeSync(e,t,n,t.length-n)}function Nf(e,t){if(t.length>65535)throw Cf(t.length);vt.mkdirSync(Ay.dirname(e),{recursive:!0});let n=`${e}.${process.pid}-${Oy(4).toString("hex")}.partial`,r=vt.openSync(n,"w");try{let s=[],o=0;for(let i of t){let c=Buffer.from(i.name,"utf8"),l="file"in i,d=l&&(i.crc===void 0||i.size===void 0)?ri(i.file):void 0,u=l?void 0:ni.deflateRawSync(i.data),p=l?d?.crc??i.crc:ti(i.data),f=l?d?.size??i.size:i.data.length,g=u?.length??f;if(f>Jn||o+30+c.length+g>Jn)throw Pf(i.name);let{local:y,central:h}=Of(c,l?0:8,p,g,f,o);if(Vr(r,y),Vr(r,c),u)Vr(r,u);else{let S=0,v=0;if(Ef(i.file,x=>{S+x.length>f||(Vr(r,x),S+=x.length,v=ti(x,v))}),S!==f||v!==p)throw new Error(`${i.name} changed while it was being packed`)}s.push(h,c),o+=y.length+c.length+g}let a=s.reduce((i,c)=>i+c.length,0);if(o+a>Jn)throw If();for(let i of s)Vr(r,i);Vr(r,_f(t.length,a,o)),vt.closeSync(r),vt.renameSync(n,e)}catch(s){try{vt.closeSync(r)}catch{}throw vt.rmSync(n,{force:!0}),s}}var fc=["off","on","retain-on-failure"],pc="trace.zip";async function Df(e,t){await e.tracing.start({screenshots:!0,snapshots:!0,sources:!1,title:t})}async function si(e,t){t&&Os.mkdirSync(uc.dirname(t),{recursive:!0}),await e.tracing.stop(t?{path:t}:void 0)}async function oi(e,t,n){let r;try{r=Os.mkdtempSync(uc.join(Py.tmpdir(),"saffron-trace-"));let s=uc.join(r,pc);await e.tracing.stop({path:s});let o=Hy(Os.readFileSync(s),n);return Ue(t,o),Kt(o)}catch{try{Os.rmSync(t,{force:!0})}catch{console.warn("Could not remove the execution trace artifact.")}console.warn("Could not save the execution trace; no trace was attached to this run.");return}finally{if(r)try{Os.rmSync(r,{recursive:!0,force:!0})}catch{console.warn("Could not remove the private temporary trace directory.")}}}async function Ff(e,t,n,r){if(!t)return r();let s=e.context().tracing;await s.group(n).catch(()=>{});try{return await r()}finally{await s.groupEnd().catch(()=>{})}}var Iy=new Set(["callId","parentId","pageId","frameId","contextId","pageref","_frameref","snapshotName","beforeSnapshot","afterSnapshot","inputSnapshot","sha1","_sha1"]),jy=new Set(["before","action","after"]),Ny=/^\[saffron:(?:agent|replay|pending|action):-?\d+\] /,My=new Set(["type","class","method"]),Dy=new Set(["__playwright_bounding_rect__","__playwright_scroll_top_","__playwright_scroll_left_","__playwright_target__","__playwright_checked_","__playwright_selected_","__playwright_popover_open_","__playwright_dialog_open_","__playwright_shadow_root_","__playwright_custom_elements__"]),Fy=new Set(["style","__playwright_style_sheet_"]),Ly=new Set(["srcset","imagesrcset"]),By=/^(?:image\/(?!svg)|font\/|audio\/|video\/)/i,Uy=/\.(?:jpe?g|png|gif|webp|avif|bmp|ico|woff2?|ttf|otf|eot|mp3|mp4|m4a|wav|ogg|webm)$/i,zy=/^text\/css\b/i,qy=/\.css$/i;function Hy(e,t){let n=mn(t,{encodings:!0});if(n.empty)return e;let r=mn(t,{encodings:!0,bytes:!0}),s=Es(e),o=new Set(s.filter(f=>f.name.includes("/")).map(f=>f.name));for(let f of s)f.name.startsWith("resources/")&&o.add(f.name.slice(10));let a={names:o,pieces:tb(t)},i=new Set,c=new Set,l=f=>{for(let g of[f.snapshot?.response?.content,f.snapshot?.request?.postData]){if(!g)continue;let y=g._file??(g._sha1&&`resources/${g._sha1}`);if(!y)continue;let h=String(g.mimeType??"");By.test(h)?i.add(y):zy.test(h)&&c.add(y)}},d=[...s],u=!1,p=(f,g)=>{g&&(d[f]={name:s[f].name,data:g},u=!0)};return s.forEach((f,g)=>{/\.(?:trace|network)$/.test(f.name)?p(g,Jy(f.read(),n,a,f.name.endsWith(".network")?l:void 0)):f.name.endsWith(".stacks")&&p(g,Vy(f.read(),n,a))}),s.forEach((f,g)=>{/\.(?:trace|network|stacks)$/.test(f.name)||i.has(f.name)||Uy.test(f.name)||p(g,Wy(f.read(),n,r,c.has(f.name)||qy.test(f.name)))}),u?jf(d):e}function Jy(e,t,n,r){let s=e.toString("utf8").split(`
|
|
49
|
+
`),o=!1;for(let a=0;a<s.length;a++){let i=s[a];if(!i.trim())continue;let c=JSON.parse(i);if(r?.(c),!t.occursIn(i)&&!t.hiddenByEscape.test(i))continue;let l=hc(i,t,{keys:!1,numbers:!1,playwright:n});l!==i&&(s[a]=l,o=!0)}return o?Buffer.from(s.join(`
|
|
50
|
+
`),"utf8"):void 0}function Vy(e,t,n){let r=e.toString("utf8");if(JSON.parse(r),!t.occursIn(r)&&!t.hiddenByEscape.test(r))return;let s=hc(r,t,{keys:!1,numbers:!1,playwright:n});return s===r?void 0:Buffer.from(s,"utf8")}function Wy(e,t,n,r=!1){if(r){let d=e.toString("latin1"),u=zf(d,n);return u===d?void 0:Buffer.from(u,"latin1")}let s=e.toString("utf8"),o=s.startsWith("\uFEFF")?"\uFEFF":"",a=s.slice(o.length);if(!s.includes("\uFFFD")||Buffer.from(s,"utf8").equals(e)){let d=/^\s*[[{"]/.test(a)?Lf(a,t):void 0,u=d===void 0&&/^\s*(?:[[{"\d-]|true|false|null)/.test(a)&&a.trim().includes(`
|
|
51
|
+
`)?Gy(a,t):void 0,p=d??u;if(p!==void 0)return p===a?void 0:Buffer.from(o+p,"utf8")}let c=e.toString("latin1"),l=n.mask(c);return l===c?void 0:Buffer.from(l,"latin1")}function Lf(e,t){try{JSON.parse(e)}catch(n){if(n instanceof SyntaxError)return;throw n}return!t.occursIn(e)&&!t.hiddenByEscape.test(e)?e:hc(e,t,{keys:!0,numbers:!0})}function Gy(e,t){let n=e.split(`
|
|
52
|
+
`),r=[];for(let s of n){if(!s.trim()){r.push(s);continue}let a=Lf(s,t);if(a===void 0)return;r.push(a)}return r.join(`
|
|
53
|
+
`)}var Bf=/^([a-z][a-z0-9+.-]*:\/\/)([^/?#]*@)?([^/?#]*)/i;function Uf(e,t=0,n=e.length){let r=Bf.exec(e.slice(t,n));if(!r)return;let[s,o,a=""]=r,i=t+o.length+a.length;return c=>c>=t&&c<t+o.length||c>=i-(a?1:0)&&c<=t+s.length&&c<n}function Ky(e,t,n){let r="",s=0;for(let o of t.matches(e)){let{token:a,kept:i=()=>!1}=n(o),c="";for(let l=o.start;l<o.end;){if(i(l)){c+=e[l++];continue}for(;l<o.end&&!i(l);)l++;c+=a(o.names)}c!==e.slice(o.start,o.end)&&(r+=e.slice(s,o.start)+c,s=o.end)}return s===0?e:r+e.slice(s)}var Yy=e=>e.map(t=>`%7Benv:${t}%7D`).join(""),Zy=e=>e.map(t=>`\\{env\\:${t}\\}`).join("");function gc(e,t,n,r){let s=n.map(([a,i])=>({start:a,end:i,kept:Uf(e,a,i)})),o=0;return Ky(e,t,a=>{for(;o<s.length&&s[o].end<a.end;)o++;let i=s[o];return i&&i.start<=a.start&&a.end<=i.end?{token:Yy,kept:i.kept}:{token:r}})}function Qy(e,t){return Uf(e)?gc(e,t,[[0,e.length]],Cr):t.mask(e)}var Xy=/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s'"]*))|@import\s+(?:"([^"]*)"|'([^']*)')/dgi;function zf(e,t){if(!t.occursIn(e))return e;let n=[...e.matchAll(Xy)].map(r=>r.indices.slice(1).find(s=>s!==void 0));return gc(e,t,n,Zy)}function eb(e,t){let n=[];for(let r=0;r<e.length;){for(;r<e.length&&/[\s,]/.test(e[r]);)r++;let s=r;for(;s<e.length&&!/\s/.test(e[s]);)s++;let o=s;for(;o>r&&e[o-1]===",";)o--;if(o>r&&n.push([r,o]),r=s,o===s)for(;r<e.length&&e[r]!==",";)r++}return gc(e,t,n,Cr)}function tb(e){let t=new Map;for(let[n,r]of e)if(!(r.length<Nn||!Bf.test(r)||!URL.canParse(r)))for(let s of new URL(r).searchParams.values())s.length>=Nn&&!t.has(s)&&t.set(s,n);return t}var Mf=e=>e===" "||e===" "||e===`
|
|
54
|
+
`||e==="\r";function hc(e,t,n){let r=[],s=0,o,a=[],i=c=>{let l=c-1;for(;l>=0&&Mf(e[l]);)l--;return e[l]};for(let c=0;c<e.length;c++){let l=e[c];if(l==="{"||l==="["){let d=a.at(-1),u=i(c)===":"?o:void 0;a.push({dom:(d?.dom??!1)||u==="html",logged:(d?.logged??!1)||u==="value"});continue}if(l==="}"||l==="]"){a.pop();continue}if(l==='"'){let d=c++,u=!1;for(;c<e.length&&e[c]!=='"';c++)e[c]==="\\"&&(u=!0,c++);let p=c+1,f=p;for(;f<e.length&&Mf(e[f]);)f++;let g=e[f]===":",y=u?JSON.parse(e.slice(d,p)):e.slice(d+1,c),h=a.at(-1),S=!g&&i(d)===":"?o:void 0,v=m=>t.mask(m);if(g){if(o=y,!n.keys)continue}else if(n.playwright){if(a.length===1&&S!==void 0&&My.has(S)||n.playwright.names.has(y))continue;let{pieces:m}=n.playwright;if(v=$=>m.has($)?Cr([m.get($)]):Qy($,t),h?.dom){if(i(d)==="["){h.tag=y.toUpperCase();continue}let $=S===void 0?h.tag:a.at(-2)?.tag;if(S!==void 0&&Dy.has(S)||S==="src"&&($==="IFRAME"||$==="FRAME"))continue;S===void 0&&$==="STYLE"||S!==void 0&&Fy.has(S)?v=T=>zf(T,t):S!==void 0&&Ly.has(S)&&(v=T=>eb(T,t))}else if(S!==void 0&&Iy.has(S)||S==="phase"&&jy.has(y))continue}let x=n.playwright&&a.length===1&&S==="title"?Ny.exec(y)?.[0]??"":"",b=x+v(y.slice(x.length));b!==y&&(r.push(e.slice(s,d),JSON.stringify(b)),s=p)}else if(l==="-"||l>="0"&&l<="9"){let d=c+1;for(;d<e.length&&/[0-9eE.+-]/.test(e[d]);)d++;(n.numbers||(a.at(-1)?.logged??!1)||i(c)===":"&&o==="value")&&t.isValue(e.slice(c,d))&&(r.push(e.slice(s,c),JSON.stringify(t.mask(e.slice(c,d)))),s=d),c=d-1}}return r.length?r.join("")+e.slice(s):e}var $c=e=>new Promise(t=>setTimeout(t,e)),yc=class{entries=[];lastMatch;seq=0;prevStepSeq=0;curStepSeq=0;requestSeq=0;actionSeq=0;requests=new WeakMap;onRequest=t=>{let n=t.redirectedFrom();this.requests.set(t,n?this.requests.get(n)??0:++this.requestSeq);let r=t.resourceType?.();(r==="fetch"||r==="xhr")&&this.inFlight.add(t)};inFlight=new Set;onDone=t=>{this.inFlight.delete(t)};async quiet(t){let n=Date.now()+t;for(await new Promise(r=>setTimeout(r,Math.min(150,t)));this.inFlight.size>0&&Date.now()<n;)await new Promise(r=>setTimeout(r,25))}listener;context;attach(t,n){this.context=t,this.listener=r=>{let s={seq:++this.seq,requestSeq:this.requests.get(r.request())??0,url:r.url(),method:r.request().method(),status:r.status()};if(this.entries.push(s),n){let o=r.headers()["content-type"]??"";/json|text|xml/i.test(o)&&r.text().then(a=>{s.body=a}).catch(()=>{})}},t.on("request",this.onRequest),t.on("response",this.listener),t.on("requestfinished",this.onDone),t.on("requestfailed",this.onDone)}detach(){this.context&&this.listener&&(this.context.off("response",this.listener),this.context.off("request",this.onRequest),this.context.off("requestfinished",this.onDone),this.context.off("requestfailed",this.onDone))}markStep(){this.prevStepSeq=this.curStepSeq,this.curStepSeq=this.seq}sincePreviousStep(){return this.entries.filter(t=>t.seq>this.prevStepSeq)}markAction(){this.actionSeq=this.requestSeq}sinceAction(){return this.entries.filter(t=>t.requestSeq>this.actionSeq)}all(){return this.entries}};function nb(e,t){if(!t)return e>=200&&e<300;let n=/^([1-5])xx$/i.exec(t.trim());if(n){let r=Number(n[1])*100;return e>=r&&e<r+100}return e===Number(t.trim())}function mc(e,t,n,r,s){return!(!t.test(e.url)&&!t.test(vc(e.url))||n&&e.method.toUpperCase()!==n.toUpperCase()||!nb(e.status,r)||s&&(e.body===void 0||!s.test(e.body)))}var qf=(e,t)=>`response matching ${e.method??"any-method"} /${t}/ status ${e.status??"2xx"}${e.pattern?` body /${e.pattern}/`:""}`,ii=new Set(["click","fill","press","selectOption","check","uncheck","hover","dragTo","uploadFile"]),kc=/(?<=(?:^|[^\\])(?:\\\\)*)(\\?)(<[^<>]+>|\{(?:env|data|date)[^{}]*\})/g;function bc(e,t){return e===void 0?!1:[...e.matchAll(kc)].some(({2:n,index:r})=>{let s=e.slice(Math.max(0,r-2),r);return!(n.startsWith("<")&&(s==="(?"||s==="\\k"))&&t(n).trim()===""})}function _s(e){let t=[],n=0;for(let r of e.matchAll(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|=\/((?:[^/\\]|\\.)*)\/[a-z]*|>>/g))r[0]===">>"&&(t.push(e.slice(n,r.index)),n=r.index+2);return[...t,e.slice(n)]}function Xf(e){let t=[];for(let n of e.matchAll(/(?<![\w-])not\(|internal:has-not(?:-text)?=/g)){if(n[0]!=="not("){let s=/^(?:(["'])(?:\\.|(?!\1)[^\\])*\1|(?:(?!>>).)*)/s.exec(e.slice(n.index+n[0].length))[0];t.push([n.index,n.index+n[0].length+s.length]);continue}let r=0;for(let s of e.slice(n.index).matchAll(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[()]/g))if(s[0]==="(")r++;else if(s[0]===")"&&--r===0){t.push([n.index,n.index+s.index+1]);break}}return t}var ep=e=>t=>!e.some(([n,r])=>t.index>=n&&t.index<r),Rc=e=>/^\s*(?:xpath=|\(*\/\/|\.\.)/.test(e);function rb(e,t){let n=0,r=0;for(let s of e.matchAll(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\\.|[\s\S]/g)){if(s.index>=t)break;s[0]==="("?n++:s[0]===")"?n--:s[0]==="["?r++:s[0]==="]"&&r--}return Rc(e)?r>1:n>0}function sb(e,t){let n=/^\s*([a-z][\w-]*(?::[\w-]+)?)=/i.exec(e)?.[1]?.toLowerCase();if(n!==void 0&&n!=="css"&&n!=="xpath")return e.length;let r=Rc(e),s=0,o=0,a=!1,i=0,c;for(let l of e.matchAll(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\\.|[\s\S]/g)){let d=l[0],u=l.index;u===t&&!r&&s>0&&(t=i),d==="("&&s===0&&(i=u),d==="("?s++:d===")"?s--:d==="["?o++:d==="]"?o--:s===0&&o===0&&(!r&&d===","&&(a=!0),c===void 0&&u>t&&(r?d==="/":/^[\s>+~]$/.test(d))&&(c=u))}return a||c===void 0||!r&&/^\s*[+~]/.test(e.slice(c))||e.slice(c).trim()===""?e.length:c}function Hf(e,t=!1){let n=t?()=>!0:ep(Xf(e)),r=[...e.matchAll(/(?:has-text\(\s*|:text\(\s*|(?<![\w-])(?:internal:)?(?:has-(?:not-)?)?text=)(["'])((?:\\.|(?!\1)[^\\])*)\1(?!s)/g)].filter(n).map(a=>({index:a.index,raw:a[2]})),s=[...e.matchAll(/(?:contains|starts-with)\(\s*(?:\.|text\(\))\s*,\s*(?:'((?:[^'\\]|\\.)*)'|"((?:[^"\\]|\\.)*)")\s*\)/g)].filter(n).map(a=>({index:a.index,raw:a[1]??a[2]})),o=_s(e).flatMap(a=>a.trim().match(/^(?:internal:)?text=(?!["/])(.*)$/s)?.[1]??[]).map(a=>({index:0,raw:a}));return[...r,...s,...o]}var tp=e=>ue(e).replaceAll("/","\\/").replace(/\s+/g,"\\s+").replace(/["'`>]/g,t=>`\\x${t.charCodeAt(0).toString(16)}`);function Jf(e){let t=ep(Xf(e)),n=new RegExp(`^\\s*${St}|${St}\\s*$`),r=[],s=(o,a,i,c="")=>{if(!t(o)||!n.test(a))return;let l=a.split(new RegExp(`(${St})`)).map((d,u)=>u%2?d:tp(d.replace(/\\(.)/gs,"$1"))).join("");r.push({index:o.index,selector:i(`/${c==="^"?"^":""}${l}${c==="$"?"$":""}/i`),raw:a})};for(let o of e.matchAll(/internal:role=([\w-]+)[^>]*?\[\s*name\s*=\s*(["'])((?:\\.|(?!\2)[^\\])*)\2\s*i?\s*\]/g))s(o,o[3],a=>`internal:role=${o[1]}[name=${a}]`);for(let o of e.matchAll(/internal:label=(["'])((?:\\.|(?!\1)[^\\])*)\1(?!s)/g))s(o,o[2],a=>`internal:label=${a}`);for(let o of e.matchAll(/internal:attr=\[\s*([\w-]+)\s*=\s*(["'])((?:\\.|(?!\2)[^\\])*)\2\s*i?\s*\]/g))s(o,o[3],a=>`internal:attr=[${o[1]}=${a}]`);if(!e.trim().startsWith("internal:")){for(let o of e.matchAll(/\[\s*([\w-]+)\s*([*^$])=\s*(["'])((?:\\.|(?!\3)[^\\])*)\3\s*[is]?\s*\]/g))s(o,o[4],a=>`internal:attr=[${o[1]}=${a}]`,o[2]);for(let o of e.matchAll(/(contains|starts-with)\(\s*@([\w-]+)\s*,\s*(?:'([^']*)'|"([^"]*)")\s*\)/g))s(o,o[3]??o[4],a=>`internal:attr=[${o[2]}=${a}]`,o[1]==="starts-with"?"^":"");for(let o of e.matchAll(/:text-matches\(\s*(["'])((?:\\.|(?!\1)[^\\])*)\1\s*(?:,\s*(["'])([a-z]*)\3\s*)?\)/g))t(o)&&new RegExp(St).test(o[2])&&r.push({index:o.index,raw:o[2].replace(/\\(.)/gs,"$1"),flags:o[4]??""})}for(let o of e.matchAll(/internal:has=(["'])((?:\\.|(?!\1)[^\\])*)\1/g))if(!(!t(o)||!new RegExp(St).test(o[2])))try{r.push({index:o.index,raw:o[2],has:o[1]==='"'?JSON.parse(`"${o[2]}"`):o[2].replace(/\\(.)/gs,"$1")})}catch{}return r}var xc=(e,t)=>new Error(`${e} "${t}" holds an empty row or data value, so it would match more than it means. Give that cell or data value a value, or give the blank case its own Scenario.`);function Tt(e,t,n,r){return e===void 0||e.trim()===""?!1:t.trim()===""?!0:r!==void 0&&r.test("")&&r.test("\u2063zq9")&&[...e.matchAll(kc)].some(({2:s,index:o})=>{let a=e.slice(Math.max(0,o-2),o);return!(s.startsWith("<")&&(a==="(?"||a==="\\k"))&&n(s).trim()===""})}var St=String.raw`(?:<[^<>]+>|\{(?:data|env|unique|date)[^{}]*\})`,Tc=(e,t=!0)=>t&&/^\p{N}/u.test(e)?String.raw`(?<![\p{L}\p{N}\p{M}]|\p{N}[.,])`:String.raw`(?<![\p{L}\p{N}\p{M}])`,Ac=(e,t=!0)=>t&&/\p{N}$/u.test(e)?String.raw`(?![\p{L}\p{N}\p{M}]|[.,]\p{N})`:String.raw`(?![\p{L}\p{N}\p{M}])`;function Gr(e,t,n){if(!e.includes(t))return!1;let r=n!==void 0&&new RegExp(`^\\s*${St}`).test(n)&&/^[\p{L}\p{N}\p{M}]/u.test(t),s=n!==void 0&&new RegExp(`${St}\\s*$`).test(n)&&/[\p{L}\p{N}\p{M}]$/u.test(t);return!r&&!s?!0:new RegExp(`${r?Tc(t):""}${ue(t)}${s?Ac(t):""}`,"u").test(e)}function Wr(e,t){let n=new RegExp(`^\\s*${St}`).test(e)&&/^[\p{L}\p{N}\p{M}]/u.test(t),r=new RegExp(`${St}\\s*$`).test(e)&&/[\p{L}\p{N}\p{M}]$/u.test(t);return!n&&!r?t:new RegExp(`${n?Tc(t.trim()):""}${tp(t.trim())}${r?Ac(t.trim()):""}`,"iu")}var vc=e=>{try{return decodeURIComponent(e)}catch{return e}},Dt=(e,t)=>new Error(`${e} "${t}" is empty for this row, so it would hold for anything. Give that cell or data value a value, or give the check its own Scenario.`);function Tn(e,t,n,r,s){let o=(c,l,d)=>c.replace(l,u=>{let p=d(u);return p.trim()===""&&r?.(),p}),a=o(e,/<[^<>]+>/g,c=>qt(c,t)),i=Ke(o(a,ve,zt),s);return us(o(i,Se,c=>md(c,n)))}function cn(e,t,n,r=!1,s=!1){return e.replace(kc,(o,a,i,c)=>{let l=e.slice(Math.max(0,c-2),c);if(i.startsWith("<")&&(l==="(?"||l==="\\k"))return o;let d=t(i);if(d===i)return o;if(!r)return a+n(d);let u=!1,p=-1;for(let x=0;x<c;x++){if(e[x]==="\\"){x++;continue}e[x]==="["&&(u=!0),e[x]==="]"&&(u=!1),!u&&e[x]==="{"&&(p=x),!u&&e[x]==="}"&&(p=-1)}if(u)return n(d).replace(/-/g,"\\x2d");if(p>=0&&e.indexOf("}",c+o.length)>=0)throw new Error("A regex quantifier cannot contain a row or data token. Use a separate Scenario with a literal repeat count.");if(!s)return n(d);let f=e.slice(0,c),g=e.slice(c+o.length);if(/^(?:[*+?]|\{\d)/.test(g))throw new Error("A regex quantifier right after a row or data value repeats only its last character, so the value is not matched whole. Write the pattern without it.");let y=np(f),h=Kr(g),S=/^[\p{L}\p{N}\p{M}]/u.test(d)&&!y?Tc(d,!/(?:\\?[.,]|\[[^\]]*[.,][^\]]*\])$/.test(f)):"",v=/[\p{L}\p{N}\p{M}]$/u.test(d)&&!h?Ac(d,!/^(?:\\?[.,]|\[[^\]]*[.,])/.test(g)):"";return S+n(d)+v})}function np(e){if(/(?:^|[^\\])(?:\((?:\?:|\?<[A-Za-z_]\w*>)?|\|)$/.test(e))return!1;let t=0,n=0;for(let s of e.matchAll(/\\.|\[(?:\\.|[^\]\\])*\]|\{\d+(?:,\d*)?\}|./gsu)){let o=s[0];t===0&&!/^(?:[*+?]|\{\d)/.test(o)&&(n=s.index),o==="("&&t++,o===")"&&t--}let r=e.slice(n);return/^\(\?<?[=!]/.test(r)?np(e.slice(0,n)):r.startsWith("(")&&rp(r).length>1?!1:Kr(r)}function rp(e){let t=[],n=/^\((?:\?:|\?<[A-Za-z_]\w*>)?/.exec(e)?.[0].length??1,r=0;for(let s of e.matchAll(/\\.|\[(?:\\.|[^\]\\])*\]|./gsu))s[0]==="("?r++:s[0]===")"?r--:s[0]==="|"&&r===1&&(t.push(e.slice(n,s.index)),n=s.index+1);return[...t,e.slice(n,-1)]}function Vf(e){let t=/^(?:\\[pP]\{[^}]*\}|\\(?:x[0-9a-fA-F]{2}|u\{[^}]*\}|u[0-9a-fA-F]{4}|c[A-Za-z]|.)|\[(?:\\.|[^\]\\])*\])/su.exec(e);if(t)return t[0].length;if(e[0]!=="(")return e?[...e][0].length:0;let n=0;for(let r of e.matchAll(/\\.|\[(?:\\.|[^\]\\])*\]|./gsu))if(r[0]==="("&&n++,r[0]===")"&&--n===0)return r.index+1;return e.length}var ai=new Map;function Kr(e){let t=ai.get(e);if(t!==void 0)return t;ai.size>1e4&&ai.clear();let n=ob(e);return ai.set(e,n),n}function ob(e){if(/^\(\?<?[=!]/.test(e))return Kr(e.slice(Vf(e)));let t=Vf(e),n=t>0&&!/^[*+?{]/.test(e)?/^(?:[*?]|\{0(?:,\d*)?\})\??/.exec(e.slice(t)):null;if(n)return Kr(e.slice(t+n[0].length));let r=e.startsWith("(")?rp(e.slice(0,t)):[];if(r.length>1){let a=e.slice(t).replace(/^(?:\+|\{\d+(?:,\d*)?\})\??/,"");return r.every(i=>Kr(i+a))}if(/^[\p{L}\p{N}\p{M}]/u.test(e)||/^(?:\\[dwp]|[*+?{])/.test(e))return!0;let s=/^\((?:\?:|\?<[A-Za-z_]\w*>)?/.exec(e);if(s)return Kr(e.slice(s[0].length));let o=/^\[((?:\\.|[^\]\\])*)\]/.exec(e);return o!==null&&!o[1].startsWith("^")&&(/[\p{L}\p{N}]/u.test(o[1].replace(/\\./g,""))||/\\[dwp]/.test(o[1]))}function Ft(e,t=""){return(/[uv]/.test(t)||e.includes(String.raw`[\p{L}\p{N}\p{M}]`))&&(e=e.replace(/\\.|[\s\S]/g,n=>/^\\['"`>\-]$/.test(n)?`\\x${n.charCodeAt(1).toString(16)}`:n),/[uv]/.test(t)||(t+="u")),new RegExp(e,t)}function Sc(e,t){return wn(e,(r,s)=>cn(r,t,fe[s],s==="regex",!0),t,!0).replace(/"((?:[^"\\]|\\.)*)"|(?<!xpath)=\/((?:[^/\\]|\\.)*)\/([a-z]*)/g,(r,s,o,a)=>s!==void 0?r:`=${Ft(o,a).toString()}`)}function Wf(e,t,n,r=!1,s=!0,o=new Set,a){let i=f=>Tn(f,n,o,void 0,a);for(let f of["name","text","label","placeholder","testId"]){if(Tt(t[f],i(t[f]??""),i))throw Dt(`The target's ${f}`,t[f]);if((f==="text"||f==="label"||f==="placeholder")&&bc(t[f],i))throw xc(`The target's ${f}`,t[f])}if(t.role&&t.nameRegex!==void 0){let f=cn(t.nameRegex,i,fe.pattern,!0,!0);if(Tt(t.nameRegex,f,i,Ft(f,"i")))throw Dt("The target's name",t.nameRegex)}let c=f=>_s(f).map(g=>g.trim().startsWith("internal:")?g:g.replace(/(\[\s*[\w-]+\s*=\s*)(["'])((?:(?!\2)[^\\]|\\.)*)\2(\s*[is]?\s*\])/g,"$1$2$2$4")).join(">>");for(let f of[...t.fallbackSelectors??[],...t.frame?[t.frame]:[]]){let g=c(f);wn(g,(v,x)=>{let b=cn(v,i,fe[x],x==="regex",!0),m;try{m=x==="regex"?Ft(b):void 0}catch{}if(Tt(v,b,i,m))throw Dt("The text in selector",f);return v},v=>v,!0);let y=[...g.matchAll(/'((?:[^'\\]|\\.)*)'/g)].map(v=>v[1]),h=_s(g).flatMap(v=>v.trim().match(/^(?:internal:)?text=(?!["/])(.*)$/s)?.[1]??[]);for(let v of[...y,...h])if(Tt(v,i(v),i))throw Dt("The text in selector",f);let S=new RegExp(`^\\s*(${St})|(${St})\\s*$`,"g");for(let v of[...Hf(f,!0).map(x=>x.raw),..._s(f).flatMap(x=>Jf(x).map(b=>b.raw))])if([...v.matchAll(S)].some(b=>i(b[1]??b[2]).trim()==="")&&i(v).trim()!=="")throw xc("The text in selector",f)}let l=[],d=f=>Sc(f,i),u=(f,g)=>{let y=new RegExp(`^\\s*${St}|${St}\\s*$`),h;for(let S of _s(g)){let v=[...Hf(S).filter(b=>y.test(b.raw)).map(b=>({index:b.index,apply:m=>m.filter({hasText:Wr(b.raw,i(b.raw))})})),...Jf(S).map(b=>({index:b.index,apply:m=>b.has!==void 0?m.filter({has:u(f,b.has)}):b.flags!==void 0?m.filter({hasText:Ft(cn(b.raw,i,fe.pattern,!0,!0),b.flags)}):rb(S,b.index)?m.filter({has:f.locator(d(b.selector))}):m.and(f.locator(d(b.selector)))}))].map(b=>({...b,end:sb(S,b.index)})),x=0;for(let b of[...new Set([...v.map(m=>m.end),S.length])].sort((m,$)=>m-$)){let m=x===0?S.slice(0,b):`${Rc(S)?"xpath=.":":scope"}${S.slice(x,b)}`;if(h=h?h.locator(d(m)):f.locator(d(m)),typeof h.filter!="function")return f.locator(d(g));for(let $ of v)$.end===b&&(h=$.apply(h));x=b}}return h},p=f=>{if(t.role){let g=t.nameRegex?Ft(cn(t.nameRegex,i,fe.pattern,!0,!0),"i"):t.name?i(t.name):void 0,y=t.role;g===void 0&&!!(t.label||t.placeholder||t.text||t.testId||t.fallbackSelectors?.length)?t.text&&l.push(f.getByRole(y).filter({hasText:Wr(t.text,i(t.text))})):typeof g=="string"?(l.push(f.getByRole(y,{name:g,exact:!0})),s&&l.push(f.getByRole(y,{name:Wr(t.name,g),exact:!1}))):l.push(f.getByRole(y,{name:g,exact:!1}))}t.label&&l.push(f.getByLabel(Wr(t.label,i(t.label)))),t.placeholder&&l.push(f.getByPlaceholder(Wr(t.placeholder,i(t.placeholder)))),t.text&&!t.role&&l.push(f.getByText(Wr(t.text,i(t.text)))),t.testId&&l.push(f.getByTestId(i(t.testId)));for(let g of t.fallbackSelectors??[])l.push(u(f,g))};if(t.frame){let f=new RegExp(St).test(t.frame)?u(e,t.frame):void 0;p(f&&typeof f.contentFrame=="function"?f.contentFrame():e.frameLocator(d(t.frame)))}else if(p(e),r)for(let f of e.frames())f!==e.mainFrame()&&p(f);if(l.length===0)throw new Error("Action target has neither role nor fallback selectors");return l}var sp=100,ib=500;async function ab(e,t,n,r){let s=Date.now()+t,o;for(;Date.now()<s;){try{if(await e())return}catch(a){o=a}await $c(r)}throw new Error(`Timed out waiting for ${n}${o?` (${String(o)})`:""}`)}async function an(e,t,n=!1){let r;for(let s of e)try{await t(s.first());return}catch(o){if(r=o,n&&await s.first().count().catch(()=>0)>0)throw o}throw r}var cb=20,rt=e=>e.replace(/\s+/g," ").trim(),Vn=new WeakMap,Ps=new WeakMap;async function Gf(e,t){let n={element:t};if(await e.count()!==1)return n;let r=await t.ownerFrame();if(!r)return n;let s=await t.getAttribute("id"),o=await t.getAttribute("data-testid"),a=[o?r.getByTestId(o):void 0,s?r.locator(`#${await t.evaluate(i=>i.ownerDocument.defaultView.CSS.escape(i.id))}`):void 0];for(let i of a)if(i&&await i.count()===1){n.stable=i;break}return n}async function lb(e){if(!await e.element.evaluate(n=>n.isConnected).catch(()=>!1)&&e.stable&&await e.stable.count()===1){let n=await e.stable.elementHandle({timeout:100});n&&(await e.element.dispose().catch(()=>{}),e.element=n)}return rt((await e.element.evaluate(Rn,!1)).text)}var Is=new WeakMap,Cs=new WeakMap,Kf="__saffron_download",Yf=5*1024*1024;async function Ec(e,t,n){let r=e.suggestedFilename(),s,o=new Promise(l=>{s=setTimeout(()=>l(`it did not finish within ${n} ms`),n)}),a=await Promise.race([e.failure(),o]).finally(()=>clearTimeout(s));if(a)throw e.cancel().catch(()=>{}),new Error(`waitForDownload failed: the download of ${r} failed (${a})`);if(!t)return e.path();let i=js.basename(r).replace(/[\u0000-\u001f<>:"/\\|?*]/g,"_"),c=js.join(t,i===""||i==="."||i===".."?"download":i);return await wc.promises.mkdir(t,{recursive:!0}),await e.saveAs(c),c}async function Oc(e){let t=js.basename(e),{size:n}=await wc.promises.stat(e);if(n>Yf)throw new Error(`the downloaded file ${t} is ${n} bytes; a content check reads text files up to ${Yf} bytes`);let r=await wc.promises.readFile(e),s;try{if(r.includes(0))throw new Error("NUL byte");s=new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{throw new Error(`the downloaded file ${t} is not a UTF-8 text file, so its content cannot be checked`)}return s=s.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
|
|
55
|
+
`),/\.(ics|ical|ifb|vcf|vcs)$/i.test(t)?s.replace(/\n[ \t]/g,""):s}function li(e,t,n,r){let s=o=>Tn(o,t,n,void 0,r);return{value:e.value===void 0?void 0:s(e.value),pattern:e.pattern===void 0?void 0:cn(e.pattern,s,fe.pattern,!0,!0)}}function _c(e,t,n,r){if(!e.value&&!e.pattern)return"expectDownload needs a value or a pattern";let s=l=>Tn(l,t,n,void 0,r),{value:o,pattern:a}=li(e,t,n,r);if(Tt(e.value,o??"",s))return Dt("The text the downloaded file must contain",e.value).message;if(a!==void 0&&Tt(e.pattern,a,s,Ft(a,"m")))return Dt("The pattern the downloaded file must match",e.pattern).message;let i=!1;if(e.value!==void 0&&Tn(e.value,t,n,()=>{i=!0},r),i)return"The text the downloaded file must contain holds an empty row or data value. Give it a value, or give the blank case its own Scenario with explicit text.";let c=!1;if(e.pattern!==void 0&&(cn(e.pattern,l=>Tn(l,t,n,()=>{c=!0},r),fe.pattern,!0),c&&!Ft(a,"m").test("")))return"The pattern the downloaded file must match holds an empty row or data value. Give it a value, or give the blank case its own Scenario with an explicit pattern."}function Cc(e,t,n,r,s){if(n&&!Gr(e,n,s))return`the downloaded file ${t} does not contain "${n}"`;if(r!==void 0&&!Ft(r,"m").test(e))return`the downloaded file ${t} does not match /${r}/m`}function Rn(e,t=!1){if(!e.isConnected)return{text:"",pieces:[],kept:!1};let n=e.ownerDocument,r=n.defaultView,s=S=>r.getComputedStyle(S),o=S=>S.checkVisibility?.({contentVisibilityAuto:!1,visibilityProperty:!1,opacityProperty:!1})??S.getClientRects().length>0,a=S=>S.replace(/\s+/g," ").trim(),i=new Set,c=S=>{S&&i.add(S)},l=n.createRange(),d=!1,u=!1;for(let S=e.parentElement;S&&!u;S=S.parentElement)u=s(S).contentVisibility==="auto";let p=(S,v,x,b)=>{if(S.tagName==="BR")return["",`
|
|
56
|
+
`,""];if(S.tagName==="TEXTAREA"){let E=v.visibility==="visible"?String(S.value??""):"";return[E,E,t?a(E):""]}let m=v.visibility!=="visible"||v.contentVisibility==="hidden"||S.tagName==="DETAILS"&&!S.open,$=/^(pre|pre-wrap|pre-line|break-spaces)$/.test(v.whiteSpace),T=b||v.contentVisibility==="auto",R="",k="",C="",P=0;for(let E of Array.from(S.childNodes)){if(E.nodeType===3){if(m)continue;let I=E.nodeValue??"",U=/\S/.test(I);if(U&&!x){l.selectNodeContents(E);let q=!!S.shadowRoot||/^(CANVAS|VIDEO|AUDIO|OBJECT|IFRAME)$/.test(S.tagName);if(l.getClientRects().length===0&&(!T||q))continue}let D=I.replace(/[ \t\n\r\f]+/g," ");$?U&&I!==D&&(d=!0):I=D,R+=I,k+=I,U&&(P+=2);continue}if(E.nodeType!==1)continue;let _=s(E);if(_.display==="none"||x&&E.hidden||!x&&_.display!=="contents"&&!o(E))continue;let[A,O,j]=p(E,_,x||E.tagName==="SELECT",T);R+=A;let L=E.tagName!=="OPTION"&&/^(inline|contents)/.test(_.display);k+=L?O:`
|
|
57
|
+
${O}
|
|
58
|
+
`,!(!t||!j)&&(P++,C=j,L&&O.includes(`
|
|
59
|
+
`)&&(c(a(O.slice(0,O.indexOf(`
|
|
60
|
+
`)))),c(a(O.slice(O.lastIndexOf(`
|
|
61
|
+
`)+1)))))}if(!t)return[R,k,""];let w=P===1?C:a(k);return c(w),[R,k,w]},f=e.closest("select"),g;if(f){g=f.getClientRects().length>0&&o(f);for(let S=e;g&&S!==f;S=S.parentElement)(S.hidden||s(S).display==="none")&&(g=!1)}else{let S=e;for(;S&&s(S).display==="contents";)S=S.parentElement;g=!S||o(S)}if(!g)return{text:"",pieces:[],kept:!1};let[y,h]=p(e,s(e),!!f,u);if(t)for(let S of h.split(`
|
|
62
|
+
`))c(a(S));return{text:y,pieces:[...i],kept:d}}function db(e,[t,n]){let r=(0,eval)("("+n+")"),s=i=>{for(let c=i;c;c=c.parentElement??c.getRootNode().host)if(c.hidden||c.ownerDocument.defaultView.getComputedStyle(c).display==="none")return!0;return!1},o=i=>String(i.textContent??"").replace(/\s+/g," ").trim(),a=i=>s(i)||o(i)!==""&&!/\S/.test(r(i).text);if(e.length===0||!a(e[0]))return 0;for(let i=1;i<Math.min(e.length,t);i++)if(!a(e[i]))return o(e[i])===o(e[0])?i:0;return 0}async function Zf(e,t){let{text:n,kept:r}=await e.evaluate(Rn,!1,t);if(/\S/.test(n)||await e.isVisible())return{text:n,kept:r}}async function Ns(e,t,n,r,s,o=new Map,a,i=sp,c=new Set,l){let d=(w,E,_)=>ab(w,E,_,i),u=Cs.get(e);if(u!==void 0&&(ii.has(t.action)&&!(t.action==="uploadFile"&&!t.target)||t.action==="goto"||t.action==="newTab")){Cs.delete(e);let w=Vn.get(e),E=e.context(),_=[],A=()=>{},O=L=>{_.push(L),_.length>=u&&A()},j=L=>{L.on("download",O)};E.pages().forEach(j),E.on("page",j);try{let L;try{L=await Ns(e,t,n,r,s,o,a,i,c,l)}catch(I){if(!/Download is starting/.test(I instanceof Error?I.message:String(I)))throw I}if(_.length<u&&await new Promise(I=>{let U=setTimeout(I,r);A=()=>{clearTimeout(U),I()}}),_.length===0)throw new Error(`waitForDownload failed: the ${t.action} after it started no download within ${r} ms`);if(_.length<u)throw new Error(`waitForDownload failed: the ${t.action} after it started ${_.length} of the ${u} downloads it started when recorded, within ${r} ms`);return o.set(Kf,await Ec(_[_.length-1],l,r)),L}catch(L){throw Cs.set(e,u),w&&!Vn.has(e)&&Vn.set(e,w),L}finally{E.off("page",j);for(let L of E.pages())L.off("download",O)}}let p=Vn.get(e);if(p&&ii.has(t.action)&&t.action!=="uploadFile"){Vn.delete(e);let w,E=A=>{w??=A};e.on("filechooser",E);let _;try{if(_=await Ns(e,t,n,r,s,o,a,i,c,l),w||await e.waitForEvent("filechooser",{timeout:r}).then(E,()=>{}),!w)throw new Error(`uploadFile failed: the ${t.action} after it opened no file chooser within ${r} ms`);try{await w.setFiles(p,{timeout:r})}catch(A){throw new Error(`uploadFile failed: ${A instanceof Error?A.message:String(A)}`)}}catch(A){throw Vn.set(e,p),A}finally{e.off("filechooser",E)}return _}o.has(Nt)||o.set(Nt,$n()),(ii.has(t.action)||t.action==="goto"||t.action==="newTab"||t.action==="closeTab")&&a?.markAction();let f=o.get(Nt),g=w=>typeof w=="string"?on(w,f):Array.isArray(w)?w.map(g):w&&typeof w=="object"?Object.fromEntries(Object.entries(w).map(([E,_])=>[E,g(_)])):w;t=g(t),n=g(n),o.has(Ao)||o.set(Ao,String(Date.now()));let y=new Date(Number(o.get(Ao))),h=w=>Tn(w,n,c,void 0,y),S=()=>JSON.stringify(Object.fromEntries(Object.entries(t.target??{}).sort(([w],[E])=>w.localeCompare(E)).map(([w,E])=>Array.isArray(E)?[w,E.map(_=>Sc(_,h))]:E===void 0||w==="role"?[w,E]:w==="nameRegex"?[w,cn(E,h,fe.pattern,!0,!0)]:w==="frame"?[w,Sc(E,h)]:[w,h(E)]))),v=(w,E)=>cn(w,_=>Tn(_,n,c,E,y),fe.pattern,!0,!0),x=!1,b=t.value!==void 0&&t.action!=="expectAmount"?Tn(t.value,n,c,()=>{x=!0},y):void 0,m=t.url!==void 0?h(t.url):void 0,$=t.action==="expectVisible"||t.action==="expectText"||t.action==="expectValue"||t.action==="expectMatches"||t.action==="expectAttribute"||t.action==="expectEach"||t.action==="expectDiffers"||t.action==="expectAmount"||t.action==="captureText",T=t.target?Wf(e,t.target,n,$,!ii.has(t.action)&&!$e.has(t.action),c,y):[],R={timeout:r},k={timeout:Math.min(1e3,r)},C=async w=>{let E=await w.evaluateAll(db,[cb,Rn.toString()]);return E>0?w.nth(E):w.first()},P=w=>async()=>{for(let E of T)try{if(await w(await C(E)))return!0}catch{}return!1};switch(t.action){case"goto":{if(!m)throw new Error("goto requires url");let w=Ss(m);if(w)throw new Error(w);await e.goto(Ja(m,s),R);return}case"click":{let{clickCount:w,button:E,modifiers:_}=t,A={...R,clickCount:w,button:E,modifiers:_};return an(T,O=>O.click(A),!0)}case"fill":return an(T,w=>w.fill(b??"",R),!0);case"press":return T.length>0?an(T,w=>w.press(b??"",R),!0):e.keyboard.press(b??"");case"selectOption":return an(T,async w=>{if(t.clearSelection){await w.selectOption([],R);return}let E=(b??"").split(`
|
|
63
|
+
`);await w.selectOption(E.length>1?E:E[0],R)},!0);case"check":return an(T,w=>w.check(R),!0);case"uncheck":return an(T,w=>w.uncheck(R),!0);case"hover":return an(T,w=>w.hover(R),!0);case"waitFor":return T.length>0?an(T,w=>w.waitFor({state:"visible",timeout:r})):$c(Math.min(Number(b??"0"),r));case"expectVisible":return d(P(w=>w.isVisible()),r,"target to be visible");case"expectNotVisible":return d(async()=>{for(let w of T){let E=await w.count();for(let _=0;_<E;_++)if(await w.nth(_).isVisible())return!1}return!0},r,`every match of every recorded locator to be hidden (${T.length} locator(s))`);case"expectText":if(rt(b??"")!==""&&x)throw new Error("The expected text contains an empty row or data value. Give it a value, or give the blank case its own Scenario with explicit expected text.");return d(P(async w=>{let E=await Zf(w,k);return E===void 0?rt(b??"")==="":rt(b??"")===""?rt(E.text)==="":Gr(rt(E.text),rt(b??""),t.value)||E.kept&&Gr(E.text,b??"",t.value)}),r,`text "${b}"`);case"expectEach":{let w=(t.each!==void 0?qt(t.each,n):void 0)?.match(/^\{data:([^}]+)\}$/)?.[1];if(!w)throw new Error(`expectEach needs a {data:...} list reference, got ${JSON.stringify(t.each)}`);let E=en(w),_=async O=>{let{pieces:j}=await O.evaluate(Rn,!0,k),L=new Set(j.map(I=>I.toLowerCase()));if(await O.isVisible())for(let I of(await O.innerText(k)).split(`
|
|
64
|
+
`))L.has(rt(I).toLowerCase())&&j.push(rt(I));return new Set(j)},A=E;return d(async()=>{for(let O of T)try{let j=await _(await C(O)),L=E.filter(I=>!j.has(I.replace(/\s+/g," ").trim()));if(L.length<A.length&&(A=L),L.length===0)return!0}catch{}return!1},r,`every value of ${t.each} to be shown`).catch(()=>{throw new Error(`${A.map(O=>`"${O}"`).join(", ")} from ${t.each} ${A.length===1?"is":"are"} not shown in the target (${E.length-A.length} of ${E.length} found)`)})}case"expectValue":return d(P(async w=>await w.isVisible()&&await w.inputValue(k)===(b??"")),r,`input value "${b}"`);case"expectUrl":{let w=m??b??"";if(w.trim()==="")throw Dt("The expected URL",t.url??t.value??"");if(bc(t.url??t.value,h))throw xc("The expected URL",t.url??t.value??"");return d(async()=>Gr(e.url(),w,t.url??t.value)||Gr(vc(e.url()),w,t.url??t.value)||Gr(vc(e.url().replace(/\+/g,"%20")),w,t.url??t.value),r,`URL containing "${w}" on the active page (${e.url()})`)}case"handleDialog":{let w=(b??"accept")!=="dismiss",E=t.promptText?h(t.promptText):void 0,_=Is.get(e);_&&e.off("dialog",_);let A=O=>{Is.delete(e),(w?O.accept(E):O.dismiss()).catch(()=>{})};Is.set(e,A),e.once("dialog",A);return}case"uploadFile":{let w=it().root,E=(b??"").split(`
|
|
65
|
+
`).filter(Boolean).map(A=>js.resolve(w,A));if(E.length===0)throw new Error("uploadFile requires a path");let _=Ya(E,w);if(_)throw new Error(_);if(T.length>0)return an(T,A=>A.setInputFiles(E,R),!0);Vn.set(e,E);return}case"waitForDownload":Cs.set(e,t.downloads??1);return;case"expectDownload":{let w=o.get(Kf);if(!w)throw new Error("expectDownload: no file was downloaded in this scenario before this check");let E=_c(t,n,c,y);if(E)throw new Error(E);let _=li(t,n,c,y),A=Cc(await Oc(w),js.basename(w),_.value,_.pattern,t.value);if(A)throw new Error(A);return}case"dragTo":{if(!t.toTarget)throw new Error("dragTo requires toTarget");let w=Wf(e,t.toTarget,n,!1,!1,c,y);return an(T,E=>E.dragTo(w[0].first(),R),!0)}case"captureText":{if(!t.saveAs)throw new Error("captureText requires saveAs");await a?.quiet(Math.min(r/2,3e3));let w=Math.min(ib,r/4),E=Date.now()+r-w,_;return d(async()=>{for(let A of T){let O;try{if(O=await(await C(A)).elementHandle(k)??void 0,!O)continue;let j=rt((await O.evaluate(Rn,!1)).text);if(j==="")continue;let L=Date.now();if(_?.text!==j&&(_={text:j,since:L}),L-_.since<w&&L<E)return!1;let I=await Gf(A,O),U=Ps.get(o);return U||Ps.set(o,U=new Map),await U.get(t.saveAs)?.tracked.element.dispose().catch(()=>{}),U.set(t.saveAs,{page:e,key:S(),value:j,tracked:I}),O=void 0,o.set(t.saveAs,j),!0}catch{}finally{await O?.dispose().catch(()=>{})}}return!1},r,`non-empty text to capture as "${t.saveAs}"`)}case"expectAmount":{let w=rr(t.value??"",A=>Tn(A,n,c,void 0,y)),E=Oo(w,A=>o.get(A));if("problem"in E)throw new Error(`expectAmount: ${E.problem}`);let _;try{return await d(P(async A=>{_=rt((await A.evaluate(Rn,!1,k)).text);let O=Rt(_);return O!==void 0&&Ln(O,E.amount)}),r,/\{env:/.test(t.value??"")?`the amount ${t.value}`:`the amount ${Ud(E.amount)} (${w})`)}catch(A){throw new Error(`${A instanceof Error?A.message:String(A)}${_===void 0?"":`; the target shows "${_}"`}`)}}case"expectDiffers":{if(!t.compareTo)throw new Error("expectDiffers requires compareTo");let w=o.get(t.compareTo);if(w===void 0)throw new Error(`expectDiffers: no captured value named "${t.compareTo}"`);if(T.length>0){let A=Ps.get(o)?.get(t.compareTo),O=A?.page===e&&A.value===w&&A.key===S()?A.tracked:void 0,j=O;try{return await d(async()=>{if(j){let L=await lb(j);if(L===""||L===w)return!1;for(let I of T)try{if(await I.evaluateAll((U,D)=>U.includes(D),j.element))return!0}catch{}return!1}for(let L of T){let I;try{if(I=await(await C(L)).elementHandle(k)??void 0,!I)continue;let U=rt((await I.evaluate(Rn,!1)).text);if(U==="")continue;return j=await Gf(L,I),U!==w}catch{}finally{I&&I!==j?.element&&await I.dispose().catch(()=>{})}}return!1},r,`target text to differ from "${t.compareTo}" (${w})`)}finally{j&&j!==O&&await j.element.dispose().catch(()=>{})}}let E=b??"",_=o.get(E);if(_===void 0)throw new Error(`expectDiffers: no captured value named "${E}"`);if(_===w)throw new Error(`expectDiffers: "${E}" (${_}) equals "${t.compareTo}" (${w})`);return}case"expectAttribute":{if(!t.attribute)throw new Error("expectAttribute requires attribute");if(!t.pattern)throw new Error("expectAttribute requires pattern");let w=!1,E=v(t.pattern,()=>{w=!0}),_=Ft(E);if(w&&E!==""&&!_.test(""))throw new Error("The attribute pattern contains an empty row or data value. Give it a value, or give the blank case its own Scenario with an explicit pattern.");let A=h(t.attribute);if(Tt(t.attribute,A,h))throw Dt("The attribute name",t.attribute);let O=Tt(t.pattern,E,h,_),j=_.test("")&&_.test("false")&&!_.test("true");return d(P(async L=>{let I=await L.getAttribute(A,k);return O?(I??"").trim()==="":I===null?j:_.test(I)}),r,`attribute ${A} to match /${t.pattern}/`)}case"expectMatches":{if(!t.pattern)throw new Error("expectMatches requires pattern");let w=!1,E=v(t.pattern,()=>{w=!0}),_=Ft(E,"i");if(w&&rt(E)!==""&&!_.test(""))throw new Error("The expected text pattern contains an empty row or data value. Give it a value, or give the blank case its own Scenario with an explicit pattern.");let A=rt(E)===""||Tt(t.pattern,E,h,_);return d(P(async O=>{let j=await Zf(O,k);return j===void 0?A:A?rt(j.text)==="":_.test(rt(j.text))||j.kept&&_.test(j.text)}),r,`target text to match /${t.pattern}/i`)}case"switchTab":{let w=Number.parseInt(b??"",10),E=()=>e.context().pages().filter(A=>!A.isClosed());await d(async()=>E().length>w,r,`tab ${b} to exist (${E().length} open: ${E().map(A=>A.url()).join(", ")})`);let _=E()[w];return await _.bringToFront(),_}case"closeTab":{let w=e.context().pages().filter(A=>!A.isClosed()),E=b===void 0?e:w[Number.parseInt(b,10)];if(!E)throw new Error(`tab ${b} does not exist (${w.length} open)`);await E.close();let _=e.context().pages().filter(A=>!A.isClosed());if(_.length===0)throw new Error("closed the last tab; nothing left to drive");return _[_.length-1]}case"newTab":{let w=m?Ss(m):void 0;if(w)throw new Error(w);let E=await e.context().newPage();return m&&await E.goto(Ja(m,s),R),E}case"waitForResponse":case"expectResponse":{if(!t.urlPattern)throw new Error(`${t.action} requires urlPattern`);let w=v(t.urlPattern),E=Ft(w),_=t.status!==void 0?h(t.status):void 0,A=t.method!==void 0?h(t.method):void 0,O=!1,j=t.pattern?v(t.pattern,()=>{O=!0}):void 0,L=j!==void 0?Ft(j):void 0;if(O&&j!==""&&L&&!L.test(""))throw new Error("The response body pattern contains an empty row or data value. Give it a value, or give the blank case its own Scenario with an explicit pattern.");if(Tt(t.urlPattern,w,h,E))throw Dt("The response URL pattern",t.urlPattern);if(Tt(t.status,_??"",h))throw Dt("The response status",t.status);if(Tt(t.method,A??"",h))throw Dt("The response method",t.method);if(L&&Tt(t.pattern,j,h,L))throw Dt("The response body pattern",t.pattern);if(t.json!==void 0){let M=ir(t.json);if(M)throw new Error(`Response json ${M}`)}let I=t.json?.map(M=>({...M,path:cn(M.path,h,B=>B.replaceAll("~","~0").replaceAll("/","~1")),...M.equals!==void 0?{equals:h(M.equals)}:{}})),U=new Map([...c].flatMap(M=>process.env[M]===void 0?[]:[[M,process.env[M]]])),D=M=>new Error(Ge(M,U));if(I){if(t.json.some(B=>bc(B.path,h)))throw new Error("A JSON field path contains an empty row or data value. Give the path a value, or check the root explicitly with an empty path.");let M=ir(I);if(M)throw new Error(`Response json ${M}`);try{for(let B of I)B.equals!==void 0&&ja(B)}catch(B){throw D(B instanceof Error?B.message:String(B))}}let q,Y=M=>{if(!mc(M,E,A,_,void 0))return I&&mc(M,E,A,`${M.status}`,void 0)&&(q=`expected status ${_??"2xx"}, got ${M.status}`),!1;if(I){let B=tu(M.body,I);if(B)return q=B,!1}return L&&(M.body===void 0||!L.test(M.body))?(I&&(q="response body does not match the expected body pattern"),!1):!0},Q=M=>{throw q?D(`${qf({...t,status:_,method:A},t.urlPattern)}: ${q}`):M};if(!a){await e.waitForResponse(async M=>{let B={seq:0,url:M.url(),method:M.request().method(),status:M.status()};if(!mc(B,E,A,_,void 0))return Y(B);if(!L&&!I)return!0;let J=await M.text().catch(()=>{});return Y({...B,body:J})},R).catch(Q);return}let N=()=>t.action==="expectResponse"?a.sinceAction():a.sincePreviousStep();return d(async()=>{q=void 0;let M=N().find(Y);return M&&(a.lastMatch=M),M!==void 0},r,qf({...t,status:_,method:A},t.urlPattern)).catch(Q)}default:throw new Error(`Unknown action type: ${t.action}`)}}var ci=(e,t)=>wt(e.actions,t);function ub(e,t){let n=e.examples;return n?e.steps.some(r=>r.actions.some(s=>Pt(s).some(o=>o!==void 0&&[...o.matchAll(/\{data:([^{}]*<[^<>{}]+>[^{}]*)\}/g)].some(([,a])=>a.replace(/<([^<>]+)>/g,(i,c)=>n[c]??"\0")===t)))):!1}var Qf=(e,t)=>bn(e.actions,t);function ln(e,t){if(!t.rowBound?.length||!t.examples||t.steps.length!==e.steps.length||t.steps.some((h,S)=>h.gherkin!==e.steps[S].text||h.kind!==e.steps[S].kind)||t.steps.some((h,S)=>JSON.stringify(h.table??null)!==JSON.stringify(e.steps[S].table??null)||(h.docString??null)!==(e.steps[S].docString??null))&&!Wn(e,t))return;let r=t.rowBound.filter(h=>h.column in e.params),s=ms([...new Set(r.map(h=>h.column))],t.examples,e.params,t.recordedAt,t.data);if(s===void 0){let h=r.find(x=>x.valueSha!==void 0&&!Po(e.params[x.column]??"",x.valueSha));if(!h)return;let{keyword:S,gherkin:v}=t.steps[h.step];return`This Outline was recorded with ${h.column} as ${t.examples[h.column]}, which resolves to another value now (or is not set), and step ${h.step+1} ("${S?`${S.trim()} `:""}${v}") still holds the value it had, so the recording cannot check this row. Record the Outline again with saffron run --rerecord.`}let{step:o,reason:a}=r.find(h=>h.column===s),i=t.examples[s],c=`this row, where ${s} is "${e.params[s]}"`,{keyword:l,gherkin:d}=t.steps[o],u=`step ${o+1} ("${l?`${l.trim()} `:""}${d}")`,p=d.includes(`<${s}>`),f=[...new Set(r.map(h=>h.column))],y=(e.exampleRows??[]).every(h=>ms(f,t.examples,h,t.recordedAt,t.data)!==void 0)?` No Examples row has ${s} "${i}" any more: record the Outline again with saffron run --rerecord.`:" Or record the Outline again on another row with saffron run --rerecord.";return(a==="unwritten"&&t.steps[o].kind==="assertion"?`This Outline was recorded on the row where ${s} is "${i}", and ${u} names <${s}> but only checks that something is shown or in a state, which reads the same whoever <${s}> is, so it cannot prove ${c}. Make the check show the value: write <${s}> in the text the step expects (\`Then the dashboard greets "<${s}>"\`), then record again with saffron run --rerecord. Or give each value its own Scenario.`:a==="unwritten"?`This Outline was recorded on the row where ${s} is "${i}", and ${u} names <${s}> but recorded no action that writes it (on that row the page already was that way, or the action holds no row value, like ticking a box), so on ${c} it would do what it did for "${i}". Give each value its own Scenario, or, where the value is what the step picks (an option or radio labelled with it), record the step picking it even when it already is.`:a==="session"?`This Outline was recorded on the row where ${s} is "${i}", and ${u} runs in the browser session <${s}> names and types a value the step does not write, which was that person's: on ${c} the other person would type it too. Write that value in the step, or give it an Examples column and write <column> there, or give each person's flow its own Scenario.`:a==="container"?`This Outline was recorded on the row where ${s} is "${i}", and ${u} acts in the section <${s}> names without being scoped to it, so on ${c} it would act in whichever such section comes first. Record the Outline again so that step's target names its section, or the dialog its action opened (saffron run --rerecord), or give each section its own Scenario.`:a==="list"?`This Outline was recorded on the row where ${s} is "${i}", and ${u} holds other rows' ${s} values too, so one recording cannot check ${c}. Give that check its own Scenario, or give the text it holds an Examples column of its own and write that column in the step.`:a==="reads"?`This Outline was recorded on the row where ${s} is "${i}", and ${u} checks a response status, method or attribute against what a {data:...} reference keyed by <${s}> reads on that row, so one recording cannot check ${c}. Give the expected value an Examples column of its own and name it in that step, or give that check its own Scenario.`:a==="value"?`This Outline was recorded on the row where ${s} is "${i}", and ${u} checks "${i}" as a response status, method or attribute without naming <${s}>, so one recording cannot check ${c}. If that check follows the row, name <${s}> in that step; if the value only coincides, give the check its own Scenario.`:a==="data"?`This Outline was recorded on the row where ${s} is "${i}", and ${u} reads a {data:...} entry that more than one of the Outline's {data:...} references chose on that row, so one recording cannot check ${c}. Write the {data:...} reference that step needs in its own text, or give that check its own Scenario.`:p?`This Outline was recorded on the row where ${s} is "${i}", and ${u} holds "${i}" spelled otherwise or inside other text (an attribute's name, a {data:...} path), where <${s}> cannot follow the row, so one recording cannot check ${c}. Spell the value as the cell does, give it an Examples column of its own, or give that check its own Scenario.`:`This Outline was recorded on the row where ${s} is "${i}", and ${u} writes "${i}" inside other text without naming <${s}>, so one recording cannot check ${c}. Put <${s}> in that step, or give that check its own Scenario.`)+y}function fb(e){let t=JSON.stringify([e.params,e.exampleRows??[],e.steps.map(n=>[n.text,n.table??[],n.docString??""])]);if(nr(t))return!0;try{let n=zt(t);return(n.match(/\{date/g)??[]).length>(t.match(/\{date/g)??[]).length?!0:nr(n)}catch{return!1}}function Pc(e,t){if(t.version>=3||!t.examples)return!1;let n=t.examples;return ei(t.steps,{...e,params:n}).some(r=>r.reason==="session"&&r.column in e.params&&n[r.column]!==e.params[r.column])}function Wn(e,t){if(t.steps.length!==e.steps.length||Pc(e,t)||t.version<3&&fb(e))return!1;let n=t.examples?[t.examples]:Object.keys(e.params).length>0?e.exampleRows??[]:[];for(let[r,s]of Object.entries(t.data??{})){let o;try{o=Le(r)}catch{continue}if(o===s)continue;let a=t.steps.some(c=>ci(c,`{data:${r}}`))||ub(t,r),i=t.steps.some(c=>Un(c.actions,s));if(!a||i)return!1}return t.steps.every((r,s)=>{let o=e.steps[s];if(r.gherkin!==o.text||r.kind!==o.kind)return!1;if(n.length>0){let c=[o.text,...o.table?.flat()??[],o.docString??""].join(`
|
|
66
|
+
`);if(n.some(d=>sr(r.actions,c,d,e.params,t.recordedAt)||hs(c,d,e.params,r.actions)))return!1;{let d=e.steps.filter((p,f)=>f!==s).map(p=>[p.text,...p.table?.flat()??[],p.docString??""].join(`
|
|
50
67
|
`)).join(`
|
|
51
|
-
`),
|
|
52
|
-
`)[0]:String(
|
|
53
|
-
`)[0]:String(l)}`)}s.length||(i?
|
|
54
|
-
`)[0],browser:o.browser}));return{runId:t.toISOString(),startedAt:t.toISOString(),finishedAt:new Date().toISOString(),baseURL:r,green:s.filter(o=>o.status==="green").length,yellow:s.filter(o=>o.status==="yellow").length,red:s.filter(o=>o.status==="red").length,aiCalls:s.reduce((o,a)=>o+a.aiCalls,0),costUsd:s.reduce((o,a)=>o+a.costUsd,0),divergentSteps:n,scenarios:s}}function
|
|
55
|
-
`)}function
|
|
56
|
-
`).filter(a=>a.trim()),s=!1,o=r.map(a=>{try{if(JSON.parse(a).runId===t.runId)return s=!0,JSON.stringify(t)}catch{}return a});s||o.push(JSON.stringify(t)),
|
|
68
|
+
`),u=c.replace(/\{[^{}]*\}|<[^<>]+>/g," ");if(n.some(p=>hs(d,p,e.params,r.actions,u)))return!1}let l=d=>r.kind==="assertion"&&!jr(r.actions)&&!(e.params[d]??"").includes("{date");if((t.examples!==void 0||r.actions.length===0)&&n.some(d=>Ir(r.gherkin,r.actions,d).some(u=>!l(u)&&!_o(c,u,e.params)&&d[u]!==void 0&&d[u]!==e.params[u])))return!1}let a=r.table,i=o.table;if(!!a!=!!i)return!1;if(a&&i){let c=Object.keys(lt(a)),l=Object.keys(lt(i));if(c.length>0&&l.length>0){if(JSON.stringify(c)!==JSON.stringify(l))return!1;let d=lt(a),u=lt(i);for(let p of c){if(d[p]===u[p])continue;let f=`<${p}>`,g=t.steps.some(h=>ci(h,f)),y=t.steps.some(h=>Qf(h,d[p]));if(!g||y)return!1}}else if(JSON.stringify(a)!==JSON.stringify(i))return!1}if(r.docString!==void 0!=(o.docString!==void 0))return!1;if(r.docString!==void 0&&o.docString!==void 0&&r.docString!==o.docString){let c=t.steps.some(d=>ci(d,"<docstring>")),l=t.steps.some(d=>ci(d,r.docString)||Qf(d,r.docString));if(!c||l)return!1}return!0})}function Ms(e,t){let n=e.steps[t],r=n?.resolvedTable??n?.table;return{...e.params,...Mn(e.steps),...lt(r),...tr(n?.resolvedDocString??n?.docString)}}async function di(e,t,n,r={}){let s=r.actionTimeoutMs??5e3,o=r.retries??1,a=Math.max(10,r.pollIntervalMs??sp),i=[],c=r.envNames??ct(t),l=r.vars??new Map;r.uniqueSeed&&l.set(Nt,r.uniqueSeed);let d=()=>Object.fromEntries(l),u=n.steps.some(P=>P.actions.some(w=>(w.action==="waitForResponse"||w.action==="expectResponse")&&(w.pattern!==void 0||w.json!==void 0))),p=r.sessions??new Map;p.set(we(t.steps[0]?.session),e);let f=new Map,g=P=>{let w=P.context();for(let O of w.pages()){Vn.delete(O),Cs.delete(O);let j=Is.get(O);j&&O.off("dialog",j),Is.delete(O)}let E=new yc;E.attach(w,u);let _=[],A=O=>_.push(O);return w.on("page",A),{context:w,active:P,seen:new Set(w.pages()),opened:_,onPage:A,netLog:E}},y=async P=>{let w=f.get(P);if(w)return w;let E=p.get(P);if(!E||E.isClosed()){if(!r.openSession)throw new Error(`browser session "${P}" cannot be opened in this replay`);E=await r.openSession(P),p.set(P,E)}let _=g(E);return f.set(P,_),_},h=await y(we(t.steps[0]?.session)),S=!1,v=()=>(S=r.keepResponseLog===!0,S?{responses:h.netLog}:{}),x=()=>{for(let[P,w]of f)w.active.isClosed()||p.set(P,w.active);return{activePage:h.active.isClosed()?void 0:h.active,sessions:p}},b=P=>new Promise(w=>{let E=h.context,_=()=>{clearTimeout(A),E.off("page",_),w()},A=setTimeout(_,P);E.on("page",_)}),m=[],T=!n.steps.some(P=>P.actions.some(w=>w.opensTab))&&n.steps.some(P=>P.actions.some(w=>w.action==="switchTab"||w.action==="closeTab"||w.action==="newTab")),R=()=>{let P=h.context.pages();for(let w of P)h.seen.has(w)||(h.seen.add(w),w.isClosed()||(h.active=w));if(h.active.isClosed()){let w=P.filter(E=>!E.isClosed());w.length>0&&(h.active=w[w.length-1])}},k=()=>{for(let P of f.values())P.context.off("page",P.onPage),S&&P===h||P.netLog.detach()};if(!Wn(t,n))return k(),{status:"stale",stepResults:i,captured:d()};let C=P=>{for(let w=P+1;w<n.steps.length;w++)i.push({gherkin:n.steps[w].gherkin,kind:n.steps[w].kind,status:"skipped"})};try{for(let P=0;P<n.steps.length;P++){let w=n.steps[P],E=Ms(t,P),_=!1,A=0,O=[],j=[];try{h=await y(we(t.steps[P]?.session))}catch(D){let q=`Could not open browser session "${ht(we(t.steps[P]?.session))}": ${D instanceof Error?D.message.split(`
|
|
69
|
+
`)[0]:String(D)}`;return i.push({gherkin:w.gherkin,fromStepSet:w.fromStepSet,kind:w.kind,status:"failed",error:q}),C(P),{status:"failed",failure:{stepIndex:P,actionIndex:0,stepText:w.gherkin,kind:w.kind,error:q},stepResults:i,captured:d(),tabOpeners:m,...x(),activePage:void 0}}for(let D of f.values())D.netLog.markStep();let L=(D,q)=>{let Y=h.context.pages().filter(B=>!B.isClosed()),Q=Y.filter(B=>!q.has(B)).at(-1),N=Q??h.active;if(N===D||N.isClosed())return;let M=Q?"opened":D.isClosed()?"closed":"switched";O.push({how:M,tab:Y.indexOf(N)+1,url:N.url()})},I=h.context;r.trace&&await I.tracing.group(`[saffron:${r.tracePhase??"replay"}:${P+(r.traceStepOffset??0)}] ${w.keyword} ${w.gherkin}`).catch(()=>{});let U=async()=>{r.trace&&await I.tracing.groupEnd().catch(()=>{})};try{if(w.kind==="assertion"&&!w.actions.some(D=>$e.has(D.action))){let D=`Assertion step "${w.gherkin}" recorded ${w.actions.length===0?"nothing":"only setup actions"}, so nothing was checked. Re-record the scenario (saffron run --rerecord) so the agent records what must be true.`;return i.push({gherkin:w.gherkin,fromStepSet:w.fromStepSet,kind:w.kind,status:"failed",drift:_,error:D}),C(P),{status:"failed",failure:{stepIndex:P,actionIndex:0,stepText:w.gherkin,kind:w.kind,error:D},stepResults:i,captured:d(),tabOpeners:m,...x(),...v()}}for(let D=0;D<w.actions.length;D++){let q=w.actions[D];R();let Y=h.active,Q=new Set(h.context.pages());h.netLog.lastMatch=void 0,q.pageFingerprint&&await Jo(h.active)!==q.pageFingerprint&&(_=!0);let N,M=!1;for(let B=0;B<=o&&!M;B++){B>0&&(A++,await $c(250*B),R());try{let J=B>0?`${ft(q)} (attempt ${B+1})`:ft(q),ne=await Ff(h.active,r.trace,`[saffron:action:${D}] ${J}`,()=>Ns(h.active,q,E,s,r.baseURL,l,h.netLog,a,c,r.downloadsDir));ne&&(h.active=ne,h.seen.add(ne));let Me=q.action==="click"||q.action==="press";if(h.opened.length===0&&q.opensTab?await h.context.waitForEvent("page",{timeout:s}).catch(()=>{}):h.opened.length===0&&Me&&T&&await b(150),q.opensTab&&h.opened.length===0)throw new Error("this action opened a new tab when it was recorded, and none opened now; the flow has changed");h.opened.length>0&&m.push({stepIndex:P,actionIndex:D});let et=q.action==="click"&&((q.modifiers?.length??0)>0||q.button==="middle");for(;h.opened.length>0;){let Ie=h.opened.shift();et&&h.seen.add(Ie),await Ie.waitForLoadState("domcontentloaded",{timeout:s}).catch(()=>{})}M=!0,L(Y,Q);let De=h.netLog.lastMatch;De&&(q.action==="waitForResponse"||q.action==="expectResponse")&&j.push({action:q.action,method:De.method,url:De.url,status:De.status})}catch(J){N=J}}if(!M){let B=N instanceof Error?N.message:String(N);i.push({gherkin:w.gherkin,fromStepSet:w.fromStepSet,kind:w.kind,status:"failed",drift:_,...A?{retries:A}:{},...O.length?{tabs:O}:{},...j.length?{responses:j}:{},failedActionIndex:D,error:B}),C(P);let J={stepIndex:P,actionIndex:D,stepText:w.gherkin,kind:w.kind,error:B,pageUrl:h.active.isClosed()?void 0:h.active.url()};return await r.onFailure?.(h.active,J).catch(()=>{}),{status:"failed",failure:J,stepResults:i,captured:d(),tabOpeners:m,...x(),...v()}}}i.push({gherkin:w.gherkin,fromStepSet:w.fromStepSet,kind:w.kind,status:"passed",drift:_,...A?{retries:A}:{},...O.length?{tabs:O}:{},...j.length?{responses:j}:{}})}finally{await U()}}return{status:"passed",stepResults:i,captured:d(),tabOpeners:m,...x()}}finally{if(k(),!r.vars){for(let P of Ps.get(l)?.values()??[])await P.tracked.element.dispose().catch(()=>{});Ps.delete(l)}}}import{createHash as pb}from"node:crypto";import gb from"node:path";var Ic=e=>pb("sha1").update(JSON.stringify(e)).digest("hex").slice(0,16);function op(e){return{steps:e.steps.map(t=>({...t,actions:t.actions.map(({pageFingerprint:n,...r})=>r)})),data:e.data??null,...e.examples?{examples:e.examples}:{},...e.rowBound?{rowBound:e.rowBound}:{},...e.rowsUseNewDates?{rowsUseNewDates:!0}:{}}}var ip=e=>Ic(e.map(t=>[t.kind,t.text,t.table??null,t.docString??null])),Ds=e=>e?Ic(op(e)):"none",ap=(e,t)=>Ic({contract:op(e),featureEdits:t??null});function cp(e,t,n,r){return{scenario:ip(e.steps),committed:Ds(t),recording:ap(n,r)}}function At(e,t,n){let r=t.meta.bound;if(!r)return;let s=[],{feature:o,scenario:a}=t.cache,i;if(n&&!(n instanceof Map))i=n;else try{i=nt(gb.join(e,o),e,n).find(l=>l.name===a)}catch(l){s.push(`${o} no longer parses: ${l instanceof Error?l.message.split(`
|
|
70
|
+
`)[0]:String(l)}`)}s.length||(i?ip(i.steps)!==r.scenario&&s.push(hb(i,t.cache)):s.push(`scenario "${a}" is no longer in ${o}`));let c;try{c=Ye(pe(e,o,a))}catch(l){if(!(l instanceof ke))throw l;return s.push(`the committed recording cannot be read (${l.problem})`),s.join("; ")}return Ds(c)!==r.committed&&s.push(r.committed==="none"?"a recording was committed for this scenario after the proposal was filed, so the diff you would review is not the one that was made":c?"the committed recording changed after the proposal was filed (an accepted heal, a propagated locator fix or a pull), so the diff you would review is not the one that was made":"the committed recording the proposal was diffed against is gone"),ap(t.cache,t.meta.featureEdits)!==r.recording&&s.push("the proposal's recording or feature edits were edited after it was filed"),s.length>0?s.join("; "):void 0}function hb(e,t){let n=e.steps,r=t.steps;if(n.length!==r.length)return`the scenario has ${n.length} steps now and had ${r.length} when the proposal was filed`;let s=n.findIndex((o,a)=>o.text!==r[a].gherkin||o.kind!==r[a].kind);return s<0?"the scenario's steps changed since the proposal was filed":`step ${s+1} now reads "${n[s].text}" and was "${r[s].gherkin}" when the proposal was filed`}var ui="not bound: filed by a runner older than 0.8.5, so changes since cannot be detected";import fr from"node:fs";import fp from"node:path";function fi(e){return`$${e.toFixed(e>=1?2:4)}`}function jc(e,t){let n=e===void 0?"?":`${Math.round(e)}%`,r=t===void 0?"?":`${Math.round(t)}%`;return`${n} \u2192 ${r}`}function Et(e){return e.costUsd>0||e.aiCalls===0}function Nc(e){return Et(e)?e.plan?` \xB7 5-hour window ${jc(e.plan.fiveHourBefore,e.plan.fiveHourAfter)} (${e.plan.subscriptionType} plan) \xB7 \u2248 ${fi(e.costUsd)} at API rates`:` \xB7 ${fi(e.costUsd)}`:" \xB7 cost not reported by the provider"}function lp(e,t){return e?t?`\u2248 ${fi(e)}`:fi(e):""}function dp(e){if(!e)return"";let t=new Date(e);return Number.isNaN(t.getTime())?"":`resets ${t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`}function Mc(e){let t=e.costUsd===void 0?"":` \xB7 cost ${e.costUsd>=0?"+":"-"}$${Math.abs(e.costUsd).toFixed(4)}`;return`vs previous run: pass rate ${e.passRatePp>=0?"+":""}${e.passRatePp}pp${t} \xB7 AI calls ${e.aiCalls>=0?"+":""}${e.aiCalls}`}function up(e,t){return`${e} pending review${t>0?` (${t} whose proof replay failed)`:""}`}var lr=e=>e.status==="yellow"&&e.verified===!1,Dc=(e,t)=>e.green+e.yellow-t.filter(lr).length;function dr(e,t){let n=e.green+e.yellow+e.red;return n===0?0:Math.round(Dc(e,t)/n*100)}function ur(e,t){if(e.name)return e.name;let n=e.scenario.replace(/ \(example \d+\)$/,"");return t&&(t(e.scenario)||!t(n))?e.scenario:n}function pi(e,t=e.provider){if(!e.provider)return"no agent (--no-agent)";let n=(r,s,o)=>r&&`${o} ${r.name} (${r.source==="flag"?s:"saffron.config.json"})`;return[`${t} agent${e.sdk?` on ${e.sdk.name} ${e.sdk.version}`:""}`,n(e.model,"--model","model")??`${t}'s default model`,n(e.healModel,"--heal-model","heal model")].filter(Boolean).join(" \xB7 ")}function pp(e,t){return e.feature===t.feature&&e.scenario===t.scenario&&(e.browser===void 0||t.browser===void 0||e.browser===t.browser)}function Lc(e){let t=r=>`${r.feature}\0${r.scenario}`,n=new Map;for(let r of e)r.browser&&n.set(t(r),(n.get(t(r))??new Set).add(r.browser));return r=>{let s=[...n.get(t(r))??[]];return s.length<2?[{key:t(r)}]:(r.browser?[r.browser]:s).map(o=>({key:`${t(r)}\0${o}`,browser:o}))}}function Bc(e){return fp.join(e,".saffron","history.jsonl")}function Uc(e,t,n,r){let s=e.map(o=>({feature:o.scenario.featurePath,scenario:o.scenario.displayName,name:o.scenario.name,tags:[...o.scenario.tags],status:o.status,source:o.source,durationMs:o.durationMs,verified:o.verified,seededSteps:o.seededSteps,adaptations:o.adaptations.length,driftSteps:o.stepResults.filter(a=>a.drift).length,aiCalls:o.usage.aiCalls,tokensInOut:o.usage.inputTokens+o.usage.outputTokens,cacheRead:o.usage.cacheReadTokens,cacheWrite:o.usage.cacheCreationTokens,costUsd:o.usage.costUsd??0,error:o.error?.split(`
|
|
71
|
+
`)[0],browser:o.browser}));return{runId:t.toISOString(),startedAt:t.toISOString(),finishedAt:new Date().toISOString(),baseURL:r,green:s.filter(o=>o.status==="green").length,yellow:s.filter(o=>o.status==="yellow").length,red:s.filter(o=>o.status==="red").length,aiCalls:s.reduce((o,a)=>o+a.aiCalls,0),costUsd:s.reduce((o,a)=>o+a.costUsd,0),divergentSteps:n,scenarios:s}}function zc(e,t){let n=Bc(e);fr.mkdirSync(fp.dirname(n),{recursive:!0}),fr.appendFileSync(n,`${JSON.stringify(t)}
|
|
72
|
+
`)}function gp(e,t){let n=Bc(e);if(!fr.existsSync(n))return zc(e,t);let r=fr.readFileSync(n,"utf8").split(`
|
|
73
|
+
`).filter(a=>a.trim()),s=!1,o=r.map(a=>{try{if(JSON.parse(a).runId===t.runId)return s=!0,JSON.stringify(t)}catch{}return a});s||o.push(JSON.stringify(t)),fr.writeFileSync(n,`${o.join(`
|
|
57
74
|
`)}
|
|
58
|
-
`)}function
|
|
59
|
-
`).filter(Boolean),s=[],o=0;for(let a=r.length-1;a>=0&&o<t;a--)try{let i=JSON.parse(r[a]);s.push(i),i.partial||o++}catch{}return s.reverse()}var
|
|
60
|
-
<path d="${
|
|
61
|
-
<path d="${
|
|
62
|
-
</svg>`}function
|
|
75
|
+
`)}function Fs(e,t=50){let n=Bc(e);if(!fr.existsSync(n))return[];let r=fr.readFileSync(n,"utf8").trim().split(`
|
|
76
|
+
`).filter(Boolean),s=[],o=0;for(let a=r.length-1;a>=0&&o<t;a--)try{let i=JSON.parse(r[a]);s.push(i),i.partial||o++}catch{}return s.reverse()}var Fc=e=>dr(e,e.scenarios);function qc(e,t){let n=e.filter(f=>!f.partial),r=[...n,t],s=r.slice(-20),o=r.slice(-10),a=n.at(-1),i=a?{passRatePp:Fc(t)-Fc(a),costUsd:Et(t)&&Et(a)?t.costUsd-a.costUsd:void 0,aiCalls:t.aiCalls-a.aiCalls,red:t.red-a.red}:void 0,c=new Map,l=Lc(o.flatMap(f=>f.scenarios));for(let f of o)for(let g of f.scenarios)for(let{key:y,browser:h}of l(g)){let S=c.get(y)??{feature:g.feature,scenario:h?`${g.scenario} [${h}]`:g.scenario,heals:0,reds:0,runs:0};S.runs++,g.source==="agent-heal"&&g.status==="yellow"&&S.heals++,g.status==="red"&&S.reds++,c.set(y,S)}let d=[...c.values()].filter(f=>f.heals>=2||f.reds>=3).sort((f,g)=>g.heals+g.reds-(f.heals+f.reds)),u=new Map;for(let f of s)for(let g of f.scenarios)g.status==="red"&&g.error&&u.set(g.error,(u.get(g.error)??0)+1);let p=[...u.entries()].sort((f,g)=>g[1]-f[1]).slice(0,3).map(([f,g])=>({message:f,count:g}));return{prev:i,series:{passRate:s.map(Fc),costUsd:s.map(f=>Et(f)?Number(f.costUsd.toFixed(4)):null),aiCalls:s.map(f=>f.aiCalls)},chronic:d,divergentSteps:t.divergentSteps,topIssues:p}}var hp=20,mb=10,wb=e=>e.scenarios.filter(lr).length,wp=e=>e.replace(/\\/g,"/"),Yr=(e,t)=>`${wp(e)}\0${t}`,yb=(e,t)=>t===0?0:Math.round(e/t*100),mp=e=>Math.max(0,Date.parse(e.finishedAt)-Date.parse(e.startedAt))||0;function yp(e,t){let n=new Map;for(let A of e)for(let O of A.scenarios)n.set(Yr(A.path,O.name),{feature:A.path,scenario:O.name,tags:O.tags});let r=A=>ur(A,O=>n.has(Yr(A.feature,O))),s=A=>n.has(Yr(A.feature,r(A))),o=e.flatMap(A=>A.scenarios),a=t.filter(A=>!A.partial),i=A=>a.at(-A)?.startedAt??"",c=a.slice(-hp),l=a.at(-1),d=new Set((l?.scenarios??[]).flatMap(A=>A.browser?[A.browser]:[])),u=A=>A===""||d.size===0||d.has(A),p=new Map,f=t.filter(A=>A.startedAt>=i(hp)),g=Lc(f.flatMap(A=>A.scenarios));for(let A of f)for(let O of A.scenarios){if(!s(O))continue;let j=r(O);for(let{key:L,browser:I}of g(O)){let U=p.get(L)??{ref:{feature:wp(O.feature),scenario:O.scenario,...j!==O.scenario?{name:j}:{},...I?{browser:I}:{}},results:[]};U.results.push({at:A.startedAt,s:O,target:A.baseURL??""}),p.set(L,U)}}let y=[],h=[],S=[];for(let{ref:A,results:O}of p.values()){if(A.browser&&!u(A.browser))continue;let j=new Map,L=0,I=0,U=0;for(let q of O){if(q.s.source==="agent-record")continue;let Y=q.s.status==="red";U++,Y&&I++;let Q=j.get(q.target);Q!==void 0&&Q!==Y&&L++,j.set(q.target,Y)}L>=2&&y.push({...A,runs:U,reds:I,flips:L,last:O.at(-1).s.status});let D=O.filter(q=>q.s.source==="agent-heal"&&q.s.status==="yellow");D.length>=2&&h.push({...A,runs:O.length,heals:D.length,unverified:D.filter(q=>lr(q.s)).length}),S.push({...A,avgMs:Math.round(O.reduce((q,Y)=>q+Y.s.durationMs,0)/O.length),lastMs:O.at(-1).s.durationMs,runs:O.length})}y.sort((A,O)=>O.flips-A.flips||O.reds-A.reds),h.sort((A,O)=>O.heals-A.heals),S.sort((A,O)=>O.avgMs-A.avgMs);let v=[],x=new Set(t.filter(A=>A.startedAt>=i(mb)).map(A=>A.startedAt));for(let{ref:A,results:O}of p.values()){if(A.browser&&!u(A.browser))continue;let j=O.findLast(U=>U.s.status==="red");if(!j||!x.has(j.at))continue;let L=O.at(-1).s.status==="red",I=0;for(let U=O.length-1;U>=0&&O[U].s.status==="red";U--)I++;v.push({...A,at:j.at,error:j.s.error,stillFailing:L,streak:I})}v.sort((A,O)=>Number(O.stillFailing)-Number(A.stillFailing)||O.at.localeCompare(A.at));let b={green:0,yellow:1,unverified:2,red:3},m=new Map;for(let A of t)for(let O of A.scenarios){let j=Yr(O.feature,r(O)),L=m.get(j)??new Map,I=L.get(O.scenario)??new Map;O.browser?I.delete(""):I.clear(),I.set(O.browser??"",lr(O)?"unverified":O.status),L.set(O.scenario,I),m.set(j,L)}let $=new Map;for(let A of e)for(let O of A.scenarios){let j=Array.from({length:O.rows},(L,I)=>`${O.name} (example ${I+1})`);$.set(Yr(A.path,O.name),new Set(O.outline===!0?j:O.outline===!1?[O.name]:[O.name,...j]))}let T=new Map;for(let[A,O]of m){let j=$.get(A),L=[...O].filter(([I])=>!j||j.has(I)).flatMap(([,I])=>{let U=[...I],D=U.filter(([q])=>u(q));return(D.length>0?D:U).map(([,q])=>q)});L.length>0&&T.set(A,L.reduce((I,U)=>b[U]>b[I]?U:I))}let R=new Set(T.keys()),k=new Set((l?.scenarios??[]).map(A=>Yr(A.feature,r(A)))),C=[],P=[];for(let[A,O]of n){let j={feature:O.feature,scenario:O.scenario};R.has(A)?l&&!k.has(A)&&P.push(j):C.push(j)}let w=l?(()=>{let A=l.scenarios.length,O=wb(l);return{startedAt:l.startedAt,durationMs:mp(l),ran:A,green:l.green,yellow:l.yellow,red:l.red,unverified:O,passRate:dr(l,l.scenarios),replayRate:yb(l.scenarios.filter(j=>j.source==="cache"&&j.status==="green").length,A)}})():void 0,E={green:0,yellow:0,unverified:0,red:0,neverRun:0},_=new Map;for(let[A,O]of n){let j=T.get(A)??"neverRun";E[j]++;for(let L of O.tags){let I=_.get(L)??{tag:L,scenarios:0,green:0,yellow:0,unverified:0,red:0,neverRun:0};I.scenarios++,I[j]++,_.set(L,I)}}return{historyRuns:t.length,suite:{features:e.length,scenarios:o.length,tests:o.reduce((A,O)=>A+O.rows,0),recorded:o.filter(A=>A.cacheState===void 0?A.cached:A.cacheState==="valid").length,...E},lastRun:w,trend:c.map(A=>({startedAt:A.startedAt,passRate:dr(A,A.scenarios),durationMs:mp(A),red:A.red,tests:A.green+A.yellow+A.red})),flaky:y,healing:h,recentFailures:v,notInLastRun:P,neverRun:C,slowest:S.slice(0,10),tags:[..._.values()].sort((A,O)=>O.red-A.red||O.scenarios-A.scenarios||A.tag.localeCompare(O.tag))}}import{execFileSync as Bb}from"node:child_process";import{createHash as Ub,randomBytes as nl}from"node:crypto";import se from"node:fs";import ye from"node:path";import zb from"node:zlib";var z=e=>String(e).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',"""),xp="M11 14 L10 4.5 L17.5 9.5 L24 2.5 L30.5 9.5 L38 4.5 L37 14 Z",bb="M24.085 45.646L24.085 45.646Q20.719 45.646 18.407 44.575Q16.095 43.504 14.905 41.651Q13.715 39.798 13.715 37.384L13.715 37.384L19.121 37.384Q19.121 38.336 19.648 39.152Q20.175 39.968 21.263 40.461Q22.351 40.954 24.085 40.954L24.085 40.954Q25.649 40.954 26.703 40.546Q27.757 40.138 28.301 39.407Q28.845 38.676 28.845 37.724L28.845 37.724Q28.845 36.534 27.825 35.837Q26.805 35.140 24.527 34.936L24.527 34.936L22.657 34.766Q18.951 34.460 16.741 32.454Q14.531 30.448 14.531 27.150L14.531 27.150Q14.531 24.770 15.670 23.036Q16.809 21.302 18.849 20.367Q20.889 19.432 23.677 19.432L23.677 19.432Q26.601 19.432 28.692 20.435Q30.783 21.438 31.905 23.257Q33.027 25.076 33.027 27.524L33.027 27.524L27.587 27.524Q27.587 26.606 27.145 25.841Q26.703 25.076 25.836 24.600Q24.969 24.124 23.677 24.124L23.677 24.124Q22.453 24.124 21.620 24.532Q20.787 24.940 20.379 25.637Q19.971 26.334 19.971 27.150L19.971 27.150Q19.971 28.204 20.719 28.986Q21.467 29.768 23.167 29.904L23.167 29.904L25.071 30.074Q27.791 30.312 29.865 31.247Q31.939 32.182 33.112 33.797Q34.285 35.412 34.285 37.724L34.285 37.724Q34.285 40.104 33.044 41.889Q31.803 43.674 29.525 44.660Q27.247 45.646 24.085 45.646Z";function pr(e){return`<svg viewBox="0 0 48 48" width="${e}" height="${e}" aria-hidden="true">
|
|
77
|
+
<path d="${xp}" fill="#F4A300"/>
|
|
78
|
+
<path d="${bb}" fill="#E7E9EC"/>
|
|
79
|
+
</svg>`}function Bs(e){return`<svg viewBox="8 1 32 15" height="${e}" aria-hidden="true"><path d="${xp}" fill="#F4A300"/></svg>`}function xb(e){let t=e.imported;if(!t)return"";let n=t.shards?` \xB7 shard${t.shards.imported.length===1?"":"s"} ${t.shards.imported.join(", ")} of ${t.shards.total}`:"",r=t.headCommit??t.commit,s=`imported from ${t.run?`run ${t.run}`:"another machine"}${t.branch?` \xB7 ${t.branch}`:""}${r?` @ ${r.slice(0,7)}`:""}${n}`;return t.url&&/^https?:\/\//i.test(t.url)?`<a class="chip" href="${z(t.url)}" target="_blank" rel="noopener noreferrer">${z(s)}</a>`:`<span class="chip">${z(s)}</span>`}var Us=`<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
63
80
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
64
|
-
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,500;12..96,600;12..96,700&family=Geist:wght@400;500;600&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">`,
|
|
81
|
+
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,500;12..96,600;12..96,700&family=Geist:wght@400;500;600&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">`,zs=` :root {
|
|
65
82
|
--bg: #131416;
|
|
66
83
|
--card: #1A1B1E;
|
|
67
84
|
--card-2: #16171A;
|
|
@@ -171,184 +188,167 @@ ${_}
|
|
|
171
188
|
code { font-family: var(--mono); font-size: 11px; background: var(--bg); border: 1px solid var(--border-2); padding: 1px 6px; border-radius: 4px; color: var(--text-dim); }
|
|
172
189
|
|
|
173
190
|
footer { margin-top: 42px; display: flex; align-items: center; justify-content: center; gap: 8px; color: var(--faint); font-family: var(--mono); font-size: 10.5px; letter-spacing: .08em; }
|
|
174
|
-
`,
|
|
191
|
+
`,vb={green:"passed",yellow:"pending review",red:"failed"};function Sb(e){return e.hooks?.length?`<div class="panel"><div class="panel-title">setup and teardown</div>${e.hooks.map(n=>{let r=n.exitCode===0,s=r?"ok":n.timedOut?"timed out":n.exitCode===null?"could not start":`exit ${n.exitCode}`;return`<div class="mono">${r?"\u2713":"\u2717"} ${z(String(n.phase))} \xB7 ${z(n.command)} \xB7 ${z(s)} \xB7 ${z(st(n.durationMs))}</div>`}).join("")}</div>`:""}function Hc(e,t=5){return[...e.scenarios].sort((n,r)=>Number(r.durationMs)-Number(n.durationMs)).slice(0,t)}function Jc(e,t=0){let n=Number(e.spanMs??t);return n>0?`${Math.min(100,Math.round(Number(e.busyMs)/n*100))}%`:"\u2013"}function $b(e){let t=e.timing?.workers??[],n=Number(e.timing?.wallMs??0),r=t.length>1&&n>0?t.map(o=>`<div class="mono">worker ${z(o.worker)} \xB7 ${Number(o.runs)} run${Number(o.runs)===1?"":"s"} \xB7 ${z(st(Number(o.busyMs)))} busy \xB7 ${z(Jc(o,n))}</div>`).join(""):"",s=e.scenarios.length>1?Hc(e).map(o=>`<div class="mono">${z(st(Number(o.durationMs)))} \xB7 ${z(o.feature)} \u203A ${z(o.scenario)}${e.browsers&&o.browser?` \xB7 ${z(o.browser)}`:""}${o.worker&&t.length>1?` \xB7 worker ${z(o.worker)}`:""}</div>`).join(""):"";return!r&&!s?"":`<div class="panel"><div class="panel-title">timing${n>0?` \xB7 ${z(st(n))} from the first scenario to the last`:""}</div>${r}${r&&s?'<div class="panel-hint">slowest scenarios</div>':""}${s}</div>`}function st(e){return e>=1e3?`${(e/1e3).toFixed(1)}s`:`${e}ms`}function Ls(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${(e/1e3).toFixed(1)}k`:Number(e).toLocaleString()}function Ae(e,t,n,r="",s="",o=""){return`<div class="kpi">
|
|
175
192
|
<div class="kpi-label">${e}</div>
|
|
176
193
|
<div class="kpi-value ${r}">${t}</div>
|
|
177
194
|
<div class="kpi-sub ${s}">${n}</div>${o}
|
|
178
|
-
</div>`}function
|
|
179
|
-
${
|
|
180
|
-
${
|
|
181
|
-
${
|
|
182
|
-
${
|
|
183
|
-
${
|
|
184
|
-
${
|
|
185
|
-
${n.plan?
|
|
186
|
-
</section>`}function
|
|
187
|
-
`)}</section>`:""}function
|
|
195
|
+
</div>`}function Zr(e,t){let n=e.filter(l=>l!==null);if(n.length<2)return"";let r=108,s=22,o=Math.min(...n),i=Math.max(...n)-o||1,c=e.map((l,d)=>{if(l===null)return"";let u=`${(d/(e.length-1)*r).toFixed(1)},${(s-2-(l-o)/i*(s-4)).toFixed(1)}`;return d===0||e[d-1]===null?`M${u}h0`:`L${u}`}).join("");return`<svg class="spark" viewBox="0 0 ${r} ${s}" width="${r}" height="${s}" aria-hidden="true"><path d="${c}" fill="none" stroke="${t}" stroke-width="1.8" stroke-linejoin="round" stroke-linecap="round"/></svg>`}var bp=(e,t="",n=0)=>`${e>=0?"+":"\u2212"}${Math.abs(e).toFixed(n)}${t} vs prev`;function kb(e){let t=e.filter(r=>r.status==="yellow");return t.length===0?"nothing to review":`\u25B2 ${[[t.filter(r=>r.verified===!0).length,"proof passed"],[t.filter(r=>r.verified===!1).length,"proof failed"],[t.filter(r=>r.verified===void 0).length,"not proved"]].filter(([r])=>r>0).map(([r,s])=>`${r} ${s}`).join(" \xB7 ")}`}function Rb(e,t){let n=e.totals,r=e.trends,[s,o,a,i]=[n.scenarios,n.green,n.yellow,n.red].map(Number),c=Dc({green:o,yellow:a},e.scenarios),l=s===0?0:Math.round(c/s*100),d=n.red>0?"red":n.yellow>0?"gold":"green",u=n.inputTokens+n.outputTokens,p=r?.prev?`${bp(r.prev.passRatePp,"pp")} \xB7 ${c} of ${s}`:`${c} of ${s} scenarios`,f=r?.prev?.costUsd!==void 0?`${bp(r.prev.costUsd,"",4).replace("+","+$").replace("\u2212","\u2212$")} \xB7 ${st(t)}`:`${st(t)} total runtime`;return`<section class="kpis">
|
|
196
|
+
${Ae("pass rate",`${l}<span class="unit">%</span>`,p,d,r?.prev?r.prev.passRatePp>=0?"green":"red":"",Zr(r?.series.passRate??[],"var(--green)"))}
|
|
197
|
+
${Ae("passed",String(o),"deterministic replay","green",o>0?"green":"")}
|
|
198
|
+
${Ae("pending",String(a),kb(e.scenarios),a>0?"gold":"",a>0?"gold":"")}
|
|
199
|
+
${Ae("failed",String(i),i>0?"\u25BC needs attention":"all clear",i>0?"red":"",i>0?"red":"green")}
|
|
200
|
+
${Ae("ai calls",String(Number(n.aiCalls)),`${Ls(u)} in+out tokens`,n.aiCalls>0?"":"green")}
|
|
201
|
+
${Ae("cache traffic",Ls(n.cacheReadTokens+n.cacheCreationTokens),n.cacheReadTokens+n.cacheCreationTokens>0?`${Ls(n.cacheReadTokens)} read \xB7 ${Ls(n.cacheCreationTokens)} written`:"zero (fully cached run)","",n.cacheReadTokens+n.cacheCreationTokens>0?"":"green")}
|
|
202
|
+
${n.plan?Ae("plan usage",`${jc(n.plan.fiveHourBefore,n.plan.fiveHourAfter)}`,[`5-hour window \xB7 ${z(n.plan.subscriptionType)} plan`,dp(n.plan.resetsAt)].filter(Boolean).join(" \xB7 "),"gold","")+Ae("api-equivalent",`<span class="unit">\u2248 $</span>${n.costUsd.toFixed(n.costUsd>=1?2:4)}`,`what this run costs on an API key \xB7 ${f}`,"","",Zr(r?.series.costUsd??[],"var(--gold)")):Ae("ai cost",Et(n)?`<span class="unit">$</span>${n.costUsd.toFixed(n.costUsd>=1?2:4)}`:"n/a",Et(n)?f:"not reported by the provider","","",Et(n)?Zr(r?.series.costUsd??[],"var(--gold)"):"")}
|
|
203
|
+
</section>`}function Tb(e){let t=e.trends;if(!t)return"";let n=[];return t.chronic.length>0&&n.push(`<div class="panel accent-gold"><div class="panel-title gold">chronic scenarios: stop paying for heals</div><ul>${t.chronic.map(r=>`<li>${z(r.feature)} \u203A ${z(r.scenario)}: ${Number(r.heals)} heal(s), ${Number(r.reds)} red(s) in the last ${Number(r.runs)} run(s). Re-record it or fix the feature text.</li>`).join("")}</ul></div>`),t.divergentSteps>0&&n.push(`<div class="panel"><div class="panel-title">step divergence (level-2 signal)</div><p>${Number(t.divergentSteps)} step text(s) currently have divergent recordings across caches.</p></div>`),t.topIssues.length>0&&n.push(`<div class="panel accent-red"><div class="panel-title red">recurring failure themes (last 20 runs)</div><ul>${t.topIssues.map(r=>`<li>${Number(r.count)}\xD7: ${z(r.message)}</li>`).join("")}</ul></div>`),n.length>0?`<section class="trends">${n.join(`
|
|
204
|
+
`)}</section>`:""}function Ab(e){let t=Array.isArray(e.sessions)?e.sessions:[];return`<ol class="steps">${e.steps.map((r,s)=>{let o=typeof t[s]=="string"&&(s===0||t[s]!==t[s-1])?t[s]:void 0,a=r.status==="passed"?'<span class="dot green"></span>':r.status==="failed"?'<span class="dot red"></span>':'<span class="dot idle"></span>';return`<li class="step ${z(r.status)}">
|
|
188
205
|
${a}
|
|
189
206
|
<div class="step-body">
|
|
190
|
-
<span class="step-text">${
|
|
191
|
-
${o?`<span class="tag indigo" title="the browser session this step and the ones after it run in, each a browser of its own">session: ${
|
|
207
|
+
<span class="step-text">${z(r.gherkin)}</span>
|
|
208
|
+
${o?`<span class="tag indigo" title="the browser session this step and the ones after it run in, each a browser of its own">session: ${z(o)}</span>`:""}
|
|
192
209
|
${r.kind==="assertion"?'<span class="tag">assert</span>':""}
|
|
193
|
-
${r.fromStepSet?`<span class="tag indigo" title="inlined from a StepSet definition: edit once, every invoking scenario follows">from StepSet: ${
|
|
210
|
+
${r.fromStepSet?`<span class="tag indigo" title="inlined from a StepSet definition: edit once, every invoking scenario follows">from StepSet: ${z(r.fromStepSet)}</span>`:""}
|
|
194
211
|
${r.drift?'<span class="tag gold" title="page fingerprint no longer matches the recording">drift</span>':""}
|
|
195
212
|
${r.retries?`<span class="tag gold" title="an action failed and was re-attempted with backoff before the step settled">retried \xD7${Number(r.retries)}</span>`:""}
|
|
196
|
-
${r.error?`<div class="step-error">${
|
|
213
|
+
${r.error?`<div class="step-error">${z(r.error)}</div>`:""}
|
|
197
214
|
</div>
|
|
198
215
|
</li>`}).join(`
|
|
199
|
-
`)}</ol>`}function
|
|
216
|
+
`)}</ol>`}function Eb(e){return e.featureEdits&&e.featureEdits.length>0?`<div class="panel">
|
|
200
217
|
<div class="panel-title gold">suggested .feature edit</div>
|
|
201
|
-
<div class="diff">${e.featureEdits.map(n=>{let r=e.steps[n.index]?.gherkin??`step ${n.index}`;return`<div class="diff-line del">\u2212 ${
|
|
218
|
+
<div class="diff">${e.featureEdits.map(n=>{let r=e.steps[n.index]?.gherkin??`step ${n.index}`;return`<div class="diff-line del">\u2212 ${z(r)}</div><div class="diff-line add">+ ${z(n.text)}</div>`}).join("")}</div>
|
|
202
219
|
<div class="panel-hint">apply with <code>saffron accept --with-feature-edit</code></div>
|
|
203
|
-
</div>`:e.suggestedFeatureEdit?`<div class="panel"><div class="panel-title gold">suggested .feature edit</div><pre>${
|
|
220
|
+
</div>`:e.suggestedFeatureEdit?`<div class="panel"><div class="panel-title gold">suggested .feature edit</div><pre>${z(e.suggestedFeatureEdit)}</pre></div>`:""}function Ob(e){let t=e.proposalDiff;if(!t)return"";let n=t.steps.filter(l=>l.change!=="same"||!t.hasCommitted).map(l=>{let d=`<div class="diff-step">${l.kind==="assertion"?'<span class="pill gold">assertion</span> ':""}${z(l.gherkin)}${l.fromStepSet?` <span class="mono">(step set "${z(l.fromStepSet)}")</span>`:""}</div>`,u=l.actions.flatMap(p=>p.change==="same"?[`<div class="diff-line"> ${z(p.before??"")}</div>`]:p.change==="added"?[`<div class="diff-line add">+ ${z(p.after??"")}</div>`]:p.change==="removed"?[`<div class="diff-line del">\u2212 ${z(p.before??"")}</div>`]:[`<div class="diff-line del">\u2212 ${z(p.before??"")}</div>`,`<div class="diff-line add">+ ${z(p.after??"")}</div>`,...(p.details??[]).map(f=>`<div class="diff-line detail">${z(f)}</div>`)]).join("");return`${d}<div class="diff">${u}</div>`}).join(""),{added:r,removed:s,changed:o,assertions:a}=t.summary,i=t.recording?.length?`<div class="diff">${t.recording.map(l=>`<div class="diff-line del">! ${z(l)}</div>`).join("")}</div>`:"",c=r+s+o===0?t.recording?.length?"No action changed, but the recording did: read the lines above first.":"No action changed.":`${o} changed, ${r} added, ${s} removed.${a>0?` ${a} touch the scenario's verdict.`:""}`;return`<div class="panel accent-gold"><div class="panel-title gold">what this proposal changes</div>${t.hasCommitted?"":'<p class="panel-hint">First recording: there is nothing to compare against.</p>'}${n}${i}<div class="panel-hint">${z(c)}</div></div>`}function _b(e,t){let n=e.usage.inputTokens+e.usage.outputTokens;if(e.usage.aiCalls===0)return'<span class="pill green">0 tokens</span>';let r=lp(e.usage.costUsd,t),s=r?` \xB7 ${r}`:"";return`<span class="pill gold">${Number(e.usage.aiCalls)} ai \xB7 ${Ls(n)} tok${s}</span>`}function Cb(e,t,n,r=!1,s){let o=e.ranAt!==void 0&&s!==void 0&&Date.parse(e.ranAt)<Date.parse(s);return`<details class="card" ${e.status!=="green"?"open":""}>
|
|
204
221
|
<summary>
|
|
205
|
-
<span class="pill ${e.status==="green"?"green":e.status==="yellow"?"gold":"red"}">${
|
|
206
|
-
<span class="card-title">${
|
|
222
|
+
<span class="pill ${e.status==="green"?"green":e.status==="yellow"?"gold":"red"}">${vb[e.status]}</span>
|
|
223
|
+
<span class="card-title">${z(e.scenario)}</span>
|
|
207
224
|
<span class="card-meta">
|
|
208
|
-
<span class="m">${
|
|
225
|
+
<span class="m">${z(e.feature)}</span>
|
|
209
226
|
<span class="m-sep">\xB7</span>
|
|
210
|
-
<span class="m">${
|
|
227
|
+
<span class="m">${z(e.source)}</span>
|
|
211
228
|
<span class="m-sep">\xB7</span>
|
|
212
|
-
<span class="m">${
|
|
213
|
-
${r&&e.browser?`<span class="m-sep">\xB7</span><span class="chip">${
|
|
214
|
-
${o?`<span class="m-sep">\xB7</span><span class="chip" title="Kept from an earlier run: this run did not run this scenario">from the run of ${
|
|
215
|
-
${
|
|
229
|
+
<span class="m">${st(Number(e.durationMs))}</span>
|
|
230
|
+
${r&&e.browser?`<span class="m-sep">\xB7</span><span class="chip">${z(e.browser)}</span>`:""}
|
|
231
|
+
${o?`<span class="m-sep">\xB7</span><span class="chip" title="Kept from an earlier run: this run did not run this scenario">from the run of ${z(new Date(e.ranAt).toISOString().replace("T"," ").slice(0,16))} UTC</span>`:""}
|
|
232
|
+
${_b(e,t)}
|
|
216
233
|
</span>
|
|
217
234
|
</summary>
|
|
218
235
|
<div class="card-body">
|
|
219
|
-
${
|
|
220
|
-
${e.narrative?`<div class="panel"><div class="panel-title">agent narrative</div><p>${
|
|
221
|
-
${e.adaptations.length>0?`<div class="panel accent-gold"><div class="panel-title gold">adaptations</div><ul>${e.adaptations.map(a=>`<li>${
|
|
222
|
-
${
|
|
223
|
-
${
|
|
224
|
-
${e.proposalFile?`<div class="panel"><div class="panel-title">cache proposal pending${e.verified===!0?' <span class="pill green">verified</span>':e.verified===!1?' <span class="pill red">unverified</span>':""}</div><p class="mono">${
|
|
236
|
+
${Ab(e)}
|
|
237
|
+
${e.narrative?`<div class="panel"><div class="panel-title">agent narrative</div><p>${z(e.narrative)}</p></div>`:""}
|
|
238
|
+
${e.adaptations.length>0?`<div class="panel accent-gold"><div class="panel-title gold">adaptations</div><ul>${e.adaptations.map(a=>`<li>${z(a)}</li>`).join("")}</ul></div>`:""}
|
|
239
|
+
${Eb(e)}
|
|
240
|
+
${Ob(e)}
|
|
241
|
+
${e.proposalFile?`<div class="panel"><div class="panel-title">cache proposal pending${e.verified===!0?' <span class="pill green">verified</span>':e.verified===!1?' <span class="pill red">unverified</span>':""}</div><p class="mono">${z(e.proposalFile)}</p>${e.verified===!1&&e.proofError?`<p class="mono" style="color:var(--red)">proof replay failed: ${z(e.proofError.split(`
|
|
225
242
|
`)[0])}</p>`:""}<div class="panel-hint">review with <code>saffron accept</code> / <code>saffron reject</code></div></div>`:""}
|
|
226
|
-
${e.error&&e.status==="red"?`<div class="panel accent-red"><div class="panel-title red">failure</div><p>${
|
|
227
|
-
${e.uniques&&e.status!=="green"?`<div class="panel"><div class="panel-title">unique values in this run</div>${Object.entries(e.uniques).map(([a,i])=>`<div class="mono">${
|
|
228
|
-
${e.proofUniques&&e.status!=="green"?`<div class="panel"><div class="panel-title">unique values in the proof replay</div>${Object.entries(e.proofUniques).map(([a,i])=>`<div class="mono">${
|
|
229
|
-
${
|
|
243
|
+
${e.error&&e.status==="red"?`<div class="panel accent-red"><div class="panel-title red">failure</div><p>${z(e.error)}</p></div>`:""}
|
|
244
|
+
${e.uniques&&e.status!=="green"?`<div class="panel"><div class="panel-title">unique values in this run</div>${Object.entries(e.uniques).map(([a,i])=>`<div class="mono">${z(a)} = ${z(i)}</div>`).join("")}</div>`:""}
|
|
245
|
+
${e.proofUniques&&e.status!=="green"?`<div class="panel"><div class="panel-title">unique values in the proof replay</div>${Object.entries(e.proofUniques).map(([a,i])=>`<div class="mono">${z(a)} = ${z(i)}</div>`).join("")}</div>`:""}
|
|
246
|
+
${Pb(e,n,r)}
|
|
230
247
|
</div>
|
|
231
|
-
</details>`}function
|
|
248
|
+
</details>`}function Pb(e,t,n=!1){let r=(e.evidence??[]).filter(i=>i.kind==="trace"),o=r[0]?`<div class="panel accent-gold"><div class="panel-title gold">execution replay</div><div>Step through this run with the page inspectable at every action:</div><div class="mono" style="margin-top:6px">npx saffron trace ${z(Ib(`${e.feature}:${e.scenario}${n&&e.browser?`@${e.browser}`:""}`))}</div><div class="panel-hint">${r.map(i=>z(i.file)).join(" \xB7 ")}</div></div>`:"",a=(e.evidence??[]).flatMap(i=>{if(!t||i.kind!=="failure"&&i.kind!=="before-heal")return[];let c=qn(t,i);if(!c)return[];try{let l=c.toString("base64"),d=i.kind==="failure"?"the page when it failed":"the page when the cached step stopped working, before the agent took over";return[`<figure class="shot"><figcaption>${z(d)}${i.step?`: <span class="mono">${z(i.step)}</span>`:""}</figcaption><a href="data:image/jpeg;base64,${l}" target="_blank" rel="noopener"><img alt="${z(d)}" src="data:image/jpeg;base64,${l}"/></a><div class="panel-hint">${z(i.file)}</div></figure>`]}catch{return[]}});return a.length===0?o:`<div class="panel ${e.status==="red"?"accent-red":"accent-gold"}"><div class="panel-title ${e.status==="red"?"red":"gold"}">screenshot</div>${a.join("")}</div>${o}`}var Ib=e=>/[^A-Za-z0-9_./:-]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e;function Gn(e,t){let n=e.totals,r=new Date(e.startedAt),s=new Date(e.finishedAt).getTime()-r.getTime(),o=r.toLocaleString("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"});return`<!doctype html>
|
|
232
249
|
<html lang="en">
|
|
233
250
|
<head>
|
|
234
251
|
<meta charset="utf-8"/>
|
|
235
252
|
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
|
236
253
|
<title>Saffron run report</title>
|
|
237
|
-
${
|
|
254
|
+
${Us}
|
|
238
255
|
<style>
|
|
239
|
-
${
|
|
256
|
+
${zs}</style>
|
|
240
257
|
</head>
|
|
241
258
|
<body>
|
|
242
259
|
<div class="topline"></div>
|
|
243
260
|
<div class="wrap">
|
|
244
261
|
<header class="top">
|
|
245
262
|
<div class="brand">
|
|
246
|
-
${
|
|
263
|
+
${pr(38)}
|
|
247
264
|
<div>
|
|
248
265
|
<div class="brand-name">saffron</div>
|
|
249
266
|
<div class="brand-sub">test run report</div>
|
|
250
267
|
</div>
|
|
251
268
|
</div>
|
|
252
269
|
<div class="run-meta">
|
|
253
|
-
<span>${
|
|
270
|
+
<span>${z(o)}</span>
|
|
254
271
|
<span>\xB7</span>
|
|
255
|
-
<span>${
|
|
256
|
-
${e.baseURL?`<span class="chip base">${
|
|
272
|
+
<span>${st(s)}</span>
|
|
273
|
+
${e.baseURL?`<span class="chip base">${z(e.baseURL)}</span>`:""}
|
|
257
274
|
${e.shards?`<span class="chip">merged from ${Number(e.shards)} shards</span>`:""}
|
|
258
|
-
${e.browsers?.length?`<span class="chip">${e.browsers.map(a=>
|
|
259
|
-
${
|
|
260
|
-
${e.provenance?`<span class="chip">${
|
|
275
|
+
${e.browsers?.length?`<span class="chip">${e.browsers.map(a=>z(a)).join(" \xB7 ")}</span>`:""}
|
|
276
|
+
${xb(e)}
|
|
277
|
+
${e.provenance?`<span class="chip">${z(pi(e.provenance))}</span>`:""}
|
|
261
278
|
${e.interrupted?`<span class="pill red" title="Ctrl-C stopped the run: the scenarios that did not run are not counted, as failed or otherwise">interrupted \xB7 ${Number(e.notRun)} not run</span>`:""}
|
|
262
279
|
</div>
|
|
263
280
|
</header>
|
|
264
281
|
|
|
265
|
-
${
|
|
266
|
-
${
|
|
267
|
-
${
|
|
268
|
-
${
|
|
282
|
+
${Rb(e,s)}
|
|
283
|
+
${Tb(e)}
|
|
284
|
+
${Sb(e)}
|
|
285
|
+
${$b(e)}
|
|
269
286
|
|
|
270
287
|
<div class="section-head">
|
|
271
288
|
<span class="section-title">scenarios \xB7 ${Number(n.scenarios)}</span>
|
|
272
|
-
<span class="section-title">saffron v${
|
|
289
|
+
<span class="section-title">saffron v${z(e.version)}</span>
|
|
273
290
|
</div>
|
|
274
|
-
${e.scenarios.map(a=>
|
|
291
|
+
${e.scenarios.map(a=>Cb(a,!!e.totals.plan,t,!!e.browsers,e.startedAt)).join(`
|
|
275
292
|
`)}
|
|
276
293
|
|
|
277
|
-
<footer>${
|
|
294
|
+
<footer>${Bs(11)} generated by saffron v${z(e.version)} \xB7 ${z(new Date(e.finishedAt).toLocaleString("en-GB",{dateStyle:"medium",timeStyle:"medium"}))}</footer>
|
|
278
295
|
</div>
|
|
279
296
|
</body>
|
|
280
297
|
</html>
|
|
281
|
-
`}import
|
|
282
|
-
`),
|
|
283
|
-
${d.name}`;o.set(p,[...o.get(p)??[],
|
|
284
|
-
`)).digest("hex").slice(0,12);return{scenarios:c.map(d=>e[d]),info:{index:t.index,total:t.total,by:n,suite:l,suiteSize:e.length,positions:c}}}function
|
|
285
|
-
`),r}var
|
|
286
|
-
`));let
|
|
287
|
-
`)??[]).map(r=>r.split(/\s+/)[1]).filter(Boolean);return[...new Set(n.map(
|
|
298
|
+
`}import hi from"node:fs";import mi from"node:path";function wi(e){let t={scenarios:e.length,green:0,yellow:0,red:0,aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0},n=new Set;for(let r of e){for(let s of r.usage.models??[])n.add(s);t[r.status]+=1,t.aiCalls+=r.usage.aiCalls,t.inputTokens+=r.usage.inputTokens,t.outputTokens+=r.usage.outputTokens,t.cacheReadTokens+=r.usage.cacheReadTokens,t.cacheCreationTokens+=r.usage.cacheCreationTokens??0,t.costUsd+=r.usage.costUsd??0}return n.size>0&&(t.models=[...n].sort()),t}function Wc(e,t,n){return{tool:"saffron",version:ut(),startedAt:t.toISOString(),finishedAt:new Date().toISOString(),baseURL:n,totals:wi(e),scenarios:e.map(r=>({feature:r.scenario.featurePath,scenario:r.scenario.displayName,name:r.scenario.name,tags:[...r.scenario.tags],status:r.status,source:r.source,proposalReplay:r.proposalReplay,durationMs:r.durationMs,usage:r.usage,steps:r.stepResults,sessions:Dn(r.scenario.steps)?r.scenario.steps.map(s=>ht(we(s.session))):void 0,narrative:r.narrative,adaptations:r.adaptations,suggestedFeatureEdit:r.suggestedFeatureEdit,featureEdits:r.featureEdits,verified:r.verified,proofError:r.proofError,proposalFile:r.proposalFile,proposalRevision:r.proposalRevision,proposalDiff:r.proposalDiff,error:r.error,evidence:r.evidence,uniques:r.uniques,proofUniques:r.proofUniques,worker:r.worker,browser:r.browser,ranAt:t.toISOString()}))}}var Ot=e=>!!e&&typeof e=="object"&&!Array.isArray(e),gi=(e,t)=>t.find(n=>typeof e[n]!="number"),qs=e=>e===void 0||typeof e=="number",jb=["scenarios","green","yellow","red","aiCalls","inputTokens","outputTokens","cacheReadTokens","costUsd"],Nb=["aiCalls","inputTokens","outputTokens","cacheReadTokens"],Vc=e=>typeof e=="string"&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(Z|[+-]\d\d:\d\d)$/.test(e)&&!Number.isNaN(Date.parse(e));function Gc(e){if(!Ot(e)||e.tool!=="saffron")return"is not a Saffron run report";if(!Vc(e.startedAt)||!Vc(e.finishedAt))return"has no start or finish time";if(!Ot(e.totals))return"has no totals";let t=gi(e.totals,jb);if(t)return`has totals.${t} that is not a number`;if(!Array.isArray(e.scenarios))return"has no list of scenarios";for(let[i,c]of e.scenarios.entries()){let l=`scenarios[${i}]`;if(!Ot(c)||typeof c.feature!="string"||typeof c.scenario!="string")return`has ${l} without a feature and scenario name`;if(!["green","yellow","red"].includes(c.status))return`has ${l}.status ${JSON.stringify(c.status)}, which this saffron-ai does not know`;if(!Ot(c.usage)||gi(c.usage,Nb))return`has ${l}.usage without its token counts`;if(!Array.isArray(c.steps))return`has ${l}.steps that is not a list`;let d=c.steps.findIndex(p=>!Ot(p)||typeof p.gherkin!="string"||typeof p.kind!="string"||typeof p.status!="string");if(d>=0)return`has ${l}.steps[${d}] without its gherkin, kind and status`;for(let[p,f]of c.steps.entries()){if(!["passed","failed","skipped"].includes(f.status))return`has ${l}.steps[${p}].status ${JSON.stringify(f.status)}, which this saffron-ai does not know`;let g=["retries","failedActionIndex"].find(y=>!qs(f[y]));if(g)return`has ${l}.steps[${p}].${g} that is not a number`}let u=["browser","worker"].find(p=>c[p]!==void 0&&typeof c[p]!="string");if(u)return`has ${l}.${u} that is not text`;if(c.ranAt!==void 0&&!Vc(c.ranAt))return`has ${l}.ranAt that is not a time`;if(c.evidence!==void 0&&!(Array.isArray(c.evidence)&&c.evidence.every(p=>Ot(p)&&typeof p.file=="string"&&typeof p.kind=="string")))return`has ${l}.evidence that is not a list of files`}if(!qs(e.notRun)||e.interrupted!==void 0&&(e.interrupted!==!0||typeof e.notRun!="number"))return"has interrupted without a count of the scenarios that did not run";let n=e.provenance,r=i=>i===void 0||Ot(i)&&typeof i.name=="string"&&typeof i.source=="string";if(n!==void 0&&!(Ot(n)&&(n.provider===void 0||typeof n.provider=="string")&&r(n.model)&&r(n.healModel)&&(n.sdk===void 0||Ot(n.sdk)&&typeof n.sdk.name=="string"&&typeof n.sdk.version=="string")))return"has provenance whose names are not text";if(e.browsers!==void 0&&!(Array.isArray(e.browsers)&&e.browsers.every(i=>typeof i=="string")))return"has browsers that is not a list of names";let s=e.timing;if(s!==void 0&&!(Ot(s)&&typeof s.wallMs=="number"&&Array.isArray(s.workers)&&s.workers.every(i=>Ot(i)&&typeof i.worker=="string"&&!gi(i,["runs","busyMs"])&&qs(i.spanMs))))return"has timing whose workers are not a list of named counts";let o=e.trends,a=(i,c)=>Array.isArray(i)&&i.every(l=>Ot(l)&&!gi(l,c));if(o!==void 0&&!(Ot(o)&&qs(o.divergentSteps)&&a(o.chronic,["heals","reds","runs"])&&a(o.topIssues,["count"])&&(o.prev===void 0||a([o.prev],["passRatePp","aiCalls","red"])&&qs(o.prev.costUsd))))return"has trends whose counts are not numbers"}var Kc=e=>Gc(e)===void 0;function Yc(e){try{let t=JSON.parse(hi.readFileSync(mi.join(e,".saffron","reports","latest.json"),"utf8"));return Kc(t)?t:void 0}catch{return}}function Zc(e,t){if(!e||e.imported||e.interrupted||e.baseURL!==t.baseURL)return t;let n=new Set,r=e.scenarios.flatMap(y=>{let h=t.scenarios.find(S=>pp(y,S));return h?n.has(h)?[]:(n.add(h),[h]):[{...y,ranAt:y.ranAt??e.startedAt}]}),s=r.filter(y=>!n.has(y)),o=t.totals.aiCalls>0;if(o&&s.some(y=>y.usage.aiCalls>0)&&!t.totals.plan!=!e.totals.plan)return t;r.push(...t.scenarios.filter(y=>!n.has(y)));let a=[...new Set(r.flatMap(y=>y.browser?[y.browser]:[]))],{trends:i,shards:c,hooks:l,timing:d,browsers:u,provenance:p,...f}=e,g=o?t.totals.plan:e.totals.plan;return{...f,version:t.version,startedAt:t.startedAt,finishedAt:t.finishedAt,totals:{...wi(r),...g?{plan:g}:{}},scenarios:r,...t.interrupted?{interrupted:!0,notRun:t.notRun}:{},...t.provenance?{provenance:t.provenance}:{},...t.shards?{shards:t.shards}:{},...t.hooks?{hooks:t.hooks}:{},...t.timing?{timing:t.timing}:{},...a.length>1?{browsers:a}:{}}}function Hs(e,t){let n=mi.join(e,".saffron","reports");hi.mkdirSync(n,{recursive:!0});let r=mi.join(n,"latest.json"),s=mi.join(n,"latest.html"),o=Gn(t,e);return hi.writeFileSync(r,`${JSON.stringify(t,null,2)}
|
|
299
|
+
`),hi.writeFileSync(s,o),{json:r,html:s}}import Mb from"node:crypto";import Js from"node:fs";import yi from"node:path";var vp=["scenario","file"];function $p(e){let t=/^\s*(\d+)\s*\/\s*(\d+)\s*$/.exec(e),n=t?Number(t[1]):NaN,r=t?Number(t[2]):NaN;if(!t||r<1||n<1||n>r)throw new Error(`invalid --shard "${e}": use <index>/<total>, e.g. --shard 2/4 (index from 1 to total)`);return{index:n,total:r}}function kp(e){if(!vp.includes(e))throw new Error(`invalid --shard-by "${e}": use ${vp.map(t=>`"${t}"`).join(" or ")}`);return e}function Qc(e){return`shard-${e.index}-of-${e.total}`}var Db=e=>`${e.featurePath}${e.displayName}`;function Rp(e,t){let n=t.by??"scenario",r=e.map(Db),s=new Set,o=new Map;e.forEach((d,u)=>{let p=n==="file"?d.featurePath:`${d.featurePath}
|
|
300
|
+
${d.name}`;o.set(p,[...o.get(p)??[],u])});let a=new Array(t.total).fill(0),i=[...o].sort((d,u)=>u[1].length-d[1].length||(d[0]<u[0]?-1:d[0]>u[0]?1:0));for(let[,d]of i){let u=a.indexOf(Math.min(...a));if(a[u]+=d.length,u===t.index-1)for(let p of d)s.add(p)}let c=e.map((d,u)=>u).filter(d=>s.has(d)),l=Mb.createHash("sha256").update([...r].sort().join(`
|
|
301
|
+
`)).digest("hex").slice(0,12);return{scenarios:c.map(d=>e[d]),info:{index:t.index,total:t.total,by:n,suite:l,suiteSize:e.length,positions:c}}}function bi(e=process.env){return e.SAFFRON_RUN_ID||e.GITHUB_RUN_ID&&`github:${e.GITHUB_RUN_ID}`||e.CI_PIPELINE_ID&&`gitlab:${e.CI_PIPELINE_ID}`||e.BUILD_BUILDID&&`azure:${e.BUILD_BUILDID}`||e.CIRCLE_WORKFLOW_ID&&`circleci:${e.CIRCLE_WORKFLOW_ID}`||void 0}var xi=(e=process.env)=>e.GITHUB_RUN_ATTEMPT||e.SYSTEM_JOBATTEMPT||void 0;function Xc(e,t){let n=yi.join(e,".saffron","reports");Js.mkdirSync(n,{recursive:!0});let r=yi.join(n,`${Qc(t.shard)}.json`);return Js.writeFileSync(r,`${JSON.stringify(t,null,2)}
|
|
302
|
+
`),r}var Sp=e=>typeof e=="number"&&Number.isFinite(e),Qr=(e,t)=>e===void 0||t(e),gr=e=>typeof e=="string",Fb=e=>{let t=e;return!!t&&typeof t=="object"&&gr(t.feature)&&gr(t.scenario)&&Qr(t.name,gr)&&Qr(t.tags,n=>Array.isArray(n)&&n.every(gr))&&["green","yellow","red"].includes(t.status)&&gr(t.source)&&[t.durationMs,t.adaptations,t.driftSteps,t.aiCalls,t.tokensInOut,t.cacheRead,t.cacheWrite,t.costUsd].every(Sp)&&Qr(t.verified,n=>typeof n=="boolean")&&Qr(t.seededSteps,Sp)&&Qr(t.error,gr)&&Qr(t.browser,gr)},Vs=e=>{let t=e;return!!t&&t.tool==="saffron"&&!!t.shard&&typeof t.shard.index=="number"&&typeof t.shard.total=="number"&&Array.isArray(t.shard.positions)&&(t.shard.browser===void 0||typeof t.shard.browser=="string")&&Array.isArray(t.scenarios)&&!!t.history&&Array.isArray(t.history.scenarios)&&t.history.scenarios.every(Fb)},Lb=/^shard-\d+-of-\d+\.json$/;function Tp(e){let t=[],n=(r,s)=>{let o=Js.statSync(r,{throwIfNoEntry:!1});if(!o)throw new Error(`not found: ${r}`);if(o.isDirectory())for(let a of Js.readdirSync(r).sort())n(yi.join(r,a),!1);else(s||Lb.test(yi.basename(r)))&&t.push(r)};for(let r of e)n(r,!0);return t.map(r=>{let s;try{s=JSON.parse(Js.readFileSync(r,"utf8"))}catch(o){throw new Error(`cannot read shard report ${r}: ${o instanceof Error?o.message:String(o)}`)}if(!Vs(s))throw new Error(`${r} is not a shard report (written by saffron run --shard)`);return{file:r,report:s}})}var hr=class extends Error{};function vi(e,t={}){if(e.length===0)throw new hr("no shard reports found. Shards write .saffron/reports/shard-<i>-of-<n>.json");let n=w=>Number(w.report.shard.attempt)||0,r=w=>{let{ciRun:E,index:_,total:A,suite:O,suiteSize:j,by:L,browser:I}=w.report.shard;return JSON.stringify([E??"",_,A,O,j,L??"scenario",w.report.baseURL??"",I??""])},s=new Map;for(let w of e)s.set(r(w),Math.max(s.get(r(w))??0,n(w)));let o=e.filter(w=>n(w)<s.get(r(w)));e=e.filter(w=>!o.includes(w));let a=e[0].report.shard,i=[],c=w=>w.map(E=>E.file).join(", "),l=new Set(e.map(w=>w.report.shard.total));l.size>1&&i.push(`shards disagree on the shard count (${[...l].sort().join(", ")}): ${c(e)}`),new Set(e.map(w=>`${w.report.shard.suite}/${w.report.shard.suiteSize}`)).size>1&&i.push("shards ran different suites (different scenarios or filters). Every shard must run the same paths and --filter");let u=new Set(e.map(w=>w.report.shard.by??"scenario"));u.size>1&&i.push(`shards split the suite in different ways (--shard-by ${[...u].sort().join(" and ")}): every shard must use the same`);let p=new Set(e.map(w=>w.report.shard.ciRun??""));p.size>1&&i.push(`shards come from different CI runs (${[...p].map(w=>w||"none recorded").join(", ")})`);let f=[...new Set(e.map(w=>w.report.baseURL??"(no base URL)"))];f.length>1&&i.push(`the shards ran against different base URLs: ${f.join(", ")}. Merge the shards of one environment at a time`);let g=[...new Set(e.map(w=>w.report.shard.browser??"(no browser recorded)"))];g.length>1&&i.push(`the shards ran in different browsers: ${g.join(", ")}. Merge the shards of one browser at a time`);let y=new Map;for(let w of e)y.set(w.report.shard.index,[...y.get(w.report.shard.index)??[],w]);for(let[w,E]of[...y].sort((_,A)=>_[0]-A[0]))E.length>1&&i.push(`shard ${w}/${a.total} appears ${E.length} times: ${c(E)}`);if(l.size===1&&!t.partial){let w=Array.from({length:a.total},(E,_)=>_+1).filter(E=>!y.has(E));w.length>0&&i.push(`missing ${w.length===1?"shard":"shards"} ${w.map(E=>`${E}/${a.total}`).join(", ")}. A merge without ${w.length===1?"it":"them"} would under-count the run`)}if(!t.partial)for(let w of e)w.report.interrupted&&i.push(`${w.file} is from a run that was interrupted (${Number(w.report.notRun)} scenario(s) did not run). Run shard ${w.report.shard.index}/${w.report.shard.total} again`);if(i.length===0){let w=new Set,E=0;for(let _ of e){let{positions:A}=_.report.shard;(A.length!==_.report.scenarios.length||A.length!==_.report.history.scenarios.length)&&i.push(`${_.file} is inconsistent: ${A.length} positions for ${_.report.scenarios.length} scenarios`);for(let O of A)w.has(O)&&i.push(`two shards both ran scenario ${O+1} of the suite`),w.add(O);E+=A.length}i.length===0&&!t.partial&&E!==a.suiteSize&&i.push(`the shards hold ${E} scenarios but the suite has ${a.suiteSize}`)}if(i.length>0)throw new hr(i.join(`
|
|
303
|
+
`));let h=e.sort((w,E)=>w.report.shard.index-E.report.shard.index).flatMap(({report:w})=>w.shard.positions.map((E,_)=>({position:E,scenario:w.scenarios[_].worker?{...w.scenarios[_],worker:`${w.shard.index}/${w.shard.total} \xB7 ${w.scenarios[_].worker}`}:w.scenarios[_],history:w.history.scenarios[_]}))).sort((w,E)=>w.position-E.position),S=e.map(w=>w.report),v=S.map(w=>w.startedAt).sort()[0],x=S.map(w=>w.finishedAt).sort().at(-1),b=h.map(w=>w.scenario),m=S.flatMap(w=>w.hooks??[]),$={tool:"saffron",version:S[0].version,startedAt:v,finishedAt:x,baseURL:S.find(w=>w.baseURL)?.baseURL,totals:wi(b),scenarios:b,shards:e.length};m.length>0&&($.hooks=m);let T=S.reduce((w,E)=>w+(E.interrupted?Number(E.notRun):0),0);S.some(w=>w.interrupted)&&Object.assign($,{interrupted:!0,notRun:T}),S[0].provenance&&new Set(S.map(w=>JSON.stringify(w.provenance??null))).size===1&&($.provenance=S[0].provenance);let R=e.filter(w=>w.report.timing).sort((w,E)=>w.report.shard.index-E.report.shard.index);R.length>0&&($.timing={wallMs:Math.max(...R.map(w=>w.report.timing.wallMs)),workers:R.flatMap(w=>w.report.timing.workers.map(E=>({...E,worker:`${w.report.shard.index}/${w.report.shard.total} \xB7 ${E.worker}`})))});let k=h.map(w=>w.history),P={runId:a.ciRun?`${a.ciRun}:${a.suite}:${$.baseURL??""}${a.browser?`:${a.browser}`:""}`:v,startedAt:v,finishedAt:x,baseURL:$.baseURL,green:k.filter(w=>w.status==="green").length,yellow:k.filter(w=>w.status==="yellow").length,red:k.filter(w=>w.status==="red").length,aiCalls:k.reduce((w,E)=>w+E.aiCalls,0),costUsd:k.reduce((w,E)=>w+E.costUsd,0),divergentSteps:Math.max(...S.map(w=>w.history.divergentSteps)),...S.some(w=>w.history.partial)?{partial:!0}:{},scenarios:k};return{report:$,history:P,replaced:o.map(w=>w.file)}}var Si=1,G=class extends Error{constructor(n,r){super(le(n,1/0));this.kind=r}kind},mr=e=>e instanceof Error?e.message:String(e);function An(e,t){try{return Bb("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim()||void 0}catch{return}}function Ip(e){let t=e.trim();if(/^[a-z]:[\\/]/i.test(t))return;let n,r;if(/^[a-z][a-z0-9+.-]*:\/\//i.test(t)){let o;try{o=new URL(t)}catch{return}if(o.protocol==="file:")return;n=o.hostname,r=o.pathname}else{let o=/^(?:[^@/\s]+@)?([^:/\s]+):(.+)$/.exec(t);if(!o)return;n=o[1],r=o[2]}try{r=decodeURIComponent(r)}catch{}r=r.replace(/^\/+|\/+$/g,"").replace(/\.git$/i,""),n=n.toLowerCase();let s=/^v3\/([^/]+)\/([^/]+)\/([^/]+)$/.exec(r);return s?(n="dev.azure.com",r=`${s[1]}/${s[2]}/_git/${s[3]}`):n.endsWith(".visualstudio.com")&&(r=`${n.slice(0,-17)}/${r.replace(/^DefaultCollection\//i,"")}`,n="dev.azure.com"),r?`${n}/${r}`.toLowerCase():void 0}function ki(e){let n=(An(e,["remote","-v"])?.split(`
|
|
304
|
+
`)??[]).map(r=>r.split(/\s+/)[1]).filter(Boolean);return[...new Set(n.map(Ip).filter(r=>r!==void 0))]}var Ap=e=>e?.replace(/^refs\/heads\//,"")||void 0,jp=e=>e.GITHUB_EVENT_NAME==="pull_request"||!!e.GITHUB_EVENT_NAME?.startsWith("pull_request_review");function qb(e){if(!e.GITHUB_EVENT_PATH||!jp(e))return{};let t=n=>typeof n=="string"&&n?n:void 0;try{let n=JSON.parse(se.readFileSync(e.GITHUB_EVENT_PATH,"utf8"))?.pull_request?.head;return{sha:t(n?.sha),ref:t(n?.ref)}}catch{return{}}}function rl(e,t){return[...(An(e,["cat-file","-p",t])??"").split(`
|
|
288
305
|
|
|
289
|
-
`)[0].matchAll(/^parent ([0-9a-f]+)$/gm)].map(r=>r[1])}function
|
|
290
|
-
`)??[],r=n.includes("origin")?"origin":n[0],s=t.GITHUB_SERVER_URL&&t.GITHUB_REPOSITORY?`${t.GITHUB_SERVER_URL}/${t.GITHUB_REPOSITORY}`:void 0,o=[r&&
|
|
291
|
-
`):c.bytes;r.push({name:"report.json",data:
|
|
292
|
-
`)},...r]),{file:h,manifest:u,proposals:o,missing:d,dropped:f,unreadable:n}}var Xo="[a-z0-9-]+",_f=new RegExp(`^proposals/${Xo}/${Xo}\\.json$`),xy="(?:chromium|chrome|msedge|firefox|webkit)/",Sy=new RegExp(`^artifacts/${Xo}/${Xo}/(?:${xy})?[A-Za-z0-9][A-Za-z0-9._-]*$`),hc=1024**3,bc=8*1024**3,$y="the bundles to import add up to more than 8 GB unzipped",$f=Math.min(bc,In),kf=100,ky=1024**2,Ry=6e5;function Ty(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function vc(e){let t=ge.join(e,".saffron","reports");for(let o of se.existsSync(t)?se.readdirSync(t):[]){let a=Number(/^run-download-(\d+)-/.exec(o)?.[1]),i=ge.join(t,o),c=a?se.statSync(i,{throwIfNoEntry:!1}):void 0;c&&Date.now()-c.mtimeMs>36e5&&!Ty(a)&&se.rmSync(i,{recursive:!0,force:!0})}let n=ge.join(t,`run-download-${process.pid}-${wc(4).toString("hex")}`),r=se.mkdirSync(n,{recursive:!0});return{dir:n,remove:()=>{se.rmSync(n,{recursive:!0,force:!0});for(let o=t;r&&o.startsWith(r);o=ge.dirname(o))try{se.rmdirSync(o)}catch{break}}}}async function Ay(e,t){let n=r=>new W(r?.name==="TimeoutError"?`cannot download ${e}: it did not finish within 10 minutes`:`cannot download ${e}: ${lr(r)}`);try{let r=await fetch(e,{redirect:"follow",signal:AbortSignal.timeout(Ry)});if(!r.ok||!r.body)throw new W(`cannot download ${e}: HTTP ${r.status}`);let s=se.openSync(t,"w");try{let o=0;for await(let a of r.body){if(o+=a.length,o>bc)throw new W(`cannot download ${e}: it is over 8 GB`);se.writeSync(s,a)}}finally{se.closeSync(s)}}catch(r){throw r instanceof W?r:n(r)}}async function Ey(e,t){if(/^https?:\/\//i.test(e)){let s=ge.join(t(),`url-${wc(4).toString("hex")}.zip`);return await Ay(e,s),[{source:e,file:s}]}let n=se.statSync(e,{throwIfNoEntry:!1});if(!n)throw new W(`not found: ${e}`);let r=n.isDirectory()?se.readdirSync(e,{recursive:!0}).map(String).filter(s=>/^saffron-(bundle|summary).*\.zip$/.test(ge.basename(s))).sort().map(s=>ge.join(e,s)):[e];if(r.length===0)throw new W(`no saffron-bundle*.zip or saffron-summary*.zip under ${e}`);return r.map(s=>({source:s,file:s}))}function _y(e,t){let n;try{n=bu(t)}catch(s){throw new W(`${e} is not a Saffron bundle: ${lr(s)}`)}let r=new Map;for(let s of n){if(r.has(s.name))throw new W(`${e} is damaged: it holds ${ce(s.name)} twice`);r.set(s.name,s)}return{source:e,file:t,entries:r}}var Oy=1024*1024;function Rf(e,t,n){let r=gy("sha256"),s=se.openSync(e,"r");try{let o=Buffer.alloc(Math.max(1,Math.min(Oy,t.size)));for(let a=0;a<t.size;){let i=se.readSync(s,o,0,Math.min(o.length,t.size-a),t.start+a);if(i===0)throw new Error("the file ends early");let c=o.subarray(0,i);r.update(c),n?.(c),a+=i}}finally{se.closeSync(s)}return r.digest("hex")}function Cy(e){try{return Io(e).sha256}catch{return}}function Py({source:e,file:t,entries:n}){let r=u=>new W(`${e} ${u}`);for(let u of n.values()){if(u.size>hc||u.compressedSize>hc)throw r(`is damaged: ${ce(u.name)} is too large`);if(u.method!==0&&u.size>ky&&u.size>kf*u.compressedSize)throw r(`is damaged: ${ce(u.name)} claims to unzip to over ${kf} times its size`)}let s=u=>{let h=n.get(u);if(!h)throw r(`is damaged: ${u} is missing`);let b;try{let g=h.raw();if(g.length!==h.compressedSize)throw new Error("the file ends early");b=h.method===0?g:hy.inflateRawSync(g,{maxOutputLength:Math.max(h.size,1)})}catch(g){throw r(`is damaged: ${u} cannot be read (${lr(g)})`)}if(b.length!==h.size)throw r(`is damaged: ${u} is truncated`);return b},o=u=>{let h=n.get(u);if(!(!h||h.method!==0)){if(h.compressedSize!==h.size)throw r(`is damaged: ${u} is truncated`);return h}},a=u=>{let h=o(u);if(!h)return zt(s(u));try{return Rf(t,h)}catch(b){throw r(`is damaged: ${u} cannot be read (${lr(b)})`)}},i=(u,h,b)=>{let g=o(u),S=()=>new Error(ce(`${e} is damaged: ${u} changed while it was imported`,1/0));if(!g){let v=s(u);if(zt(v)!==b)throw S();Je(h,v);return}se.mkdirSync(ge.dirname(h),{recursive:!0});let y=`${h}.${process.pid}-${wc(4).toString("hex")}.partial`,w=se.openSync(y,"w");try{let v;try{v=Rf(t,g,x=>{for(let $=0;$<x.length;)$+=se.writeSync(w,x,$,x.length-$)})}finally{se.closeSync(w)}if(v!==b)throw S();se.renameSync(y,h)}catch(v){throw se.rmSync(y,{force:!0}),v}},c=u=>{try{return JSON.parse(s(u).toString("utf8"))}catch(h){throw h instanceof W?h:r(`is damaged: ${u} is not JSON`)}};if(!n.has("manifest.json"))throw r("is not a Saffron bundle: it has no manifest.json");let l=c("manifest.json");if(!l||l.tool!=="saffron"||typeof l.format!="number")throw r("is not a Saffron bundle");for(let u of["runner","createdAt","repository","branch","commit","headCommit","run","attempt","url"])if(l[u]!==void 0){if(typeof l[u]!="string")throw r(`is damaged: its manifest's ${u} is not text`);if(l[u].length>2048)throw r(`is damaged: its manifest's ${u} is over 2048 characters`);l[u]=ce(l[u],2048)}if(l.format>Qo)throw r(`is bundle format ${l.format}, made by saffron-ai ${l.runner}; this saffron-ai (${ot()}) reads format ${Qo}. Update saffron-ai to import it`);if(l.format!==Qo)throw r(`has bundle format ${l.format}, which this saffron-ai does not read`);if(!Array.isArray(l.proposals)||!Array.isArray(l.evidence))throw r("is damaged: its manifest has no proposal or evidence list");if(l.summary!==void 0&&l.summary!==!0)throw r("is damaged: its manifest's summary is not true");if(l.summary&&l.proposals.length>0)throw r("is damaged: it is a summary and lists proposals");let{shard:d}=l;if(d!==void 0&&!(Number.isInteger(d?.index)&&Number.isInteger(d?.total)&&d.index>=1&&d.index<=d.total))throw r("is damaged: its manifest's shard is not <index> of <total>");let f=new Map;for(let u of l.proposals){if(!u||typeof u.entry!="string"||!_f.test(u.entry)||typeof u.revision!="string")throw r(`is damaged: its manifest lists a proposal at ${ce(JSON.stringify(u?.entry)??"nothing")}`);typeof u.feature=="string"&&(u.feature=ce(u.feature)),typeof u.scenario=="string"&&(u.scenario=ce(u.scenario));let h=s(u.entry);if(zt(h)!==u.revision)throw r(`is damaged: ${u.entry} is not the proposal its manifest names`);f.set(u.entry,h)}for(let u of l.evidence){if(!u||typeof u.entry!="string"||!Sy.test(u.entry)||typeof u.sha256!="string")throw r(`is damaged: its manifest lists evidence at ${ce(JSON.stringify(u?.entry)??"nothing")}`);if(a(u.entry)!==u.sha256)throw r(`is damaged: ${u.entry} is not the file its manifest names`)}let p;if(l.report!==void 0){if(l.report!=="report.json")throw r(`is damaged: its manifest names the report ${JSON.stringify(l.report)}`);let u=c("report.json"),h=lc(u);if(h)throw r(`is damaged: report.json ${h}`);try{Ln(u)}catch(b){throw r(`is damaged: report.json cannot be shown (${lr(b)})`)}p=u}if(d&&!(p&&Es(p)))throw r("is damaged: it is a shard's bundle without the shard's report");return{source:e,manifest:l,report:p,files:f,read:s,write:i}}function Iy(e,t){let n=t.headCommit??t.commit,r=gn(e,["rev-parse","HEAD"]);if(!n||!r||r===n)return;let s=`${n.slice(0,7)}${t.branch?` on ${t.branch}`:""}`;if(!/^[0-9a-f]{7,64}$/i.test(n)||!gn(e,["rev-parse","--verify","--quiet",`${n}^{commit}`]))return`this checkout is at ${r.slice(0,7)}, and the bundle was made at ${s}, which this clone does not have: fetch it to review against the same files`;let[o,a]=(gn(e,["rev-list","--left-right","--count",`HEAD...${n}`,"--"])??"").split(/\s+/).map(Number),i=[o?`${o} commit${o===1?"":"s"} ahead of`:"",a?`${a} commit${a===1?"":"s"} behind`:""].filter(Boolean).join(" and ");return`this checkout (${r.slice(0,7)}) is ${i||"not at"} the commit the bundle was made at, ${s}`}function mc(e){let{repository:t,branch:n,commit:r,headCommit:s,run:o,attempt:a,url:i}=e;return Object.fromEntries(Object.entries({repository:t,branch:n,commit:r,headCommit:s,run:o,attempt:a,url:i}).filter(([,c])=>typeof c=="string"))}var Of=e=>ge.join(e,".saffron","reports","imported.json");function hn(e){let t;try{t=JSON.parse(se.readFileSync(Of(e),"utf8"))}catch{return{}}return!t||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,n])=>!!n&&typeof n.revision=="string"&&!!n.from&&typeof n.from=="object"))}function Ny(e,t){try{return se.readFileSync(e).equals(t)}catch{return!1}}function Cf(e,t,n,r,s){let o;try{o=va(t,n)}catch(S){let y={file:`.saffron/${n}`,feature:"",scenario:""},w=`cannot be read: ${S instanceof $e?S.problem:lr(S)}`;return{verdict:{...y,outcome:"refused",reason:w},shown:y,file:ge.join(e,".saffron",n),revision:"",verified:!1}}let{proposal:a,revision:i}=o,{feature:c,scenario:l}=a.cache,d=xt(e,c,l),f={file:Be(e,d),feature:ce(c),scenario:ce(l)},p=S=>({verdict:S,shown:f,file:d,revision:i,verified:a.meta.verified===!0}),u=S=>p({...f,outcome:"refused",reason:S});if(!a.meta.bound)return u("carries no binding (a runner older than 0.8.5 filed it), so nothing can tell whether it fits this checkout");let h=s?`. ${s}`:"";if(!se.existsSync(ge.join(e,c)))return u(`is for ${f.feature}, which is not in this checkout${h}`);let b=Jt(me(e,c,l));if(b&&bs(b)===bs(a.cache))return p({...f,outcome:"unchanged",reason:"already accepted here: the committed recording is this proposal's"});let g;try{g=$t(e,a,r)}catch(S){g=`cannot be checked: ${lr(S)}`}return g?u(`does not fit this checkout: ${ce(g,1e3)}${h}`):p()}function Pf(e,t){if(se.existsSync(e.file)){if(Ot(e.file)===e.revision)return{...e.shown,outcome:"unchanged"};if(!t)return{...e.shown,outcome:"refused",reason:"differs from the proposal already pending here for this scenario: review that one first (saffron diff), or import with --overwrite to replace it"}}}function jy(e,t,n,r,s,o){let a=Cf(e,t,n,r,o);if(a.verdict)return a.verdict;se.mkdirSync(ge.dirname(a.file),{recursive:!0});try{return Cr(a.file,()=>{let i=Pf(a,s);return i||(Je(a.file,t),{...a.shown,outcome:"imported"})})}catch(i){if(i instanceof er)return{...a.shown,outcome:"refused",reason:"is being decided by another process. Try again."};throw i}}async function If(e,t,n,r={}){let s;try{let o=jf(await Mf(t,()=>(s??=vc(e)).dir,r.describe));return Dy(e,o,n,r)}finally{s?.remove()}}function Nf(e){let t=e.report&&Es(e.report)?e.report.shard:void 0,n=[...new Set([t?.browser,...(e.report?.scenarios??[]).map(r=>r.browser)].filter(Boolean))].sort();return JSON.stringify([e.manifest.repository??"",e.manifest.run??"",e.manifest.shard?.index??0,t?.suite??"",t?.total??0,t?t.by??"scenario":"",n,e.report?.baseURL??""])}function jf(e){let t=r=>`${Nf(r)}|${Number(r.manifest.attempt)||0}`,n=new Set(e.filter(r=>!r.manifest.summary&&r.report).map(t));return e.filter(r=>!r.manifest.summary||!n.has(t(r)))}async function Mf(e,t,n){let r=[];for(let s of e)for(let o of await Ey(s,t))r.push(_y(n?.(o.source)??o.source,o.file));if(r.reduce((s,o)=>s+[...o.entries.values()].reduce((a,i)=>a+i.size,0),0)>bc)throw new W($y);return r.map(Py)}function My(e){let t=[...new Set(e)].sort((n,r)=>n-r);return t.length>1?`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`:String(t[0]??"")}function Df(e,t,n){let r=t;if(r.length===0)throw new W("no bundle to import");let s=new Set,o=ei(e);for(let p of r){if(n.run!==void 0&&p.manifest.run!==n.run)throw new W(`${p.source} was made by ${p.manifest.run?`run ${p.manifest.run}`:"no CI run"}, not by ${n.run}, the run it was downloaded from. If that is expected, download the artifact and import the file`);let u=p.manifest.repository;if(!u&&!n.allowUnknownRepository)throw new W(`${p.source} does not say which repository it comes from (it was made outside a git checkout). Import it with --allow-unknown-repository to check it by its proposals' bindings only`);if(!u)s.add(`${p.source} does not say which repository it comes from: it is checked by its proposals' bindings only`);else if(o.length===0)s.add(`this project has no git remote to compare ${u} with: the bundle is checked by its proposals' bindings only`);else if(!o.includes(u)){let h=g=>g.slice(g.indexOf("/")),b=o.find(g=>h(g)===h(u));if(!b)throw new W(`${p.source} comes from ${u}, and this checkout is ${o.join(", ")}. Import it into a checkout of ${u}`);s.add(`${r.length===1?"the bundle comes":"the bundles come"} from ${u}, and this checkout is ${b}: the same repository under another host name (an SSH host alias, or a mirror), so each proposal is checked by its binding`)}}if(r.length>1){let p=new Set(r.map(w=>w.manifest.run??""));if(p.size>1)throw new W(`these bundles come from different runs (${[...p].map(w=>w||"none recorded").join(", ")}). Import one run at a time`);let u=w=>Number(w.manifest.attempt)||0,h=Nf,b=w=>w.manifest.shard?.index??0,g=w=>r.filter(v=>b(v)===b(w)&&(!w.report||h(v)===h(w))).reduce((v,x)=>u(x)>u(v)?x:v),S=r.filter(w=>u(w)<u(g(w)));for(let w of S){let v=w.manifest.shard?`shard ${w.manifest.shard.index}`:"the whole run";s.add(`${w.source} is ${v} of attempt ${u(w)}, which attempt ${u(g(w))} ran again: left out`)}r=r.filter(w=>!S.includes(w));let y=r.filter(w=>!w.manifest.shard);if(y.length>0&&r.length>1)throw new W(`${y.map(w=>w.source).join(", ")} ${y.length===1?"holds a whole run, not a shard of one":"hold whole runs, not shards of one"}: import one run at a time`)}let a,i=r.filter(p=>p.report);if(r.length===1&&i.length===1){let{shard:p,history:u,...h}=i[0].report;a=h}else if(i.length>0)try{let p=Zo(i.map(u=>({file:u.source,report:u.report})),{partial:!0});if(p.replaced.length>0)throw new cr(`${p.replaced.join(", ")} holds a shard that another bundle of the same attempt holds too`);a=p.report}catch(p){throw p instanceof cr?new W(`these shard bundles do not belong together: ${p.message.split(`
|
|
293
|
-
`).join("; ")}`):p}let c=r[0].manifest,l=
|
|
294
|
-
`))?l="unchanged":(
|
|
295
|
-
`),{bundles:s.map(
|
|
296
|
-
`),
|
|
297
|
-
`)[0]:void 0,failedStep:(R.steps??[]).find(k=>k.status==="failed")?.gherkin??R.evidence?.find(k=>k.step)?.step,evidence:(R.evidence??[]).filter(k=>k.kind==="trace"?
|
|
298
|
-
`)[0]}`:""}`)}if(e.tags.length&&console.log(`tags: ${e.tags.map(i=>`${i.tag} (${i.scenarios})`).join(", ")}`),console.log(e.proposals.length?`${e.proposals.length} proposal(s) pending review: ${e.proposals.map(i=>i.file).join(", ")}`:"no proposals pending review",...e.unreadableProposals.map(i=>`\u26A0 proposal ${i.file} cannot be read: ${i.problem}`),...e.features.flatMap(i=>i.scenarios.filter(c=>c.cacheProblem).map(c=>`\u26A0 recording of ${i.path} \u203A ${c.name} cannot be read: ${c.cacheProblem}`)),...e.features.flatMap(i=>i.scenarios.filter(c=>c.refused!==void 0).map(c=>`\u2717 ${i.path} \u203A ${c.name} is refused on ${c.rows>1?`${c.refusedRows??1} of its ${c.rows} rows`:"this row"}: ${c.refused}`))),e.lastRun){let i=e.lastRun.totals;console.log(`last run ${e.lastRun.finishedAt}: ${i.green} passed \xB7 ${i.yellow} pending review \xB7 ${i.red} failed \xB7 ${i.costUsd===void 0?"cost not reported":`$${i.costUsd.toFixed(2)}`}${e.lastRun.interrupted?` \xB7 interrupted, ${e.lastRun.notRun} not run`:""}`)}let a=e.vocabulary;console.log(`vocabulary: ${a.steps} steps (${a.recorded} recorded, ${a.unrecorded} unrecorded), ${a.stepSets} step sets, ${a.divergent.length} divergent, ${a.duplicateWordings.length} duplicate wording group(s)`),e.orphanScan.complete?e.orphans.length&&console.log(`${e.orphans.length} recording(s) belong to no scenario: run \`saffron prune\` to see them`):console.log(`orphaned recordings not checked: ${e.orphanScan.errors[0]}`),(e.data.files.length||e.data.unresolved.length)&&console.log(`test data: ${e.data.files.length} file(s) in ${e.data.dir}/${e.data.env?` \xB7 environment "${e.data.env}"`:""}`+(e.data.unresolved.length?` \xB7 ${e.data.unresolved.length} reference(s) do not resolve: ${e.data.unresolved.map(i=>`{data:${i.ref}}`).join(", ")}`:"")),console.log(`config: ${e.config.file??"(defaults, no saffron.config.json)"}`)}var
|
|
306
|
+
`)[0].matchAll(/^parent ([0-9a-f]+)$/gm)].map(r=>r[1])}function Hb(e,t=process.env){let n=An(e,["remote"])?.split(`
|
|
307
|
+
`)??[],r=n.includes("origin")?"origin":n[0],s=t.GITHUB_SERVER_URL&&t.GITHUB_REPOSITORY?`${t.GITHUB_SERVER_URL}/${t.GITHUB_REPOSITORY}`:void 0,o=[r&&An(e,["remote","get-url",r]),s,t.BUILD_REPOSITORY_URI].map(g=>g?Ip(g):void 0).find(Boolean),a=An(e,["rev-parse","--abbrev-ref","HEAD"]),i=qb(t),c=(jp(t)?t.GITHUB_HEAD_REF||i.ref:void 0)||(t.GITHUB_EVENT_NAME==="pull_request_target"?t.GITHUB_BASE_REF:void 0)||(t.GITHUB_REF_TYPE==="tag"?void 0:t.GITHUB_REF_NAME)||Ap(t.SYSTEM_PULLREQUEST_SOURCEBRANCH)||(t.BUILD_SOURCEBRANCH?.startsWith("refs/heads/")?Ap(t.BUILD_SOURCEBRANCH):void 0)||(a!=="HEAD"?a:void 0),l=An(e,["rev-parse","HEAD"])||t.GITHUB_SHA||t.BUILD_SOURCEVERSION,d=i.sha||t.SYSTEM_PULLREQUEST_SOURCECOMMITID,u=d&&l&&rl(e,l)[1]===d?d:void 0,p=t.GITHUB_SERVER_URL&&t.GITHUB_REPOSITORY&&t.GITHUB_RUN_ID?`${t.GITHUB_SERVER_URL}/${t.GITHUB_REPOSITORY}/actions/runs/${t.GITHUB_RUN_ID}`:t.SYSTEM_COLLECTIONURI&&t.SYSTEM_TEAMPROJECT&&t.BUILD_BUILDID?`${t.SYSTEM_COLLECTIONURI.replace(/\/?$/,"/")}${encodeURIComponent(t.SYSTEM_TEAMPROJECT)}/_build/results?buildId=${t.BUILD_BUILDID}`:void 0,f={repository:o,branch:c,commit:l,headCommit:u&&u!==l?u:void 0,run:t.GITHUB_RUN_ID&&`github:${t.GITHUB_RUN_ID}`||t.BUILD_BUILDID&&`azure:${t.BUILD_BUILDID}`||bi(t),attempt:xi(t),url:p};return Object.fromEntries(Object.entries(f).filter(([,g])=>g!==void 0))}function Ws(e){let t=e.headCommit??e.commit;return[e.run?`run ${e.run}${e.attempt&&e.attempt!=="1"?` (attempt ${e.attempt})`:""}`:"a local run",e.branch||t?`${e.branch??"detached"}${t?` @ ${t.slice(0,7)}`:""}`:void 0,e.repository].filter(Boolean).join(" \xB7 ")}var Jb=/^(latest|shard-\d+-of-\d+)\.json$/;function Vb(e){let t=ye.join(e,".saffron","reports"),n;try{n=se.readdirSync(t).filter(s=>Jb.test(s)).sort()}catch{return}let r;for(let s of n)try{let o=se.readFileSync(ye.join(t,s)),a=JSON.parse(o.toString("utf8"));Kc(a)&&(!r||a.finishedAt>r.report.finishedAt)&&(r={bytes:o,report:a})}catch{}return r}function Wb(e,t,n=!1){let r=n?"saffron-summary":"saffron-bundle";return ye.join(e,".saffron","reports",t?`${r}-${Qc(t)}.zip`:`${r}.zip`)}var Ep=e=>`${(e/1024**3).toFixed(1)} GB`,Op='Keep fewer traces ("trace": "retain-on-failure" in saffron.config.json, or --trace retain-on-failure) and run again';function Np(e,t={}){let n=[],r=[],s=[],o=[],a=ye.join(e,".saffron","proposals"),i=t.summary===!0;for(let{file:y,proposal:h,revision:S,bytes:v}of i?[]:sn(e,(x,b)=>n.push({file:He(e,x),problem:b}))){let x=`proposals/${He(a,y)}`;r.push({name:x,data:v}),s.push({entry:x,feature:h.cache.feature,scenario:h.cache.scenario,revision:S,bound:h.meta.bound}),o.push({file:y,proposal:h,bytes:v})}let c=Vb(e),l=[],d=[],u=[];if(c){let y=i?Buffer.from(`${JSON.stringify({...c.report,scenarios:c.report.scenarios.map(x=>({...x,evidence:x.evidence?.filter(b=>b.kind!=="trace")}))},null,2)}
|
|
308
|
+
`):c.bytes;r.push({name:"report.json",data:y});let h=[],S=new Set;for(let x of c.report.scenarios)for(let b of x.evidence??[]){if(S.has(b.file)||i&&b.kind==="trace")continue;S.add(b.file);let m=b.file.startsWith(".saffron/artifacts/")?se.statSync(ye.join(e,b.file),{throwIfNoEntry:!1}):void 0;if(!m?.isFile()){d.push(b.file);continue}let $=x.status==="green"&&b.kind==="trace";if(m.size>el){if($){u.push(b.file);continue}throw new G(`${b.file} is ${Ep(m.size)}, over the 1 GB a bundle holds per file. ${Op}`)}h.push({e:b,size:m.size,greenTrace:$})}let v=()=>r.reduce((x,b)=>x+("data"in b?b.data.length:b.size??0)+1024,0)+h.reduce((x,b)=>x+b.size+1024,0);if(v()>_p)for(let x of h.filter(b=>b.greenTrace))h.splice(h.indexOf(x),1),u.push(x.e.file);if(v()>_p)throw new G(`the bundle would hold ${Ep(v())}${u.length?" even without the traces of green scenarios":""}, over the 4 GB one bundle holds. ${Op}, or split the run into shards (--shard)`);for(let{e:x}of h){let b=ye.join(e,x.file),m;try{m=It(ye.join(e,".saffron","artifacts"),b)?ri(b):void 0}catch{m=void 0}if(!m||x.sha256&&m.sha256!==x.sha256){d.push(x.file);continue}let $=x.file.slice(9);r.push({name:$,file:b,crc:m.crc,size:m.size}),l.push({entry:$,sha256:m.sha256})}}if(!c&&(i||s.length===0))throw new G(`nothing to export: no run report${i?"":" and no pending proposals"} under .saffron. Run \`saffron run\` first.`);let p=c&&Vs(c.report)?{index:c.report.shard.index,total:c.report.shard.total}:void 0,f={tool:"saffron",format:Si,runner:ut(),createdAt:new Date().toISOString(),...Hb(e,t.env),...p?{shard:p}:{},...c?{report:"report.json"}:{},...i?{summary:!0}:{},proposals:s,evidence:l},g=t.out??Wb(e,p,i);if(se.existsSync(g)&&se.statSync(g).isDirectory())throw new G(`${g} is a folder: give --out a file name, such as ${ye.join(g,"saffron-bundle.zip")}`);return Nf(g,[{name:"manifest.json",data:Buffer.from(`${JSON.stringify(f,null,2)}
|
|
309
|
+
`)},...r]),{file:g,manifest:f,proposals:o,missing:d,dropped:u,unreadable:n}}var $i="[a-z0-9-]+",Mp=new RegExp(`^proposals/${$i}/${$i}\\.json$`),Gb="(?:chromium|chrome|msedge|firefox|webkit)/",Kb=new RegExp(`^artifacts/${$i}/${$i}/(?:${Gb})?[A-Za-z0-9][A-Za-z0-9._-]*$`),el=1024**3,sl=8*1024**3,Yb="the bundles to import add up to more than 8 GB unzipped",_p=Math.min(sl,Jn),Cp=100,Zb=1024**2,Qb=6e5;function Xb(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function ol(e){let t=ye.join(e,".saffron","reports");for(let o of se.existsSync(t)?se.readdirSync(t):[]){let a=Number(/^run-download-(\d+)-/.exec(o)?.[1]),i=ye.join(t,o),c=a?se.statSync(i,{throwIfNoEntry:!1}):void 0;c&&Date.now()-c.mtimeMs>36e5&&!Xb(a)&&se.rmSync(i,{recursive:!0,force:!0})}let n=ye.join(t,`run-download-${process.pid}-${nl(4).toString("hex")}`),r=se.mkdirSync(n,{recursive:!0});return{dir:n,remove:()=>{se.rmSync(n,{recursive:!0,force:!0});for(let o=t;r&&o.startsWith(r);o=ye.dirname(o))try{se.rmdirSync(o)}catch{break}}}}async function ex(e,t){let n=r=>new G(r?.name==="TimeoutError"?`cannot download ${e}: it did not finish within 10 minutes`:`cannot download ${e}: ${mr(r)}`);try{let r=await fetch(e,{redirect:"follow",signal:AbortSignal.timeout(Qb)});if(!r.ok||!r.body)throw new G(`cannot download ${e}: HTTP ${r.status}`);let s=se.openSync(t,"w");try{let o=0;for await(let a of r.body){if(o+=a.length,o>sl)throw new G(`cannot download ${e}: it is over 8 GB`);se.writeSync(s,a)}}finally{se.closeSync(s)}}catch(r){throw r instanceof G?r:n(r)}}async function tx(e,t){if(/^https?:\/\//i.test(e)){let s=ye.join(t(),`url-${nl(4).toString("hex")}.zip`);return await ex(e,s),[{source:e,file:s}]}let n=se.statSync(e,{throwIfNoEntry:!1});if(!n)throw new G(`not found: ${e}`);let r=n.isDirectory()?se.readdirSync(e,{recursive:!0}).map(String).filter(s=>/^saffron-(bundle|summary).*\.zip$/.test(ye.basename(s))).sort().map(s=>ye.join(e,s)):[e];if(r.length===0)throw new G(`no saffron-bundle*.zip or saffron-summary*.zip under ${e}`);return r.map(s=>({source:s,file:s}))}function nx(e,t){let n;try{n=Af(t)}catch(s){throw new G(`${e} is not a Saffron bundle: ${mr(s)}`)}let r=new Map;for(let s of n){if(r.has(s.name))throw new G(`${e} is damaged: it holds ${le(s.name)} twice`);r.set(s.name,s)}return{source:e,file:t,entries:r}}var rx=1024*1024;function Pp(e,t,n){let r=Ub("sha256"),s=se.openSync(e,"r");try{let o=Buffer.alloc(Math.max(1,Math.min(rx,t.size)));for(let a=0;a<t.size;){let i=se.readSync(s,o,0,Math.min(o.length,t.size-a),t.start+a);if(i===0)throw new Error("the file ends early");let c=o.subarray(0,i);r.update(c),n?.(c),a+=i}}finally{se.closeSync(s)}return r.digest("hex")}function sx(e){try{return ri(e).sha256}catch{return}}function ox({source:e,file:t,entries:n}){let r=f=>new G(`${e} ${f}`);for(let f of n.values()){if(f.size>el||f.compressedSize>el)throw r(`is damaged: ${le(f.name)} is too large`);if(f.method!==0&&f.size>Zb&&f.size>Cp*f.compressedSize)throw r(`is damaged: ${le(f.name)} claims to unzip to over ${Cp} times its size`)}let s=f=>{let g=n.get(f);if(!g)throw r(`is damaged: ${f} is missing`);let y;try{let h=g.raw();if(h.length!==g.compressedSize)throw new Error("the file ends early");y=g.method===0?h:zb.inflateRawSync(h,{maxOutputLength:Math.max(g.size,1)})}catch(h){throw r(`is damaged: ${f} cannot be read (${mr(h)})`)}if(y.length!==g.size)throw r(`is damaged: ${f} is truncated`);return y},o=f=>{let g=n.get(f);if(!(!g||g.method!==0)){if(g.compressedSize!==g.size)throw r(`is damaged: ${f} is truncated`);return g}},a=f=>{let g=o(f);if(!g)return Kt(s(f));try{return Pp(t,g)}catch(y){throw r(`is damaged: ${f} cannot be read (${mr(y)})`)}},i=(f,g,y)=>{let h=o(f),S=()=>new Error(le(`${e} is damaged: ${f} changed while it was imported`,1/0));if(!h){let b=s(f);if(Kt(b)!==y)throw S();Ue(g,b);return}se.mkdirSync(ye.dirname(g),{recursive:!0});let v=`${g}.${process.pid}-${nl(4).toString("hex")}.partial`,x=se.openSync(v,"w");try{let b;try{b=Pp(t,h,m=>{for(let $=0;$<m.length;)$+=se.writeSync(x,m,$,m.length-$)})}finally{se.closeSync(x)}if(b!==y)throw S();se.renameSync(v,g)}catch(b){throw se.rmSync(v,{force:!0}),b}},c=f=>{try{return JSON.parse(s(f).toString("utf8"))}catch(g){throw g instanceof G?g:r(`is damaged: ${f} is not JSON`)}};if(!n.has("manifest.json"))throw r("is not a Saffron bundle: it has no manifest.json");let l=c("manifest.json");if(!l||l.tool!=="saffron"||typeof l.format!="number")throw r("is not a Saffron bundle");for(let f of["runner","createdAt","repository","branch","commit","headCommit","run","attempt","url"])if(l[f]!==void 0){if(typeof l[f]!="string")throw r(`is damaged: its manifest's ${f} is not text`);if(l[f].length>2048)throw r(`is damaged: its manifest's ${f} is over 2048 characters`);l[f]=le(l[f],2048)}if(l.format>Si)throw r(`is bundle format ${l.format}, made by saffron-ai ${l.runner}; this saffron-ai (${ut()}) reads format ${Si}. Update saffron-ai to import it`);if(l.format!==Si)throw r(`has bundle format ${l.format}, which this saffron-ai does not read`);if(!Array.isArray(l.proposals)||!Array.isArray(l.evidence))throw r("is damaged: its manifest has no proposal or evidence list");if(l.summary!==void 0&&l.summary!==!0)throw r("is damaged: its manifest's summary is not true");if(l.summary&&l.proposals.length>0)throw r("is damaged: it is a summary and lists proposals");let{shard:d}=l;if(d!==void 0&&!(Number.isInteger(d?.index)&&Number.isInteger(d?.total)&&d.index>=1&&d.index<=d.total))throw r("is damaged: its manifest's shard is not <index> of <total>");let u=new Map;for(let f of l.proposals){if(!f||typeof f.entry!="string"||!Mp.test(f.entry)||typeof f.revision!="string")throw r(`is damaged: its manifest lists a proposal at ${le(JSON.stringify(f?.entry)??"nothing")}`);typeof f.feature=="string"&&(f.feature=le(f.feature)),typeof f.scenario=="string"&&(f.scenario=le(f.scenario));let g=s(f.entry);if(Kt(g)!==f.revision)throw r(`is damaged: ${f.entry} is not the proposal its manifest names`);u.set(f.entry,g)}for(let f of l.evidence){if(!f||typeof f.entry!="string"||!Kb.test(f.entry)||typeof f.sha256!="string")throw r(`is damaged: its manifest lists evidence at ${le(JSON.stringify(f?.entry)??"nothing")}`);if(a(f.entry)!==f.sha256)throw r(`is damaged: ${f.entry} is not the file its manifest names`)}let p;if(l.report!==void 0){if(l.report!=="report.json")throw r(`is damaged: its manifest names the report ${JSON.stringify(l.report)}`);let f=c("report.json"),g=Gc(f);if(g)throw r(`is damaged: report.json ${g}`);try{Gn(f)}catch(y){throw r(`is damaged: report.json cannot be shown (${mr(y)})`)}p=f}if(d&&!(p&&Vs(p)))throw r("is damaged: it is a shard's bundle without the shard's report");return{source:e,manifest:l,report:p,files:u,read:s,write:i}}function ix(e,t){let n=t.headCommit??t.commit,r=An(e,["rev-parse","HEAD"]);if(!n||!r||r===n)return;let s=`${n.slice(0,7)}${t.branch?` on ${t.branch}`:""}`;if(!/^[0-9a-f]{7,64}$/i.test(n)||!An(e,["rev-parse","--verify","--quiet",`${n}^{commit}`]))return`this checkout is at ${r.slice(0,7)}, and the bundle was made at ${s}, which this clone does not have: fetch it to review against the same files`;let[o,a]=(An(e,["rev-list","--left-right","--count",`HEAD...${n}`,"--"])??"").split(/\s+/).map(Number),i=[o?`${o} commit${o===1?"":"s"} ahead of`:"",a?`${a} commit${a===1?"":"s"} behind`:""].filter(Boolean).join(" and ");return`this checkout (${r.slice(0,7)}) is ${i||"not at"} the commit the bundle was made at, ${s}`}function tl(e){let{repository:t,branch:n,commit:r,headCommit:s,run:o,attempt:a,url:i}=e;return Object.fromEntries(Object.entries({repository:t,branch:n,commit:r,headCommit:s,run:o,attempt:a,url:i}).filter(([,c])=>typeof c=="string"))}var Dp=e=>ye.join(e,".saffron","reports","imported.json");function En(e){let t;try{t=JSON.parse(se.readFileSync(Dp(e),"utf8"))}catch{return{}}return!t||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,n])=>!!n&&typeof n.revision=="string"&&!!n.from&&typeof n.from=="object"))}function ax(e,t){try{return se.readFileSync(e).equals(t)}catch{return!1}}function Fp(e,t,n,r,s){let o;try{o=qa(t,n)}catch(S){let v={file:`.saffron/${n}`,feature:"",scenario:""},x=`cannot be read: ${S instanceof ke?S.problem:mr(S)}`;return{verdict:{...v,outcome:"refused",reason:x},shown:v,file:ye.join(e,".saffron",n),revision:"",verified:!1}}let{proposal:a,revision:i}=o,{feature:c,scenario:l}=a.cache,d=dt(e,c,l),u={file:He(e,d),feature:le(c),scenario:le(l)},p=S=>({verdict:S,shown:u,file:d,revision:i,verified:a.meta.verified===!0}),f=S=>p({...u,outcome:"refused",reason:S});if(!a.meta.bound)return f("carries no binding (a runner older than 0.8.5 filed it), so nothing can tell whether it fits this checkout");let g=s?`. ${s}`:"";if(!se.existsSync(ye.join(e,c)))return f(`is for ${u.feature}, which is not in this checkout${g}`);let y=tn(pe(e,c,l));if(y&&Ds(y)===Ds(a.cache))return p({...u,outcome:"unchanged",reason:"already accepted here: the committed recording is this proposal's"});let h;try{h=At(e,a,r)}catch(S){h=`cannot be checked: ${mr(S)}`}return h?f(`does not fit this checkout: ${le(h,1e3)}${g}`):p()}function Lp(e,t){if(se.existsSync(e.file)){if(jt(e.file)===e.revision)return{...e.shown,outcome:"unchanged"};if(!t)return{...e.shown,outcome:"refused",reason:"differs from the proposal already pending here for this scenario: review that one first (saffron diff), or import with --overwrite to replace it"}}}function cx(e,t,n,r,s,o){let a=Fp(e,t,n,r,o);if(a.verdict)return a.verdict;se.mkdirSync(ye.dirname(a.file),{recursive:!0});try{return Ur(a.file,()=>{let i=Lp(a,s);return i||(Ue(a.file,t),{...a.shown,outcome:"imported"})})}catch(i){if(i instanceof cr)return{...a.shown,outcome:"refused",reason:"is being decided by another process. Try again."};throw i}}async function Bp(e,t,n,r={}){let s;try{let o=zp(await qp(t,()=>(s??=ol(e)).dir,r.describe));return dx(e,o,n,r)}finally{s?.remove()}}function Up(e){let t=e.report&&Vs(e.report)?e.report.shard:void 0,n=[...new Set([t?.browser,...(e.report?.scenarios??[]).map(r=>r.browser)].filter(Boolean))].sort();return JSON.stringify([e.manifest.repository??"",e.manifest.run??"",e.manifest.shard?.index??0,t?.suite??"",t?.total??0,t?t.by??"scenario":"",n,e.report?.baseURL??""])}function zp(e){let t=r=>`${Up(r)}|${Number(r.manifest.attempt)||0}`,n=new Set(e.filter(r=>!r.manifest.summary&&r.report).map(t));return e.filter(r=>!r.manifest.summary||!n.has(t(r)))}async function qp(e,t,n){let r=[];for(let s of e)for(let o of await tx(s,t))r.push(nx(n?.(o.source)??o.source,o.file));if(r.reduce((s,o)=>s+[...o.entries.values()].reduce((a,i)=>a+i.size,0),0)>sl)throw new G(Yb);return r.map(ox)}function lx(e){let t=[...new Set(e)].sort((n,r)=>n-r);return t.length>1?`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`:String(t[0]??"")}function Hp(e,t,n){let r=t;if(r.length===0)throw new G("no bundle to import");let s=new Set,o=ki(e);for(let p of r){if(n.run!==void 0&&p.manifest.run!==n.run)throw new G(`${p.source} was made by ${p.manifest.run?`run ${p.manifest.run}`:"no CI run"}, not by ${n.run}, the run it was downloaded from. If that is expected, download the artifact and import the file`);let f=p.manifest.repository;if(!f&&!n.allowUnknownRepository)throw new G(`${p.source} does not say which repository it comes from (it was made outside a git checkout). Import it with --allow-unknown-repository to check it by its proposals' bindings only`);if(!f)s.add(`${p.source} does not say which repository it comes from: it is checked by its proposals' bindings only`);else if(o.length===0)s.add(`this project has no git remote to compare ${f} with: the bundle is checked by its proposals' bindings only`);else if(!o.includes(f)){let g=h=>h.slice(h.indexOf("/")),y=o.find(h=>g(h)===g(f));if(!y)throw new G(`${p.source} comes from ${f}, and this checkout is ${o.join(", ")}. Import it into a checkout of ${f}`);s.add(`${r.length===1?"the bundle comes":"the bundles come"} from ${f}, and this checkout is ${y}: the same repository under another host name (an SSH host alias, or a mirror), so each proposal is checked by its binding`)}}if(r.length>1){let p=new Set(r.map(x=>x.manifest.run??""));if(p.size>1)throw new G(`these bundles come from different runs (${[...p].map(x=>x||"none recorded").join(", ")}). Import one run at a time`);let f=x=>Number(x.manifest.attempt)||0,g=Up,y=x=>x.manifest.shard?.index??0,h=x=>r.filter(b=>y(b)===y(x)&&(!x.report||g(b)===g(x))).reduce((b,m)=>f(m)>f(b)?m:b),S=r.filter(x=>f(x)<f(h(x)));for(let x of S){let b=x.manifest.shard?`shard ${x.manifest.shard.index}`:"the whole run";s.add(`${x.source} is ${b} of attempt ${f(x)}, which attempt ${f(h(x))} ran again: left out`)}r=r.filter(x=>!S.includes(x));let v=r.filter(x=>!x.manifest.shard);if(v.length>0&&r.length>1)throw new G(`${v.map(x=>x.source).join(", ")} ${v.length===1?"holds a whole run, not a shard of one":"hold whole runs, not shards of one"}: import one run at a time`)}let a,i=r.filter(p=>p.report);if(r.length===1&&i.length===1){let{shard:p,history:f,...g}=i[0].report;a=g}else if(i.length>0)try{let p=vi(i.map(f=>({file:f.source,report:f.report})),{partial:!0});if(p.replaced.length>0)throw new hr(`${p.replaced.join(", ")} holds a shard that another bundle of the same attempt holds too`);a=p.report}catch(p){throw p instanceof hr?new G(`these shard bundles do not belong together: ${p.message.split(`
|
|
310
|
+
`).join("; ")}`):p}let c=r[0].manifest,l=ix(e,c);l&&s.add(l),c.headCommit&&c.commit&&s.add(`the run tested ${c.commit.slice(0,7)}, a pull request's merge commit, not the head of ${c.branch??"its branch"} (${c.headCommit.slice(0,7)}): each proposal is checked against this checkout by its binding`);let d=c.headCommit??c.commit,u=l&&d?`The bundle was made at ${d.slice(0,7)}${c.branch?` on ${c.branch}`:""}: check that out and import again`:void 0;if(a){let p=r.flatMap(f=>f.manifest.shard?[f.manifest.shard]:[]);a.imported={...tl(c),...p.length>0?{shards:{imported:p.map(f=>f.index).sort((f,g)=>f-g),total:p[0].total}}:{}}}return{bundles:r,report:a,warnings:s,hint:u}}function Jp(e,t,n){let r={written:0,unchanged:0},s=new Map;for(let o of n?.scenarios??[])for(let a of o.evidence??[])s.set(ye.posix.dirname(a.file),{feature:o.feature,scenario:o.scenario});for(let o of t)for(let{entry:a,sha256:i}of o.manifest.evidence){let c=ye.join(e,".saffron",...a.split("/"));if(sx(c)===i){r.unchanged++;continue}o.write(a,c,i),r.written++;let l=s.get(`.saffron/${ye.posix.dirname(a)}`);l&&se.writeFileSync(ye.join(e,".saffron",...a.split("/").slice(0,3),ar),JSON.stringify(l,null,2))}return r}function Vp(e){let t=new Map;for(let s of e)for(let o of s.manifest.proposals){let a=t.get(o.entry)??{revisions:new Set,shards:[]};a.revisions.add(o.revision),s.manifest.shard&&a.shards.push(s.manifest.shard.index),t.set(o.entry,a)}let n=[],r=new Set;for(let s of e)for(let o of s.manifest.proposals){let a=t.get(o.entry);if(a.revisions.size===1){n.push({b:s,p:o});continue}r.has(o.entry)||(r.add(o.entry),n.push({b:s,p:o,conflict:{file:`.saffron/${o.entry}`,feature:typeof o.feature=="string"?o.feature:"",scenario:typeof o.scenario=="string"?o.scenario:"",outcome:"refused",reason:`is a conflict between the run's shards: shards ${lx(a.shards)} filed different proposals for this scenario (a Scenario Outline's rows split across shards), so no proposal for it was imported. Run the scenario again on one machine and import that run`}}))}return n}function dx(e,t,n,r){let{bundles:s,report:o,warnings:a,hint:i}=Hp(e,t,r);if(s.every(f=>f.manifest.summary))throw new G(`${s[0].source} is a summary (saffron export --report-only): the run's results, which saffron report --run shows, and no proposals. Import the run's full bundle (saffron-bundle*)`);let c=Jp(e,s,o),l;if(o){for(let g of o.scenarios){let y=typeof g.proposalFile=="string"?g.proposalFile.split(/[\\/]/).slice(-2):[];Mp.test(`proposals/${y.join("/")}`)&&(g.proposalFile=`.saffron/proposals/${y.join("/")}`)}let f=ye.join(e,".saffron","reports","latest.json");ax(f,Buffer.from(`${JSON.stringify(o,null,2)}
|
|
311
|
+
`))?l="unchanged":(Hs(e,o),l="written")}let d=[],u=En(e),p=JSON.stringify(u);for(let{b:f,p:g,conflict:y}of Vp(s)){if(y){d.push(y);continue}let h=cx(e,f.files.get(g.entry),g.entry,n,r.overwrite===!0,i),S=h.reason===void 0?h:{...h,reason:le(h.reason,1/0)};d.push(S),(S.outcome==="imported"||S.outcome==="unchanged"&&!S.reason)&&(u[S.file]={revision:g.revision,from:{...tl(f.manifest),...f.manifest.shard?{shard:f.manifest.shard}:{}}})}for(let[f,g]of Object.entries(u)){let y;try{y=jt(ye.join(e,f))}catch{y=void 0}y!==g.revision&&delete u[f]}return JSON.stringify(u)!==p&&Ue(Dp(e),`${JSON.stringify(u,null,2)}
|
|
312
|
+
`),{bundles:s.map(f=>{let{runner:g,createdAt:y,shard:h}=f.manifest;return{source:f.source,runner:g,createdAt:y,origin:tl(f.manifest),...h?{shard:{index:h.index,total:h.total}}:{}}}),warnings:[...a],proposals:d,evidence:c,...l?{report:l}:{}}}async function Wp(e,t,n,r,s={}){let o=zp(await qp(n,()=>{throw new G("a viewed run is read from its downloaded folder")},s.describe)),{bundles:a,report:i,warnings:c,hint:l}=Hp(e,o,{run:s.run});Jp(t,a,i);let d=Vp(a).map(({b:u,p,conflict:f})=>{if(f)return{feature:f.feature,scenario:f.scenario,verified:!1,importable:!1,reason:f.reason};let g=Fp(e,u.files.get(p.entry),p.entry,r,l),y=g.verdict??Lp(g,!1),{feature:h,scenario:S}=g.shown,v={feature:h||(typeof p.feature=="string"?p.feature:""),scenario:S||(typeof p.scenario=="string"?p.scenario:""),verified:g.verified};return y?{...v,importable:!1,reason:le(y.reason??"already pending here",1/0)}:{...v,importable:!0}});return{report:i,warnings:[...c],proposals:d,summaryOnly:a.every(u=>u.manifest.summary===!0)}}var ux=/^\s*StepSet:/;function Kn(e,t){return $t.relative(e,t).split($t.sep).join("/")}function fx(e,t){let n={green:0,yellow:1,red:2};return!e||n[t]>n[e]?t:e}function Gs(e,t,n={}){let r=t.features??"features",s=$t.isAbsolute(r)?r:$t.join(e,r),o=$t.join(e,".saffron","reports","latest.json"),a=$t.join(e,".saffron","reports","latest.html"),i;try{i=JSON.parse(dn.readFileSync(o,"utf8"))}catch{i=void 0}let c=new Map;for(let R of i?.scenarios??[])c.set(R.feature,[...c.get(R.feature)??[],R]);let l=new Map,d;try{l=Vt(yn(s),e)}catch(R){d=R instanceof Error?R.message:String(R)}let u=Gt(s,Wt),p=[],f=new Map,g=new Map,y={parsedFiles:new Set,owned:new Set,unreadable:d?[d]:[]};for(let R of u){let k=Kn(e,R),C="";try{C=dn.readFileSync(R,"utf8")}catch(U){p.push({path:k,name:k,scenarios:[],stepSets:0,error:String(U)}),y.unreadable.push(`${k}: ${String(U)}`);continue}let P=C.split(`
|
|
313
|
+
`),w=P.filter(U=>ux.test(U)).length,E=P.find(U=>/^\s*Feature:/.test(U)),_=E?E.replace(/^\s*Feature:\s*/,"").trim():k,A;try{A=nt(R,e,l)}catch(U){p.push({path:k,name:_,scenarios:[],stepSets:w,error:d??(U instanceof Error?U.message:String(U))}),y.unreadable.push(`${k}: ${U instanceof Error?U.message:String(U)}`);continue}y.parsedFiles.add(R),g.set(R,A);let O=new Set(A.map(U=>U.name)),j=new Map;for(let U of(A[0]&&c.get(A[0].featurePath))??[]){let D=ur(U,q=>O.has(q));j.set(D,fx(j.get(D),U.status))}let L=new Map,I=new Map;for(let U of A){y.owned.add(vn(e,U.featurePath,U.displayName));let D=L.get(U.name);if(D){D.rows+=1;let M=I.get(U.name),B=M?ln(U,M):void 0;B!==void 0&&(D.refused??=B,D.refusedRows=(D.refusedRows??0)+1);for(let J of U.tags)D.tags.includes(J)||(D.tags.push(J),f.set(J,(f.get(J)??0)+1));continue}let q=pe(e,U.featurePath,U.name);y.owned.add(q),y.owned.add(dt(e,U.featurePath,U.name));let Y="missing",Q,N;if(dn.existsSync(q))try{let M=Ye(q);M&&I.set(U.name,M),N=M?ln(U,M):void 0,Y=M&&(Wn(U,M)||N!==void 0)?"valid":"stale"}catch(M){Y="invalid",Q=M instanceof ke?M.problem:M instanceof Error?M.message:String(M)}L.set(U.name,{name:U.name,line:U.line,tags:[...U.tags],outline:Object.keys(U.params).length>0,rows:1,cached:Y!=="missing",cacheState:Y,...Q?{cacheProblem:Q}:{},...N!==void 0?{refused:N,refusedRows:1}:{},proposal:dn.existsSync(dt(e,U.featurePath,U.name)),lastStatus:j.get(U.name)});for(let M of U.tags)f.set(M,(f.get(M)??0)+1)}p.push({path:k,name:_,scenarios:[...L.values()],stepSets:w})}let h=[],S=En(e),v=sn(e,(R,k)=>h.push({file:Kn(e,R),problem:k})).map(({file:R,proposal:k,revision:C})=>({file:Kn(e,R),feature:k.cache.feature,scenario:k.cache.scenario,mode:k.meta.mode,createdAt:k.meta.createdAt,verified:k.meta.verified,proofError:k.meta.proofError,stale:k.meta.bound?At(e,k,l):void 0,unbound:k.meta.bound?void 0:!0,revision:C,adaptations:k.meta.adaptations??[],narrative:k.meta.narrative,suggestedFeatureEdit:k.meta.suggestedFeatureEdit,recordedFor:k.meta.recordedFor,aiCalls:k.meta.usage?.aiCalls??0,costUsd:k.meta.usage&&Et({costUsd:k.meta.usage.costUsd??0,aiCalls:k.meta.usage.aiCalls})?k.meta.usage.costUsd:void 0,importedFrom:S[Kn(e,R)]?.revision===C?S[Kn(e,R)].from:void 0})).sort((R,k)=>R.file.localeCompare(k.file)),x;try{x=rn(e,r,l,g)}catch{x={steps:[],stepSets:[],scannedFiles:0,scannedCaches:0}}let b=hx(e),m=Fs(e,Math.max(100,n.historyLimit??30)),$=m.filter(R=>!R.partial).slice(-(n.historyLimit??30)).map(R=>({startedAt:R.startedAt,green:R.green,yellow:R.yellow,red:R.red,passRate:dr(R,R.scenarios),aiCalls:R.aiCalls,costUsd:Et(R)?R.costUsd:void 0})),T=$t.join(e,"saffron.config.json");return{tool:"saffron",version:ut(),projectRoot:e,packageInstalled:px(e),config:{file:dn.existsSync(T)?"saffron.config.json":void 0,effective:Ru(t)},featuresDir:($t.relative(e,s)||".").split($t.sep).join("/"),features:p,tags:[...f.entries()].map(([R,k])=>({tag:R,scenarios:k})).sort((R,k)=>R.tag.localeCompare(k.tag)),proposals:v,unreadableProposals:h,lastRun:i?{startedAt:i.startedAt,finishedAt:i.finishedAt,totals:{...i.totals,costUsd:Et(i.totals)?i.totals.costUsd:void 0},...i.interrupted?{interrupted:!0,notRun:i.notRun}:{},reportHtml:dn.existsSync(a)?Kn(e,a):void 0,...i.browsers?.length?{browsers:i.browsers}:{},attention:i.scenarios.filter(R=>R.status!=="green").map(R=>({feature:R.feature,scenario:R.scenario,baseScenario:ur(R,k=>p.some(C=>C.path===R.feature&&C.scenarios.some(P=>P.name===k))),status:R.status,...R.browser?{browser:R.browser}:{},error:R.status==="red"?R.error?.split(`
|
|
314
|
+
`)[0]:void 0,failedStep:(R.steps??[]).find(k=>k.status==="failed")?.gherkin??R.evidence?.find(k=>k.step)?.step,evidence:(R.evidence??[]).filter(k=>k.kind==="trace"?dn.existsSync($t.join(e,k.file)):qn(e,k)!==void 0).map(k=>({kind:k.kind,file:k.file,...k.step?{step:k.step}:{},...k.sha256?{sha256:k.sha256}:{},...k.proof===!0?{proof:!0}:{},...typeof k.session=="string"?{session:k.session}:{}}))})).sort((R,k)=>R.status===k.status?0:R.status==="red"?-1:1)}:void 0,history:$,quality:yp(p,m),vocabulary:{steps:x.steps.length,recorded:x.steps.filter(R=>R.status==="recorded").length,unrecorded:x.steps.filter(R=>R.status==="unrecorded").length,stepSets:x.stepSets.length,divergent:x.steps.filter(R=>R.status==="divergent").map(R=>R.text),duplicateWordings:b.slice(0,50)},data:(()=>{let R=it(),k=[],C=new Set;for(let[P,w]of g)for(let E of w)for(let _ of hn(at(E)))if(!C.has(_)){C.add(_);try{wo(_)}catch(A){k.push({ref:_,reason:A instanceof Error?A.message:String(A),feature:Kn(e,P),scenario:E.name})}}return{dir:Kn(e,R.dir),env:R.env,files:dn.existsSync(R.dir)?dn.readdirSync(R.dir).filter(P=>/\.(json|csv)$/.test(P)).sort():[],unresolved:k}})(),...(()=>{let R=qo(e,r,y),k=R.unreadable.length===0;return{orphans:k?R.orphans:[],orphanScan:{complete:k,errors:R.unreadable}}})()}}function px(e){for(let t=$t.resolve(e);;t=$t.dirname(t)){if(dn.existsSync($t.join(t,"node_modules","saffron-ai")))return!0;if($t.dirname(t)===t)return!1}}function Kp(e){let t=e.features.reduce((i,c)=>i+c.scenarios.length,0),n=e.features.reduce((i,c)=>i+c.scenarios.filter(l=>l.cacheState==="valid"&&l.refused===void 0).length,0),r=e.features.reduce((i,c)=>i+c.scenarios.filter(l=>l.refused!==void 0).length,0),s=e.features.reduce((i,c)=>i+c.scenarios.filter(l=>l.cacheState==="stale").length,0),o=e.features.reduce((i,c)=>i+c.scenarios.filter(l=>l.cacheState==="invalid").length,0);console.log(`saffron ${e.version} \xB7 ${e.features.length} feature file(s) \xB7 ${t} scenario(s), ${n} replay from cache`+(s?`, ${s} stale (\u26A0) and will re-record`:"")+(o?`, ${o} unreadable (\u26A0): fix the file or run with --rerecord`:"")+(r?`, ${r} refused (\u2717) by a recording bound to another Examples row`:""));for(let i of e.features){let c=i.scenarios.map(l=>l.proposal?"\u25D0":l.refused!==void 0?"\u2717":l.cacheState==="valid"?"\u25CF":l.cacheState==="missing"?"\u25CB":"\u26A0").join("");console.log(` ${i.path} ${c}${i.error?` \u2717 ${i.error.split(`
|
|
315
|
+
`)[0]}`:""}`)}if(e.tags.length&&console.log(`tags: ${e.tags.map(i=>`${i.tag} (${i.scenarios})`).join(", ")}`),console.log(e.proposals.length?`${e.proposals.length} proposal(s) pending review: ${e.proposals.map(i=>i.file).join(", ")}`:"no proposals pending review",...e.unreadableProposals.map(i=>`\u26A0 proposal ${i.file} cannot be read: ${i.problem}`),...e.features.flatMap(i=>i.scenarios.filter(c=>c.cacheProblem).map(c=>`\u26A0 recording of ${i.path} \u203A ${c.name} cannot be read: ${c.cacheProblem}`)),...e.features.flatMap(i=>i.scenarios.filter(c=>c.refused!==void 0).map(c=>`\u2717 ${i.path} \u203A ${c.name} is refused on ${c.rows>1?`${c.refusedRows??1} of its ${c.rows} rows`:"this row"}: ${c.refused}`))),e.lastRun){let i=e.lastRun.totals;console.log(`last run ${e.lastRun.finishedAt}: ${i.green} passed \xB7 ${i.yellow} pending review \xB7 ${i.red} failed \xB7 ${i.costUsd===void 0?"cost not reported":`$${i.costUsd.toFixed(2)}`}${e.lastRun.interrupted?` \xB7 interrupted, ${e.lastRun.notRun} not run`:""}`)}let a=e.vocabulary;console.log(`vocabulary: ${a.steps} steps (${a.recorded} recorded, ${a.unrecorded} unrecorded), ${a.stepSets} step sets, ${a.divergent.length} divergent, ${a.duplicateWordings.length} duplicate wording group(s)`),e.orphanScan.complete?e.orphans.length&&console.log(`${e.orphans.length} recording(s) belong to no scenario: run \`saffron prune\` to see them`):console.log(`orphaned recordings not checked: ${e.orphanScan.errors[0]}`),(e.data.files.length||e.data.unresolved.length)&&console.log(`test data: ${e.data.files.length} file(s) in ${e.data.dir}/${e.data.env?` \xB7 environment "${e.data.env}"`:""}`+(e.data.unresolved.length?` \xB7 ${e.data.unresolved.length} reference(s) do not resolve: ${e.data.unresolved.map(i=>`{data:${i.ref}}`).join(", ")}`:"")),console.log(`config: ${e.config.file??"(defaults, no saffron.config.json)"}`)}var gx=/^(<[^>]+>|\{env:[^}]+\}|\{date[^}]*\})$/;function Gp(e){return e?e.role?`${e.role}${e.name?` "${e.name}"`:e.nameRegex?` /${e.nameRegex}/`:""}`:e.label?`label "${e.label}"`:e.text?`text "${e.text}"`:e.testId?`testid ${e.testId}`:e.placeholder?`placeholder "${e.placeholder}"`:e.fallbackSelectors?.length?e.fallbackSelectors[0]:"":""}function hx(e){let t;try{t=nn(e)}catch{return[]}let n=new Map;for(let r of t.steps.values()){if(r.actions.length===0)continue;let s=me(r.gherkin),o=jo(s).pattern,a=[...s.matchAll(/"([^"]*)"/g)].map(p=>p[1]),i=p=>p!==void 0&&(a.includes(p)||gx.test(p))?"\xABarg\xBB":p,c=r.actions.map(p=>{let{pageFingerprint:f,value:g,promptText:y,...h}=p;return{...h,value:i(g),promptText:i(y)}}),l=JSON.stringify(c),d=r.actions.map(p=>`${p.action}${Gp(p.target)?` ${Gp(p.target)}`:p.url?` ${p.url}`:""}`).join(" \xB7 "),u=n.get(l)??{steps:new Map,actions:d};u.steps.has(o)||u.steps.set(o,r.gherkin),n.set(l,u)}return[...n.values()].filter(r=>r.steps.size>1).map(r=>({steps:[...r.steps.values()].sort(),actions:r.actions})).sort((r,s)=>s.steps.length-r.steps.length||r.steps[0].localeCompare(s.steps[0]))}async function Yp(e,t){let n=new mx({name:"saffron",version:ut()},{capabilities:{tools:{}}});n.setRequestHandler(bx,async()=>({tools:[{name:"search_steps",description:"Search the project's step vocabulary. Returns known Gherkin steps with status (recorded = replays at zero tokens, divergent, unrecorded), usage counts, and source files. ALWAYS reuse an existing wording exactly instead of inventing a near-duplicate: exact step text is the replay-cache identity, so a new wording costs a fresh AI recording.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Case-insensitive substring filter over step text; omit to list everything."}}}},{name:"list_step_sets",description:"List the project's StepSet definitions (named reusable step sequences from .saffron files) with their steps, defining file, and usage. Invoke one inside a scenario with a line reading exactly: StepSet <name>",inputSchema:{type:"object",properties:{}}},{name:"project_status",description:"The project overview (same data as `saffron status --json`): every feature file with its scenarios (header line, tags, outline rows, cached / proposal pending / last run status), the tag list, pending proposals with narrative and proof-replay verdict (and, for one imported from CI with `saffron import`, the run, branch and commit it came from, as importedFrom), the last run's totals, run history, vocabulary health (divergent steps, duplicate wordings proven by identical recordings) and the effective config. Call it before editing tests to see what is already recorded and what awaits review. Other scenarios reuse only accepted recordings, never a pending proposal's steps: accept a shared setup before recording more scenarios that use it.",inputSchema:{type:"object",properties:{}}}]})),n.setRequestHandler(yx,async r=>xx(r.params.name,r.params.arguments,e)),await n.connect(new wx)}function xx(e,t,n){let r=a=>({content:[{type:"text",text:JSON.stringify(a,null,2)}]}),s=_e(n),o=s.features??Fr.features;if(e==="search_steps"){let a=rn(n,o),i=typeof t?.query=="string"?t.query:void 0,c=i?Mo(a,i):a;return r({steps:c.steps.map(({sessions:l,recordings:d,...u})=>u),scannedFiles:c.scannedFiles,scannedCaches:c.scannedCaches})}if(e==="list_step_sets"){let a=rn(n,o);return r({stepSets:a.stepSets})}return e==="project_status"?r(Gs(n,s)):{content:[{type:"text",text:`Unknown tool: ${e}`}],isError:!0}}import{query as vx}from"@anthropic-ai/claude-agent-sdk";function Zp(e,t){let n=t.steps.map(s=>`- [${s.status}] ${s.keyword} ${s.text}`).join(`
|
|
299
316
|
`),r=t.stepSets.map(s=>`- StepSet ${s.name}
|
|
300
317
|
${s.steps.map(o=>` ${o}`).join(`
|
|
301
318
|
`)}`).join(`
|
|
302
319
|
`);return["Draft a Saffron feature file from the requirements below.","","EXISTING STEP VOCABULARY \u2014 reuse these wordings EXACTLY (character for character) wherever they express what a step needs to do. Steps marked [recorded] or [divergent] already have replay recordings: reusing them makes the new file replay almost for free. Only invent a new wording when nothing in the vocabulary expresses the intent, and then follow the same style:",n.length>0?n:"(none yet \u2014 this is the project's first file)","",t.stepSets.length>0?`EXISTING STEP SETS \u2014 for .saffron output, invoke with a line reading exactly \`StepSet <name>\` instead of repeating their steps:
|
|
303
320
|
${r}`:void 0,"","RULES:","1. Output ONLY the feature file content \u2014 no prose, no code fences, no explanations.","2. Gherkin/.saffron syntax: Feature:, Scenario:, Scenario Outline: + Examples, Given/When/Then/And/But. Prefer concrete scenarios; use an Outline only when the requirements list variations of the same flow.","3. Then steps are assertions \u2014 state exactly what must be true, one condition per step. End every scenario with at least one Then.","4. In .saffron, reuse a StepSet for a repeated flow (first step a guard, last step an exit assertion). Definition uses a colon (StepSet: Name), invocation does not (StepSet Name). If the requirements request .feature, use standard Gherkin without StepSets or file-backed Examples.",'5. Use 2-column data tables for key/value input, header tables for lists of records, and """ doc strings for free text.',"6. Steps are natural language for an AI browser agent \u2014 never CSS selectors or code.","7. One independently testable behavior per scenario and one clear intent per step; keep necessary setup and waits without a fixed step-count limit. When translating existing tests, preserve intended coverage but split independent changes. Do not assume every intermediate value must differ from every earlier value.",'8. Name every captured value explicitly, e.g. I record the displayed price for the selected date as "beforePrice", then the displayed price for the selected date should differ from "beforePrice". Reuse that exact name; never say only "the price I noted". Capture before the change, compare the same target afterwards, and never recreate the baseline or change application state inside a final assertion.','9. Captures store text, not parsed numbers. For an amount change, capture amount-only text rather than a whole label containing currency, date or guest count. Calling a capture "numeric" does not enable arithmetic.',"10. Use observable waits from the supplied evidence: the relevant UI state or API response, not a fixed sleep or an unspecified 'finished loading'. Distinguish a selector's option code (GBP) from the price's display symbol (\xA3); selecting a currency alone does not prove prices refreshed.","11. Use {env:VAR} for secrets, existing {data:file.key} references for shared data, and named captures for changing display values. Establish the relevant starting state and document required fixtures. Do not invent data-file keys or application behavior.","12. This is a draft-only call with no browser inspection or execution. Use supplied observations and vocabulary; flag missing UI evidence, prerequisites, or uncertain expectations in Gherkin comments for inspection before recording. Never claim the draft was inspected, recorded, verified, or passed. Completion requires targeted recording, review of verified proposals for faithful assertions, acceptance, and replay with --no-agent; those happen after this call.","","REQUIREMENTS:",e.trim()].filter(s=>s!==void 0).join(`
|
|
304
|
-
`)}var
|
|
305
|
-
`}import
|
|
306
|
-
${o.name}`,r=new Set(e.map(n)),s=new Set(e);return[...e,...t.filter(o=>!s.has(o)&&r.has(n(o)))]}function
|
|
321
|
+
`)}var Qp="You are Saffron's feature-file author. You write clean, assertive Gherkin that reuses the project's exact step vocabulary. You output only file content.";async function eg(e,t,n,r){let s={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0},o="";if(r)return await r({systemPrompt:Qp,prompt:Zp(e,t),model:n,maxTurns:1,mcpServers:{},mcpToken:"",usage:s,lastOutput:i=>{o=i},finished:()=>!1}),{content:Xp(o),usage:s};let a=vx({prompt:Zp(e,t),options:{model:n,maxTurns:1,tools:[],persistSession:!1,settingSources:[],strictMcpConfig:!0,settings:{disableClaudeAiConnectors:!0},allowedTools:[],systemPrompt:Qp}});for await(let i of a)if(i.type==="assistant")for(let c of i.message.content)c.type==="text"&&(o+=c.text);else i.type==="result"&&(s.aiCalls=i.num_turns,s.costUsd=i.total_cost_usd,"usage"in i&&i.usage&&(s.inputTokens=i.usage.input_tokens??0,s.outputTokens=i.usage.output_tokens??0,s.cacheReadTokens=i.usage.cache_read_input_tokens??0,s.cacheCreationTokens=i.usage.cache_creation_input_tokens??0));return{content:Xp(o),usage:s}}function Xp(e){return e.replace(/^\s*```(?:gherkin|saffron)?\s*\n/,"").replace(/\n```\s*$/,"").trim()+`
|
|
322
|
+
`}import Lt from"node:fs";import{fileURLToPath as Yn,pathToFileURL as cl}from"node:url";import Ce from"node:path";import{createConnection as Ax,ProposedFeatures as Ex,TextDocuments as Ox,TextDocumentSyncKind as _x,DidChangeWatchedFilesNotification as Cx,WatchKind as Px,CompletionItemKind as Zn,InsertTextFormat as lg,DiagnosticSeverity as es,MarkupKind as dg}from"vscode-languageserver/node";import{TextDocument as Ix}from"vscode-languageserver-textdocument";import{createRequire as jx}from"node:module";import tg from"node:path";var Ks=class extends Error{},il=new Set(["and","or","not","(",")"]);function Sx(e){let t=[...e.matchAll(/[(),|]|[^\s(),|]+(?:\([^\s(),|]*\))*/g)].flatMap(([s])=>{let o=/^(and|or|not)\((.*)\)$/i.exec(s);return o?[o[1],"(",o[2],")"].filter(Boolean):[s]}),n=s=>s===","||s==="|",r=[];return t.forEach((s,o)=>{let a=r.at(-1),i=t[o+1];n(s)&&(a===void 0||n(a)||a==="("||i===void 0||n(i)||i===")")||r.push(s)}),r.map(s=>n(s)?"or":il.has(s.toLowerCase())?s.toLowerCase():s.startsWith("@")?s:`@${s}`)}function $x(e){let t=Sx(e),n=0,r=()=>t[n],s=d=>{throw new Ks(`--filter "${e}": ${d}`)},o=!t.some(d=>d==="and"||d==="not"||d==="("||d===")"),a=()=>{let d=i();for(;r()==="or"||o&&r()!==void 0&&r()!==")";){r()==="or"&&n++;let u=i(),p=d;d=f=>p(f)||u(f)}return d},i=()=>{let d=c();for(;r()==="and";){n++;let u=c(),p=d;d=f=>p(f)&&u(f)}return d},c=()=>{let d=r();if(d===void 0)return s("expected a tag at the end");if(d==="not"){n++;let u=c();return p=>!u(p)}if(d==="("){n++;let u=a();return r()!==")"?s("missing a closing parenthesis"):(n++,u)}return il.has(d)?s(`expected a tag, found "${d}"`):(n++,u=>u.has(d))},l=a();return n<t.length?s(il.has(t[n])?`unexpected "${t[n]}"`:`unexpected "${t[n]}": with and, not or parentheses, join every tag with and/or`):l}function ng(e){let t=(e===void 0?[]:Array.isArray(e)?e:[e]).map(r=>r.trim()).filter(Boolean);if(t.length===0)return;let n=t.map($x);return{text:t.length===1?t[0]:t.map(r=>`(${r})`).join(" or "),matches:r=>{let s=new Set(r);return n.some(o=>o(s))}}}function rg(e,t){return t?e.filter(n=>t.matches(n.tags)):e}function sg(e,t){return[...t??[],e]}var kx=new RegExp(`^(.+?(?:${xa.map(e=>e.replace(".","\\.")).join("|")})):(.+)$`),al=/^\d+(?::\d+)*$/;function og(e){let t=[],n=new Map;for(let r of e){let s=kx.exec(r);if(!s){t.push(r);continue}let o=al.test(s[2])?s[2].split(":").map(Number):[s[2]];n.set(s[1],[...n.get(s[1])??[],...o])}return{plain:t,picks:n}}var wr=class extends Error{};function ig(e,t){let n=o=>`${o.featurePath}
|
|
323
|
+
${o.name}`,r=new Set(e.map(n)),s=new Set(e);return[...e,...t.filter(o=>!s.has(o)&&r.has(n(o)))]}function ag(e){let t=e.length>10?[...e.slice(0,10),`\u2026 (${e.length} in all)`]:e;return t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`}function Rx(e,t,n,r){let s=n.filter(c=>c.kind==="scenario").map(c=>String(c.line)),o=s.length===0?" It has no scenarios.":` Its scenario${s.length===1?" starts at line":"s start at lines"} ${ag(s)}.`,a=c=>{throw new wr(`${e}:${t} ${c}.${o}`)};t<1&&a("is not a line: lines count from 1"),t>r&&a(`is past the end of the file, which has ${r} lines`);let i=n.filter(c=>c.start<=t).at(-1);return i?(i.kind==="background"&&a("is in the Background, which runs before every scenario, not in a scenario"),i.kind==="stepSet"&&a(`is in StepSet "${i.name}", which runs where a scenario invokes it, not in a scenario`),i.kind==="rule"&&a(`is the header of Rule "${i.name}", not a scenario`),{line:i.rows.includes(t)?t:i.line,block:i}):a("is in the feature's header, not in a scenario")}function Tx(e,t,n){let r=n.filter(a=>a.kind==="scenario"),s=r.find(a=>a.name===t);if(s)return{line:s.line,block:s};let o=r.map(a=>`"${a.name}"`);throw new wr(`${e}:${t} names no scenario.${o.length===0?" It has no scenarios.":` Its scenario${o.length===1?" is":"s are"} ${ag(o)}.`}`)}function cg(e,t,n,r){let s=new Map,o=new Map;for(let[i,c]of n){let l=tg.resolve(t,i);if(r.has(l))continue;let{blocks:d,lineCount:u}=Od(l,t),p=tg.relative(t,l),f=s.get(p)??new Map;for(let g of c){if(typeof g=="string"&&!d.some(v=>v.kind==="scenario"&&v.name===g)&&e.some(v=>v.featurePath===p&&v.displayName===g)){o.set(p,(o.get(p)??new Set).add(g));continue}let{line:h,block:S}=typeof g=="number"?Rx(i,g,d,u):Tx(i,g,d);f.set(h,`${i}:${g} is in Scenario Outline "${S.name}", whose Examples have no rows yet: nothing to run`)}s.set(p,f)}let a=e.filter(i=>{let c=s.get(i.featurePath);return!c||c.has(i.line??0)||c.has(i.exampleLine??0)||o.get(i.featurePath)?.has(i.displayName)===!0});for(let[i,c]of s)for(let[l,d]of c)if(!a.some(u=>u.featurePath===i&&(u.line===l||u.exampleLine===l)))throw new wr(`${d}.`);return a}var ug=/^(\s*)(Given|When|Then|And|But|\*)\s+(.+?)\s*$/,Nx=/^\s*StepSet:\s*(.+?)\s*$/,ll=/^(\s*)(StepSet)\s+([^\s:].*?)\s*$/,dl={recorded:"\u25CF recorded: replays at zero tokens",divergent:"\u25CF divergent: same text, different recordings",unrecorded:"\u25CB written, not recorded yet"};function Mx(e,t){let n=a=>new Set(a.toLowerCase().replace(/"[^"]*"/g,'"x"').split(/[^a-z0-9"<>]+/).filter(Boolean)),r=n(e),s=n(t);if(r.size===0||s.size===0)return 0;let o=0;for(let a of r)s.has(a)&&o++;return o/(r.size+s.size-o)}function fg(e){try{return JSON.parse(Lt.readFileSync(Ce.join(e,"saffron.config.json"),"utf8"))}catch{return{}}}function pg(e){try{let t=JSON.parse(Lt.readFileSync(Ce.join(e,"saffron.config.json"),"utf8"));return typeof t.features=="string"&&t.features.trim()!==""?t.features:void 0}catch{return}}function Xr(e,t){let n=Ce.dirname(e),r=Ce.resolve(t);for(;;){if(Lt.existsSync(Ce.join(n,"saffron.config.json")))return n;if(n===r||Ce.dirname(n)===n)return t;n=Ce.dirname(n)}}function Ys(e,t,n){return e.recordings?e.recordings[Sn(tt([t],n)[0],t)]??"unrecorded":t===e.text?e.status:e.sessions?.[t]??"unrecorded"}function Dx(e,t,n){return`${dl[Ys(e,t,n)]}
|
|
307
324
|
|
|
308
325
|
Used in ${e.usage} place(s): ${e.files.join(", ")}${e.fromStepSet?`
|
|
309
326
|
|
|
310
|
-
Defined in StepSet **${e.fromStepSet}**`:""}`}function
|
|
311
|
-
`),P=[...
|
|
312
|
-
`),
|
|
313
|
-
`),
|
|
314
|
-
`);return{contents:{kind:
|
|
327
|
+
Defined in StepSet **${e.fromStepSet}**`:""}`}function bg(e,t,n={}){let r=e,s=t,o=e,a=!1,i=!1,c=k=>{if(!k.startsWith("file:"))return;let C=Xr(Yn(k),o);if(C===r)return;v(C);let P=h.get(C);if(!P||!a||S.has(C))return b();({vocab:f,registry:g,files:y}=P);for(let w of p.all())d(w)&&R(w)},l=k=>{if(!k.startsWith("file:"))return;let C=Yn(k),P=Xr(C,o);h.get(P)?.files.has(C)||S.add(P)},d=k=>!k.uri.startsWith("file:")||Xr(Yn(k.uri),o)===r,u=Ax(Ex.all,process.stdin,process.stdout),p=new Ox(Ix),f={steps:[],stepSets:[],scannedFiles:0,scannedCaches:0},g=new Map,y=new Set,h=new Map,S=new Set,v=k=>{r=k,s=pg(k)??(Lt.existsSync(Ce.join(k,"saffron.config.json"))?"features":t);try{let C=fg(k);Ut(k,C.dataDir,gg(k,C.env))}catch(C){u.console.warn(`saffron vocabulary rebuild: ${String(C)}`)}},x,b=()=>{try{let k=Ce.isAbsolute(s)?s:Ce.join(r,s),C=fg(r);Ut(r,C.dataDir,gg(r,C.env)),g=Vt(yn(k),r),f=rn(r,s,g),y=new Set(La(k)),h.set(r,{vocab:f,registry:g,files:y}),S.delete(r)}catch(k){u.console.warn(`saffron vocabulary rebuild: ${String(k)}`),{vocab:f,registry:g,files:y}=h.get(r)??{vocab:{steps:[],stepSets:[],scannedFiles:0,scannedCaches:0},registry:new Map,files:new Set}}for(let k of p.all())d(k)&&R(k)},m=()=>{clearTimeout(x),x=setTimeout(()=>{let k=r,C=new Set(p.all().filter(P=>P.uri.startsWith("file:")).map(P=>Xr(Yn(P.uri),o)));for(let P of h.keys())!C.has(P)&&P!==k&&h.delete(P);C.delete(k);for(let P of[...C,k])v(P),b()},300)};function $(k){let C=me(k);return f.steps.find(P=>P.text===C)}function T(k,C){let P=$(k);return P&&Ys(P,k,C)}function R(k){let C=k.getText().split(`
|
|
328
|
+
`),P=[...qx(C),...Hx(C)];if(!k.uri.endsWith(".saffron")){u.sendDiagnostics({uri:k.uri,diagnostics:P});return}let w=$o(C,f.stepSets,new Set(gs(k.getText()).map(_=>_.line-1))),E=new Map;for(let _=0;_<C.length;_++){let A=C[_],O={start:{line:_,character:0},end:{line:_,character:A.length}},j=A.match(ll);j&&!g.has(j[3])&&P.push({range:O,severity:es.Error,source:"saffron",message:`StepSet "${j[3]}" is not defined anywhere in the project.`});let L=A.match(Nx);if(L){let D=g.get(L[1]),q=Ce.relative(r,Yn(k.uri)).replace(/\\/g,"/");(E.has(L[1])||D&&D.file.replace(/\\/g,"/")!==q)&&P.push({range:O,severity:es.Error,source:"saffron",message:`StepSet "${L[1]}" is defined twice. Set names are project-wide. If this line was meant to INVOKE the set, remove the colon: "StepSet ${L[1]}".`}),E.set(L[1],_)}let I=A.trim();if(I&&!j&&!L){for(let[D]of g)if(I.toLowerCase()===D.toLowerCase()){P.push({range:O,severity:es.Warning,source:"saffron",message:`Did you mean "StepSet ${D}"? Invoking a step set needs the StepSet keyword, like a step needs Given/When/Then.`});break}}let U=A.match(ug);if(U&&T(U[3],w[_])!=="recorded"){let D=me(U[3]);for(let q of f.steps)if(!(q.text===D||Ys(q,q.text,w[_])==="unrecorded")&&Mx(q.text,D)>=.7){P.push({range:{start:{line:_,character:A.indexOf(U[3])},end:{line:_,character:A.length}},severity:es.Information,source:"saffron",message:`Similar to the ${Ys(q,q.text,w[_])} step "${q.text}" (\xD7${q.usage}). Reusing the exact wording replays at zero tokens; a new wording costs a fresh AI recording.`});break}}}u.sendDiagnostics({uri:k.uri,diagnostics:P})}u.onInitialize(k=>{if(n.rootFromClient){let C=k.workspaceFolders?.[0]?.uri??k.rootUri??void 0;if(C&&C.startsWith("file:")){let P=Yn(C);Lt.existsSync(P)&&(o=r=P,s=pg(P)??t)}}return a=k.capabilities.workspace?.didChangeWatchedFiles?.dynamicRegistration===!0,i=k.initializationOptions?.runLenses===!0,b(),{capabilities:{textDocumentSync:_x.Incremental,completionProvider:{triggerCharacters:[" ",":","."]},definitionProvider:!0,hoverProvider:!0,...i?{codeLensProvider:{resolveProvider:!1}}:{}}}}),u.onCodeLens(k=>{let C=p.get(k.textDocument.uri);if(!i||!C||!C.uri.startsWith("file:"))return[];let P=Yn(C.uri),w=Lx(P,o);return w?!P.endsWith(".saffron")&&!Lt.existsSync(Ce.join(w,"saffron.config.json"))?[]:Bx(P,C.getText(),w):[]}),u.onInitialized(()=>{if(!a)return;let k=[...["**/*.saffron","**/*.feature","**/saffron.config.json","**/.saffron/cache/**","**/data/**"].map(C=>({globPattern:C})),{globPattern:"**",kind:Px.Delete}];u.client.register(Cx.type,{watchers:k}).catch(()=>{a=!1})}),u.onCompletion(k=>{let C=p.get(k.textDocument.uri);if(!C)return[];c(C.uri);let P=C.getText({start:{line:k.position.line,character:0},end:k.position}),w=Jx(P);if(w)return w;let E=C.getText({start:k.position,end:{line:k.position.line+1,character:0}}).replace(/\r?\n$/,"");return Vx(C.uri,P,k.position.line,f,E,$o(C.getText().split(`
|
|
329
|
+
`),f.stepSets,new Set(gs(C.getText()).map(_=>_.line-1)))[k.position.line])}),u.onDefinition(k=>{let C=p.get(k.textDocument.uri);if(!C)return;c(C.uri);let P=C.getText({start:{line:k.position.line,character:0},end:{line:k.position.line+1,character:0}}).replace(/\n$/,""),w=hg(P,k.position.character);if(w){let j=zx(w.ref);return j?{uri:cl(j.file).href,range:{start:{line:j.line,character:0},end:{line:j.line,character:0}}}:void 0}let E=wg(P,k.position.character);if(E){let j=yg(r,E.name);return j?{uri:cl(j.file).href,range:{start:{line:j.line,character:0},end:{line:j.line,character:0}}}:void 0}let _=P.match(ll);if(!_)return;let A=g.get(_[3]);return A?{uri:cl(Ce.join(r,A.file)).href,range:{start:{line:A.line-1,character:0},end:{line:A.line-1,character:0}}}:void 0}),u.onHover(k=>{let C=p.get(k.textDocument.uri);if(!C)return;c(C.uri);{let A=C.getText({start:{line:k.position.line,character:0},end:{line:k.position.line+1,character:0}}).replace(/\n$/,""),O=hg(A,k.position.character);if(O)return{contents:{kind:"markdown",value:xg(O.ref)}};let j=wg(A,k.position.character);if(j){let L=yg(r,j.name),I=L?`defined in ${Ce.relative(r,L.file)} (line ${L.line+1}); the value is resolved at replay and never shown here`:"not found in .env or .env.example; export it in the shell or add it to a git-ignored .env";return{contents:{kind:"markdown",value:`**{env:${j.name}}** ${I}.`}}}}let P=C.getText({start:{line:k.position.line,character:0},end:{line:k.position.line+1,character:0}}).replace(/\n$/,""),w=$o(C.getText().split(`
|
|
330
|
+
`),f.stepSets,new Set(gs(C.getText()).map(A=>A.line-1)))[k.position.line],E=P.match(ll);if(E){let A=f.stepSets.find(L=>L.name===E[3]);if(!A)return;let O=tt(A.steps,w),j=A.steps.map((L,I)=>`- ${dl[T(L,O[I])??"unrecorded"][0]} ${L}`).join(`
|
|
331
|
+
`);return{contents:{kind:dg.Markdown,value:`**StepSet ${A.name}** expands to:
|
|
315
332
|
|
|
316
|
-
${
|
|
317
|
-
`),
|
|
318
|
-
`))?.[1]??"en",s=
|
|
319
|
-
`).findIndex(a=>new RegExp(`^\\s*(?:export\\s+)?${t}\\s*=`).test(a));if(o!==-1)return{file:r,line:o}}}function
|
|
320
|
-
`)}));let d=/^\s*(?:Given|When|Then|And|But|\*)\s+(As "[^"]+"\s+)?/,
|
|
333
|
+
${j}`}}}let _=P.match(ug);if(_){let A=$(_[3]);return A?{contents:{kind:dg.Markdown,value:Dx(A,_[3],w)}}:void 0}}),p.onDidOpen(k=>{if(l(k.document.uri),k.document.uri.startsWith("file:")){let C=Yn(k.document.uri);Xr(C,o)===r&&!y.has(C)&&m()}c(k.document.uri),R(k.document)}),p.onDidClose(k=>l(k.document.uri)),p.onDidChangeContent(k=>{c(k.document.uri),R(k.document)}),p.onDidSave(()=>m()),u.onDidChangeWatchedFiles(()=>m()),p.listen(u),u.listen()}var Fx="saffron.runScenario";function Lx(e,t){let n=Xr(e,t),r=Ce.relative(Ce.resolve(t),n);return r.split(/[\\/]/)[0]===".."||Ce.isAbsolute(r)?void 0:n}function Bx(e,t,n){let r=Ce.relative(n,e).split(Ce.sep).join("/");if(r.startsWith("../")||Ce.isAbsolute(r))return[];let s=gs(t);return s.flatMap(({line:o,name:a})=>{let i={start:{line:o-1,character:0},end:{line:o-1,character:0}},c=s.filter(d=>d.name===a).length>1,l=(d,u)=>{let p=a&&!al.test(a)&&!c?`${r}:${a}`:`${r}:${o}`;return{range:i,command:{title:d,command:Fx,arguments:[{root:n,target:p,scenario:a,mode:u}]}}};return[l("\u25B6 Run scenario","run"),l("Replay only","replay"),l("Headed","headed")]})}function gg(e,t){return process.env.SAFFRON_ENV??ma(e).SAFFRON_ENV??t}function hg(e,t){let n=/\{data:([A-Za-z0-9_.-]+)\}/g,r;for(;r=n.exec(e);)if(t>=r.index&&t<=r.index+r[0].length)return{ref:r[1],start:r.index,end:r.index+r[0].length}}var Ux=e=>/^\s*Examples:/.test(e);function xg(e,t=!1){let{env:n}=it(),r=n?` (environment "${n}")`:"";try{if(t||!e.includes(".")){let{headers:a,rows:i}=yo(e);return`**{data:${e}}** ${i.length} Examples row(s), columns ${a.map(c=>`\`${c}\``).join(", ")}${r}.`}let s=en(e);return Array.isArray(er(e))?`**{data:${e}}** a list of ${s.length}: ${s.map(a=>`"${a}"`).join(", ")}${r}. Use it with "every": replay checks each value, so adding one needs no re-record.`:`**{data:${e}}** = "${s[0]}"${r}. Resolved at replay: change the file and the next run uses the new value at zero tokens.`}catch(s){return`**{data:${e}}** does not resolve: ${s instanceof Error?s.message:String(s)}`}}function zx(e){let{dir:t,env:n}=it(),[r,...s]=e.split("."),o=[n&&`${r}.${n}.json`,`${r}.json`,n&&`${r}.${n}.csv`,`${r}.csv`].filter(Boolean),a=[...s].reverse().find(c=>!/^\d+$/.test(c)),i;for(let c of o){let l=Ce.join(t,c);if(!Lt.existsSync(l))continue;let d=Lt.readFileSync(l,"utf8").split(`
|
|
334
|
+
`),u=a?d.findIndex(p=>p.includes(`"${a}"`)):0;if(u>=0)return{file:l,line:u};i??={file:l,line:0}}return i}function qx(e){let t=[];return e.forEach((n,r)=>{for(let s of n.matchAll(/\{data:([A-Za-z0-9_.-]+)\}/g)){let o=xg(s[1],Ux(n));o.includes("does not resolve")&&t.push({range:{start:{line:r,character:s.index??0},end:{line:r,character:(s.index??0)+s[0].length}},severity:es.Error,source:"saffron",message:o.replace(/\*\*/g,"")})}}),t}var mg=jx(import.meta.url)("@cucumber/gherkin").dialects;function Hx(e){let t,n=e.map(i=>{let c=/^\s*("""|```)/.exec(i)?.[1];return c&&(t===void 0||t===c)?(t=t===void 0?c:void 0,!0):t!==void 0}),r=/^\s*#\s*language:\s*(\S+)/m.exec(e.slice(0,5).join(`
|
|
335
|
+
`))?.[1]??"en",s=mg[r]??mg.en,o=[...s.given,...s.when,...s.then,...s.and,...s.but],a=(i,c)=>n[c]||/^\s*\|/.test(i)||o.some(l=>i.trimStart().startsWith(l));return e.flatMap((i,c)=>a(i,c)?[...i.matchAll(ka)].flatMap(l=>{let d=Eo(l[0]),u=l.index??0;return d?[{range:{start:{line:c,character:u},end:{line:c,character:u+l[0].length}},severity:es.Error,source:"saffron",message:d}]:[]}):[])}function Jx(e){let t=e.match(/\{data:([A-Za-z0-9_.-]*)$/);if(!t)return;let n=t[1],{dir:r}=it(),s=n.split(".");if(s.length===1)return(Lt.existsSync(r)?[...new Set(Lt.readdirSync(r).filter(a=>/\.(json|csv)$/.test(a)).map(a=>a.split(".")[0]))].sort():[]).map(a=>({label:a,kind:Zn.File,detail:"data file",insertText:a}));try{let o=er(s.slice(0,-1).join("."));return o===null||typeof o!="object"?[]:Object.entries(o).map(([a,i])=>({label:a,kind:i!==null&&typeof i=="object"?Zn.Module:Zn.Value,detail:Array.isArray(i)?`list of ${i.length}`:i!==null&&typeof i=="object"?"object":JSON.stringify(i),insertText:a}))}catch{return[]}}function wg(e,t){let n=/\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g,r;for(;r=n.exec(e);)if(t>=r.index&&t<=r.index+r[0].length)return{name:r[1],start:r.index,end:r.index+r[0].length}}function yg(e,t){for(let n of[".env",".env.example"]){let r=Ce.join(e,n);if(!Lt.existsSync(r))continue;let o=Lt.readFileSync(r,"utf8").split(`
|
|
336
|
+
`).findIndex(a=>new RegExp(`^\\s*(?:export\\s+)?${t}\\s*=`).test(a));if(o!==-1)return{file:r,line:o}}}function Vx(e,t,n,r,s="",o){let a=e.endsWith(".saffron"),i=t.length+s.trimEnd().length,c=g=>({start:{line:n,character:g},end:{line:n,character:i}}),l=/^\s*StepSet\s+/.exec(t);if(l&&a)return r.stepSets.map(g=>({textEdit:{range:c(l[0].length),newText:g.name},label:g.name,kind:Zn.Function,detail:`step set \xB7 ${g.steps.length} step(s) \xB7 \xD7${g.usage}`,documentation:g.steps.join(`
|
|
337
|
+
`)}));let d=/^\s*(?:Given|When|Then|And|But|\*)\s+(As "[^"]+"\s+)?/,u=d.test(t)?d.exec(t+s):null;if(u&&u[0].length>t.length)return[];if(u)return r.steps.map((g,y)=>({textEdit:{range:c(u[0].length),newText:g.text},label:g.text,kind:Zn.Text,detail:`${dl[Ys(g,`${u[1]??""}${g.text}`,o)]} \xB7 \xD7${g.usage}`,sortText:String(y).padStart(5,"0"),filterText:g.text}));let f=t.replace(/^\s*/,"").trimEnd().toLowerCase().replace(/\s+/g,"");if(f.length>0&&("stepset:".startsWith(f)||f.startsWith("stepset"))&&a){let g={start:{line:n,character:t.length-t.replace(/^\s*/,"").length},end:{line:n,character:t.length}},y=[{label:"StepSet: \u2026",kind:Zn.Keyword,detail:"define a reusable step set",documentation:`StepSet: Name
|
|
321
338
|
Given \u2026
|
|
322
339
|
When \u2026
|
|
323
340
|
|
|
324
|
-
Invoke it anywhere with: StepSet Name`,filterText:"step set stepset:",sortText:"0",insertTextFormat:
|
|
325
|
-
`),filterText:`step set ${
|
|
326
|
-
`)
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
`);
|
|
331
|
-
`)){let c=Cb(i.trim(),t);c&&s.push(c)}}return Ib(s)}function Ib(e){return e.filter((t,n)=>{let r=e[n+1];return!(t.action==="fill"&&(t.value??"")===""&&r?.action==="fill"&&JSON.stringify(r.target)===JSON.stringify(t.target))})}function _p(e){let t=[];for(let n of e){if(n.kind==="assertion"&&n.actions.length===0){t.push(`Step "${n.gherkin}" is an assertion but recorded no check, so nothing would be verified. Re-record with: saffron run --rerecord`);continue}let r=fe(n.gherkin),s=r.replace(/"[^"]*"|<[^<>]+>/g," "),o=/\b(?:clear|clears|clearing|erase|erases|wipe|wipes)\b/i.test(s)||/(?<!\b(?:the|is|are)\s+)\b(?:empty|empties|blank)\b/i.test(s);if(!/"[^"]+"|<[^<>]+>/.test(r)||o)continue;n.actions.filter(i=>i.action==="fill"&&(i.value??"")==="").length>(r.match(/""/g)??[]).length&&t.push(`Step "${n.gherkin}" recorded a fill with an empty value although the step passes one; the typed value was lost. Re-record with: saffron run --rerecord`)}return t}function Op(e,t,n=ue.pattern){for(let[r,s]of t){let o=bd(e,n(s));if(o)return o==="bare"?`<${r}>`:`^<${r}>$`}}function zr(e,t,n=o=>o,r=!1,s=Object.keys(t)){let o=Object.entries(t).filter(([,i])=>i.length>=3);if(!r)return ni(e,o,i=>new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),n,s);let a=o.find(([,i])=>!da(i)&&e===n(i));return a?`<${a[0]}>`:ni(e,o.filter(([,i])=>da(i)),i=>xe(i,"gu"),n,s)}function ni(e,t,n,r=o=>o,s=t.map(([o])=>o)){let o=new RegExp(`(${Qn(s).source}|\\{(?:env|data|unique|date)[^{}<]*<[^{}]*\\})`);return[...t].sort((a,i)=>i[1].length-a[1].length).reduce((a,[i,c])=>a.split(o).map((l,d)=>{if(d%2)return l;let f=l.normalize("NFC"),p=f.replace(n(r(c).normalize("NFC"),c),()=>`<${i}>`);return p===f?l:p}).join(""),e)}function Nb(e,t,n){if(/^\s*(?:xpath=|\/\/)/.test(e))return e.replace(/'([^']*)'|"([^"]*)"/g,(o,a,i)=>a!==void 0?`'${n(a)}'`:`"${n(i)}"`);let r,s=!0;return Wn(e,t,o=>o.split(/(>>)/).map((a,i)=>i%2?a:((s||i>0)&&(r=a.match(/^\s*([a-z_-]+(?::[a-z_-]+)?)=/i)?.[1]?.toLowerCase()),s=!1,r===void 0?a.replace(/([#.])((?:[\p{L}\p{N}\p{M}_-]|\\.)+)/gu,(c,l,d)=>l+n(d)):/^(?:id|data-testid|data-test-id|data-test)$/.test(r)?a.replace(/=(.*)$/s,(c,l)=>`=${n(l)}`):a)).join(""))}function ii(e,t){let n=[fe(e??""),fe(t?.text??""),...t?.table?.flat()??[],t?.docString??""].join(`
|
|
332
|
-
`);
|
|
333
|
-
|
|
334
|
-
${v.replace(Ae,(k,C)=>x.get(C)??k)}`.toLowerCase(),R=k=>v.includes(k)&&($===k||$.startsWith(k)&&/^[/?#]/.test($.slice(k.length))||E.includes($.toLowerCase()));return w.replace(Qn(n)," ").replace(Ae,(k,C)=>R(k)?k:a.get(C)??x.get(C)??k).replace(Ce,(k,C)=>R(k)?k:process.env[C]??k).replace(/\{(?:env|data|unique|date)[^{}]*\}/g," ")},p=[],u=[...new Set(t.steps.flatMap(w=>[w.text,...w.table?.flat()??[],w.docString??""]).flatMap(w=>[...w.matchAll(/\{data:([^{}]*<[^<>{}]+>[^{}]*)\}/g)].map(v=>v[1])))].flatMap(w=>{let v=[...w.matchAll(/<([^<>]+)>/g)].map(E=>E[1]).filter(E=>E in t.params),$=(E=>{if(!v.some(R=>/[{}<>]/.test(E[R]??"{")))try{return qe(w.replace(/<([^<>]+)>/g,(R,k)=>E[k]??R))}catch{return}})(t.params);return v.length===0||$===void 0||$.trim()===""?[]:[{used:v,value:$.trim().toLowerCase()}]}),h=[...js(t).all].filter(([,w])=>w.size>1);h.length>0&&e.forEach((w,v)=>{let x=w.actions.flatMap($=>Et($)).filter($=>$!==void 0);for(let[$,E]of h){if(!x.some(k=>k.includes($)))continue;let R=new Set([...E].flatMap(k=>[...k.matchAll(/<([^<>]+)>/g)].map(C=>C[1])));for(let k of R)k in t.params&&p.push({column:k,step:v,reason:"data"})}});let{own:b,all:g}=js(t),S=[...si(g)];S.length>0&&e.forEach((w,v)=>{let x=si(b[v]??new Map),$=Ns(t.steps[v],R=>R).replace(/\{[^{}]*\}/g," "),E=w.actions.flatMap(R=>Et(R)).filter(R=>R!==void 0);for(let[R,k]of S){let C=x.get(R),P=R.trim()!==""&&(xe(R).test($)||R.length>=4&&$.includes(R));if(!C&&P)continue;let m=C??k,A=Tr(R).exact,O=I=>R.trim()===""?I.trim()==="":A.some(L=>R.length>=3?I.includes(L):xe(L).test(I)),T=[t.steps[v]?.text??w.gherkin,...t.steps[v]?.table?.flat()??[],t.steps[v]?.docString??""].join(`
|
|
335
|
-
`),_=[...m].some(I=>JSON.stringify(w.actions).split(I).length>T.split(I).length);if(!(C===void 0?ca(w.actions,R):m.size>1&&E.some(O)||P&&(E.some(O)||_)||On(w.actions,R)))continue;let F=new Set([...m].flatMap(I=>[...I.matchAll(/<([^<>]+)>/g)].map(L=>L[1])));for(let I of F)I in t.params&&!p.some(L=>L.column===I&&L.step===v)&&p.push({column:I,step:v,reason:"data"})}});let y=w=>{let v=vd(t.params[w]);return v?{valueSha:v}:{}};return e.forEach((w,v)=>{let x=ii(w.gherkin,t.steps[v]),$=Mc(c,x,c,Ns(t.steps[v],M=>M),d),E=Object.entries($).filter(([M,U])=>l(U)&&U.trim()!==""&&(U.length>=3||x.has(M))),R=new Set(E.filter(([M])=>x.has(M)).map(([,M])=>M)),k=t.steps[v],C=[k?.text??w.gherkin,...k?.table?.flat()??[],k?.docString??""].join(`
|
|
336
|
-
`),P=xr([C]),m=[C,...P.values()].join(`
|
|
337
|
-
`),A=w.actions.flatMap(M=>_n(M)).flatMap(M=>M===void 0?[]:[f(M,m,P).normalize("NFC")]),T=w.actions.flatMap(M=>M.each!==void 0&&!C.includes(M.each)?M.each.match(/^\{data:([^{}]+)\}$/)?.slice(1)??[]:[]).map(M=>M.toLowerCase()),_=w.actions.flatMap(M=>M.attribute!==void 0?[M.attribute]:[]),N=M=>[M,M.replace(/\s+/g,"-"),M.replace(/\s+/g,"_")].some(U=>T.some(z=>z.includes(U))||_.some(z=>Ic(U,"i").test(z))),F=w.actions.flatMap(M=>[M.status,M.method,M.attribute]).flatMap(M=>M===void 0?[]:[f(M,m,P).trim().toLowerCase()]),I=new Set;for(let[M,U]of Object.entries(c)){let z=U.trim().toLowerCase();x.has(M)||/\{(?:date|unique)/.test(t.params[M]??"")||z===""||!F.includes(z)||(p.push({column:M,step:v,reason:"value",...y(M)}),I.add(M))}for(let[M,U]of Object.entries(c)){if(I.has(M)||/\{(?:date|unique)/.test(t.params[M]??""))continue;let z=U.trim().toLowerCase();z.length<3||!N(z)||(p.push({column:M,step:v,reason:"glued",...y(M)}),I.add(M))}for(let{used:M,value:U}of u)if(F.includes(U))for(let z of M)I.has(z)||(p.push({column:z,step:v,reason:"reads",...y(z)}),I.add(z));for(let[M,U]of E){if(I.has(M))continue;let z=Cp(d,M,U,x);z.length>0&&A.some(V=>Rr(V,U,R.has(U))&&z.some(ee=>Rr(V,ee,R.has(U))))?p.push({column:M,step:v,reason:"list",...y(M)}):!x.has(M)&&U.length>=3&&A.some(V=>aa(U.normalize("NFC")).test(V))&&p.push({column:M,step:v,reason:"glued",...y(M)})}let L=M=>p.some(U=>U.column===M&&U.step===v);for(let M of Object.keys(t.params)){let U=c[M]??"";if(L(M)||U.trim()==="")continue;let z=Object.keys(c).filter(ee=>c[ee]===U);if(z.length>1&&o.some(ee=>new Set(z.map(Ie=>i(ee[Ie]??""))).size>1))continue;let V={...t.params,...Object.fromEntries(z.map(ee=>[ee,"\u2063another row\u2063"]))};Zn(w.actions,C,t.params,V,s)&&p.push({column:M,step:v,reason:"glued",...y(M)})}if(w.actions.some(M=>M.target!==void 0)){let M=new Set(Is(w.gherkin,!0));for(let U of Is(w.gherkin))for(let[,z]of U.matchAll(/<([^<>]+)>/g))!(z in t.params)||L(z)||jc(w.actions,`<${z}>`,w.kind==="assertion",M.has(U)).length===0||p.push({column:z,step:v,reason:"container",...y(z)})}let j=M=>w.kind==="assertion"&&!kr(w.actions)&&!(t.params[M]??"").includes("{date"),H=[t.steps[v]?.text??w.gherkin,...t.steps[v]?.table?.flat()??[],t.steps[v]?.docString??""].join(`
|
|
338
|
-
`),Z=M=>go(H,M,c);for(let M of $r(w.gherkin,w.actions,t.params).filter(U=>!j(U)&&!Z(U)))M in t.params&&!L(M)&&(c[M]??"").trim()!==""&&p.push({column:M,step:v,reason:"unwritten",...y(M)});let Q=r[v];if(Q!==void 0&&/<[^<>]+>/.test(Q)){let M=`${C}
|
|
339
|
-
${C.replace(Ae,(V,ee)=>P.get(ee)??V).replace(Ce,(V,ee)=>process.env[ee]??V)}`,U=V=>new RegExp(Qn(n).source).test(V)||/\{(?:date[^{}]*|unique:[^{}]+)\}/.test(V);if(w.actions.some(V=>(V.action==="fill"||V.action==="selectOption")&&(V.value??"").trim()!==""&&!U(V.value)&&!xe(V.value).test(M)))for(let[,V]of Q.matchAll(/<([^<>]+)>/g))V in t.params&&!L(V)&&p.push({column:V,step:v,reason:"session",...y(V)})}if(w.kind==="assertion")for(let[M,U]of Object.entries(t.params)){let z=(c[M]??"").trim();L(M)||x.has(M)||z===""||z.length>2||/\{(?:date|unique)/.test(U)||xe(z,"u").test(C)||w.actions.some(V=>_n(V).some(ee=>ee!==void 0&&Rr(f(ee,m,P),z,!1)))&&p.push({column:M,step:v,reason:"glued",...y(M)})}}),p}function jb(e,t,n=[],r=t,s=a=>a,o=[]){let a=d=>ri(o.length>0?o:[t],d,s),i=new Map,c=d=>i.get(d)??i.set(d,ri(o.length>0?o:[t],d,f=>f)).get(d),l=Object.keys(t);return e.map((d,f)=>{let p=ii(d.gherkin,n[f]),u=[...p].filter(m=>m in t&&(r[m]??t[m])===""),h=u.length===1?`<${u[0]}>`:void 0,b=Mc(t,p,r,Ns(n[f],s),a),g=Object.entries(b).map(([m,A])=>[m,A.includes("{date")?A:r[m]??A]).filter(([m,A])=>A.length>=3||A!==""&&p.has(m));if(g.length===0&&!h)return d;let S=new Set(g.filter(([m])=>p.has(m)).map(([,m])=>m)),y=(m,A)=>ho(A,m,"gu",S.has(A)),w=(m,A,O)=>Op(m,A,O)??ni(m,A,y,O,l),v=[...p].flatMap(m=>{let A=m in b?vt(r[m]??t[m]):void 0;return A===void 0?[]:[[m,A]]}),$=[...g.filter(([m])=>p.has(m))].sort((m,A)=>A[1].length-m[1].length),E=m=>m===void 0?m:$.reduce((A,[O,T])=>A.replace(Ic(T,"gi"),(_,N)=>`${N}<${O}>`),m),R=(m,A=O=>O)=>{if(m===void 0)return;let O=w(m,g,A),T=O.replace(Qn(l)," "),_=g.filter(([N,F])=>!/\{(?:env|data|unique|date)/.test(t[N])&&Rr(m,F,S.has(F),A(F))&&Cp(c,N,F,p).some(I=>Rr(T,I,S.has(F),A(I))));return _.length===0?O:w(m,g.filter(N=>!_.includes(N)),A)},k=m=>R(m,ue.pattern),C=m=>m===void 0?void 0:Nb(m,(A,O)=>R(A,ue[O]),A=>ni(A,g,y,void 0,l)),P=m=>m?{...m,name:R(m.name),nameRegex:k(m.nameRegex),label:R(m.label),text:R(m.text),placeholder:R(m.placeholder),testId:R(m.testId),frame:C(m.frame),fallbackSelectors:m.fallbackSelectors?.map(A=>C(A))}:void 0;return{...d,actions:d.actions.map(m=>({...m,value:m.action==="expectDiffers"?m.value:m.action==="expectAmount"&&m.value!==void 0?Yn(m.value,A=>ld(R(A)??A,v)):(m.action==="fill"||Se.has(m.action))&&m.value===""&&h?h:R(m.value),url:R(m.url),pattern:k(m.pattern),urlPattern:k(m.urlPattern),promptText:R(m.promptText),each:m.each!==void 0&&!d.gherkin.includes(m.each)?m.each.replace(/^\{data:([^{}]+)\}$/,(A,O)=>`{data:${$.reduce((T,[_,N])=>T.replace(Ic(N,"g"),(F,I)=>`${I}<${_}>`),O)}}`):m.each,status:E(m.status),method:E(m.method),attribute:E(m.attribute),target:P(m.target),toTarget:P(m.toTarget)}))}})}function Mb(e,t,n=r=>r){let r=Tn(t.steps);return e.map((s,o)=>{let a=t.steps[o],i=a?.resolvedTable??a?.table,c=a?.resolvedDocString??a?.docString,l={...rt(i),...Jn(c)},d=new Set,f=Object.entries({...r,...l}).map(([g,S])=>{let y=n(S);return S.includes("{date")&&d.add(g),[g,y]}).filter(([g,S])=>S.length>=3&&(!d.has(g)||g in l||Ip(S))).filter(([g,S])=>g in l||!(a?.resolvedText??a?.text??"").includes(S)),p=new Set(f.map(([,g])=>g).filter((g,S,y)=>y.indexOf(g)!==S)),u=f.filter(([,g])=>!p.has(g)).sort((g,S)=>S[1].length-g[1].length);if(u.length===0)return s;let h=(g,S=w=>w,y=!1)=>g===void 0?void 0:u.reduce((w,[v,x])=>zr(w,{[v]:x},S,y||d.has(v)),g),b=g=>g?{...g,name:h(g.name),nameRegex:h(g.nameRegex,ue.pattern),label:h(g.label),text:h(g.text),placeholder:h(g.placeholder),testId:h(g.testId,void 0,!0),frame:h(g.frame,void 0,!0),fallbackSelectors:g.fallbackSelectors?.map(S=>Wn(S,(y,w)=>h(y,ue[w])??y))}:void 0;return{...s,actions:s.actions.map(g=>({...g,value:g.action==="expectDiffers"?g.value:g.action==="expectAmount"&&g.value!==void 0?Yn(g.value,S=>h(S)):h(g.value),url:h(g.url),pattern:h(g.pattern,ue.pattern),urlPattern:h(g.urlPattern,ue.pattern),promptText:h(g.promptText),target:b(g.target),toTarget:b(g.toTarget)}))}})}var Ip=e=>/(?<!\d)\d{4}(?!\d)/.test(e);function Db(e,t){for(let n=1;n<=400;n++){let r=new Date(t.getTime()+n*864e5),s=Ve(e[0],r);if(e.some(o=>Ve(o,r)!==s))return!1}return!0}function Fb(e){let t=new RegExp(`^${Sr.source}$`).exec(e)?.[4],n=t===void 0?"YYYY-MM-DD":t.replace(/:[a-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$/,"");return/Y/.test(n)&&/[MD]/.test(n)}var Lb=["DD/MM/YYYY","MM/DD/YYYY","DD.MM.YYYY","D MMM YYYY","MMM D, YYYY","D MMMM YYYY","MMMM D, YYYY"];function Bb(e,t,n,r=[],s=[]){let o=t.steps.map(c=>[c.text,...c.table?.flat()??[],c.docString??""].flatMap(l=>l.match(Sr)??[])),a=(c,l)=>c.map(d=>[d,Ve(d,n)]).filter(([,d])=>!r.some(f=>f.includes(d))&&!(s[l]??[]).includes(d)),i=o.flat().filter(Fb).flatMap(c=>[c,.../^\{date(?:[+-]\d+)?\}$/.test(c)?Lb.map(l=>`${c.slice(0,-1)}:${l}}`):[]]);return e.map((c,l)=>{let d=[...new Map([...a(o[l]??[],l),...a(i,l)])],f=new Map;for(let[h,b]of d)f.set(b,[...f.get(b)??[],h]);let p=d.filter(([h,b])=>{let g=f.get(b);return g.length===1||g[0]===h&&Db(g,n)}).sort((h,b)=>b[1].length-h[1].length);if(p.length===0)return c;let u=(h,b=g=>g)=>p.find(([,g])=>h===b(g))?.[0]??p.filter(([,g])=>g.length>=3).reduce((g,[S,y])=>g.split(/(\{(?:env|data|unique|date)[^{}]*\}|<[^<>{}]+>)/).map((w,v)=>v%2?w:w.replace(xe(b(y),"gu"),()=>S)).join(""),h);return{...c,actions:c.actions.map(h=>mn(h,b=>u(b),(b,g)=>u(b,ue[g])))}})}function Ub(e,t=new Date,n=[]){return e.map(r=>({...r,actions:r.actions.map(s=>mn(s,o=>id(o,t,n)))}))}function mn(e,t,n,r=t,s=t){let o=(d,f,p=t)=>{let u={...d};for(let h of f)typeof d[h]=="string"&&(u[h]=p(d[h]));return u},a=d=>n?n(d,"pattern"):t(d),i=d=>{let f=o(o(d,["name","label","text","placeholder","testId","frame"]),["nameRegex"],a);return d.fallbackSelectors&&(f.fallbackSelectors=d.fallbackSelectors.map(p=>n?Wn(p,n,s):t(p))),f},c=e.action==="expectDiffers"?["url","promptText"]:["value","url","promptText"],l=o(o(o(e,c),["status","method","attribute","each"],r),["pattern","urlPattern"],a);return e.action==="expectAmount"&&e.value!==void 0&&(l.value=Yn(e.value,t)),e.target&&(l.target=i(e.target)),e.toTarget&&(l.toTarget=i(e.toTarget)),l}function zb(e,t){if(t.length===0)return e;let n=new Map(t.map(([o,a])=>[a,o])),r=[...n.keys()].sort((o,a)=>a.length-o.length).map(be).join("|"),s=new RegExp(String.raw`(?<=^|[^A-Za-z0-9\\]|\\[A-Za-z])(?:${r})(?![A-Za-z0-9])`,"g");return e.split(/(\{(?:env|data|unique|date)[^{}]*\})/).map((o,a)=>a%2?o:o.replace(s,i=>`{env:${n.get(i)}}`)).join("")}function Hb(e,t){let n=tt(t),r=rn(lt(t)),s=new RegExp(`${Ce.source}|${Ae.source}`,"g"),o=a=>a.replace(s,(i,c,l)=>(c!==void 0?n.has(c):r.has(l))?i:Ll(i));return e.map(a=>({...a,actions:a.actions.map(i=>({...mn(i,o),...i.each!==void 0?{each:i.each}:{}}))}))}function vp(e,t,n=[]){if(t.size===0)return e;let r=Gi(n,t),s=Rn(t,{standaloneBelow:6}),o=v=>{let x=encodeURIComponent(v),$=x.replace(/[!'()*]/g,E=>`%${E.charCodeAt(0).toString(16).toUpperCase()}`);return[...new Set([x,$,x.replace(/%20/g,"+"),$.replace(/%20/g,"+"),encodeURI(v)])].filter(E=>E!==v)},a=v=>v.length>=6&&v.toLowerCase()!==v.toUpperCase(),i=[...t].filter(([,v])=>v.length>=kn).flatMap(([v,x])=>o(x).map($=>[v,$,a(x)])).sort((v,x)=>x[1].length-v[1].length),c=(v,x=$=>$)=>i.reduce(($,[E,R,k])=>{let C=Wi(x(R));return $.replace(new RegExp(C,k?"gi":"g"),()=>`{env:${E}}`)},v),l=[...t].filter(([,v])=>a(v)).sort((v,x)=>x[1].length-v[1].length).map(([v,x])=>[v,new RegExp(be(x),"gi")]),d=v=>l.reduce((x,[$,E])=>x.split(/(\{[^{}]*\})/).map((R,k)=>k%2?R:R.replace(E,`{env:${$}}`)).join(""),v),f=v=>d(s.mask(r(c(v)))),p=[...t].filter(([,v])=>v.length>=kn),u=v=>{let x=Gi(n,t,ue[v]),$=Rn(new Map(p.filter(([,R])=>R.length>=6).map(([R,k])=>[R,ue[v](k)]))),E=p.filter(([,R])=>R.length<6).map(([R,k])=>[R,ue[v](k)]);return R=>f(zb($.mask(x(c(R,ue[v]))),E))},h={quoted:u("quoted"),regex:u("regex"),pattern:u("pattern")},b=new Set(e.flatMap(v=>v.actions.flatMap(x=>[x.saveAs,x.compareTo,x.action==="expectDiffers"?x.value:void 0,...x.action==="expectAmount"?[...(x.value??"").matchAll(/"([^"]*)"/g)].map($=>$[1]):[]].filter($=>$!==void 0)))),g=Rn(t,{encodings:!0}),S=new Map,y=new Set(b);for(let v of b){let x=g.mask(v);if(x===v)continue;let $=`capture-${xb("sha256").update(x).digest("hex")}`;if(y.has($)||g.mask($)!==$)throw new Error("Secret-bearing capture names cannot be safely distinguished. Record again with distinct capture names that contain no secrets.");y.add($),S.set(v,$)}let w=v=>v===void 0?void 0:S.get(v)??v;return e.map(v=>({...v,actions:v.actions.map(x=>{let $=mn(x,f,(E,R)=>h[R](E));return{...$,...x.saveAs!==void 0?{saveAs:w(x.saveAs)}:{},...x.compareTo!==void 0?{compareTo:w(x.compareTo)}:{},...x.action==="expectDiffers"&&x.value!==void 0?{value:w(x.value)}:{},...x.action==="expectAmount"&&$.value!==void 0?{value:Yn($.value,E=>E,E=>w(E))}:{}}})}))}function Np(e,t,n="",r=new Date){let s=lt(t),o=Pe(t),a=r,i=E=>Ve(Dt(Yt(E,n)),a).replace(Ce,(R,k)=>o.get(k)??R),c=Object.fromEntries(Object.entries(t.params).map(([E,R])=>{try{return[E,i(R)]}catch{return[E,R]}})),l=e.map((E,R)=>ii(E.gherkin,t.steps[R])),d=l.map((E,R)=>Mc(t.params,E,c,Ns(t.steps[R],i),k=>ri(t.exampleRows??[t.params],k,i))),f=Object.entries(t.params).filter(([,E])=>E.includes("{date")).map(([E,R])=>[E,R,c[E]]),p=(E,R)=>Ip(R)||/\{date[^{}]*:[^{}]*(?:MMM|ddd)/.test(E),u=E=>f.filter(([R,k,C])=>R in(d[E]??{})&&(l[E]?.has(R)||p(k,C))),b=jb(Mb(Hb(qb(Jb(vp(e,o,s),t,c,o),t),t),t,E=>Ve(Dt(Yt(E,n)),a)),t.params,t.steps,c,i,t.exampleRows).map((E,R)=>{let k=[...l[R]].flatMap(C=>{let P=c[C];if(P===void 0||P.length<3)return[];let m=encodeURIComponent(P);return m===P?[]:[...new Set([m,m.replace(/%20/g,"+")])].map(A=>[A,`<${C}>`])});return k.length===0?E:{...E,actions:E.actions.map(C=>C.url===void 0?C:{...C,url:k.reduce((P,[m,A])=>P.split(m).join(A),C.url)})}}),g=[...s,...es(s),...o.values()],S=e.map((E,R)=>f.filter(([k])=>l[R]?.has(k)).map(([,,k])=>k)),y=Bb(b,t,a,g,S).map((E,R)=>{let k=f.filter(([C,P,m])=>l[R]?.has(C)||p(P,m)).map(([,,C])=>C);return Ub([E],a,[...g,...k])[0]}),w=vp(Wb(Gb(y,new Map([...xr(s)].map(([E,R])=>[E,R.includes("{date")?Ve(R,a):R]))),Ir(s,n)),o,s),v=Object.fromEntries(Object.entries(t.params).filter(([,E])=>!E.includes("{date")&&/\{(?:env|data|unique):/.test(E))),x=Object.keys(t.params),$=Vb(w,t);return Object.keys(v).length===0&&f.length===0?$:$.map((E,R)=>{let k=u(R),C={...Object.fromEntries(Object.entries(v).filter(([_])=>_ in(d[R]??{}))),...Object.fromEntries(k.map(([_,N])=>[_,N]))},P=Object.fromEntries(k.filter(([,,_])=>!_.includes("{date")).map(([_,,N])=>[_,N])),m=Object.entries(P).filter(([,_])=>_.length<3),A=(_,N)=>{let F=m.find(([,I])=>_===(N?N(I):I));return F?`<${F[0]}>`:zr(_,P,N,!0,x)},O=_=>A(zr(_,C,void 0,!1,x)),T=(_,N)=>{let F=zr(_,C,void 0,!1,x);return(N==="pattern"?Op(F,m):void 0)??A(F,ue[N])};return{...E,actions:E.actions.map(_=>mn(_,O,T))}})}function js(e){let t=e.steps.map(o=>[o.text,...o.table?.flat()??[],o.docString??""]),n=t.flat(),r=t.map(()=>new Map),s=new Map;return t.forEach((o,a)=>{for(let i of o)for(let[c,l]of i.matchAll(/\{data:([^{}]*<[^<>{}]+>[^{}]*)\}/g)){let d=!0,f=`{data:${l.replace(/<([^<>]+)>/g,(p,u)=>{let h=e.params[u];return(h===void 0||/[{}<>]/.test(h))&&(d=!1),h??""})}}`;if(!(!d||n.some(p=>p.includes(f))))for(let p of[r[a],s])(p.get(f)??p.set(f,new Set).get(f)).add(c)}}),{own:r,all:s}}function si(e){let t=new Map;for(let[n,r]of e){let s;try{s=qe(n.slice(6,-1))}catch{continue}let o=Ve(s.replace(Ce,(a,i)=>process.env[i]??a));for(let a of new Set([s,o]))for(let i of r)(t.get(a)??t.set(a,new Set).get(a)).add(i)}return t}function qb(e,t){let{own:n}=js(t),r=s=>[...si(s)].flatMap(([o,a])=>a.size===1&&o.trim()!==""?[[o,[...a][0]]]:[]);return e.map((s,o)=>{let a=Ns(t.steps[o],l=>l).replace(/\{[^{}]*\}/g," "),i=new Map(r(n[o]??new Map).filter(([l])=>!xe(l).test(a)));if(i.size===0)return s;let c=l=>{let d=i.get(l);if(d!==void 0)return d;let f=l;for(let[p,u]of i)f=f.split(/(\{[^{}]*\}|<[^<>\s]+>)/).map((h,b)=>b%2?h:h.replace(xe(p,"gu"),u)).join("");return f};return{...s,actions:s.actions.map(l=>mn(l,c,d=>d,c,d=>jp(d,c)))}})}function Vb(e,t){let{own:n,all:r}=js(t),s=a=>[...a].filter(([,i])=>i.size===1).map(([i,c])=>[i,[...c][0]]),o=s(r);return o.length===0&&n.every(a=>a.size===0)?e:e.map((a,i)=>{let c=new Map([...o,...s(n[i]??new Map)]);if(c.size===0)return a;let l=d=>{let f=d;for(let[p,u]of c)f=f.split(p).join(u);return f};return{...a,actions:a.actions.map(d=>mn(d,l,f=>l(f)))}})}function jp(e,t){let n=[],r=e.replace(/(^|[\s>+~,(])([A-Za-z][\w-]*)(?=$|[.#[:\s>+~,)])/g,(s,o,a)=>`${o}\0${n.push(a)-1}\0`);return t(r).replace(/\u0000(\d+)\u0000/g,(s,o)=>n[Number(o)])}function Jb(e,t,n,r){if(r.size===0)return e;let{own:s}=js(t),o=[...r].sort((c,l)=>l[1].length-c[1].length),a=c=>c.replace(/\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g,(l,d)=>r.get(d)??l),i=c=>c.split(/(<[^<>\s]+>|\{[^{}]*\})/).map((l,d)=>d%2?l:o.reduce((f,[p,u])=>u===""?f:f.split(u).join(`{env:${p}}`),l)).join("");return e.map((c,l)=>{let d=ii(c.gherkin,t.steps[l]),f=[c.gherkin,...c.table?.flat()??[],c.docString??""].join(`
|
|
340
|
-
`),p=si(s[l]??new Map),u=[...d].flatMap(g=>{let S=n[g],y=!fe(f.replace(/\{data:[^{}]*\}/g," ")).includes(`<${g}>`);return S===void 0||S.length<3||y||/\{env:/.test(t.params[g]??"")||p.has(S)?[]:[...r].filter(([v,x])=>x!==""&&S.includes(x)&&!f.includes(`{env:${v}}`)).length===0?[]:Object.entries(t.params).some(([v,x])=>/\{env:/.test(x)&&n[v]===S)?[]:[[g,S]]}),h=new Map([...p].filter(([g,S])=>S.size===1&&g.trim()!=="").map(([g,S])=>[g,[...S][0]]));if(u.length===0&&h.size===0)return c;let b=g=>{let S=a(g),y=h.get(S);if(y!==void 0&&S!==g)return y;let w=S===g?S:[...h].filter(([x])=>x.length>=4).reduce((x,[$,E])=>x.split($).join(E),S),v=u.reduce((x,[$,E])=>x.split(E).join(`<${$}>`),w);return v===S?g:i(v)};return{...c,actions:c.actions.map(g=>mn(g,b,S=>b(S)))}})}function Wb(e,t){if(t.size===0)return e;let n=r=>typeof r=="string"?cu(r,t):Array.isArray(r)?r.map(n):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([s,o])=>[s,s==="pageFingerprint"?o:n(o)])):r;return e.map(r=>({...r,actions:r.actions.map(s=>n(s))}))}function Gb(e,t){return t.size===0?e:e.map(n=>{let r=new Set([...n.gherkin.matchAll(Ae)].map(b=>b[1])),s=[n.gherkin,...n.table?.flat()??[],n.docString??""].join(`
|
|
341
|
-
`).replace(/\{[^{}]*\}|<[^<>]+>/g," "),a=!/\{data:/.test(n.gherkin)?new Map([...t].filter(([,b])=>b===""||!xe(b).test(s))):t,i=[...new Set((s.match(/[\p{L}\p{N}]+(?:[-'][\p{L}\p{N}]+)*/gu)??[]).filter(b=>[...a.values()].some(g=>g.length>=4&&b!==g&&b.includes(g))))],c=i.length>0?new RegExp(`(${i.sort((b,g)=>g.length-b.length).map(be).join("|")})`):void 0,l=b=>c?b.split(c).map((g,S)=>S%2?g:ro(g,a,r)).join(""):ro(b,a,r),d=b=>new Map([...a].filter(([,g])=>g.length>=4).map(([g,S])=>[g,ue[b](S)])),f={quoted:d("quoted"),regex:d("regex"),pattern:d("pattern")},p=b=>b.split(/(\{(?:env|data|unique|date)[^{}]*\})/).map((g,S)=>S%2?g:l(g)).join(""),u=(b,g)=>p(ro(b,f[g],r)),h=b=>{let g=[...a].filter(([S,y])=>r.has(S)&&y===b);return g.length===1?`{data:${g[0][0]}}`:b};return{...n,actions:n.actions.map(b=>mn(b,l,u,h,g=>jp(g,p)))}})}function Dc(e,t,n){if(e!=="mcp__playwright__browser_tabs")return;let r=t??{},s=typeof r.index=="number"?String(r.index):void 0;switch(r.action){case"select":return s===void 0?void 0:{action:"switchTab",value:s};case"close":return s===void 0?{action:"closeTab"}:{action:"closeTab",value:s};case"new":return typeof r.url=="string"&&r.url?{action:"newTab",url:cs(r.url,n)}:{action:"newTab"};default:return}}function Mp(e,t){let n=t??{};if(e==="mcp__playwright__browser_handle_dialog"){let r={action:"handleDialog",value:n.accept?"accept":"dismiss"};return typeof n.promptText=="string"&&n.promptText&&(r.promptText=n.promptText),r}if(e==="mcp__playwright__browser_file_upload"){let r=Array.isArray(n.paths)?n.paths:[];if(r.length===0)return;let s=et().root+vb.sep;return{action:"uploadFile",value:r.map(a=>typeof a=="string"&&a.startsWith(s)?a.slice(s.length):a).join(`
|
|
342
|
-
`)}}}function qr(e,t){let n=e.pages().filter(s=>!s.isClosed()),r=s=>[...n].reverse().find(s);return(t?r(s=>s.url()===t):void 0)??r(s=>s.url()!=="about:blank")??n.at(-1)}async function ai(e,t,n=[]){let r=t.context();for(let o of e.contexts())if(!(o===r||n.includes(o)))for(let a of o.pages())await a.close().catch(()=>{});await t.bringToFront().catch(()=>{});let s=r.pages().filter(o=>!o.isClosed());return{index:Math.max(s.indexOf(t),0),count:s.length,url:t.url()}}var ci=class{constructor(t,n,r,s=o=>o.newPage()){this.main=t;this.mainKey=n;this.create=r;this.newPage=s;this.follow(t,n)}main;mainKey;create;newPage;pages=new Map;others=new Map;follow(t,n){t.on("page",r=>this.pages.set(n,r))}contextOf(t){return t===this.mainKey?this.main:this.others.get(t)}contexts(){return[this.main,...this.others.values()]}opened(){return[...this.others]}async open(t){let n=await this.create(t);this.others.set(t,n),this.follow(n,t);let r=await this.newPage(n);return this.pages.set(t,r),r}livePage(t){let n=this.pages.get(t);if(n&&!n.isClosed())return n;let r=this.contextOf(t);return r&&qr(r)}pageOf=async t=>{let n=this.livePage(t);if(n)return this.pages.set(t,n),n;let r=this.contextOf(t);if(!r)return this.open(t);let s=await this.newPage(r);return this.pages.set(t,s),s};selectTab(t,n){t??=this.mainKey;let r=this.contextOf(t)?.pages().filter(s=>!s.isClosed())[n];r&&this.pages.set(t,r)}async blank(){for(let[t,n]of this.others){let r=qr(n)??await this.newPage(n);await r.goto("about:blank").catch(()=>{}),this.pages.set(t,r)}}async close(){for(let t of this.others.values())await t.close().catch(()=>{});this.others.clear()}};var Ms="Agent session error: ";var zc=["chromium","chrome","msedge","firefox","webkit"],Bc={chrome:{label:"Google Chrome"},msedge:{label:"Microsoft Edge"}};function Up(e){return zc.includes(e)}function ur(e){return e==="chromium"||Bc[e]!==void 0}var Tt=class extends Error{},Uc=class extends Tt{},Hc=Object.keys(Lc);function zp(e){let t=/^(\d{2,5})x(\d{2,5})$/.exec(e.trim());return t?{width:Number(t[1]),height:Number(t[2])}:void 0}var Xb=/usage limit|insufficient_quota|exceeded your (?:current )?quota|quota exceeded|credit balance is too low/i,ev=/per min(?:ute)?\b|\b[TR]PM\b|(?:re)?try (?:again )?(?:in|after) \d+(?:\.\d+)?\s*(?:ms|s|sec|seconds?)\b/i,tv=e=>Xb.test(e)&&!ev.test(e);function Vr(e,t){return nt(e,t).split(`
|
|
343
|
-
`)[0]}function nv(e,t){let n=(r,s)=>{t.reason!==void 0||!tv(r)||(t.reason=Vr(r,Pe(s.scenario)).replace(/\.$/,""),console.log(` \u26A0 the agent's provider reported a usage limit; no new AI session starts in this run: ${t.reason}`))};return{run:async r=>{if(t.reason!==void 0)throw new Error(`the agent's provider reported a usage limit earlier in this run: ${t.reason}`);try{let s=await e.run(r);return!s.success&&s.narrative.startsWith(Ms)&&n(s.narrative.slice(Ms.length),r),s}catch(s){throw n(s instanceof Error?s.message:String(s),r),s}},...e.planUsage?{planUsage:()=>e.planUsage()}:{}}}var wn={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0};async function rv(){return new Promise((e,t)=>{let n=Kb.createServer();n.listen(0,"127.0.0.1",()=>{let{port:r}=n.address();n.close(()=>e(r))}),n.on("error",t)})}function sv(e){try{return`${e}
|
|
344
|
-
${Dt(e)}`}catch{return e}}function Dp(e,t){let n=xr(lt(e)),r=Pp(t,e);return{...n.size>0?{data:Object.fromEntries([...n].sort(([s],[o])=>s.localeCompare(o)))}:{},...Object.keys(e.params).length>0?{examples:e.params}:{},...r.length>0?{rowBound:r}:{},...(e.exampleRows??[]).some(s=>Kn(sv(JSON.stringify(s))))?{rowsUseNewDates:!0}:{}}}function Fc(e,t){return e.livePage(t??e.mainKey)}function Hp(e){let t=e.length;for(let n=e.length-1;n>=0&&e[n].kind==="assertion";n--)t=n;return t}function li(e,t){return e[t]?.kind==="assertion"&&t>=Hp(e)}function Fp(e,t,n=!1,r){let s=Hp(e);return e.map((o,a)=>{if(r&&a<r.stepIndex)return o;let i=t[a],c=i&&i.actions.length>0;return o.kind==="assertion"&&!(n&&a<s)||!c?o:r&&a===r.stepIndex&&r.actionIndex>0?{...i,actions:[...o.actions.slice(0,r.actionIndex),...i.actions]}:i})}function ov(e,t,n,r){let s=Lu(e,t);return s.length===0||!n?.pageUrl?s:[`page at failure: replay stopped at step ${n.stepIndex+1} ("${n.stepText}") on ${cs(n.pageUrl,r)}, where the heal started.`,...s]}function iv(e,t,n=0){return e.map((r,s)=>{if(s<n)return r;let o=t[s];return o&&o.actions.length>0?o:r})}function Lp(e,t){let n=[];for(let r=0;r<Math.min(t,e.length);r++){let s=e[r].actions.length;s!==0&&n.push(`recording: kept the existing recording of step ${r+1} ("${e[r].gherkin}"), which ran before the agent took over; ignored ${s} action${s===1?"":"s"} the agent's session held for it.`)}return n}function qp(e,t,n,r){let s=t.filter(c=>c>=0&&c<e.length),o=s.length>0?Math.max(...s):0,a=Math.min(n&&n.stepIndex>=o?n.stepIndex:o,e.length-1),i=n&&a===n.stepIndex?n.error:r;return e.map((c,l)=>({gherkin:c.gherkin,kind:c.kind,status:l<a?"passed":l===a?"failed":"skipped",...l===a&&i?{error:i}:{}}))}function av(e,t,n){let r=n.success?e.map(s=>({gherkin:s.gherkin,kind:s.kind,status:"passed"})):qp(e,n.announcedSteps??[],t,n.narrative);return e.map((s,o)=>o<t.stepIndex?s:r[o])}function Bp(e,t){return{aiCalls:e.aiCalls+t.aiCalls,inputTokens:e.inputTokens+t.inputTokens,outputTokens:e.outputTokens+t.outputTokens,cacheReadTokens:e.cacheReadTokens+t.cacheReadTokens,cacheCreationTokens:e.cacheCreationTokens+t.cacheCreationTokens,costUsd:(e.costUsd??0)+(t.costUsd??0),models:e.models||t.models?[...new Set([...e.models??[],...t.models??[]])]:void 0}}var di=class{constructor(t){this.options=t;this.filedThisRun=t.filedThisRun??new Map,this.agentHalt=t.agentHalt??{},t.agent&&(this.options={...t,agent:nv(t.agent,this.agentHalt)})}options;browser;cdpEndpoint;stepIndex;tabListeners=new Set;downloadListeners=new Set;armDialogs;openingOwnPages=new Set;filedThisRun;agentHalt;get agent(){return this.options.agent}getStepIndex(){if(!this.stepIndex&&(this.stepIndex=Wt(this.options.projectRoot),this.stepIndex.steps.size>0)){let t=this.stepIndex.divergent.length>0?` \xB7 ${this.stepIndex.divergent.length} step(s) have divergent recordings (Level-2 signal)`:"";console.log(`step index: ${this.stepIndex.steps.size} reusable steps from ${this.stepIndex.scannedCaches} cache(s)${t}`)}return this.stepIndex}async recordWithSeeding(t,n,r,s){let o=this.getStepIndex(),a=t.steps.length,i={...t.params,...Tn(t.steps)},c=t.steps.map(x=>{let $=o.steps.size>0?Bd(o,x,i):void 0;return $?{gherkin:x.text,keyword:x.keyword,kind:x.kind,table:x.table,docString:x.docString,fromStepSet:x.source?.fromStepSet,actions:$.actions}:void 0}),l=t.steps.map(x=>({gherkin:x.text,keyword:x.keyword,kind:x.kind,table:x.table,docString:x.docString,fromStepSet:x.source?.fromStepSet,actions:[]})),d=new Map;d.set(Ct,r);let f=[],p=[],u=[],h=[],b={...wn},g=x=>s.pageOf(pe(t.steps[x]?.session)),S=0,y=0,w=0,v=(x,$)=>({success:x,narrative:p.join(" ")||"Composed entirely from seeded recordings.",adaptations:f,suggestedFeatureEdit:h.length>0?h.join(`
|
|
345
|
-
`):void 0,featureEdits:u,recordedSteps:l,announcedSteps:$===void 0?[]:Array.from({length:$+1},(E,R)=>R),usage:b,seededCount:S});for(;w<a;){if(c[w]){let C=w;for(;C<a&&c[C];)C++;let P=c.slice(w,C),m={...t,steps:t.steps.slice(w,C)},A=await Bo(await g(w),m,this.buildCandidateCache(t,P),{sessions:s.pages,openSession:s.pageOf,downloadsDir:this.downloads(t),baseURL:this.options.baseURL,actionTimeoutMs:this.options.actionTimeoutMs,retries:this.options.retries,pollIntervalMs:this.options.pollIntervalMs,vars:d,trace:this.options.trace!==void 0&&this.options.trace!=="off",traceStepOffset:w,envNames:tt(t)}),O=A.status==="passed"?C-w:A.failure?.stepIndex??0;for(let _=0;_<O;_++)l[w+_]=P[_];if(S+=O,A.status==="passed"){w=C;continue}let T=w+O;f.push(`Seeded recording for "${t.steps[T].text}" did not replay in this scenario's context; the agent re-recorded it fresh. Divergence signal.`),c[T]=void 0,w=T;continue}if(!this.options.agent)return v(!1,w);y++;let x=w;for(;x<a&&!c[x];)x++;y>=3&&(x=a);let $=await ai(this.browser,await g(w),s.contexts()),E=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:this.options.baseURL,traceContext:this.options.trace&&this.options.trace!=="off"?n.context():void 0,mode:"record",cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,completedSteps:w>0?t.steps.slice(0,w).map(C=>C.resolvedText):void 0,recordOnly:x<a?{from:w,to:x-1}:void 0,liveTab:$,uniqueSeed:d.get(Ct),onTabOpened:this.tabWatcher(),onDownload:this.downloadWatcher(),...this.sessionHooks(t,s,n)}));if(b=Bp(b,E.usage),p.push(E.narrative),f.push(...E.adaptations),u.push(...E.featureEdits),E.suggestedFeatureEdit&&h.push(E.suggestedFeatureEdit),!E.success){let C=E.announcedSteps.filter(P=>P>=w&&P<a);return v(!1,C.length>0?Math.max(...C):w)}let R=E.announcedSteps.filter(C=>C>=w&&C<a),k=Math.min(a-1,Math.max(R.length>0?Math.max(...R):x-1,w));for(let C=w;C<=k;C++)l[C]=E.recordedSteps[C];w=k+1}return v(!0)}async withDialogsVisible(t){let n=()=>{},r=[],s=[],o=i=>{i.on("dialog",n),r.push(i)},a=i=>{i.on("page",o),s.push(i);for(let c of i.pages())o(c)};for(let i of this.browser?.contexts()??[])a(i);this.armDialogs=a;try{return await t()}finally{this.armDialogs=void 0;for(let i of s)i.off("page",o);for(let i of r)try{i.off("dialog",n)}catch{}}}async start(){let t=this.options.browser??"chromium";if(ur(t)){let r=await rv();try{this.browser=await Yb.launch({headless:!this.options.headed,channel:Bc[t]?t:void 0,args:[`--remote-debugging-port=${r}`],handleSIGINT:!1})}catch(s){let o=s instanceof Error?s.message:String(s),a=Bc[t];throw a&&/is not found at|distribution .* is not found/i.test(o)?new Uc(`${a.label} is not installed on this machine, so --browser ${t} cannot run.
|
|
346
|
-
Install it (npx playwright install ${t} does that), or use --browser chromium, which Saffron ships with.`):s}this.cdpEndpoint=`http://127.0.0.1:${r}`}else this.browser=await(t==="firefox"?Zb:Qb).launch({headless:!this.options.headed,handleSIGINT:!1}),this.cdpEndpoint=void 0;let n;try{n=this.contextOptions();let r=this.options.sessions??{},s=i=>typeof i=="object"&&i!==null&&!Array.isArray(i);if(!s(r))throw new Tt('"sessions" in saffron.config.json must map session names to their settings, such as { "buyer": { "storageState": ".auth/buyer.json" } }.');for(let[i,c]of Object.entries(r)){let l=`{ "storageState": ".auth/${ns(i)}.json" }`;if(!s(c)||Object.keys(c).some(d=>d!=="storageState"))throw new Tt(`sessions."${i}" in saffron.config.json takes only a storageState, such as ${l}.`);if(c.storageState!==void 0&&(typeof c.storageState!="string"||c.storageState.trim()===""))throw new Tt(`sessions."${i}".storageState in saffron.config.json must be a file path, such as ".auth/${ns(i)}.json".`);if(i===Ft&&c.storageState!==void 0&&bt.resolve(this.options.projectRoot,c.storageState)!==n.storageState)throw new Tt(`sessions."${Ft}".storageState in saffron.config.json is never read: the default session signs in with the top-level storageState. Set that instead, or make the two the same.`);i!==Ft&&this.contextOptions(i)}let o=new Set([n.storageState,...Object.keys(r).filter(i=>i!==Ft).map(i=>this.contextOptions(i).storageState)]),a=this.browser;await Promise.all([...o].filter(i=>typeof i=="string").map(async i=>{try{let c=JSON.parse(Xt.readFileSync(i,"utf8"));if(!c||typeof c!="object"||Array.isArray(c))throw new Error("it is not a JSON object");await(await a.newContext({storageState:i})).close()}catch(c){throw new Tt(`storageState file ${i} cannot be used: ${(c instanceof Error?c.message:String(c)).split(`
|
|
347
|
-
`)[0]}. Generate it again with: npx playwright open --save-storage=${Be(this.options.projectRoot,i)} <url>`)}}))}catch(r){throw await this.stop(),r}if(this.options.device||this.options.viewport){if(t==="firefox"&&this.options.device&&Lc[this.options.device]?.isMobile)throw await this.stop(),new Tt(`--device "${this.options.device}" is a mobile profile, and Playwright does not emulate mobile devices in Firefox. Run it in chromium or webkit, or give Firefox a --viewport instead.`);try{await(await this.browser.newContext(n)).close()}catch(r){await this.stop();let s=(r instanceof Error?r.message:String(r)).split(`
|
|
348
|
-
`)[0];throw new Tt(`${this.options.device?`--device "${this.options.device}"`:"--viewport"} cannot run in ${t}: ${s}`)}}}async stop(){await this.browser?.close(),this.browser=void 0}resolveStorageState(t=this.options.storageState){if(!t)return;let n=bt.isAbsolute(t)?t:bt.join(this.options.projectRoot,t);if(!Xt.existsSync(n))throw new Tt(`storageState file not found: ${n}. Generate one with: npx playwright open --save-storage=${t} <url>`);return n}contextOptions(t){let{defaultBrowserType:n,...r}=this.options.device?Lc[this.options.device]??{}:{},s=t===void 0?void 0:this.options.sessions?.[t]?.storageState;return{storageState:this.resolveStorageState(s??this.options.storageState),...r,...this.options.viewport?{viewport:this.options.viewport}:{},...this.options.timezone?{timezoneId:this.options.timezone}:{}}}artifacts(t){let n=ln(this.options.projectRoot,t.featurePath,t.displayName);return this.options.artifactsPerBrowser?bt.join(n,this.options.browser??"chromium"):n}downloads(t){return bt.join(this.artifacts(t),"downloads")}buildCandidateCache(t,n){let r={version:1,feature:t.featurePath,scenario:t.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:n,...Dp(t,n)};return{...r,version:as(r)}}tabWatcher(){return t=>{let n=r=>t(r);return this.tabListeners.add(n),()=>{this.tabListeners.delete(n)}}}downloadWatcher(){return t=>(this.downloadListeners.add(t),()=>{this.downloadListeners.delete(t)})}async newContext(t,n){let r=await this.browser.newContext(this.contextOptions(t||void 0));return r.on("page",()=>{if(!this.openingOwnPages.has(r))for(let s of this.tabListeners)s(t)}),r.on("page",s=>s.on("download",o=>{for(let a of this.downloadListeners)a(o)})),this.armDialogs?.(r),n&&this.options.trace!==void 0&&this.options.trace!=="off"&&await _u(r,n),r}sessionsFor(t,n,r){return new ci(n,pe(t.steps[0]?.session),s=>this.newContext(s,`${r} \xB7 session "${dt(s)}"`),async s=>{this.openingOwnPages.add(s);try{return await s.newPage()}finally{this.openingOwnPages.delete(s)}})}sessionHooks(t,n,r){return{sessionPage:n.pageOf,onActiveTab:(s,o)=>n.selectTab(o,s),takeFingerprint:async s=>_o(Fc(n,s)??r)}}namedSession(t,n){return An(n)?{session:dt(t.mainKey)}:{}}async saveSessionTraces(t,n,r,s){let o=[],a=Pe(t),i=new Set;for(let[c,l]of n.opened()){if(!r){await No(l).catch(()=>{});continue}let d=ns(dt(c));for(let u=2;i.has(d);u++)d=`${ns(dt(c))}-${u}`;i.add(d);let f=bt.join(this.artifacts(t),`${r}.${d}.zip`),p=await jo(l,f,a);p&&(this.claimArtifactDir(t),o.push({...s,kind:"trace",file:Be(this.options.projectRoot,f),sha256:p,session:dt(c)}))}return o}async proofReplay(t,n,r,s){let o=this.options.trace!==void 0&&this.options.trace!=="off",a=s?t.displayName:`${t.displayName} (proof replay)`,i=await this.newContext(pe(t.steps[0]?.session),a),c=this.sessionsFor(t,i,a),l=await i.newPage();return{result:await Bo(l,t,n,{sessions:c.pages,openSession:c.pageOf,downloadsDir:this.downloads(t),baseURL:this.options.baseURL,actionTimeoutMs:this.options.actionTimeoutMs,retries:this.options.retries,pollIntervalMs:this.options.pollIntervalMs,uniqueSeed:r,trace:o,tracePhase:s}),context:i,page:l,sessions:c}}async runScenario(t,n={}){let r=await this.runScenarioInner(t,n),s=Pe(t);if(s.size>0){let o=i=>i===void 0?i:nt(i,s);r.error=o(r.error),r.narrative=o(r.narrative),r.proofError=o(r.proofError),r.suggestedFeatureEdit=o(r.suggestedFeatureEdit),r.adaptations=r.adaptations.map(i=>nt(i,s));let a=[r.stepResults,r.executionStepResults,...(r.evidence??[]).map(i=>i.traceSteps)];for(let i of a.flatMap(c=>c??[])){i.error=o(i.error);for(let c of i.tabs??[])c.url=nt(c.url,s);for(let c of i.responses??[])c.url=nt(c.url,s)}}return r}async screenshot(t,n,r,s){let o=this.options.screenshot??"viewport";if(o!=="off")try{let a=this.artifacts(n);this.claimArtifactDir(n);let i=bt.join(a,`${r}.jpg`),c=await t.screenshot({path:i,type:"jpeg",quality:80,fullPage:o==="full-page",timeout:5e3});return{kind:r,file:Be(this.options.projectRoot,i),step:s,sha256:zt(c)}}catch{return}}claimArtifactDir(t){let n=ln(this.options.projectRoot,t.featurePath,t.displayName);Xt.mkdirSync(this.artifacts(t),{recursive:!0}),Xt.writeFileSync(bt.join(n,Xn),JSON.stringify({feature:t.featurePath,scenario:t.displayName},null,2))}async runScenarioInner(t,n={}){if(!this.browser)throw new Error("Orchestrator not started");let r=Date.now(),{projectRoot:s,baseURL:o,actionTimeoutMs:a,retries:i,pollIntervalMs:c}=this.options,l=me(s,t.featurePath,t.name),d;try{d=st(l)}catch(_){if(!(_ instanceof $e))throw _;return{scenario:t,status:"red",source:"cache",stepResults:[],adaptations:[],usage:wn,durationMs:Date.now()-r,error:`The recording cannot be read: ${_.problem}. Fix the file, or re-record it with saffron run --rerecord.`}}let f=xt(s,t.featurePath,t.name),p=Be(s,f),u,h;if(Xt.existsSync(f))try{({proposal:u,revision:h}=ko(f))}catch(_){if(!(_ instanceof $e)&&_.code!=="ENOENT")throw _;u=void 0}let b=!1;u&&!Xd(s,f,h)&&(b=!this.options.rerecord,u=void 0),u&&$t(s,u,t)&&(u=void 0),u&&this.options.rerecord&&this.filedThisRun.get(f)!==h&&(u=void 0);let g=d&&Fn(t,d)||u&&Fn(t,u.cache);if(g)return{scenario:t,status:"red",source:"cache",stepResults:[],adaptations:[],usage:wn,durationMs:Date.now()-r,error:g};let S=_=>_.status==="stale"?"the committed recording no longer matches the scenario":`the committed recording failed${_.failure?` at "${_.failure.stepText}"`:""}`,y=_=>{let N=hn(s)[p],F=N?.revision===h?` from ${ce(_s(N.from))}`:"",I=_?S(_):"";return{scenario:t,status:"yellow",source:d?"cache":"agent-record",stepResults:_?.stepResults??[],narrative:(I?`${I[0].toUpperCase()}${I.slice(1)}. `:"")+`A proposal${F} is pending review at ${p}. It was not filed on this machine, so this run does not replay it, heal or record over it. Review it with saffron diff ${p}, then saffron accept or saffron reject it.`,adaptations:[],proposalFile:p,proposalRevision:h,usage:wn,durationMs:Date.now()-r}};if(Xt.rmSync(this.artifacts(t),{recursive:!0,force:!0}),this.options.artifactsPerBrowser){let _=ln(s,t.featurePath,t.displayName);for(let N of Xt.existsSync(_)?Xt.readdirSync(_,{withFileTypes:!0}):[])N.isFile()&&N.name!==Xn&&Xt.rmSync(bt.join(_,N.name),{force:!0})}if(b&&!d)return y();let w=(_,N)=>({scenario:t,status:"yellow",source:"agent-record",proposalReplay:!0,stepResults:_.stepResults,narrative:`Replayed the pending proposal recorded for "${u.meta.recordedFor??t.name}" at zero AI${N?` instead of ${N.status==="stale"?"recording":"healing"} again: ${S(N)}`:""}; accept it to go green.`,adaptations:[],verified:!0,proposalFile:p,proposalRevision:h,usage:wn,durationMs:Date.now()-r}),v=this.options.trace??"off",x=v!=="off",$=await this.newContext(pe(t.steps[0]?.session),t.displayName),E=this.sessionsFor(t,$,t.displayName),R=new Map,k=!x,C,P,m=await $.newPage(),A=fn(),O=[],T=(_,N)=>this.screenshot(_,t,"before-heal",N.stepText).then(F=>{F&&O.push(F)});try{let _=await(async()=>{let I;if(u&&!d){let M=fn(),U=await this.proofReplay(t,u.cache,M,"pending"),z=U.result,V=u.meta.recordedFor??t.name,ee=Object.keys(t.params).length>0&&V!==t.displayName;if(z.status==="passed"||ee?(C=U.context,P=U.sessions,A=M):(await U.sessions.close(),await U.context.close()),z.status==="passed")return w(z);if(ee){let Ie=z.failure,Ke=u.cache.examples??{},Ne=Ie?t.steps[Ie.stepIndex]?.text??"":"",Te=Object.keys(t.params).filter(at=>at in Ke&&Ke[at]!==t.params[at]).sort((at,Sn)=>Number(Ne.includes(`<${Sn}>`))-Number(Ne.includes(`<${at}>`))),qt=Te.slice(0,3).map(at=>`<${at}> is ${JSON.stringify(t.params[at])} here, ${JSON.stringify(Ke[at])} there${Ne.includes(`<${at}>`)?" (the failing step uses it)":""}`);return{scenario:t,status:"red",source:"agent-record",proposalReplay:!0,stepResults:z.stepResults,adaptations:[],proposalFile:p,proposalRevision:h,usage:wn,durationMs:Date.now()-r,error:`The pending proposal recorded for "${V}" does not replay for this Examples row`+(Ie?` (step "${Ie.stepText}": ${Vr(Ie.error,Pe(t))})`:"")+(qt.length>0?`. This row differs from it where ${qt.join("; ")}${Te.length>3?`; and ${Te.length-3} more column(s)`:""}`:"")+`. Check whether that step recorded the other row's value instead of a <placeholder> or acts on the wrong element (saffron diff ${p}); if so, reject it and re-record with saffron run --rerecord.`}}console.log(nt(` \u21BA pending proposal for "${t.displayName}" did not replay`+(z.failure?` (step "${z.failure.stepText}": ${Vr(z.failure.error,Pe(t))})`:"")+"; recording again",Pe(t)))}if(d){if(I=await Bo(m,t,d,{vars:R,sessions:E.pages,openSession:E.pageOf,downloadsDir:this.downloads(t),baseURL:o,actionTimeoutMs:a,retries:i,pollIntervalMs:c,uniqueSeed:A,trace:x,onFailure:T,keepResponseLog:!0}),I.status==="passed")return{scenario:t,status:"green",source:"cache",stepResults:I.stepResults,adaptations:[],usage:wn,durationMs:Date.now()-r};if(b)return I.responses?.detach(),y(I);let M=U=>d.steps[U].kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||li(d.steps,U));if(u&&I.status==="failed"&&d.steps.some((U,z)=>M(z)&&!ha(u.cache.steps[z]?.actions??[],U.actions))&&(u=void 0),u){let U=fn(),z=await this.proofReplay(t,u.cache,U,"pending");if(z.result.status==="passed")return I.responses?.detach(),C=z.context,P=z.sessions,A=U,w(z.result,I);await z.sessions.close(),await z.context.close(),console.log(nt(` \u21BA pending proposal for "${t.displayName}" did not replay`+(z.result.failure?` (step "${z.result.failure.stepText}": ${Vr(z.result.failure.error,Pe(t))})`:"")+(I.status==="failed"?"; healing":"; recording again"),Pe(t)))}}if(!(this.options.agent!==void 0&&this.cdpEndpoint!==void 0&&!n.agentDisabled&&this.agentHalt.reason===void 0)){let M=this.options.agent!==void 0&&!n.agentDisabled&&this.agentHalt.reason!==void 0?`the agent's provider reported a usage limit earlier in this run, so no AI session was started for it: ${this.agentHalt.reason}. Run it again once the limit resets.`:this.options.agent!==void 0&&this.cdpEndpoint===void 0&&!n.agentDisabled?`recording/healing needs a Chromium-family browser (the agent attaches over CDP). Record with --browser chromium (the default), chrome or msedge, then replay with --browser ${this.options.browser}.`:this.options.agent!==void 0&&n.agentDisabled?this.cdpEndpoint===void 0?`recording/healing needs a Chromium-family browser (the agent attaches over CDP). Record with --browser chromium (the default), chrome or msedge, then replay with --browser ${this.options.browser}.`:"this run was started without the agent (--no-agent), so nothing records it.":"no agent is configured.";I?.responses?.detach();let U=d!==void 0&&d.examples===void 0&&Object.keys(t.params).length>0&&d.steps.length===t.steps.length&&d.steps.every((z,V)=>{let ee=t.steps[V];return z.gherkin===ee.text&&z.kind===ee.kind&&z.docString===ee.docString&&JSON.stringify(z.table)===JSON.stringify(ee.table)})&&Object.entries(d.data??{}).every(([z,V])=>{try{return qe(z)===V}catch{return!0}});return{scenario:t,status:"red",source:"cache",stepResults:I?.stepResults??[],adaptations:[],usage:wn,durationMs:Date.now()-r,error:d?I?.status==="stale"?U?`The recording was made by an older saffron-ai and still holds another Examples row's value, so this row needs it recorded again once, and ${M}`:`Cache is stale (feature file changed) and ${M}`:`Replay failed and ${M} ${I?.failure?.error??""}`.trimEnd():`No cache exists and ${M}`}}let j=d!==void 0&&I!==void 0&&I.status==="failed",H=0,Z,Q;try{if(j){Q=I.responses;let M=E.contextOf(pe(t.steps[I.failure.stepIndex]?.session))??m.context(),U=await ai(this.browser,I.activePage??qr(M,I.failure.pageUrl)??m,E.contexts());Z=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:o,traceContext:x?m.context():void 0,mode:"heal",onBrowserAction:z=>{z===pe(t.steps[I.failure.stepIndex]?.session)&&Q?.markAction()},liveTab:U,model:this.options.healModel,cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,completedSteps:I.stepResults.filter(z=>z.status==="passed").map(z=>z.gherkin),failedStep:{text:I.failure.stepText,kind:I.failure.kind,error:I.failure.error,pageUrl:I.failure.pageUrl,stepIndex:I.failure.stepIndex},uniqueSeed:A,onTabOpened:this.tabWatcher(),onDownload:this.downloadWatcher(),...this.sessionHooks(t,E,m)}))}else if(await m.goto("about:blank"),await E.blank(),E.pages.set(E.mainKey,m),this.options.reuseSteps!==!1){let M=await this.recordWithSeeding(t,m,A,E);H=M.seededCount,Z=M}else Z=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:o,traceContext:x?m.context():void 0,mode:"record",cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,uniqueSeed:A,onTabOpened:this.tabWatcher(),onDownload:this.downloadWatcher(),...this.sessionHooks(t,E,m)}))}catch(M){Q?.detach();let U=M instanceof Error?M.message:String(M);return{scenario:t,status:"red",source:j?"agent-heal":"agent-record",stepResults:I?.stepResults??[],adaptations:[],usage:wn,durationMs:Date.now()-r,error:`Agent invocation failed: ${Vr(U,Pe(t))}`}}if(Z.success&&j&&I.failure.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||li(d.steps,I.failure.stepIndex))){let M=d.steps[I.failure.stepIndex],U=Fc(E,pe(t.steps[I.failure.stepIndex]?.session))??m,z=Wa(t,I.failure.stepIndex);try{for(let V of M.actions)await ys(U,V,z,this.options.actionTimeoutMs??5e3,o,R,Q,void 0,tt(t))}catch(V){let ee=V instanceof Error?V.message:String(V),Ie=`Assertion failed as written: "${M.gherkin}". Saffron never adapts assertions. If this change is intended, update the .feature file or re-record the scenario (saffron run --rerecord --filter @tag). If the recording itself looks wrong (an empty value, a wrong target), re-record it the same way. Verification error: ${Vr(ee,Pe(t))}`,Ke=I.failure.stepIndex,Ne=I.stepResults.map((Te,qt)=>qt===Ke?{...Te,status:"failed",error:Ie}:Te);return{scenario:t,status:"red",source:"agent-heal",stepResults:Ne,executionStepResults:Ne.map((Te,qt)=>qt>Ke&&Te.status==="skipped"?{...Te,status:"passed"}:Te),narrative:Z.narrative,adaptations:Z.adaptations,suggestedFeatureEdit:Z.suggestedFeatureEdit,usage:Z.usage,durationMs:Date.now()-r,error:Ie}}finally{Q?.detach()}}return Q?.detach(),await this.finalizeAgentRun(t,Z,j,d,r,H,j?I?.failure:void 0,A)})(),N=O.find(I=>I.kind==="before-heal");if(_.source==="cache"&&N){let I=N.file.replace(/before-heal\.jpg$/,"failure.jpg");try{Xt.renameSync(bt.join(s,N.file),bt.join(s,I)),N.file=I}catch{}N.kind="failure"}else if(_.status==="red"){let I=_.stepResults.findIndex(Z=>Z.status==="failed"),L=_.stepResults[I]?.gherkin,j=pe(t.steps[Math.max(I,0)]?.session),H=await this.screenshot(Fc(P??E,j)??m,t,"failure",L);H&&O.push(H)}let F=Ir(lt(t),A);if(F.size>0&&(_.uniques=Object.fromEntries(F)),O.push(..._.evidence??[]),x){let L=v==="on"||_.status!=="green"?bt.join(this.artifacts(t),Oa):void 0;k=!0;let j=C??$;L||await No(j).catch(()=>{});let H=L?await jo(j,L,Pe(t)):void 0,Z=Pe(t),Q=(_.executionStepResults??_.stepResults).map(z=>({...z,error:z.error&&nt(z.error,Z)})),M=P??E,U=await this.saveSessionTraces(t,M,L&&H?bt.basename(L,".zip"):void 0,{traceSteps:Q});L&&H&&(this.claimArtifactDir(t),O.unshift({kind:"trace",file:Be(s,L),sha256:H,traceSteps:Q,...this.namedSession(M,t.steps)},...U))}return O.length>0&&(_.status!=="green"||O.some(I=>I.kind==="trace"))&&(_.evidence=O),_}finally{k||await No($).catch(()=>{}),await P?.close(),await C?.close(),await E.close(),await $.close()}}async finalizeAgentRun(t,n,r,s,o,a=0,i,c=fn()){let l=r?"agent-heal":"agent-record",d=n.success?n.recordedSteps.map(j=>({gherkin:j.gherkin,kind:j.kind,status:"passed"})):qp(n.recordedSteps,n.announcedSteps??[],i&&{stepIndex:i.stepIndex,error:i.error},n.narrative);if(!n.success)return{scenario:t,status:"red",source:l,stepResults:d,narrative:n.narrative,adaptations:n.adaptations,usage:n.usage,durationMs:Date.now()-o,error:n.narrative};let f=r?Fp(s.steps,n.recordedSteps,this.options.assertionPolicy==="adaptable-mid",i?{stepIndex:i.stepIndex,actionIndex:i.actionIndex}:void 0):n.recordedSteps,p=[...n.adaptations,...r&&i?Lp(n.recordedSteps,i.stepIndex):[]],u={...n.usage},h,b,g,S,y=[],w=0,v=new Set,x,$=async({context:j,sessions:H},Z,Q=Z.stepResults)=>{if(!v.has(j)){v.add(j);try{if(this.options.trace&&this.options.trace!=="off"){let M=`proof-${++w}`,U=bt.join(this.artifacts(t),`${M}.zip`),z=Pe(t),V=await jo(j,U,z),ee=Z.captured[Ct],Ie=ee?Ir(lt(t),ee):new Map,Ke={proof:!0,traceSteps:Q.map(Te=>({...Te,error:Te.error&&nt(Te.error,z)})),traceUniques:Ie.size?Object.fromEntries(Ie):void 0},Ne=await this.saveSessionTraces(t,H,V?M:void 0,Ke);V&&(this.claimArtifactDir(t),y.push({kind:"trace",file:Be(this.options.projectRoot,U),sha256:V,...Ke,...this.namedSession(H,t.steps)},...Ne))}}finally{await H.close(),await j.close()}}};if(this.options.verifyProposals!==!1){let j=await this.proofReplay(t,this.buildCandidateCache(t,f),fn());S=j.result.captured[Ct];try{if(j.result.status!=="passed"&&j.result.failure){let H=j.result.failure;if(this.options.agent&&!(r&&H.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||li(s.steps,H.stepIndex))))try{let Q=j.sessions.contextOf(pe(t.steps[H.stepIndex]?.session))??j.context,M=await ai(this.browser,j.result.activePage??qr(Q,H.pageUrl)??j.page,j.sessions.contexts()),U=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:this.options.baseURL,traceContext:this.options.trace&&this.options.trace!=="off"?j.context:void 0,mode:"refine",model:r?this.options.healModel:void 0,cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,completedSteps:j.result.stepResults.filter(z=>z.status==="passed").map(z=>z.gherkin),failedStep:{text:H.stepText,kind:H.kind,error:H.error,pageUrl:H.pageUrl,stepIndex:H.stepIndex},liveTab:M,uniqueSeed:j.result.captured[Ct],onTabOpened:this.tabWatcher(),onDownload:this.downloadWatcher(),...this.sessionHooks(t,j.sessions,j.page)}));u=Bp(u,U.usage),x=av(j.result.stepResults,H,U),U.success&&(p.push(...U.adaptations),p.push(...Lp(U.recordedSteps,H.stepIndex)),f=r?Fp(f,U.recordedSteps,this.options.assertionPolicy==="adaptable-mid",{stepIndex:H.stepIndex,actionIndex:0}):iv(f,U.recordedSteps,H.stepIndex),await $(j,j.result,x),x=void 0,j=await this.proofReplay(t,this.buildCandidateCache(t,f),fn()),S=j.result.captured[Ct])}catch{}}for(let H of j.result.tabOpeners??[]){let Z=f[H.stepIndex]?.actions[H.actionIndex];Z&&(Z.opensTab=!0)}h=j.result.status==="passed",h||(b=j.result.failure?.error??`proof replay ${j.result.status}`,g=j.result.stepResults)}finally{await $(j,j.result,x).catch(()=>{})}}r&&s&&p.push(...ov(s.steps,f,i,this.options.baseURL));let E=j=>r&&t.steps[j]?.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||li(s.steps,j)),R=n.featureEdits.filter(j=>!E(j.index));for(let j of Ud(f,Wt(this.options.projectRoot)))p.push(`duplicate wording: "${j.from}" recorded exactly the same actions as the existing step "${j.to}" (${j.feature} \u203A ${j.scenario}). Accept with --with-feature-edit to converge on the canonical wording.`),R.some(H=>H.index===j.index)||R.push({index:j.index,text:j.to});let k=_p(f);k.length>0&&(h=!1,b=[b,...k].filter(Boolean).join(" "));let C=Pe(t),P=j=>C.size>0?nt(j,C):j;p=p.map(P);let m=R.map(j=>({index:j.index,text:P(j.text)})),A=P(n.narrative),O=n.suggestedFeatureEdit?P(n.suggestedFeatureEdit):void 0,T={version:1,feature:t.featurePath,scenario:t.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:f,...Dp(t,f)},_={...T,version:as(T)},N={meta:{createdAt:_.recordedAt,mode:r?"heal":"record",narrative:A,adaptations:p,suggestedFeatureEdit:O,featureEdits:m.length>0?m:void 0,verified:h,proofError:b?P(b):void 0,seededSteps:a>0?a:void 0,recordedFor:t.displayName,usage:u,bound:ef(t,s,_,m.length>0?m:void 0)},cache:_},F=xt(this.options.projectRoot,t.featurePath,t.name),I=Yd(F,N);eu(this.options.projectRoot,F,I),this.filedThisRun.set(F,I);let L=st(me(this.options.projectRoot,t.featurePath,t.name));return{proposalDiff:Nn(L,N.cache),scenario:t,status:"yellow",source:l,stepResults:g??d,executionStepResults:d,evidence:y,proofUniques:(()=>{let j=S?Ir(lt(t),S):void 0;return j&&j.size>0?Object.fromEntries(j):void 0})(),narrative:A,adaptations:p,suggestedFeatureEdit:O,featureEdits:m.length>0?m:void 0,verified:h,proofError:b,seededSteps:a>0?a:void 0,proposalFile:Be(this.options.projectRoot,F),proposalRevision:I,usage:u,durationMs:Date.now()-o}}};import ki from"node:fs";import mx from"node:os";import Sg from"node:path";import{query as Bv}from"@anthropic-ai/claude-agent-sdk";import{createRequire as cv}from"node:module";import lv from"node:path";import{McpServer as dv}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as ne}from"zod";var _e=e=>({content:[{type:"text",text:e}]});function Jr(e,t,n,r){let s=async o=>{let a=await r(o);return a.content[0]?.text.startsWith("ERROR:")?{...a,isError:!0}:a};return o=>{o.registerTool(e,{description:t,inputSchema:n},s)}}function uv(e){let t=new dv({name:e.name,version:e.version});for(let n of e.tools)n(t);return{type:"sdk",name:e.name,instance:t}}function Vp(e){let t={};return e.role&&(t.role=e.role),e.name&&(t.name=e.name),e.nameRegex&&(t.nameRegex=e.nameRegex),e.label&&(t.label=e.label),e.text&&(t.text=e.text),e.selector&&(t.fallbackSelectors=[e.selector]),e.frame&&(t.frame=e.frame),Object.keys(t).length>0?t:void 0}var fv=new Set(["main","banner","contentinfo","status","alert","alertdialog","dialog","search"]);function Jp(e){if(!e?.role)return;let{role:t,frame:n,...r}=e;if(!(Object.keys(r).length>0||fv.has(t)))return`ERROR: role="${t}" alone matches every ${t} on the page, and replay would use the first one. Add a name (or nameRegex), text, label or selector that picks exactly the element you checked, then call again.`}function pv(e,t){if(t.index>=e.steps.length)return`ERROR: there is no step ${t.index}: this scenario's steps are numbered from 0 to ${e.steps.length-1}. Call saffron_step again with the zero-based index of the step you are about to perform.`;if(e.announce(t.index,t.text,t.adaptation),t.index<e.firstStep)return`Step ${t.index} already ran before you took over and keeps its recording; nothing you do under it is recorded. Do not redo it: continue from step ${e.firstStep} on the page as it is.`;let n=e.steps[t.index].kind==="assertion"?"verify it from a snapshot and record the check with saffron_assert":"do it now with the browser tools";return`Recording step ${t.index}: ${t.text}. This only files the browser calls that follow under the step; it performs nothing itself, so ${n}.`}function gv(e){let t=Math.max(-1,...e.announced,e.lastStep??-1),n=[],r=[],s=c=>[...fe(e.steps[c]?.gherkin??"").matchAll(/<([^<>]+)>/g)].some(l=>e.params?.[l[1]]!==void 0),o=[...new Set([...e.announced,...e.lastStep===void 0?[]:e.steps.map((c,l)=>l).filter(c=>c<=e.lastStep)])].filter(c=>c>=e.firstStep&&e.steps[c]?.kind==="assertion"&&!e.steps[c].actions.some(l=>Se.has(l.action))).sort((c,l)=>c-l);o.length>0&&n.push(`Assertion step ${o.join(", ")} recorded no check, so replay would verify nothing. Record what you verified with saffron_assert under that step (saffron_step first if you moved on).`);let a=[],i=!1;for(let c=0;c<=t;c++){let l=e.steps[c],d=l?.keyword.trim().toLowerCase(),f=d===void 0?void 0:hv.get(d);if(e.setupSteps[c]!==void 0?i=e.setupSteps[c]:f!==void 0&&(i=f==="given"),c<e.firstStep||l?.kind!=="action"&&l?.kind!=="assertion")continue;let p=l.kind==="assertion";if(!p&&l.actions.length===0){(!i||s(c))&&a.push(c);continue}if(l.actions.filter(b=>Hr(b)||oi(b)||p&&b.target!==void 0&&Se.has(b.action)).length===0)continue;let h=new Set(Is(e.resolvedTexts[c]??"",!0));for(let b of Is(e.resolvedTexts[c]??"")){let g;try{g=Dt(b)}catch{continue}let S=/[{}<>]/.test(g)?[]:jc(l.actions,g,p,h.has(b));if(S.length!==0){r.push({index:c,actions:S}),n.push(`Step ${c} acts in "${g}", but ${S.length===1?"this target does":"these targets do"} not name it (${S.map(it).join("; ")}). Replay would act on the first match, which on a page with two such sections is the wrong one. If its element is still on the page, call saffron_step ${c} again and perform only ${S.length===1?"that action":"those actions"} once more with a target scoped to that container, e.g. selector 'role=region[name="${g}"] >> role=textbox[name="..."]' (a snapshot ref is not scoped; a capture or a check is saffron_capture or saffron_assert again with that selector): the new action takes the old one's place, and the step's other actions stay. An element of a dialog or menu that a scoped action opened is not in the section: scope it to that dialog instead ('role=dialog >> role=button[name="..."]'). If the page has moved on, do not go back for it.`);break}}}if(a.length>0){let c=a.filter(s);n.push(`Action step ${a.join(", ")} recorded no browser action. saffron_step performs nothing: perform the step with a browser tool right after announcing it, or, for a step that waits for the page, record what it waits for with saffron_assert so replay waits too. If you already performed its action under another step, do not perform it again: replay runs it there. `+(c.length===a.length?"":"If the page already was in the state the step asks for, it needs nothing. ")+(c.length===0?"":`Step ${c.join(", ")} names an Examples column, which other rows set to other values: even if the page already shows this row's value, call saffron_step again and pick it (click the option or radio labelled with it), so replay picks each row's own. Left empty, every row replays this row's page.`))}return{problems:n,redo:r}}var hv=(()=>{let e=cv(import.meta.url)("@cucumber/gherkin").dialects,t=new Map;for(let n of Object.values(e))for(let r of["when","then","given"])for(let s of n[r])s.trim()!=="*"&&t.set(s.trim().toLowerCase(),r);return t})(),Wp=new WeakSet;function mv(e,t){if(t.success&&!Wp.has(e)){let{problems:n,redo:r}=gv(e);if(n.length>0)return Wp.add(e),e.redo(r),`ERROR: not finalized. ${n.join(" ")} Then call saffron_done again. If a condition does not hold, call saffron_done with success=false.`}return e.done=!0,e.success=t.success,e.narrative=t.narrative,e.suggestedFeatureEdit=t.suggestedFeatureEdit,e.featureEdits=(t.featureEdits??[]).filter(n=>!ua.test(n.text)&&n.text.trim()!==""),"Run finalized."}function wv(e,t){let n=new Set(e.steps.flatMap(a=>a.actions.flatMap(i=>i.action==="captureText"&&i.saveAs?[i.saveAs]:[]))),r=e.resolvedTexts.slice(0,Math.min(e.firstStep,Math.max(e.currentStepIndex,0))).join(`
|
|
349
|
-
`),s=t;try{s=Dt(t)}catch{}let o=po(s,a=>n.has(a)||r.includes(`"${a}"`)?"0":void 0);if("problem"in o)return`ERROR: kind=amount: ${o.problem}. Capture each value first with saffron_capture (its saveAs), then name it in double quotes, operators between spaces: '"before" + "breakfast"'.`}async function yv(e,t,n){if(e.downloadUnarmed)return"ERROR: the latest download began when no action of yours was running and none could be credited with it, so replay would not wait for it. Announce the step that downloads it, perform that action again, then record the check.";if(!e.lastDownload)return e.firstStep===0?'ERROR: nothing was downloaded in this session. Perform the action that downloads the file first (its result lists "Downloading file"), then record the check.':void 0;let r=await e.lastDownload;if(!r)return"ERROR: the file this session downloaded last did not finish downloading, so its content cannot be checked.";let s,o;try{let i=p=>p===void 0||p===""?void 0:Yt(p,e.uniqueSeed),c=Object.fromEntries(Object.entries(e.params).map(([p,u])=>[p,Yt(u,e.uniqueSeed)])),l={value:i(t),pattern:i(n)},d=Va(l,c,e.envNames,e.startedAt);if(d)return`ERROR: ${d} Not recorded.`;s=await qa(r);let f=Lo(l,c,e.envNames,e.startedAt);o=Ja(s,lv.basename(r),f.value,f.pattern,l.value)}catch(i){return`ERROR: ${i instanceof Error?i.message:String(i)}.`}if(!o)return;let a=2e3;return`ERROR: ${o}. Not recorded. Its text${s.length>a?` begins (${a} of ${s.length} characters)`:" is"}:
|
|
350
|
-
${s.slice(0,a)}
|
|
351
|
-
Record the check the step asks for as the file holds it. If the file does not hold what the step says, call saffron_done with success=false.`}var Gp={role:ne.string().optional().describe("ARIA role of the element"),name:ne.string().optional().describe("Full accessible name (exact match). For volatile content like prices or dates, use nameRegex instead."),nameRegex:ne.string().optional().describe("Regex for the accessible name when it embeds volatile content, e.g. 'Select \\\\{date\\\\+1\\\\} as checkin' cannot work \u2014 instead use nameRegex 'Select .* as checkin'"),label:ne.string().optional().describe("Form-label text for getByLabel \u2014 the literal <label> text only, never a free-text description"),text:ne.string().optional().describe("getByText locator text"),selector:ne.string().optional().describe("CSS fallback selector"),frame:ne.string().optional().describe(`CSS selector of the iframe hosting the element, e.g. 'iframe[title="Feedback widget"]' \u2014 REQUIRED whenever the element lives inside an iframe; without it replay looks only at the top-level page`)};function ui(e){return uv({name:"saffron",version:"0.1.0",tools:[Jr("saffron_step","Announce the Gherkin step you are about to perform. MUST be called before executing browser actions for each step, with the step's zero-based index and exact text.",{index:ne.number().int().min(0),text:ne.string(),adaptation:ne.string().optional().describe("If the written step does not match the real UI and you are deviating from it, describe the deviation in one sentence: the kind of change (a locator or label change on the same page, a page removed or merged, a page added or flow reordered) and the page it happened on.")},async t=>_e(pv(e,t))),Jr("saffron_capture",`Record a captureText action for the current step: at replay time, the target element's text is read and stored under saveAs for later expectDiffers comparisons. Use for steps like 'I record the displayed price as "X"'. The target must select exactly the element whose text is the value.`,{saveAs:ne.string().describe("Name to store the captured text under"),...Gp},async t=>{let n=Vp(t);if(!n)return _e("ERROR: capture needs a target (role/name, nameRegex, label, text, or selector).");let r=Jp(n);return r?_e(r):(e.addActions([{action:"captureText",target:n,saveAs:t.saveAs}]),_e(`Capture recorded as "${t.saveAs}".`))}),Jr("saffron_dialog","Record how a native dialog (alert/confirm/prompt) must be handled at replay. Call this IMMEDIATELY whenever an action triggers a native dialog \u2014 whether you handled it via browser_handle_dialog or the browser reported it as already handled. At replay Saffron arms this handler BEFORE the triggering action, so without this call the replay will auto-dismiss the dialog and diverge from what you saw.",{accept:ne.boolean().describe("true = accept/OK the dialog, false = dismiss/cancel"),promptText:ne.string().optional().describe("Text typed into a prompt() before accepting")},async t=>(e.addArmedAction({action:"handleDialog",value:t.accept?"accept":"dismiss",...t.promptText?{promptText:t.promptText}:{}}),_e(`Dialog handling recorded (${t.accept?"accept":"dismiss"}).`))),Jr("saffron_wait_api","Record a network wait for the current step: replay will block until a matching API response is observed (responses from the triggering step count). Call AFTER you verified via browser_network_requests that the response actually occurred with the expected status/body. Use a path-only urlPattern regex and never literal volatile IDs (/api/orders/\\d+, not /api/orders/8842).",{urlPattern:ne.string().describe("Regex matched against the response URL \u2014 path-only for portability"),method:ne.string().optional().describe("HTTP method to match (any if omitted)"),status:ne.string().optional().describe("Expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:ne.string().optional().describe(`Regex the response body must match, e.g. '"status"\\s*:\\s*"READY"' for polling waits`)},async t=>(e.addActions([{action:"waitForResponse",urlPattern:t.urlPattern,...t.method?{method:t.method}:{},...t.status?{status:t.status}:{},...t.bodyPattern?{pattern:t.bodyPattern}:{}}]),_e("Network wait recorded."))),Jr("saffron_assert","Record a verified assertion for the current Then step. Call ONLY after you have confirmed the condition holds via a page snapshot. If the condition does NOT hold, do not call this: call saffron_done with success=false instead. NEVER record volatile content the step does not state (prices, counters, a date the step does not give) as literal expected text: use kind=matches with a pattern, kind=differs against captured values, or kind=amount. A value or date the step itself states, record exactly as the step shows it to you: Saffron turns a date back into the step's token, so it moves with the calendar.",{kind:ne.enum(["visible","notVisible","text","url","value","differs","matches","attribute","response","each","download","amount"]),...Gp,expected:ne.string().optional().describe(`Required for kind=text|value. Stable expected text/value; use an explicit empty string only for an empty check. kind=download: text the downloaded file must contain, e.g. 'DTSTART;VALUE=DATE:{date+7:YYYYMMDD}' (write a date as the step writes it). kind=amount: the amount the target must show, as arithmetic over values captured with saffron_capture (their saveAs in double quotes) and written amounts, operators between spaces, e.g. '"before" + "breakfast"', '"night" * 2', '"total" - "discount"'; compared to the cent, whatever the currency format`),url:ne.string().optional().describe("URL substring for kind=url (path only, no host)"),pattern:ne.string().optional().describe("kind=matches|attribute: regex the target's text (or attribute) must match, e.g. 'NOK [\\\\d,]+' for a price. Attribute patterns are case-sensitive. kind=download: regex the downloaded file's text must match (case-sensitive, ^ and $ at each line)"),attribute:ne.string().optional().describe("kind=attribute: attribute name to check, e.g. 'href' for link-target assertions \u2014 use this for 'X should link to Y' instead of clicking through"),capture:ne.string().optional().describe("kind=differs: name of the captured value on the LEFT of the comparison (omit when comparing the target element's live text)"),urlPattern:ne.string().optional().describe("kind=response: regex matched against the response URL. Check before the next browser interaction or navigation; only requests started since the latest action qualify. Use a path for portability, never literal volatile IDs (use /api/orders/\\d+)."),method:ne.string().optional().describe("kind=response: HTTP method to match (any if omitted)"),status:ne.string().optional().describe("kind=response: expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:ne.string().optional().describe("kind=response: regex the response body must match (verify via browser_network_requests first)"),each:ne.string().optional().describe("kind=each: the data-list token exactly as the step writes it, e.g. '{data:enums.OrderStatus}'. The target is the CONTAINER (dropdown, table, list) that must show every value of that list. Never pass the values themselves."),compareTo:ne.string().optional().describe("kind=differs: name of the captured value to compare against")},async t=>{let n=Vp(t),r=Jp(n);if(r)return _e(r);if((t.kind==="text"||t.kind==="value")&&t.expected===void 0)return _e(`ERROR: kind=${t.kind} requires expected. Use an explicit empty string only to check that the element is empty.`);let s;switch(t.kind){case"visible":s={action:"expectVisible",target:n};break;case"notVisible":s={action:"expectNotVisible",target:n};break;case"text":s={action:"expectText",target:n,value:t.expected??""};break;case"value":s={action:"expectValue",target:n,value:t.expected??""};break;case"url":s={action:"expectUrl",url:t.url??""};break;case"differs":if(!t.compareTo)return _e("ERROR: kind=differs requires compareTo.");if(!t.capture&&!n)return _e("ERROR: kind=differs needs either capture (a stored name) or a target element.");s={action:"expectDiffers",target:n,value:t.capture,compareTo:t.compareTo};break;case"matches":if(!t.pattern)return _e("ERROR: kind=matches requires pattern.");s={action:"expectMatches",target:n,pattern:t.pattern};break;case"attribute":if(!t.attribute||!t.pattern)return _e("ERROR: kind=attribute requires attribute and pattern.");s={action:"expectAttribute",target:n,attribute:t.attribute,pattern:t.pattern};break;case"each":if(!t.each||!/^\{data:[^}]+\}$/.test(t.each))return _e("ERROR: kind=each requires each='{data:file.list}', the token exactly as the step writes it (not the values).");s={action:"expectEach",target:n,each:t.each};break;case"amount":{if(!t.expected)return _e(`ERROR: kind=amount requires expected: the amount as arithmetic over captured names in double quotes and written amounts, e.g. '"before" + "breakfast"'.`);let o=wv(e,t.expected);if(o)return _e(o);s={action:"expectAmount",target:n,value:t.expected};break}case"download":{if(!t.expected&&!t.pattern)return _e("ERROR: kind=download requires expected (text the file contains) or pattern (a regex its text matches).");s={action:"expectDownload",...t.expected?{value:t.expected}:{},...t.pattern?{pattern:t.pattern}:{}};let o=await yv(e,t.expected,t.pattern);if(o)return _e(o);break}case"response":if(!t.urlPattern)return _e("ERROR: kind=response requires urlPattern.");s={action:"expectResponse",urlPattern:t.urlPattern,...t.method?{method:t.method}:{},...t.status?{status:t.status}:{},...t.bodyPattern?{pattern:t.bodyPattern}:{}};break}return!["url","differs","response","download"].includes(t.kind)&&!n?_e("ERROR: assertion needs a target (role/name, nameRegex, label, text, or selector)."):(e.addActions([s]),_e("Assertion recorded."))}),Jr("saffron_done","Finalize the run. Call exactly once, after the final step: success=true only if every step's intent was achieved and every assertion verified.",{success:ne.boolean(),narrative:ne.string().describe("2-4 sentence summary of the run: what happened, and why it failed if it did. After a heal, say what kind of change the app went through (a locator change, or a page removed, merged, added or reordered) and on which page."),suggestedFeatureEdit:ne.string().optional().describe("If you adapted any steps: the corrected Gherkin for those steps, as you would rewrite them in the .feature file (free text, for the human report)."),featureEdits:ne.array(ne.object({index:ne.number().int().min(0).describe("zero-based step index"),text:ne.string().min(1).regex(/\S/,"a step text cannot be blank").describe("replacement step text WITHOUT the Given/When/Then keyword")})).optional().describe("Machine-applicable version of the suggested edits: one entry per adapted step. Provide this whenever you adapted a step.")},async t=>_e(mv(e,t)))]})}function pi(e={}){let t=e.deliberateSnapshots?`
|
|
341
|
+
Invoke it anywhere with: StepSet Name`,filterText:"step set stepset:",sortText:"0",insertTextFormat:lg.Snippet,textEdit:{range:g,newText:"StepSet: ${1:Name}\n "}}];r.stepSets.length===0&&y.push({label:"StepSet \u2026",kind:Zn.Keyword,detail:"invoke a step set (none defined yet)",filterText:"step set stepset",sortText:"1",insertTextFormat:lg.Snippet,textEdit:{range:g,newText:"StepSet ${1:Name}"}});for(let h of r.stepSets)y.push({label:`StepSet ${h.name}`,kind:Zn.Function,detail:`invoke step set \xB7 ${h.steps.length} step(s)`,documentation:h.steps.join(`
|
|
342
|
+
`),filterText:`step set ${h.name}`,sortText:`1${h.name}`,textEdit:{range:g,newText:`StepSet ${h.name}`}});return y}return[]}async function ul(e,t,n){let r=[...e],s;if(await Promise.all(Array.from({length:Math.min(t,r.length)},async(o,a)=>{for(let i=r.shift();i&&!s;i=r.shift())for(let c of i){if(s)return;try{await n(c,a)}catch(l){s??={error:l};return}}})),s)throw s.error}function vg(e,t){let n=new Map;for(let r of e)n.set(t(r),[...n.get(t(r))??[],r]);return[...n.values()]}import un from"node:fs";import Wx from"node:net";import kt from"node:path";import{chromium as Gx,devices as pl,firefox as Kx,webkit as Yx}from"playwright";function ts(e,t){let n=e.pages().filter(s=>!s.isClosed()),r=s=>[...n].reverse().find(s);return(t?r(s=>s.url()===t):void 0)??r(s=>s.url()!=="about:blank")??n.at(-1)}async function Ri(e,t,n=[]){let r=t.context();for(let o of e.contexts())if(!(o===r||n.includes(o)))for(let a of o.pages())await a.close().catch(()=>{});await t.bringToFront().catch(()=>{});let s=r.pages().filter(o=>!o.isClosed());return{index:Math.max(s.indexOf(t),0),count:s.length,url:t.url()}}var Ti=class{constructor(t,n,r,s=o=>o.newPage()){this.main=t;this.mainKey=n;this.create=r;this.newPage=s;this.follow(t,n)}main;mainKey;create;newPage;pages=new Map;others=new Map;follow(t,n){t.on("page",r=>this.pages.set(n,r))}contextOf(t){return t===this.mainKey?this.main:this.others.get(t)}contexts(){return[this.main,...this.others.values()]}opened(){return[...this.others]}async open(t){let n=await this.create(t);this.others.set(t,n),this.follow(n,t);let r=await this.newPage(n);return this.pages.set(t,r),r}livePage(t){let n=this.pages.get(t);if(n&&!n.isClosed())return n;let r=this.contextOf(t);return r&&ts(r)}pageOf=async t=>{let n=this.livePage(t);if(n)return this.pages.set(t,n),n;let r=this.contextOf(t);if(!r)return this.open(t);let s=await this.newPage(r);return this.pages.set(t,s),s};selectTab(t,n){t??=this.mainKey;let r=this.contextOf(t)?.pages().filter(s=>!s.isClosed())[n];r&&this.pages.set(t,r)}async blank(){for(let[t,n]of this.others){let r=ts(n)??await this.newPage(n);await r.goto("about:blank").catch(()=>{}),this.pages.set(t,r)}}async close(){for(let t of this.others.values())await t.close().catch(()=>{});this.others.clear()}};var Zs="Agent session error: ";var ml=["chromium","chrome","msedge","firefox","webkit"],gl={chrome:{label:"Google Chrome"},msedge:{label:"Microsoft Edge"}};function Tg(e){return ml.includes(e)}function yr(e){return e==="chromium"||gl[e]!==void 0}var _t=class extends Error{},hl=class extends _t{},wl=Object.keys(pl);function Ag(e){let t=/^(\d{2,5})x(\d{2,5})$/.exec(e.trim());return t?{width:Number(t[1]),height:Number(t[2])}:void 0}var Zx=/usage limit|insufficient_quota|exceeded your (?:current )?quota|quota exceeded|credit balance is too low/i,Qx=/per min(?:ute)?\b|\b[TR]PM\b|(?:re)?try (?:again )?(?:in|after) \d+(?:\.\d+)?\s*(?:ms|s|sec|seconds?)\b/i,Xx=e=>Zx.test(e)&&!Qx.test(e);function ns(e,t){return Ge(e,t).split(`
|
|
343
|
+
`)[0]}function ev(e,t){let n=(r,s)=>{t.reason!==void 0||!Xx(r)||(t.reason=ns(r,Te(s.scenario)).replace(/\.$/,""),console.log(` \u26A0 the agent's provider reported a usage limit; no new AI session starts in this run: ${t.reason}`))};return{run:async r=>{if(t.reason!==void 0)throw new Error(`the agent's provider reported a usage limit earlier in this run: ${t.reason}`);try{let s=await e.run(r);return!s.success&&s.narrative.startsWith(Zs)&&n(s.narrative.slice(Zs.length),r),s}catch(s){throw n(s instanceof Error?s.message:String(s),r),s}},...e.planUsage?{planUsage:()=>e.planUsage()}:{}}}var On={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0};async function tv(){return new Promise((e,t)=>{let n=Wx.createServer();n.listen(0,"127.0.0.1",()=>{let{port:r}=n.address();n.close(()=>e(r))}),n.on("error",t)})}function nv(e){try{return`${e}
|
|
344
|
+
${zt(e)}`}catch{return e}}function Sg(e,t){let n=Er(at(e)),r=ei(t,e);return{...n.size>0?{data:Object.fromEntries([...n].sort(([s],[o])=>s.localeCompare(o)))}:{},...Object.keys(e.params).length>0?{examples:e.params}:{},...r.length>0?{rowBound:r}:{},...(e.exampleRows??[]).some(s=>nr(nv(JSON.stringify(s))))?{rowsUseNewDates:!0}:{}}}function fl(e,t){return e.livePage(t??e.mainKey)}function Eg(e){let t=e.length;for(let n=e.length-1;n>=0&&e[n].kind==="assertion";n--)t=n;return t}function Ai(e,t){return e[t]?.kind==="assertion"&&t>=Eg(e)}function $g(e,t,n=!1,r){let s=Eg(e);return e.map((o,a)=>{if(r&&a<r.stepIndex)return o;let i=t[a],c=i&&i.actions.length>0;return o.kind==="assertion"&&!(n&&a<s)||!c?o:r&&a===r.stepIndex&&r.actionIndex>0?{...i,actions:[...o.actions.slice(0,r.actionIndex),...i.actions]}:i})}function rv(e,t,n,r){let s=Qu(e,t);return s.length===0||!n?.pageUrl?s:[`page at failure: replay stopped at step ${n.stepIndex+1} ("${n.stepText}") on ${xs(n.pageUrl,r)}, where the heal started.`,...s]}function sv(e,t,n=0){return e.map((r,s)=>{if(s<n)return r;let o=t[s];return o&&o.actions.length>0?o:r})}function kg(e,t){let n=[];for(let r=0;r<Math.min(t,e.length);r++){let s=e[r].actions.length;s!==0&&n.push(`recording: kept the existing recording of step ${r+1} ("${e[r].gherkin}"), which ran before the agent took over; ignored ${s} action${s===1?"":"s"} the agent's session held for it.`)}return n}function Og(e,t,n,r){let s=t.filter(c=>c>=0&&c<e.length),o=s.length>0?Math.max(...s):0,a=Math.min(n&&n.stepIndex>=o?n.stepIndex:o,e.length-1),i=n&&a===n.stepIndex?n.error:r;return e.map((c,l)=>({gherkin:c.gherkin,kind:c.kind,status:l<a?"passed":l===a?"failed":"skipped",...l===a&&i?{error:i}:{}}))}function ov(e,t,n){let r=n.success?e.map(s=>({gherkin:s.gherkin,kind:s.kind,status:"passed"})):Og(e,n.announcedSteps??[],t,n.narrative);return e.map((s,o)=>o<t.stepIndex?s:r[o])}function Rg(e,t){return{aiCalls:e.aiCalls+t.aiCalls,inputTokens:e.inputTokens+t.inputTokens,outputTokens:e.outputTokens+t.outputTokens,cacheReadTokens:e.cacheReadTokens+t.cacheReadTokens,cacheCreationTokens:e.cacheCreationTokens+t.cacheCreationTokens,costUsd:(e.costUsd??0)+(t.costUsd??0),models:e.models||t.models?[...new Set([...e.models??[],...t.models??[]])]:void 0}}var Ei=class{constructor(t){this.options=t;this.filedThisRun=t.filedThisRun??new Map,this.agentHalt=t.agentHalt??{},t.agent&&(this.options={...t,agent:ev(t.agent,this.agentHalt)})}options;browser;cdpEndpoint;stepIndex;tabListeners=new Set;downloadListeners=new Set;armDialogs;openingOwnPages=new Set;filedThisRun;agentHalt;get agent(){return this.options.agent}getStepIndex(){if(!this.stepIndex&&(this.stepIndex=nn(this.options.projectRoot),this.stepIndex.steps.size>0)){let t=this.stepIndex.divergent.length>0?` \xB7 ${this.stepIndex.divergent.length} step(s) have divergent recordings (Level-2 signal)`:"";console.log(`step index: ${this.stepIndex.steps.size} reusable steps from ${this.stepIndex.scannedCaches} cache(s)${t}`)}return this.stepIndex}async recordWithSeeding(t,n,r,s){let o=this.getStepIndex(),a=t.steps.length,i={...t.params,...Mn(t.steps)},c=t.steps.map(m=>{let $=o.steps.size>0?xu(o,m,i):void 0;return $?{gherkin:m.text,keyword:m.keyword,kind:m.kind,table:m.table,docString:m.docString,fromStepSet:m.source?.fromStepSet,actions:$.actions}:void 0}),l=t.steps.map(m=>({gherkin:m.text,keyword:m.keyword,kind:m.kind,table:m.table,docString:m.docString,fromStepSet:m.source?.fromStepSet,actions:[]})),d=new Map;d.set(Nt,r);let u=[],p=[],f=[],g=[],y={...On},h=m=>s.pageOf(we(t.steps[m]?.session)),S=0,v=0,x=0,b=(m,$)=>({success:m,narrative:p.join(" ")||"Composed entirely from seeded recordings.",adaptations:u,suggestedFeatureEdit:g.length>0?g.join(`
|
|
345
|
+
`):void 0,featureEdits:f,recordedSteps:l,announcedSteps:$===void 0?[]:Array.from({length:$+1},(T,R)=>R),usage:y,seededCount:S});for(;x<a;){if(c[x]){let C=x;for(;C<a&&c[C];)C++;let P=c.slice(x,C),w={...t,steps:t.steps.slice(x,C)},E=await di(await h(x),w,this.buildCandidateCache(t,P),{sessions:s.pages,openSession:s.pageOf,downloadsDir:this.downloads(t),baseURL:this.options.baseURL,actionTimeoutMs:this.options.actionTimeoutMs,retries:this.options.retries,pollIntervalMs:this.options.pollIntervalMs,vars:d,trace:this.options.trace!==void 0&&this.options.trace!=="off",traceStepOffset:x,envNames:ct(t)}),_=E.status==="passed"?C-x:E.failure?.stepIndex??0;for(let O=0;O<_;O++)l[x+O]=P[O];if(S+=_,E.status==="passed"){x=C;continue}let A=x+_;u.push(`Seeded recording for "${t.steps[A].text}" did not replay in this scenario's context; the agent re-recorded it fresh. Divergence signal.`),c[A]=void 0,x=A;continue}if(!this.options.agent)return b(!1,x);v++;let m=x;for(;m<a&&!c[m];)m++;v>=3&&(m=a);let $=await Ri(this.browser,await h(x),s.contexts()),T=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:this.options.baseURL,traceContext:this.options.trace&&this.options.trace!=="off"?n.context():void 0,mode:"record",cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,completedSteps:x>0?t.steps.slice(0,x).map(C=>C.resolvedText):void 0,recordOnly:m<a?{from:x,to:m-1}:void 0,liveTab:$,uniqueSeed:d.get(Nt),onTabOpened:this.tabWatcher(),onDownload:this.downloadWatcher(),...this.sessionHooks(t,s,n)}));if(y=Rg(y,T.usage),p.push(T.narrative),u.push(...T.adaptations),f.push(...T.featureEdits),T.suggestedFeatureEdit&&g.push(T.suggestedFeatureEdit),!T.success){let C=T.announcedSteps.filter(P=>P>=x&&P<a);return b(!1,C.length>0?Math.max(...C):x)}let R=T.announcedSteps.filter(C=>C>=x&&C<a),k=Math.min(a-1,Math.max(R.length>0?Math.max(...R):m-1,x));for(let C=x;C<=k;C++)l[C]=T.recordedSteps[C];x=k+1}return b(!0)}async withDialogsVisible(t){let n=()=>{},r=[],s=[],o=i=>{i.on("dialog",n),r.push(i)},a=i=>{i.on("page",o),s.push(i);for(let c of i.pages())o(c)};for(let i of this.browser?.contexts()??[])a(i);this.armDialogs=a;try{return await t()}finally{this.armDialogs=void 0;for(let i of s)i.off("page",o);for(let i of r)try{i.off("dialog",n)}catch{}}}async start(){let t=this.options.browser??"chromium";if(yr(t)){let r=await tv();try{this.browser=await Gx.launch({headless:!this.options.headed,channel:gl[t]?t:void 0,args:[`--remote-debugging-port=${r}`],handleSIGINT:!1})}catch(s){let o=s instanceof Error?s.message:String(s),a=gl[t];throw a&&/is not found at|distribution .* is not found/i.test(o)?new hl(`${a.label} is not installed on this machine, so --browser ${t} cannot run.
|
|
346
|
+
Install it (npx playwright install ${t} does that), or use --browser chromium, which Saffron ships with.`):s}this.cdpEndpoint=`http://127.0.0.1:${r}`}else this.browser=await(t==="firefox"?Kx:Yx).launch({headless:!this.options.headed,handleSIGINT:!1}),this.cdpEndpoint=void 0;let n;try{n=this.contextOptions();let r=this.options.sessions??{},s=i=>typeof i=="object"&&i!==null&&!Array.isArray(i);if(!s(r))throw new _t('"sessions" in saffron.config.json must map session names to their settings, such as { "buyer": { "storageState": ".auth/buyer.json" } }.');for(let[i,c]of Object.entries(r)){let l=`{ "storageState": ".auth/${fs(i)}.json" }`;if(!s(c)||Object.keys(c).some(d=>d!=="storageState"))throw new _t(`sessions."${i}" in saffron.config.json takes only a storageState, such as ${l}.`);if(c.storageState!==void 0&&(typeof c.storageState!="string"||c.storageState.trim()===""))throw new _t(`sessions."${i}".storageState in saffron.config.json must be a file path, such as ".auth/${fs(i)}.json".`);if(i===Ht&&c.storageState!==void 0&&kt.resolve(this.options.projectRoot,c.storageState)!==n.storageState)throw new _t(`sessions."${Ht}".storageState in saffron.config.json is never read: the default session signs in with the top-level storageState. Set that instead, or make the two the same.`);i!==Ht&&this.contextOptions(i)}let o=new Set([n.storageState,...Object.keys(r).filter(i=>i!==Ht).map(i=>this.contextOptions(i).storageState)]),a=this.browser;await Promise.all([...o].filter(i=>typeof i=="string").map(async i=>{try{let c=JSON.parse(un.readFileSync(i,"utf8"));if(!c||typeof c!="object"||Array.isArray(c))throw new Error("it is not a JSON object");await(await a.newContext({storageState:i})).close()}catch(c){throw new _t(`storageState file ${i} cannot be used: ${(c instanceof Error?c.message:String(c)).split(`
|
|
347
|
+
`)[0]}. Generate it again with: npx playwright open --save-storage=${He(this.options.projectRoot,i)} <url>`)}}))}catch(r){throw await this.stop(),r}if(this.options.device||this.options.viewport){if(t==="firefox"&&this.options.device&&pl[this.options.device]?.isMobile)throw await this.stop(),new _t(`--device "${this.options.device}" is a mobile profile, and Playwright does not emulate mobile devices in Firefox. Run it in chromium or webkit, or give Firefox a --viewport instead.`);try{await(await this.browser.newContext(n)).close()}catch(r){await this.stop();let s=(r instanceof Error?r.message:String(r)).split(`
|
|
348
|
+
`)[0];throw new _t(`${this.options.device?`--device "${this.options.device}"`:"--viewport"} cannot run in ${t}: ${s}`)}}}async stop(){await this.browser?.close(),this.browser=void 0}resolveStorageState(t=this.options.storageState){if(!t)return;let n=kt.isAbsolute(t)?t:kt.join(this.options.projectRoot,t);if(!un.existsSync(n))throw new _t(`storageState file not found: ${n}. Generate one with: npx playwright open --save-storage=${t} <url>`);return n}contextOptions(t){let{defaultBrowserType:n,...r}=this.options.device?pl[this.options.device]??{}:{},s=t===void 0?void 0:this.options.sessions?.[t]?.storageState;return{storageState:this.resolveStorageState(s??this.options.storageState),...r,...this.options.viewport?{viewport:this.options.viewport}:{},...this.options.timezone?{timezoneId:this.options.timezone}:{}}}artifacts(t){let n=vn(this.options.projectRoot,t.featurePath,t.displayName);return this.options.artifactsPerBrowser?kt.join(n,this.options.browser??"chromium"):n}downloads(t){return kt.join(this.artifacts(t),"downloads")}buildCandidateCache(t,n){let r={version:1,feature:t.featurePath,scenario:t.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:n,...Sg(t,n)};return{...r,version:ws(r)}}tabWatcher(){return t=>{let n=r=>t(r);return this.tabListeners.add(n),()=>{this.tabListeners.delete(n)}}}downloadWatcher(){return t=>(this.downloadListeners.add(t),()=>{this.downloadListeners.delete(t)})}async newContext(t,n){let r=await this.browser.newContext(this.contextOptions(t||void 0));return r.on("page",()=>{if(!this.openingOwnPages.has(r))for(let s of this.tabListeners)s(t)}),r.on("page",s=>s.on("download",o=>{for(let a of this.downloadListeners)a(o)})),this.armDialogs?.(r),n&&this.options.trace!==void 0&&this.options.trace!=="off"&&await Df(r,n),r}sessionsFor(t,n,r){return new Ti(n,we(t.steps[0]?.session),s=>this.newContext(s,`${r} \xB7 session "${ht(s)}"`),async s=>{this.openingOwnPages.add(s);try{return await s.newPage()}finally{this.openingOwnPages.delete(s)}})}sessionHooks(t,n,r){return{sessionPage:n.pageOf,onActiveTab:(s,o)=>n.selectTab(o,s),takeFingerprint:async s=>Jo(fl(n,s)??r)}}namedSession(t,n){return Dn(n)?{session:ht(t.mainKey)}:{}}async saveSessionTraces(t,n,r,s){let o=[],a=Te(t),i=new Set;for(let[c,l]of n.opened()){if(!r){await si(l).catch(()=>{});continue}let d=fs(ht(c));for(let f=2;i.has(d);f++)d=`${fs(ht(c))}-${f}`;i.add(d);let u=kt.join(this.artifacts(t),`${r}.${d}.zip`),p=await oi(l,u,a);p&&(this.claimArtifactDir(t),o.push({...s,kind:"trace",file:He(this.options.projectRoot,u),sha256:p,session:ht(c)}))}return o}async proofReplay(t,n,r,s){let o=this.options.trace!==void 0&&this.options.trace!=="off",a=s?t.displayName:`${t.displayName} (proof replay)`,i=await this.newContext(we(t.steps[0]?.session),a),c=this.sessionsFor(t,i,a),l=await i.newPage();return{result:await di(l,t,n,{sessions:c.pages,openSession:c.pageOf,downloadsDir:this.downloads(t),baseURL:this.options.baseURL,actionTimeoutMs:this.options.actionTimeoutMs,retries:this.options.retries,pollIntervalMs:this.options.pollIntervalMs,uniqueSeed:r,trace:o,tracePhase:s}),context:i,page:l,sessions:c}}async runScenario(t,n={}){let r=await this.runScenarioInner(t,n),s=Te(t);if(s.size>0){let o=i=>i===void 0?i:Ge(i,s);r.error=o(r.error),r.narrative=o(r.narrative),r.proofError=o(r.proofError),r.suggestedFeatureEdit=o(r.suggestedFeatureEdit),r.adaptations=r.adaptations.map(i=>Ge(i,s));let a=[r.stepResults,r.executionStepResults,...(r.evidence??[]).map(i=>i.traceSteps)];for(let i of a.flatMap(c=>c??[])){i.error=o(i.error);for(let c of i.tabs??[])c.url=Ge(c.url,s);for(let c of i.responses??[])c.url=Ge(c.url,s)}}return r}async screenshot(t,n,r,s){let o=this.options.screenshot??"viewport";if(o!=="off")try{let a=this.artifacts(n);this.claimArtifactDir(n);let i=kt.join(a,`${r}.jpg`),c=await t.screenshot({path:i,type:"jpeg",quality:80,fullPage:o==="full-page",timeout:5e3});return{kind:r,file:He(this.options.projectRoot,i),step:s,sha256:Kt(c)}}catch{return}}claimArtifactDir(t){let n=vn(this.options.projectRoot,t.featurePath,t.displayName);un.mkdirSync(this.artifacts(t),{recursive:!0}),un.writeFileSync(kt.join(n,ar),JSON.stringify({feature:t.featurePath,scenario:t.displayName},null,2))}async runScenarioInner(t,n={}){if(!this.browser)throw new Error("Orchestrator not started");let r=Date.now(),{projectRoot:s,baseURL:o,actionTimeoutMs:a,retries:i,pollIntervalMs:c}=this.options,l=pe(s,t.featurePath,t.name),d;try{d=Ye(l)}catch(O){if(!(O instanceof ke))throw O;return{scenario:t,status:"red",source:"cache",stepResults:[],adaptations:[],usage:On,durationMs:Date.now()-r,error:`The recording cannot be read: ${O.problem}. Fix the file, or re-record it with saffron run --rerecord.`}}let u=dt(s,t.featurePath,t.name),p=He(s,u),f,g;if(un.existsSync(u))try{({proposal:f,revision:g}=Lo(u))}catch(O){if(!(O instanceof ke)&&O.code!=="ENOENT")throw O;f=void 0}let y=!1;f&&!Iu(s,u,g)&&(y=!this.options.rerecord,f=void 0),f&&At(s,f,t)&&(f=void 0),f&&this.options.rerecord&&this.filedThisRun.get(u)!==g&&(f=void 0);let h=d&&ln(t,d)||f&&ln(t,f.cache);if(h)return{scenario:t,status:"red",source:"cache",stepResults:[],adaptations:[],usage:On,durationMs:Date.now()-r,error:h};let S=O=>O.status==="stale"?"the committed recording no longer matches the scenario":`the committed recording failed${O.failure?` at "${O.failure.stepText}"`:""}`,v=O=>{let j=En(s)[p],L=j?.revision===g?` from ${le(Ws(j.from))}`:"",I=O?S(O):"";return{scenario:t,status:"yellow",source:d?"cache":"agent-record",stepResults:O?.stepResults??[],narrative:(I?`${I[0].toUpperCase()}${I.slice(1)}. `:"")+`A proposal${L} is pending review at ${p}. It was not filed on this machine, so this run does not replay it, heal or record over it. Review it with saffron diff ${p}, then saffron accept or saffron reject it.`,adaptations:[],proposalFile:p,proposalRevision:g,usage:On,durationMs:Date.now()-r}};if(un.rmSync(this.artifacts(t),{recursive:!0,force:!0}),this.options.artifactsPerBrowser){let O=vn(s,t.featurePath,t.displayName);for(let j of un.existsSync(O)?un.readdirSync(O,{withFileTypes:!0}):[])j.isFile()&&j.name!==ar&&un.rmSync(kt.join(O,j.name),{force:!0})}if(y&&!d)return v();let x=(O,j)=>({scenario:t,status:"yellow",source:"agent-record",proposalReplay:!0,stepResults:O.stepResults,narrative:`Replayed the pending proposal recorded for "${f.meta.recordedFor??t.name}" at zero AI${j?` instead of ${j.status==="stale"?"recording":"healing"} again: ${S(j)}`:""}; accept it to go green.`,adaptations:[],verified:!0,proposalFile:p,proposalRevision:g,usage:On,durationMs:Date.now()-r}),b=this.options.trace??"off",m=b!=="off",$=await this.newContext(we(t.steps[0]?.session),t.displayName),T=this.sessionsFor(t,$,t.displayName),R=new Map,k=!m,C,P,w=await $.newPage(),E=$n(),_=[],A=(O,j)=>this.screenshot(O,t,"before-heal",j.stepText).then(L=>{L&&_.push(L)});try{let O=await(async()=>{let I;if(f&&!d){let N=$n(),M=await this.proofReplay(t,f.cache,N,"pending"),B=M.result,J=f.meta.recordedFor??t.name,ne=Object.keys(t.params).length>0&&J!==t.displayName;if(B.status==="passed"||ne?(C=M.context,P=M.sessions,E=N):(await M.sessions.close(),await M.context.close()),B.status==="passed")return x(B);if(ne){let Me=B.failure,et=f.cache.examples??{},De=Me?t.steps[Me.stepIndex]?.text??"":"",Ie=Object.keys(t.params).filter(pt=>pt in et&&et[pt]!==t.params[pt]).sort((pt,jn)=>Number(De.includes(`<${jn}>`))-Number(De.includes(`<${pt}>`))),Qt=Ie.slice(0,3).map(pt=>`<${pt}> is ${JSON.stringify(t.params[pt])} here, ${JSON.stringify(et[pt])} there${De.includes(`<${pt}>`)?" (the failing step uses it)":""}`);return{scenario:t,status:"red",source:"agent-record",proposalReplay:!0,stepResults:B.stepResults,adaptations:[],proposalFile:p,proposalRevision:g,usage:On,durationMs:Date.now()-r,error:`The pending proposal recorded for "${J}" does not replay for this Examples row`+(Me?` (step "${Me.stepText}": ${ns(Me.error,Te(t))})`:"")+(Qt.length>0?`. This row differs from it where ${Qt.join("; ")}${Ie.length>3?`; and ${Ie.length-3} more column(s)`:""}`:"")+`. Check whether that step recorded the other row's value instead of a <placeholder> or acts on the wrong element (saffron diff ${p}); if so, reject it and re-record with saffron run --rerecord.`}}console.log(Ge(` \u21BA pending proposal for "${t.displayName}" did not replay`+(B.failure?` (step "${B.failure.stepText}": ${ns(B.failure.error,Te(t))})`:"")+"; recording again",Te(t)))}if(d){if(I=await di(w,t,d,{vars:R,sessions:T.pages,openSession:T.pageOf,downloadsDir:this.downloads(t),baseURL:o,actionTimeoutMs:a,retries:i,pollIntervalMs:c,uniqueSeed:E,trace:m,onFailure:A,keepResponseLog:!0}),I.status==="passed")return{scenario:t,status:"green",source:"cache",stepResults:I.stepResults,adaptations:[],usage:On,durationMs:Date.now()-r};if(y)return I.responses?.detach(),v(I);let N=M=>d.steps[M].kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||Ai(d.steps,M));if(f&&I.status==="failed"&&d.steps.some((M,B)=>N(B)&&!Fa(f.cache.steps[B]?.actions??[],M.actions))&&(f=void 0),f){let M=$n(),B=await this.proofReplay(t,f.cache,M,"pending");if(B.result.status==="passed")return I.responses?.detach(),C=B.context,P=B.sessions,E=M,x(B.result,I);await B.sessions.close(),await B.context.close(),console.log(Ge(` \u21BA pending proposal for "${t.displayName}" did not replay`+(B.result.failure?` (step "${B.result.failure.stepText}": ${ns(B.result.failure.error,Te(t))})`:"")+(I.status==="failed"?"; healing":"; recording again"),Te(t)))}}if(!(this.options.agent!==void 0&&this.cdpEndpoint!==void 0&&!n.agentDisabled&&this.agentHalt.reason===void 0)){let N=this.options.agent!==void 0&&!n.agentDisabled&&this.agentHalt.reason!==void 0?`the agent's provider reported a usage limit earlier in this run, so no AI session was started for it: ${this.agentHalt.reason}. Run it again once the limit resets.`:this.options.agent!==void 0&&this.cdpEndpoint===void 0&&!n.agentDisabled?`recording/healing needs a Chromium-family browser (the agent attaches over CDP). Record with --browser chromium (the default), chrome or msedge, then replay with --browser ${this.options.browser}.`:this.options.agent!==void 0&&n.agentDisabled?this.cdpEndpoint===void 0?`recording/healing needs a Chromium-family browser (the agent attaches over CDP). Record with --browser chromium (the default), chrome or msedge, then replay with --browser ${this.options.browser}.`:"this run was started without the agent (--no-agent), so nothing records it.":"no agent is configured.";I?.responses?.detach();let M=d!==void 0&&d.examples===void 0&&Object.keys(t.params).length>0&&d.steps.length===t.steps.length&&d.steps.every((B,J)=>{let ne=t.steps[J];return B.gherkin===ne.text&&B.kind===ne.kind&&B.docString===ne.docString&&JSON.stringify(B.table)===JSON.stringify(ne.table)})&&Object.entries(d.data??{}).every(([B,J])=>{try{return Le(B)===J}catch{return!0}});return{scenario:t,status:"red",source:"cache",stepResults:I?.stepResults??[],adaptations:[],usage:On,durationMs:Date.now()-r,error:d?I?.status==="stale"?M?`The recording was made by an older saffron-ai and still holds another Examples row's value, so this row needs it recorded again once, and ${N}`:Pc(t,d)?`The recording was made before saffron-ai 1.0.1 for another person's row (As "..."), and would type that person's values here, so it needs recording again once, and ${N}`:`Cache is stale (feature file changed) and ${N}`:`Replay failed and ${N} ${I?.failure?.error??""}`.trimEnd():`No cache exists and ${N}`}}let D=d!==void 0&&I!==void 0&&I.status==="failed",q=0,Y,Q;try{if(D){Q=I.responses;let N=T.contextOf(we(t.steps[I.failure.stepIndex]?.session))??w.context(),M=await Ri(this.browser,I.activePage??ts(N,I.failure.pageUrl)??w,T.contexts());Y=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:o,traceContext:m?w.context():void 0,mode:"heal",onBrowserAction:B=>{B===we(t.steps[I.failure.stepIndex]?.session)&&Q?.markAction()},liveTab:M,model:this.options.healModel,cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,completedSteps:I.stepResults.filter(B=>B.status==="passed").map(B=>B.gherkin),failedStep:{text:I.failure.stepText,kind:I.failure.kind,error:I.failure.error,pageUrl:I.failure.pageUrl,stepIndex:I.failure.stepIndex},uniqueSeed:E,onTabOpened:this.tabWatcher(),onDownload:this.downloadWatcher(),...this.sessionHooks(t,T,w)}))}else if(await w.goto("about:blank"),await T.blank(),T.pages.set(T.mainKey,w),this.options.reuseSteps!==!1){let N=await this.recordWithSeeding(t,w,E,T);q=N.seededCount,Y=N}else Y=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:o,traceContext:m?w.context():void 0,mode:"record",cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,uniqueSeed:E,onTabOpened:this.tabWatcher(),onDownload:this.downloadWatcher(),...this.sessionHooks(t,T,w)}))}catch(N){Q?.detach();let M=N instanceof Error?N.message:String(N);return{scenario:t,status:"red",source:D?"agent-heal":"agent-record",stepResults:I?.stepResults??[],adaptations:[],usage:On,durationMs:Date.now()-r,error:`Agent invocation failed: ${ns(M,Te(t))}`}}if(Y.success&&D&&I.failure.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||Ai(d.steps,I.failure.stepIndex))){let N=d.steps[I.failure.stepIndex],M=fl(T,we(t.steps[I.failure.stepIndex]?.session))??w,B=Ms(t,I.failure.stepIndex);try{for(let J of N.actions)await Ns(M,J,B,this.options.actionTimeoutMs??5e3,o,R,Q,void 0,ct(t))}catch(J){let ne=J instanceof Error?J.message:String(J),Me=`Assertion failed as written: "${N.gherkin}". Saffron never adapts assertions. If this change is intended, update the .feature file or re-record the scenario (saffron run --rerecord --filter @tag). If the recording itself looks wrong (an empty value, a wrong target), re-record it the same way. Verification error: ${ns(ne,Te(t))}`,et=I.failure.stepIndex,De=I.stepResults.map((Ie,Qt)=>Qt===et?{...Ie,status:"failed",error:Me}:Ie);return{scenario:t,status:"red",source:"agent-heal",stepResults:De,executionStepResults:De.map((Ie,Qt)=>Qt>et&&Ie.status==="skipped"?{...Ie,status:"passed"}:Ie),narrative:Y.narrative,adaptations:Y.adaptations,suggestedFeatureEdit:Y.suggestedFeatureEdit,usage:Y.usage,durationMs:Date.now()-r,error:Me}}finally{Q?.detach()}}return Q?.detach(),await this.finalizeAgentRun(t,Y,D,d,r,q,D?I?.failure:void 0,E)})(),j=_.find(I=>I.kind==="before-heal");if(O.source==="cache"&&j){let I=j.file.replace(/before-heal\.jpg$/,"failure.jpg");try{un.renameSync(kt.join(s,j.file),kt.join(s,I)),j.file=I}catch{}j.kind="failure"}else if(O.status==="red"){let I=O.stepResults.findIndex(Y=>Y.status==="failed"),U=O.stepResults[I]?.gherkin,D=we(t.steps[Math.max(I,0)]?.session),q=await this.screenshot(fl(P??T,D)??w,t,"failure",U);q&&_.push(q)}let L=qr(at(t),E);if(L.size>0&&(O.uniques=Object.fromEntries(L)),_.push(...O.evidence??[]),m){let U=b==="on"||O.status!=="green"?kt.join(this.artifacts(t),pc):void 0;k=!0;let D=C??$;U||await si(D).catch(()=>{});let q=U?await oi(D,U,Te(t)):void 0,Y=Te(t),Q=(O.executionStepResults??O.stepResults).map(B=>({...B,error:B.error&&Ge(B.error,Y)})),N=P??T,M=await this.saveSessionTraces(t,N,U&&q?kt.basename(U,".zip"):void 0,{traceSteps:Q});U&&q&&(this.claimArtifactDir(t),_.unshift({kind:"trace",file:He(s,U),sha256:q,traceSteps:Q,...this.namedSession(N,t.steps)},...M))}return _.length>0&&(O.status!=="green"||_.some(I=>I.kind==="trace"))&&(O.evidence=_),O}finally{k||await si($).catch(()=>{}),await P?.close(),await C?.close(),await T.close(),await $.close()}}async finalizeAgentRun(t,n,r,s,o,a=0,i,c=$n()){let l=r?"agent-heal":"agent-record",d=n.success?n.recordedSteps.map(D=>({gherkin:D.gherkin,kind:D.kind,status:"passed"})):Og(n.recordedSteps,n.announcedSteps??[],i&&{stepIndex:i.stepIndex,error:i.error},n.narrative);if(!n.success)return{scenario:t,status:"red",source:l,stepResults:d,narrative:n.narrative,adaptations:n.adaptations,usage:n.usage,durationMs:Date.now()-o,error:n.narrative};let u=r?$g(s.steps,n.recordedSteps,this.options.assertionPolicy==="adaptable-mid",i?{stepIndex:i.stepIndex,actionIndex:i.actionIndex}:void 0):n.recordedSteps,p=[...n.adaptations,...r&&i?kg(n.recordedSteps,i.stepIndex):[]],f={...n.usage},g,y,h,S,v=[],x=0,b=new Set,m,$=async({context:D,sessions:q},Y,Q=Y.stepResults)=>{if(!b.has(D)){b.add(D);try{if(this.options.trace&&this.options.trace!=="off"){let N=`proof-${++x}`,M=kt.join(this.artifacts(t),`${N}.zip`),B=Te(t),J=await oi(D,M,B),ne=Y.captured[Nt],Me=ne?qr(at(t),ne):new Map,et={proof:!0,traceSteps:Q.map(Ie=>({...Ie,error:Ie.error&&Ge(Ie.error,B)})),traceUniques:Me.size?Object.fromEntries(Me):void 0},De=await this.saveSessionTraces(t,q,J?N:void 0,et);J&&(this.claimArtifactDir(t),v.push({kind:"trace",file:He(this.options.projectRoot,M),sha256:J,...et,...this.namedSession(q,t.steps)},...De))}}finally{await q.close(),await D.close()}}};if(this.options.verifyProposals!==!1){let D=await this.proofReplay(t,this.buildCandidateCache(t,u),$n());S=D.result.captured[Nt];try{if(D.result.status!=="passed"&&D.result.failure){let q=D.result.failure;if(this.options.agent&&!(r&&q.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||Ai(s.steps,q.stepIndex))))try{let Q=D.sessions.contextOf(we(t.steps[q.stepIndex]?.session))??D.context,N=await Ri(this.browser,D.result.activePage??ts(Q,q.pageUrl)??D.page,D.sessions.contexts()),M=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:this.options.baseURL,traceContext:this.options.trace&&this.options.trace!=="off"?D.context:void 0,mode:"refine",model:r?this.options.healModel:void 0,cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,completedSteps:D.result.stepResults.filter(B=>B.status==="passed").map(B=>B.gherkin),failedStep:{text:q.stepText,kind:q.kind,error:q.error,pageUrl:q.pageUrl,stepIndex:q.stepIndex},liveTab:N,uniqueSeed:D.result.captured[Nt],onTabOpened:this.tabWatcher(),onDownload:this.downloadWatcher(),...this.sessionHooks(t,D.sessions,D.page)}));f=Rg(f,M.usage),m=ov(D.result.stepResults,q,M),M.success&&(p.push(...M.adaptations),p.push(...kg(M.recordedSteps,q.stepIndex)),u=r?$g(u,M.recordedSteps,this.options.assertionPolicy==="adaptable-mid",{stepIndex:q.stepIndex,actionIndex:0}):sv(u,M.recordedSteps,q.stepIndex),await $(D,D.result,m),m=void 0,D=await this.proofReplay(t,this.buildCandidateCache(t,u),$n()),S=D.result.captured[Nt])}catch{}}for(let q of D.result.tabOpeners??[]){let Y=u[q.stepIndex]?.actions[q.actionIndex];Y&&(Y.opensTab=!0)}g=D.result.status==="passed",g||(y=D.result.failure?.error??`proof replay ${D.result.status}`,h=D.result.stepResults)}finally{await $(D,D.result,m).catch(()=>{})}}r&&s&&p.push(...rv(s.steps,u,i,this.options.baseURL));let T=D=>r&&t.steps[D]?.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||Ai(s.steps,D)),R=n.featureEdits.filter(D=>!T(D.index));for(let D of vu(u,nn(this.options.projectRoot)))p.push(`duplicate wording: "${D.from}" recorded exactly the same actions as the existing step "${D.to}" (${D.feature} \u203A ${D.scenario}). Accept with --with-feature-edit to converge on the canonical wording.`),R.some(q=>q.index===D.index)||R.push({index:D.index,text:D.to});let k=gf(u);k.length>0&&(g=!1,y=[y,...k].filter(Boolean).join(" "));let C=Te(t),P=D=>C.size>0?Ge(D,C):D;p=p.map(P);let w=R.map(D=>({index:D.index,text:P(D.text)})),E=P(n.narrative),_=n.suggestedFeatureEdit?P(n.suggestedFeatureEdit):void 0,A={version:1,feature:t.featurePath,scenario:t.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:u,...Sg(t,u)},O={...A,version:ws(A)},j={meta:{createdAt:O.recordedAt,mode:r?"heal":"record",narrative:E,adaptations:p,suggestedFeatureEdit:_,featureEdits:w.length>0?w:void 0,verified:g,proofError:y?P(y):void 0,seededSteps:a>0?a:void 0,recordedFor:t.displayName,usage:f,bound:cp(t,s,O,w.length>0?w:void 0)},cache:O},L=dt(this.options.projectRoot,t.featurePath,t.name),I=_u(L,j);ju(this.options.projectRoot,L,I),this.filedThisRun.set(L,I);let U=Ye(pe(this.options.projectRoot,t.featurePath,t.name));return{proposalDiff:Hn(U,j.cache),scenario:t,status:"yellow",source:l,stepResults:h??d,executionStepResults:d,evidence:v,proofUniques:(()=>{let D=S?qr(at(t),S):void 0;return D&&D.size>0?Object.fromEntries(D):void 0})(),narrative:E,adaptations:p,suggestedFeatureEdit:_,featureEdits:w.length>0?w:void 0,verified:g,proofError:y,seededSteps:a>0?a:void 0,proposalFile:He(this.options.projectRoot,L),proposalRevision:I,usage:f,durationMs:Date.now()-o}}};import zi from"node:fs";import gS from"node:os";import lh from"node:path";import{query as Fv}from"@anthropic-ai/claude-agent-sdk";import{createRequire as iv}from"node:module";import av from"node:path";import{McpServer as cv}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as ee}from"zod";var Ee=e=>({content:[{type:"text",text:e}]}),_g=ee.array(ee.object({path:ee.string().describe("JSON Pointer: /order/status, /items/0/sku; ~1 means slash, ~0 means tilde"),equals:ee.string().optional().describe("Expected scalar as text. Keep the step's <column>, {data:...}, {env:...} and date tokens. Use type for numbers, booleans or null."),type:ee.enum(["string","number","boolean","null"]).optional().describe("Type for equals; default string. For null use equals='null'."),exists:ee.boolean().optional().describe("Check presence (true) or absence (false), instead of equals. A present null is present.")})).superRefine((e,t)=>{let n=ir(e);n&&t.addIssue({code:"custom",message:n})}).optional().describe("JSON field checks, all on the matching response. Prefer these over bodyPattern for JSON fields. Verify the response first; expected values come from the step, never copied from the observed result.");function rs(e,t,n,r){return(s,o)=>{let a=async i=>{let c;try{c=await r(i)}catch(d){c=Ee(`ERROR: ${d instanceof Error?d.message:String(d)}`)}let l={...c,content:c.content.map(d=>({...d,text:o(d.text)}))};return l.content[0]?.text.startsWith("ERROR:")?{...l,isError:!0}:l};s.registerTool(e,{description:t,inputSchema:n},a)}}function lv(e){let t=new cv({name:e.name,version:e.version});for(let n of e.tools)n(t,e.hide);return{type:"sdk",name:e.name,instance:t}}function Cg(e){let t={};return e.role&&(t.role=e.role),e.name&&(t.name=e.name),e.nameRegex&&(t.nameRegex=e.nameRegex),e.label&&(t.label=e.label),e.text&&(t.text=e.text),e.selector&&(t.fallbackSelectors=[e.selector]),e.frame&&(t.frame=e.frame),Object.keys(t).length>0?t:void 0}var dv=new Set(["main","banner","contentinfo","status","alert","alertdialog","dialog","search"]);function Pg(e){if(!e?.role)return;let{role:t,frame:n,...r}=e;if(!(Object.keys(r).length>0||dv.has(t)))return`ERROR: role="${t}" alone matches every ${t} on the page, and replay would use the first one. Add a name (or nameRegex), text, label or selector that picks exactly the element you checked, then call again.`}function uv(e,t){if(t.index>=e.steps.length)return`ERROR: there is no step ${t.index}: this scenario's steps are numbered from 0 to ${e.steps.length-1}. Call saffron_step again with the zero-based index of the step you are about to perform.`;if(e.announce(t.index,t.text,t.adaptation),t.index<e.firstStep)return`Step ${t.index} already ran before you took over and keeps its recording; nothing you do under it is recorded. Do not redo it: continue from step ${e.firstStep} on the page as it is.`;let n=e.steps[t.index].kind==="assertion"?"verify it from a snapshot and record the check with saffron_assert":"do it now with the browser tools";return`Recording step ${t.index}: ${t.text}. This only files the browser calls that follow under the step; it performs nothing itself, so ${n}.`}function fv(e){let t=Math.max(-1,...e.announced,e.lastStep??-1),n=[],r=[],s=c=>[...me(e.steps[c]?.gherkin??"").matchAll(/<([^<>]+)>/g)].some(l=>e.params?.[l[1]]!==void 0),o=[...new Set([...e.announced,...e.lastStep===void 0?[]:e.steps.map((c,l)=>l).filter(c=>c<=e.lastStep)])].filter(c=>c>=e.firstStep&&e.steps[c]?.kind==="assertion"&&!e.steps[c].actions.some(l=>$e.has(l.action))).sort((c,l)=>c-l);o.length>0&&n.push(`Assertion step ${o.join(", ")} recorded no check, so replay would verify nothing. Record what you verified with saffron_assert under that step (saffron_step first if you moved on).`);let a=[],i=!1;for(let c=0;c<=t;c++){let l=e.steps[c],d=l?.keyword.trim().toLowerCase(),u=d===void 0?void 0:pv.get(d);if(e.setupSteps[c]!==void 0?i=e.setupSteps[c]:u!==void 0&&(i=u==="given"),c<e.firstStep||l?.kind!=="action"&&l?.kind!=="assertion")continue;let p=l.kind==="assertion";if(!p&&l.actions.length===0){(!i||s(c))&&a.push(c);continue}if(l.actions.filter(y=>Jr(y)||Qo(y)||p&&y.target!==void 0&&$e.has(y.action)).length===0)continue;let g=new Set(Rs(e.resolvedTexts[c]??"",!0));for(let y of Rs(e.resolvedTexts[c]??"")){let h;try{h=zt(y)}catch{continue}let S=/[{}<>]/.test(h)?[]:ac(l.actions,h,p,g.has(y));if(S.length!==0){r.push({index:c,actions:S}),n.push(`Step ${c} acts in "${h}", but ${S.length===1?"this target does":"these targets do"} not name it (${S.map(ft).join("; ")}). Replay would act on the first match, which on a page with two such sections is the wrong one. If its element is still on the page, call saffron_step ${c} again and perform only ${S.length===1?"that action":"those actions"} once more with a target scoped to that container, e.g. selector 'role=region[name="${h}"] >> role=textbox[name="..."]' (a snapshot ref is not scoped; a capture or a check is saffron_capture or saffron_assert again with that selector): the new action takes the old one's place, and the step's other actions stay. An element of a dialog or menu that a scoped action opened is not in the section: scope it to that dialog instead ('role=dialog >> role=button[name="..."]'). If the page has moved on, do not go back for it.`);break}}}if(a.length>0){let c=a.filter(s);n.push(`Action step ${a.join(", ")} recorded no browser action. saffron_step performs nothing: perform the step with a browser tool right after announcing it, or, for a step that waits for the page, record what it waits for with saffron_assert so replay waits too. If you already performed its action under another step, do not perform it again: replay runs it there. `+(c.length===a.length?"":"If the page already was in the state the step asks for, it needs nothing. ")+(c.length===0?"":`Step ${c.join(", ")} names an Examples column, which other rows set to other values: even if the page already shows this row's value, call saffron_step again and pick it (click the option or radio labelled with it), so replay picks each row's own. Left empty, every row replays this row's page.`))}return{problems:n,redo:r}}var pv=(()=>{let e=iv(import.meta.url)("@cucumber/gherkin").dialects,t=new Map;for(let n of Object.values(e))for(let r of["when","then","given"])for(let s of n[r])s.trim()!=="*"&&t.set(s.trim().toLowerCase(),r);return t})(),Ig=new WeakSet;function gv(e,t){if(t.success&&!Ig.has(e)){let{problems:n,redo:r}=fv(e);if(n.length>0)return Ig.add(e),e.redo(r),`ERROR: not finalized. ${n.join(" ")} Then call saffron_done again. If a condition does not hold, call saffron_done with success=false.`}return e.done=!0,e.success=t.success,e.narrative=t.narrative,e.suggestedFeatureEdit=t.suggestedFeatureEdit,e.featureEdits=(t.featureEdits??[]).filter(n=>!Na.test(n.text)&&n.text.trim()!==""),"Run finalized."}function hv(e,t){let n=new Set(e.steps.flatMap(a=>a.actions.flatMap(i=>i.action==="captureText"&&i.saveAs?[i.saveAs]:[]))),r=e.resolvedTexts.slice(0,Math.min(e.firstStep,Math.max(e.currentStepIndex,0))).join(`
|
|
349
|
+
`),s=t;try{s=zt(t)}catch{}let o=Oo(s,a=>n.has(a)||r.includes(`"${a}"`)?"0":void 0);if("problem"in o)return`ERROR: kind=amount: ${o.problem}. Capture each value first with saffron_capture (its saveAs), then name it in double quotes, operators between spaces: '"before" + "breakfast"'.`}async function mv(e,t,n,r){if(e.downloadUnarmed)return"ERROR: the latest download began when no action of yours was running and none could be credited with it, so replay would not wait for it. Announce the step that downloads it, perform that action again, then record the check.";if(!e.lastDownload)return e.firstStep===0?'ERROR: nothing was downloaded in this session. Perform the action that downloads the file first (its result lists "Downloading file"), then record the check.':void 0;let s=await e.lastDownload;if(!s)return"ERROR: the file this session downloaded last did not finish downloading, so its content cannot be checked.";let o,a;try{let l=g=>g===void 0||g===""?void 0:on(g,e.uniqueSeed),d=Object.fromEntries(Object.entries(e.params).map(([g,y])=>[g,on(y,e.uniqueSeed)])),u={value:l(n),pattern:l(r)},p=_c(u,d,e.envNames,e.startedAt);if(p)return`ERROR: ${p} Not recorded.`;o=await Oc(s);let f=li(u,d,e.envNames,e.startedAt);a=Cc(o,av.basename(s),f.value,f.pattern,u.value)}catch(l){return`ERROR: ${l instanceof Error?l.message:String(l)}.`}if(!a)return;let i=2e3,c=t(o);return`ERROR: ${a}. Not recorded. Its text${c.length>i?` begins (${i} of ${c.length} characters)`:" is"}:
|
|
350
|
+
${c.slice(0,i)}
|
|
351
|
+
Record the check the step asks for as the file holds it. If the file does not hold what the step says, call saffron_done with success=false.`}var jg={role:ee.string().optional().describe("ARIA role of the element"),name:ee.string().optional().describe("Full accessible name (exact match). For volatile content like prices or dates, use nameRegex instead."),nameRegex:ee.string().optional().describe("Regex for the accessible name when it embeds volatile content, e.g. 'Select \\\\{date\\\\+1\\\\} as checkin' cannot work \u2014 instead use nameRegex 'Select .* as checkin'"),label:ee.string().optional().describe("Form-label text for getByLabel \u2014 the literal <label> text only, never a free-text description"),text:ee.string().optional().describe("getByText locator text"),selector:ee.string().optional().describe("CSS fallback selector"),frame:ee.string().optional().describe(`CSS selector of the iframe hosting the element, e.g. 'iframe[title="Feedback widget"]' \u2014 REQUIRED whenever the element lives inside an iframe; without it replay looks only at the top-level page`)};function Oi(e){let t=new Map([...e.envNames].flatMap(r=>process.env[r]===void 0?[]:[[r,process.env[r]]])),n=So(e.writtenTexts,t);return lv({name:"saffron",version:"0.1.0",hide:n,tools:[rs("saffron_step","Announce the Gherkin step you are about to perform. MUST be called before executing browser actions for each step, with the step's zero-based index and exact text.",{index:ee.number().int().min(0),text:ee.string(),adaptation:ee.string().optional().describe("If the written step does not match the real UI and you are deviating from it, describe the deviation in one sentence: the kind of change (a locator or label change on the same page, a page removed or merged, a page added or flow reordered) and the page it happened on.")},async r=>Ee(uv(e,r))),rs("saffron_capture",`Record a captureText action for the current step: at replay time, the target element's text is read and stored under saveAs for later expectDiffers comparisons. Use for steps like 'I record the displayed price as "X"'. The target must select exactly the element whose text is the value.`,{saveAs:ee.string().describe("Name to store the captured text under"),...jg},async r=>{let s=Cg(r);if(!s)return Ee("ERROR: capture needs a target (role/name, nameRegex, label, text, or selector).");let o=Pg(s);return o?Ee(o):(e.addActions([{action:"captureText",target:s,saveAs:r.saveAs}]),Ee(`Capture recorded as "${r.saveAs}".`))}),rs("saffron_dialog","Record how a native dialog (alert/confirm/prompt) must be handled at replay. Call this IMMEDIATELY whenever an action triggers a native dialog \u2014 whether you handled it via browser_handle_dialog or the browser reported it as already handled. At replay Saffron arms this handler BEFORE the triggering action, so without this call the replay will auto-dismiss the dialog and diverge from what you saw.",{accept:ee.boolean().describe("true = accept/OK the dialog, false = dismiss/cancel"),promptText:ee.string().optional().describe("Text typed into a prompt() before accepting")},async r=>(e.addArmedAction({action:"handleDialog",value:r.accept?"accept":"dismiss",...r.promptText?{promptText:r.promptText}:{}}),Ee(`Dialog handling recorded (${r.accept?"accept":"dismiss"}).`))),rs("saffron_wait_api","Record a network wait for the current step: replay will block until a matching API response is observed (responses from the triggering step count). Call AFTER you verified via browser_network_requests that the response actually occurred with the expected status/body. Use a path-only urlPattern regex and never literal volatile IDs (/api/orders/\\d+, not /api/orders/8842).",{json:_g,urlPattern:ee.string().describe("Regex matched against the response URL \u2014 path-only for portability"),method:ee.string().optional().describe("HTTP method to match (any if omitted)"),status:ee.string().optional().describe("Expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:ee.string().optional().describe(`Regex the response body must match, e.g. '"status"\\s*:\\s*"READY"' for polling waits`)},async r=>(e.addActions([{action:"waitForResponse",urlPattern:r.urlPattern,...r.method?{method:r.method}:{},...r.status?{status:r.status}:{},...r.bodyPattern?{pattern:r.bodyPattern}:{},...r.json?{json:r.json}:{}}]),Ee("Network wait recorded."))),rs("saffron_assert","Record a verified assertion for the current Then step. Call ONLY after you have confirmed the condition holds via a page snapshot. If the condition does NOT hold, do not call this: call saffron_done with success=false instead. NEVER record volatile content the step does not state (prices, counters, a date the step does not give) as literal expected text: use kind=matches with a pattern, kind=differs against captured values, or kind=amount. A value or date the step itself states, record exactly as the step shows it to you: Saffron turns a date back into the step's token, so it moves with the calendar.",{json:_g,kind:ee.enum(["visible","notVisible","text","url","value","differs","matches","attribute","response","each","download","amount"]),...jg,expected:ee.string().optional().describe(`Required for kind=text|value. Stable expected text/value; use an explicit empty string only for an empty check. kind=download: text the downloaded file must contain, e.g. 'DTSTART;VALUE=DATE:{date+7:YYYYMMDD}' (write a date as the step writes it). kind=amount: the amount the target must show, as arithmetic over values captured with saffron_capture (their saveAs in double quotes) and written amounts, operators between spaces, e.g. '"before" + "breakfast"', '"night" * 2', '"total" - "discount"'; compared to the cent, whatever the currency format`),url:ee.string().optional().describe("URL substring for kind=url (path only, no host)"),pattern:ee.string().optional().describe("kind=matches|attribute: regex the target's text (or attribute) must match, e.g. 'NOK [\\\\d,]+' for a price. Attribute patterns are case-sensitive. kind=download: regex the downloaded file's text must match (case-sensitive, ^ and $ at each line)"),attribute:ee.string().optional().describe("kind=attribute: attribute name to check, e.g. 'href' for link-target assertions \u2014 use this for 'X should link to Y' instead of clicking through"),capture:ee.string().optional().describe("kind=differs: name of the captured value on the LEFT of the comparison (omit when comparing the target element's live text)"),urlPattern:ee.string().optional().describe("kind=response: regex matched against the response URL. Check before the next browser interaction or navigation; only requests started since the latest action qualify. Use a path for portability, never literal volatile IDs (use /api/orders/\\d+)."),method:ee.string().optional().describe("kind=response: HTTP method to match (any if omitted)"),status:ee.string().optional().describe("kind=response: expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:ee.string().optional().describe("kind=response: regex the response body must match (verify via browser_network_requests first)"),each:ee.string().optional().describe("kind=each: the data-list token exactly as the step writes it, e.g. '{data:enums.OrderStatus}'. The target is the CONTAINER (dropdown, table, list) that must show every value of that list. Never pass the values themselves."),compareTo:ee.string().optional().describe("kind=differs: name of the captured value to compare against")},async r=>{let s=Cg(r),o=Pg(s);if(o)return Ee(o);if((r.kind==="text"||r.kind==="value")&&r.expected===void 0)return Ee(`ERROR: kind=${r.kind} requires expected. Use an explicit empty string only to check that the element is empty.`);let a;if(r.json&&r.kind!=="response")return Ee("ERROR: json is only supported for kind=response.");switch(r.kind){case"visible":a={action:"expectVisible",target:s};break;case"notVisible":a={action:"expectNotVisible",target:s};break;case"text":a={action:"expectText",target:s,value:r.expected??""};break;case"value":a={action:"expectValue",target:s,value:r.expected??""};break;case"url":a={action:"expectUrl",url:r.url??""};break;case"differs":if(!r.compareTo)return Ee("ERROR: kind=differs requires compareTo.");if(!r.capture&&!s)return Ee("ERROR: kind=differs needs either capture (a stored name) or a target element.");a={action:"expectDiffers",target:s,value:r.capture,compareTo:r.compareTo};break;case"matches":if(!r.pattern)return Ee("ERROR: kind=matches requires pattern.");a={action:"expectMatches",target:s,pattern:r.pattern};break;case"attribute":if(!r.attribute||!r.pattern)return Ee("ERROR: kind=attribute requires attribute and pattern.");a={action:"expectAttribute",target:s,attribute:r.attribute,pattern:r.pattern};break;case"each":if(!r.each||!/^\{data:[^}]+\}$/.test(r.each))return Ee("ERROR: kind=each requires each='{data:file.list}', the token exactly as the step writes it (not the values).");a={action:"expectEach",target:s,each:r.each};break;case"amount":{if(!r.expected)return Ee(`ERROR: kind=amount requires expected: the amount as arithmetic over captured names in double quotes and written amounts, e.g. '"before" + "breakfast"'.`);let i=hv(e,r.expected);if(i)return Ee(i);a={action:"expectAmount",target:s,value:r.expected};break}case"download":{if(!r.expected&&!r.pattern)return Ee("ERROR: kind=download requires expected (text the file contains) or pattern (a regex its text matches).");a={action:"expectDownload",...r.expected?{value:r.expected}:{},...r.pattern?{pattern:r.pattern}:{}};let i=await mv(e,n,r.expected,r.pattern);if(i)return Ee(i);break}case"response":if(!r.urlPattern)return Ee("ERROR: kind=response requires urlPattern.");a={action:"expectResponse",urlPattern:r.urlPattern,...r.method?{method:r.method}:{},...r.status?{status:r.status}:{},...r.bodyPattern?{pattern:r.bodyPattern}:{},...r.json?{json:r.json}:{}};break}return!["url","differs","response","download"].includes(r.kind)&&!s?Ee("ERROR: assertion needs a target (role/name, nameRegex, label, text, or selector)."):(e.addActions([a]),Ee("Assertion recorded."))}),rs("saffron_done","Finalize the run. Call exactly once, after the final step: success=true only if every step's intent was achieved and every assertion verified.",{success:ee.boolean(),narrative:ee.string().describe("2-4 sentence summary of the run: what happened, and why it failed if it did. After a heal, say what kind of change the app went through (a locator change, or a page removed, merged, added or reordered) and on which page."),suggestedFeatureEdit:ee.string().optional().describe("If you adapted any steps: the corrected Gherkin for those steps, as you would rewrite them in the .feature file (free text, for the human report)."),featureEdits:ee.array(ee.object({index:ee.number().int().min(0).describe("zero-based step index"),text:ee.string().min(1).regex(/\S/,"a step text cannot be blank").describe("replacement step text WITHOUT the Given/When/Then keyword")})).optional().describe("Machine-applicable version of the suggested edits: one entry per adapted step. Provide this whenever you adapted a step.")},async r=>Ee(gv(e,r)))]})}function Ci(e={}){let t=e.deliberateSnapshots?`
|
|
352
352
|
8. Tool responses do NOT include a page snapshot. Take snapshots deliberately with browser_snapshot, and only when you actually need to see the page: after navigation, before locating an element you haven't seen yet, and when verifying an assertion. Do NOT snapshot after actions whose outcome is predictable (filling a field you just located, pressing Enter, a click whose result you will verify later anyway). Every snapshot is expensive.
|
|
353
353
|
9. Minimize round-trips: batch tool calls in a single response whenever they don't depend on each other's results \u2014 saffron_step together with that step's browser actions, several fills in one turn, bookkeeping calls (saffron_capture, saffron_assert) alongside the actions they belong to. Only stop and wait when you genuinely need a result before deciding your next call. Do not write narration between tool calls.`:"";return`You are Saffron's test execution agent. You execute Gherkin scenarios in a real browser using the playwright MCP tools, while Saffron records your actions into a deterministic replay cache.
|
|
354
354
|
|
|
@@ -362,47 +362,48 @@ Non-negotiable rules:
|
|
|
362
362
|
5a. For "X should link to Y" assertions, use saffron_assert kind=attribute (attribute='href', pattern for the URL) on the link element \u2014 do NOT click through and assert the page URL; the recorded assertion must be verifiable without navigation. NEVER bake volatile values into the recording. For steps that store a displayed value ('I record the price as "X"'), use saffron_capture. For comparisons ('X should differ from Y'), verify yourself from snapshots, then record with saffron_assert kind=differs referencing the captured names. For arithmetic ('the total should be "before" plus "breakfast"', 'the price should be twice "night"'), capture each input with saffron_capture where the step says (amount-only text), verify the sum yourself, then record saffron_assert kind=amount on the element showing the result, expected '"before" + "breakfast"' or '"night" * 2'. For 'something dynamic should be visible', use kind=matches with a pattern (e.g. 'NOK [\\d,]+') instead of literal text.
|
|
363
363
|
5a2. When a Then step quotes the expected text (or carries a <param> that resolves to it), pass EXACTLY that quoted text as the expected argument of saffron_assert. Replay checks containment, so the step's own wording is enough; never substitute the page's longer sentence, and never a value from a different Examples row.
|
|
364
364
|
5b. Literal ISO dates (YYYY-MM-DD) in recorded locators are auto-templated to {date\xB1N} relative to today, so date-picker recordings stay valid tomorrow. For non-ISO date formats in names, use nameRegex.
|
|
365
|
+
5b2. SECRETS: a {env:NAME} token in a step stands for a secret you never see. Type, fill, select or navigate with the token exactly as written (browser_type text='{env:PASSWORD}', or 'user-{env:USER_ID}@shop.test' inside other text): Saffron puts the real value into the browser. Wherever the value shows up afterwards (snapshots, code, network, console), you see its token instead. Write the token in assertions too (saffron_assert expected='Welcome, {env:USER}'). Never try to read or reveal the value.
|
|
365
366
|
6. When all steps are done, call saffron_done exactly once. If you adapted steps, include BOTH suggestedFeatureEdit (human-readable corrected Gherkin) AND featureEdits (one {index, text} entry per adapted step, text without the keyword) so the correction can be applied automatically.
|
|
366
367
|
5a3. DATA LISTS: when a step shows a token followed by '(a data list, currently: \u2026)', e.g. "should list every {data:enums.OrderStatus} (a data list, currently: "New", "Paid")", verify from a snapshot that EVERY listed value is shown inside one container (the dropdown, table, list or menu the step is about), then record ONE assertion: saffron_assert kind=each, each='{data:enums.OrderStatus}' (the token exactly as written, never the values), targeting that container. Do NOT record one assertion per value: replay reads the list from the data file, so values added to it later are checked without recording again. If any listed value is missing, the step FAILS.
|
|
367
368
|
5c. Real-world page furniture is supported: elements inside IFRAMES record and replay fine (interact normally) \u2014 but when a saffron_assert targets an element INSIDE an iframe, you MUST pass the iframe's CSS selector as the 'frame' argument (e.g. frame='iframe[title="Feedback widget"]'); replay cannot see into frames otherwise. File uploads: use browser_file_upload with the file path. Drag-and-drop: use browser_drag. All of these are recorded and replay deterministically.
|
|
368
369
|
5d. NATIVE DIALOGS (alert/confirm/prompt): when an action opens one, the page blocks and the snapshot reports a modal state \u2014 resolve it with browser_handle_dialog (accept true/false; promptText for prompt()). That call is recorded automatically as an armed handler replay places BEFORE the triggering action, so do NOT also call saffron_dialog. After handling, verify the post-dialog state as usual. If a step's wording says to confirm/accept, accept; if it says cancel/dismiss, dismiss.
|
|
369
|
-
5e. NETWORK WAITS: when a step says to wait for an API call ("wait for the order API to succeed", "until the job API reports READY"), do it verify-first: perform the trigger, check via browser_network_requests that the matching response actually occurred with the expected status/body, then record it with saffron_wait_api. For Then steps about API contracts ("the request should have returned 201") verify the same way and record with saffron_assert kind=response. urlPattern is a path-only regex \u2014 NEVER a literal volatile ID (/api/orders/\\d+, not /api/orders/8842) and never the host. browser_network_request returns a whole response body, which Saffron cuts at ${
|
|
370
|
+
5e. NETWORK WAITS: when a step says to wait for an API call ("wait for the order API to succeed", "until the job API reports READY"), do it verify-first: perform the trigger, check via browser_network_requests that the matching response actually occurred with the expected status/body, then record it with saffron_wait_api. For Then steps about API contracts ("the request should have returned 201") verify the same way and record with saffron_assert kind=response. For JSON fields, use json checks instead of a body regex: path is a JSON Pointer (/order/status, /items/0/sku), equals is the expected scalar as text, type is string (default), number, boolean or null. Use exists=true/false instead of equals for presence/absence. Keep the step's data, env, date and Examples tokens in expected values; never infer expectations from the response. urlPattern is a path-only regex \u2014 NEVER a literal volatile ID (/api/orders/\\d+, not /api/orders/8842) and never the host. browser_network_request returns a whole response body, which Saffron cuts at ${Ga.toLocaleString("en-US")} characters: fetch a body only when the step is about its content, and prefer a saffron_assert kind=response on the field you need.
|
|
370
371
|
5f. TABS: a click that opens a new tab needs nothing extra, replay follows the new tab by itself. When a step says to switch to another tab, go back to the first tab, or close a tab, do it with browser_tabs (list first if unsure of the index); select, close and new are recorded and replay in the same order. Steps that assert on the other tab's content are ordinary assertions after the switch.
|
|
371
372
|
5g. SCOPE: when a step names the section, dialog, card or form it acts in ('in "Your contact information"', 'inside the "Compact Double" room card'), scope the target to that container even when only one match is visible now, e.g. selector 'role=region[name="Your contact information"] >> role=textbox[name="E-mail (required)"]'. A snapshot ref records the element alone, unscoped: for these steps pass the scoped selector instead of the ref. Another Examples row or page state can show a second form with the same labels. An option of a dropdown that renders outside the container may be targeted on its own once the scoped trigger opened it, and a button of a dialog it opened is scoped to that dialog instead ('role=dialog >> role=button[name="Yes, cancel"]').
|
|
372
373
|
5h. READINESS: a step that waits for the page ("I wait until the prices have loaded", "until the dialog's fields are filled") must record what it waits for: saffron_assert kind=visible, notVisible, matches or value on the element that shows the page is ready (a price, a loaded field, a spinner gone). Replay waits for that condition; a step with no recorded action waits for nothing.
|
|
373
374
|
5i. STALE REFS: when a ref no longer resolves (the page re-rendered since the snapshot), take a fresh browser_snapshot and use its ref. Never reuse or guess an old ref.
|
|
374
375
|
5j. DOWNLOADS: a click that downloads a file needs nothing extra: its result lists "Downloading file ..." and Saffron records the download with that click, so replay waits for it and keeps the file. For a step about what the file says (an .ics calendar entry, a .csv export, a text receipt), record saffron_assert kind=download, no target, with expected (text the file must contain) and/or pattern (a regex its text matches). You cannot open the file yourself: Saffron checks it when you record and, when the check does not hold, replies with the start of the file. Write a date exactly as the step shows it to you (the day it names, e.g. DTSTART;VALUE=DATE:20261024): Saffron turns that day back into the step's date token, so the check moves with the calendar. Never a pattern that would accept any date. A link's href or download file name is still kind=attribute.
|
|
375
|
-
7. Never ask the user questions; you are unattended.${t}`}function
|
|
376
|
-
${
|
|
377
|
-
`)}`),
|
|
376
|
+
7. Never ask the user questions; you are unattended.${t}`}function wv(e,t){if(e[t].kind!=="assertion")return"action";let n=e.length;for(let r=e.length-1;r>=0&&e[r].kind==="assertion";r--)n=r;return t>=n?"assertion:final":"assertion"}var yv=`When you heal, tell the reviewer WHAT KIND of change you adapted to, in saffron_step's adaptation and again in saffron_done's narrative, and name the page (its URL path) where it happened. Pick the kind that fits: (1) locator or label change: the same control on the same page, found differently (renamed button, new test id, native select instead of a custom one); (2) page removed or merged: a page no longer exists and its fields or controls now live on another page, so a navigation step (e.g. a 'Continue' click) is no longer needed; (3) page added or flow reordered: a new intermediate page, dialog or step order; (4) timing only: nothing changed, the element was slow. When you skip or add a click, key press or navigation the step used to perform, say so explicitly, e.g. "The guest information page is gone: its fields are now on /checkout, so the 'Continue to payment' click was dropped." Never describe a flow change as a locator change.`,bv=`BROWSER SESSIONS: this scenario runs in several browser sessions, one per person, each a separate browser with its own cookies, login and tabs. [session: ...] on each step names its session ("default" for the steps before the first As "..."). Your browser tools act in the session of the step you announced last with saffron_step, so always announce a step before acting for it, and when the next step is in another session, call saffron_step for it on its own and wait for its reply before any browser call; browser_tabs lists that session's tabs only. A session keeps its page while you work in another one: when you come back to it, take a snapshot before acting. Never sign one session in as another session's person.`;function _i(e){let t=e.liveTab;if(t)return t.count<=1?`Live page: the only open tab, at ${t.url}. Work on it; do not open or select another tab to start over.`:`Live page: tab ${t.index} of ${t.count} open tabs, at ${t.url}. This is where replay left off. If browser_tabs shows another tab as current, select tab ${t.index} before anything else (Saffron does not record that selection); never start over on another tab.`}function Ng(e){let t=e.failedStep?.stepIndex;return`ANNOUNCE FIRST: call saffron_step for ${t===void 0?"the failed step":`the failed step (index ${t})`} BEFORE any state-changing browser action (click, type, select, key press, navigation, tab change). To diagnose, look with browser_snapshot, never with clicks or navigation: Saffron discards every action made before that announcement, and going back through earlier steps changes the state replay reached.`}function Pi(e,t=new Date){let{scenario:n}=e,r=Te(n),s=So(Or(n),r),o=l=>l===void 0?void 0:s(l),a=Dn(n.steps),i=n.steps.map((l,d)=>{let u=S=>Ke(dd(on(S,e.uniqueSeed??"")),t),p=a?` [session: ${ht(we(l.session))}]`:"",f=`${d}. [${wv(n.steps,d)}]${p} ${l.keyword} ${u(l.resolvedText)}`,g=l.resolvedTable??l.table,y=l.resolvedDocString??l.docString,h=f;return g&&(h+=`
|
|
377
|
+
${g.map(S=>` | ${S.map(u).join(" | ")} |`).join(`
|
|
378
|
+
`)}`),y!==void 0&&(h+=`
|
|
378
379
|
"""
|
|
379
|
-
${
|
|
380
|
-
`).map(
|
|
380
|
+
${u(y).split(`
|
|
381
|
+
`).map(S=>` ${S}`).join(`
|
|
381
382
|
`)}
|
|
382
383
|
"""`),h}).join(`
|
|
383
|
-
`),
|
|
384
|
-
`:void 0];if(e.mode==="refine")
|
|
385
|
-
${(e.completedSteps??[]).map(
|
|
386
|
-
`)||" (none)"}`,"",`Failed step: [${e.failedStep?.kind}] ${e.failedStep?.text}`,`Replay failure: ${e.failedStep?.error}`,"","Typical causes: a locator that only matched during your session (volatile accessible name \u2014 use nameRegex or a shorter stable name), a literal dynamic value baked into an assertion (use kind=matches/differs/captureText), or an assertion that cannot be checked without navigation (use kind=attribute for link targets).","Re-perform and re-record the failed step and every step after it in a REPLAYABLE form via saffron_step + browser tools / saffron_capture / saffron_assert. Express the SAME conditions the steps state \u2014 do not weaken them.","If a step genuinely cannot be expressed replayably, call saffron_done success=false and explain why.",
|
|
387
|
-
${(e.completedSteps??[]).map(
|
|
388
|
-
`)||" (none)"}`,"",`Failed step: [${e.failedStep?.kind}] ${e.failedStep?.text}`,`Failure: ${e.failedStep?.error}`,e.failedStep?.pageUrl?`Page when replay failed: ${e.failedStep.pageUrl}`:void 0,"","First diagnose: did the UI legitimately change (heal: adapt the actions, record via saffron_step + browser tools), or is the application broken (fail: saffron_done success=false with your diagnosis)?",
|
|
389
|
-
${e.completedSteps.map(
|
|
390
|
-
`)}`:"You are starting from a blank page.",
|
|
391
|
-
`),"",`The browser currently shows the state after those ${
|
|
392
|
-
`)}import{query as
|
|
393
|
-
`);if(!U.includes(Xp))throw new Error(U.replace(/^### Error\s*/,"").trim()||"the browser backend did not start");let z=O.pages().filter(ee=>!ee.isClosed()),V=T?z.indexOf(T):-1;if(V>0&&(await j.callTool({name:"browser_tabs",arguments:{action:"list"}}),(await j.callTool({name:"browser_tabs",arguments:{action:"select",index:V}})).isError))throw new fr(`could not start on the session's tab ${V}`)}catch(Z){throw await Promise.allSettled([j.close(),L?.close()]),I(!1),Z}let H=L;return{context:O,client:j,close:async()=>{await Promise.allSettled([j.close()]),await Promise.allSettled([H.close()])},release:I}},h=0,b=O=>{h++;let T=!1,_=()=>{T||(T=!0,clearTimeout(F),O.off("close",N),--h===0&&d())},N=()=>{setTimeout(_,1e3).unref()},F=setTimeout(_,3e5);return F.unref(),O.on("close",N),_},g=new Map,S=new Set,y=!1,w=!1,v=O=>{let T=g.get(O);if(!T){if(y)return Promise.reject(new fr("the agent session is over"));T=o?o.pageOf(O).then(_=>u(_.context(),_),_=>{throw new fr(`browser session "${dt(O)}" could not open: ${_ instanceof Error?_.message:String(_)}`)}):u(e),g.set(O,T),T.then(_=>{w?_.close().finally(()=>_.release(!1)):S.add(_)},()=>{}),T.catch(()=>{g.get(O)===T&&g.delete(O)})}return T},x=()=>o?.keyOf()??"",$;try{$=await v(x())}catch(O){throw d(),O}let E=Promise.resolve(),R,k=(O,T)=>{let _=E.then(async()=>{let N=x(),F=await v(N);R=N;try{return await Jc(F.context,t(),O,T)}finally{R=void 0}});return E=_.then(()=>{},()=>{}),_},P=Aa({listTools:(...O)=>$.client.listTools(...O),callTool:async(...O)=>(await v(R??x())).client.callTool(...O)},(O,T,_)=>k(Pv(O,T),_),s.projectRoot,s.toolHooks),m=async()=>{let O=[...f];if(O.length===0)return;let T=Promise.all(O.map(N=>N.path().then(()=>!0,()=>!0))),_=!await Promise.race([T,Ds(Ev).then(()=>!1)]);_&&Vc++;try{_&&(await Promise.allSettled(O.map(N=>N.cancel())),await Promise.allSettled(O.map(N=>N.failure()))),await Ds(0),await Ds(0)}finally{_&&Vc--}};return{config:{type:"sdk",name:"playwright",instance:P},close:async()=>{y=!0,await Promise.race([E,Ds(Qp)]),await m().catch(()=>{});let O=Promise.allSettled([...g.values()]);await Promise.race([O.then(_v),Ds(Qp).then(Ov)]);let T=[...S];w=!0;for(let _ of T)await _.close();await Promise.allSettled([P.close()]);for(let _ of T)_.release(!0)},grouped:(O,T)=>k(O,T)}}var Nv=Iv(import.meta.url),jv=3e4,rg="This scenario runs in several browser sessions, and the agent needs Playwright's in-process browser tools to act in each of them; they could not start";function Mv(){let e=Nv.resolve("@playwright/mcp/package.json");return Wc.join(Wc.dirname(e),"cli.js")}var og=new Set(["mcp__playwright__browser_navigate","mcp__playwright__browser_click","mcp__playwright__browser_type","mcp__playwright__browser_fill_form","mcp__playwright__browser_select_option","mcp__playwright__browser_press_key"]),Dv=new Set([...og,"mcp__playwright__browser_press_sequentially","mcp__playwright__browser_check","mcp__playwright__browser_uncheck","mcp__playwright__browser_hover","mcp__playwright__browser_drag","mcp__playwright__browser_file_upload"]),Fv=new Set(["mcp__playwright__browser_network_requests","mcp__playwright__browser_network_request","mcp__playwright__browser_console_messages"]),sg=e=>e.startsWith("mcp__playwright__")&&!Fv.has(e),Lv=new Set(["mcp__playwright__browser_snapshot","mcp__playwright__browser_find","mcp__playwright__browser_wait_for","mcp__playwright__browser_take_screenshot","mcp__playwright__browser_console_messages","mcp__playwright__browser_network_requests","mcp__playwright__browser_network_request","mcp__saffron__saffron_step","mcp__saffron__saffron_capture","mcp__saffron__saffron_dialog","mcp__saffron__saffron_wait_api","mcp__saffron__saffron_assert","mcp__saffron__saffron_done"]);function mi(e,t){if(Lv.has(e))return!1;if(e==="mcp__playwright__browser_tabs"){let n=t?.action;return!(n==="list"||n==="select"||n==="close")}return!0}var Wr=class e{constructor(t,n){this.ctx=t;this.snapshotMode=n;this.state=new ti(t.scenario,{firstStep:Nc(t),discardBeforeAnnounce:xp(t),startedAt:this.startedAt,uniqueSeed:t.uniqueSeed,lastStep:t.recordOnly?t.recordOnly.to:t.mode==="record"?t.scenario.steps.length-1:void 0})}ctx;snapshotMode;state;usage={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0};resultText="";toolCalls=0;traced;seenNames=new Map;capped;outputDir=du();get projectRoot(){return this.ctx.projectRoot??process.cwd()}stopTabWatch;stopDownloadWatch;downloadsHeard=0;heardAt=new Map;startedAt=new Date;static async open(t,n,r){let s=new e(t,n);try{return await e.attach(s,t,n,r)}catch(o){throw ng.rmSync(s.outputDir,{recursive:!0,force:!0}),o}}static async attach(t,n,r,s){let o=An(n.scenario.steps)?n.sessionPage:void 0;if(o&&s.traceBridgeUnavailable)throw new Error(rg);if((n.traceContext||o)&&!s.traceBridgeUnavailable){let a=Pe(n.scenario),i=n.traceContext??(await o(t.sessionKey())).context();try{let c=o&&{keyOf:()=>t.sessionKey(),pageOf:o};t.traced=await tg(i,()=>t.currentStep(),r,l=>{let d=l instanceof Error?l.message:String(l);console.warn(`A promise rejected during the agent session and nothing handled it: ${nt(d,a)}`)},{outputDir:t.outputDir,projectRoot:t.projectRoot,toolHooks:t.browserHooks},c)}catch(c){if(c instanceof fr)throw c;let l=nt(c instanceof Error?c.message:String(c),a);if(o)throw new Error(`${rg} (${l})`);s.traceBridgeUnavailable=!0,console.warn(`Agent tracing could not start (${l}). Continuing through the standard browser connection; agent calls will be absent from these traces.`)}}return t}sessionKey(){let t=this.state.currentStepIndex>=0?this.state.currentStepIndex:Nc(this.ctx);return pe(this.ctx.scenario.steps[t]?.session)}currentStep(){let t=this.state.currentStepIndex,n=this.ctx.scenario.steps[t];return{index:t,title:n?`${n.keyword} ${n.text}`:"Agent exploration"}}async playwrightServer(){return this.traced?this.traced.config:(this.capped??=await fu(this.playwrightStdio(),this.projectRoot,this.browserHooks),this.capped.config)}playwrightStdio(){return{command:process.execPath,args:[Mv(),"--cdp-endpoint",this.ctx.cdpEndpoint,"--snapshot-mode",this.snapshotMode,"--image-responses","omit","--output-dir",this.outputDir]}}noteThePage(t){let n="note the page for the recording";return this.traced?this.traced.grouped(n,t):this.ctx.traceContext?Jc(this.ctx.traceContext,this.currentStep(),n,t):t()}async beforeTool(t,n,r){this.toolCalls++;let s=Dc(n,r);if((Dv.has(n)||s?.action==="newTab"||s?.action==="closeTab")&&this.ctx.onBrowserAction?.(this.sessionKey()),this.state.beginToolCall(t),n.startsWith("mcp__playwright__")&&mi(n,r)&&this.heardAt.set(t,this.downloadsHeard),og.has(n)&&this.ctx.takeFingerprint&&!this.traced&&!this.state.pendingFingerprint)try{let o=this.ctx.takeFingerprint;this.state.pendingFingerprint=await this.noteThePage(()=>o(this.sessionKey()))}catch{}}afterTool(t,n,r,s){let o=Mp(n,r);o&&this.state.addArmedAction(o);let a=Dc(n,r,this.ctx.baseURL);a&&this.state.addActions([a]);let i=this.heardAt.get(t);if(this.heardAt.delete(t),sg(n)&&this.recordBrowserResult(s,i===void 0?void 0:this.downloadsHeard-i,Tp(r)),sg(n)){let c=this.seenNames.get(this.sessionKey())??new Map;for(let[l,d]of Rp(s))c.set(l,d);this.seenNames.set(this.sessionKey(),c)}this.state.endToolCall(t,mi(n,r))}browserHooks={beforeAction:()=>this.ctx.onBrowserAction?.(this.sessionKey()),onPartialResult:t=>this.recordBrowserResult(t)};recordBrowserResult(t,n,r=[]){let s=$p(t);s!==void 0&&this.ctx.onActiveTab?.(s,this.sessionKey());let o=Ep(t,this.ctx.baseURL);r.length>0&&Ap(o,r,this.seenNames.get(this.sessionKey())??new Map),this.state.addActions(o),this.state.pendingFingerprint=void 0;let i=this.stopDownloadWatch!==void 0?n??0:kp(t);i>0&&(this.state.addArmedAction({action:"waitForDownload",...i>1?{downloads:i}:{}}),this.state.downloadUnarmed=!1)}failedTool(t,n,r){this.heardAt.delete(t),n.startsWith("mcp__playwright__")&&(this.state.pendingFingerprint=void 0),this.state.endToolCall(t,mi(n,r))}watchTabs(){this.stopTabWatch=this.ctx.onTabOpened?.(n=>this.state.markTabOpened(n));let t=0;this.stopDownloadWatch=this.ctx.onDownload?.(n=>{this.downloadsHeard++,this.heardAt.size===0&&(this.state.downloadUnarmed=!this.state.creditLateDownload()),this.state.lastDownload=Ha(n,Wc.join(this.outputDir,"downloads",String(++t)),jv).catch(()=>{})})}sessionError(t){if(this.state.done)return;let n=t instanceof Error?t.message:String(t);this.state.done=!0,this.state.success=!1,this.state.narrative=`${Ms}${n}`}async close(){this.stopTabWatch?.(),this.stopTabWatch=void 0,this.stopDownloadWatch?.(),this.stopDownloadWatch=void 0,await this.traced?.close(),await this.capped?.close(),ng.rmSync(this.outputDir,{recursive:!0,force:!0})}result(){let{ctx:t,state:n}=this;if(!n.done){n.success=!1;let r=this.toolCalls===0?" The agent made no browser or Saffron tool call, so its tools did not reach it: check the provider's SDK version and its login.":"";n.narrative=n.narrative||`Agent session ended without finalizing the run.${r} Last output: ${nt(this.resultText,Pe(t.scenario)).slice(0,500)}`}return{success:n.success,narrative:n.narrative,adaptations:[...n.adaptations,...n.attributionNotes()],suggestedFeatureEdit:n.suggestedFeatureEdit,featureEdits:n.featureEdits.map(r=>{let s=zr(r.text,t.scenario.params),o=t.scenario.steps[r.index];return{index:r.index,text:o?zl(o.text,s):s}}),recordedSteps:Np(n.steps,t.scenario,t.uniqueSeed,this.startedAt),announcedSteps:[...n.announced].sort((r,s)=>r-s),usage:this.usage}}};var wi=class{constructor(t={}){this.opts=t}opts;planBefore;traceBridgeUnavailable=!1;async planUsage(){if(!this.planBefore)return;let t=await this.planBefore;if(!t)return;let n=await Yp();return{subscriptionType:t.subscriptionType,fiveHourBefore:t.utilization,fiveHourAfter:n?.utilization,resetsAt:n?.resetsAt??t.resetsAt}}async run(t){let n=await Wr.open(t,this.opts.snapshotMode??"none",this),r;try{r=Bv({prompt:gi(t,n.startedAt),options:{systemPrompt:pi({deliberateSnapshots:n.snapshotMode==="none",adaptableMidAssertions:t.assertionPolicy==="adaptable-mid"}),model:t.model??this.opts.model,maxTurns:this.opts.maxTurns??100,tools:[],permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,persistSession:!1,settingSources:[],strictMcpConfig:!0,settings:{disableClaudeAiConnectors:!0},mcpServers:{playwright:await n.playwrightServer(),saffron:ui(n.state)},hooks:{PreToolUse:[{hooks:[async s=>{let o=s;return await n.beforeTool(o.tool_use_id,o.tool_name,o.tool_input),{continue:!0}}]}],PostToolUse:[{hooks:[async s=>{let o=s;return n.afterTool(o.tool_use_id,o.tool_name,o.tool_input,o.tool_response),{continue:!0}}]}],PostToolUseFailure:[{hooks:[async s=>{let o=s;return n.failedTool(o.tool_use_id,o.tool_name,o.tool_input),{continue:!0}}]}]}}})}catch(s){throw await n.close(),s}this.planBefore||(this.planBefore=qc(r)),n.watchTabs();try{let s;for await(let o of r){let a=o.type==="rate_limit_event"?o.rate_limit_info:void 0;if(a?.status==="rejected"&&!a.isUsingOverage&&a.overageStatus!=="allowed"&&a.overageStatus!=="allowed_warning"){let i=a.resetsAt;s=`Claude usage limit reached${i?`; it resets at ${new Date(i*1e3).toISOString()}`:""}`}o.type==="result"&&o.is_error&&(s??=`Claude: ${"result"in o&&o.result?o.result:o.subtype}`),o.type==="result"&&(n.usage.aiCalls=o.num_turns,n.usage.costUsd=o.total_cost_usd,"modelUsage"in o&&o.modelUsage&&(n.usage.models=Object.keys(o.modelUsage)),"usage"in o&&o.usage&&(n.usage.inputTokens=o.usage.input_tokens??0,n.usage.outputTokens=o.usage.output_tokens??0,n.usage.cacheReadTokens=o.usage.cache_read_input_tokens??0,n.usage.cacheCreationTokens=o.usage.cache_creation_input_tokens??0),o.subtype==="success"&&(n.resultText=o.result))}s&&n.sessionError(new Error(s))}catch(s){n.sessionError(s)}finally{await n.close()}return n.result()}};import Uv from"node:http";import{randomBytes as zv,randomUUID as Hv,timingSafeEqual as qv}from"node:crypto";import{Client as Vv}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as Jv}from"@modelcontextprotocol/sdk/inMemory.js";import{Server as Wv}from"@modelcontextprotocol/sdk/server/index.js";import{StreamableHTTPServerTransport as Gv}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as Kv,ListToolsRequestSchema as Yv}from"@modelcontextprotocol/sdk/types.js";var Zv=5e3;async function Qv(e,t){let n=zv(16).toString("hex"),r=Buffer.from(`Bearer ${n}`),s=u=>{let h=Buffer.from(u??"");return h.length===r.length&&qv(h,r)},o=Promise.resolve(),a=!1,i=new AbortController,c,l=u=>{let h=o.then(u);return o=h.catch(()=>{}),h},d=(u,h)=>{let b=new Wv({name:u,version:"1"},{capabilities:{tools:{}}});return b.setRequestHandler(Yv,g=>h.listTools(g.params)),b.setRequestHandler(Kv,(g,S)=>l(async()=>{if(a||S.signal.aborted)throw new Error(a?"the agent session is over":"the call was cancelled before its turn came");let y=Hv(),w=`mcp__${u}__${g.params.name}`,v=g.params.arguments??{};await t.beforeTool(y,w,v);try{i.signal.throwIfAborted();let x=await h.callTool(g.params,void 0,{timeout:Ra,signal:i.signal});return x.isError?t.failedTool(y,w,v):t.afterTool(y,w,v,x),x}catch(x){throw t.failedTool(y,w,v),x}})),b},f=Uv.createServer(async(u,h)=>{let b=(u.url??"").split("?")[0].slice(1),g=s(u.headers.authorization)?e[b]:void 0;if(!g)return void h.writeHead(404).end();if(u.method!=="POST")return void h.writeHead(405,{Allow:"POST"}).end();let S=d(b,g),y=new Gv({sessionIdGenerator:void 0,enableJsonResponse:!0});h.on("close",()=>{Promise.allSettled([y.close(),S.close()])});try{await S.connect(y),await y.handleRequest(u,h)}catch{h.headersSent||h.writeHead(500).end()}});f.requestTimeout=0,await new Promise((u,h)=>{f.once("error",h),f.listen(0,"127.0.0.1",()=>u())});let{port:p}=f.address();return{urls:Object.fromEntries(Object.keys(e).map(u=>[u,`http://127.0.0.1:${p}/${u}`])),token:n,close:()=>c??=(async()=>{a=!0,f.closeAllConnections(),await new Promise(h=>f.close(()=>h()));let u;try{await Promise.race([o,new Promise((h,b)=>{u=setTimeout(()=>{let g=new Error("Agent shutdown timed out after 5 seconds waiting for a browser tool; the incomplete recording cannot be used.");i.abort(g),b(g)},Zv),u.unref()})])}finally{clearTimeout(u)}})()}}async function ig(e){let[t,n]=Jv.createLinkedPair();await e.connect(n);let r=new Vv({name:"saffron-gateway",version:"1"});return await r.connect(t),r}async function ag(e,t=e){let n=[];try{let r=await ig((await e.playwrightServer()).instance);n.push(r);let s=await ig(ui(e.state).instance);n.push(s);let o=await Qv({playwright:r,saffron:s},t);return{urls:o.urls,token:o.token,close:async()=>{try{await o.close()}finally{await Promise.allSettled(n.map(a=>a.close()))}}}}catch(r){throw await Promise.allSettled(n.map(s=>s.close())),r}}var yi=class{constructor(t,n={},r=()=>{}){this.drive=t;this.opts=n;this.blocker=r}drive;opts;blocker;traceBridgeUnavailable=!1;async run(t){let n=this.blocker();if(n)throw new Error(n);let r=await Wr.open(t,this.opts.snapshotMode??"none",this),s=this.opts.maxTurns??100,o=new AbortController,a=0,i;try{i=await ag(r,{beforeTool:async(l,d,f)=>{if(++a>s)throw o.abort(new Error(pr(s))),o.signal.reason;await r.beforeTool(l,d,f)},afterTool:r.afterTool.bind(r),failedTool:r.failedTool.bind(r)})}catch(l){throw await r.close(),l}r.watchTabs();let c;try{if(await this.drive({systemPrompt:pi({deliberateSnapshots:r.snapshotMode==="none",adaptableMidAssertions:t.assertionPolicy==="adaptable-mid"}),prompt:gi(t,r.startedAt),model:t.model??this.opts.model,maxTurns:s,signal:o.signal,mcpServers:i.urls,mcpToken:i.token,usage:r.usage,lastOutput:l=>{r.resultText=l},finished:()=>r.state.done}),o.signal.aborted)throw o.signal.reason}catch(l){c={error:l}}finally{try{try{await i.close()}catch(l){c={error:l},r.state.done=!1}c&&r.sessionError(c.error)}finally{await r.close()}}return r.result()}};async function Ls(e,t){try{return await import(e)}catch(n){let r=n.code;throw(r==="ERR_MODULE_NOT_FOUND"||r==="MODULE_NOT_FOUND")&&String(n.message).includes(`'${e}'`)?new Error(`the ${t} provider needs ${e}: npm install --save-dev ${e}`):n}}function pr(e){return`stopped after ${e} tool calls, the session's turn limit: raise maxTurns in saffron.config.json, or look at what the agent kept retrying`}import Gr from"node:fs";import Gc from"node:os";import en from"node:path";import{createHash as Xv}from"node:crypto";import{createRequire as cg}from"node:module";function ex(){try{let e=cg(import.meta.resolve("@openai/codex-sdk")).resolve("@openai/codex/package.json"),t=cg(e).resolve(`@openai/codex-${process.platform}-${process.arch}/package.json`),n=en.join(en.dirname(t),"vendor");for(let r of Gr.readdirSync(n))for(let s of[en.join(n,r,"bin","codex"),en.join(n,r,"codex","codex")])if(Gr.existsSync(s))return s}catch{}}function bi(e=process.platform){return e==="win32"?"the codex provider is not available on Windows yet: Saffron must run Codex without your ~/.codex/config.toml (your own MCP servers, plugins and hooks), and cannot on Windows":void 0}function tx(e){return`'${e.replaceAll("'","'\\''")}'`}function nx(){let e=bi();if(e)throw new Error(e);let t=ex();if(!t)throw new Error("the Codex binary is missing from @openai/codex-sdk's install: reinstall it with npm install --save-dev @openai/codex-sdk");let n=en.join(process.env.XDG_CACHE_HOME||en.join(Gc.homedir(),".cache"),"saffron");Gr.mkdirSync(n,{recursive:!0});let r=en.join(n,`codex-${Xv("sha256").update(t).digest("hex").slice(0,12)}`);return Je(r,`#!/bin/sh
|
|
384
|
+
`),c=[`Feature: ${n.featureName} (${n.featurePath})`,`Scenario: ${n.displayName}`,e.baseURL?`Base URL: ${o(e.baseURL)}`:void 0,"",a?"Steps (index. [kind] [session] keyword text):":"Steps (index. [kind] keyword text):",i,"",a?`${bv}
|
|
385
|
+
`:void 0];if(e.mode==="refine")c.push("MODE: REFINE. You (or a previous agent session) just recorded this scenario and it completed successfully \u2014 but the deterministic zero-AI replay of that recording FAILED at the step below. The application is working; the RECORDING is not replayable.","The browser tab shows the state where the proof replay stopped.",o(_i(e)),"",`Steps that replayed fine:
|
|
386
|
+
${(e.completedSteps??[]).map(l=>` \u2713 ${o(l)}`).join(`
|
|
387
|
+
`)||" (none)"}`,"",`Failed step: [${e.failedStep?.kind}] ${e.failedStep?.text}`,`Replay failure: ${o(e.failedStep?.error)}`,"","Typical causes: a locator that only matched during your session (volatile accessible name \u2014 use nameRegex or a shorter stable name), a literal dynamic value baked into an assertion (use kind=matches/differs/captureText), or an assertion that cannot be checked without navigation (use kind=attribute for link targets).","Re-perform and re-record the failed step and every step after it in a REPLAYABLE form via saffron_step + browser tools / saffron_capture / saffron_assert. Express the SAME conditions the steps state \u2014 do not weaken them.","If a step genuinely cannot be expressed replayably, call saffron_done success=false and explain why.",Ng(e));else if(e.mode==="heal")c.push("MODE: HEAL. A cached deterministic replay of this scenario failed mid-run.","The browser tab already holds the page state reached so far \u2014 do NOT restart from step 0; verify where you are with a snapshot and continue from the failed step.",o(_i(e)),"",`Steps already completed by replay:
|
|
388
|
+
${(e.completedSteps??[]).map(l=>` \u2713 ${o(l)}`).join(`
|
|
389
|
+
`)||" (none)"}`,"",`Failed step: [${e.failedStep?.kind}] ${e.failedStep?.text}`,`Failure: ${o(e.failedStep?.error)}`,e.failedStep?.pageUrl?`Page when replay failed: ${o(e.failedStep.pageUrl)}`:void 0,"","First diagnose: did the UI legitimately change (heal: adapt the actions, record via saffron_step + browser tools), or is the application broken (fail: saffron_done success=false with your diagnosis)?",yv,e.assertionPolicy==="adaptable-mid"?"If the failed step is an [assertion:final]: you may re-verify the SAME condition once against the live page (timing), but if it does not hold AS WRITTEN, the run FAILS \u2014 call saffron_done success=false; never substitute it. If the failed step is a mid-scenario [assertion]: this project's policy allows adapting it \u2014 verify the equivalent condition on the legitimately-changed UI, record it via saffron_assert, and report the deviation via saffron_step's adaptation field plus featureEdits. An application defect still fails.":"If the failed step is an [assertion] or [assertion:final]: you may re-verify the SAME condition once against the live page (it may have been a timing issue). If the condition AS WRITTEN does not hold, the run FAILS \u2014 call saffron_done success=false. Do NOT substitute a different element, text, or URL that 'means the same thing'; suggesting a corrected assertion belongs in suggestedFeatureEdit of your failure report, never in saffron_assert.","Announce (saffron_step) and perform only the failed step and the steps after it. Earlier steps keep their recordings.",Ng(e));else if(e.mode==="record"&&e.recordOnly){let{from:l,to:d}=e.recordOnly;c.push("MODE: RECORD (segment). This scenario is being composed from existing recordings plus your work.",e.completedSteps&&e.completedSteps.length>0?`Already executed against the live browser (do NOT redo):
|
|
390
|
+
${e.completedSteps.map(u=>` \u2713 ${o(u)}`).join(`
|
|
391
|
+
`)}`:"You are starting from a blank page.",o(_i(e)),"",`Record ONLY steps ${l} through ${d} (inclusive).`,`CRITICAL STOP RULE: the steps AFTER step ${d} already have recordings and will be replayed automatically the moment you stop. After completing step ${d}, immediately call saffron_done \u2014 do NOT perform, verify, or navigate into any later step. Executing a later step yourself would make the automatic replay run it TWICE.`)}else if(e.completedSteps&&e.completedSteps.length>0){let l=e.completedSteps.length;c.push("MODE: RECORD (seeded). No cache exists for this scenario yet, but its first steps matched existing recordings and were ALREADY EXECUTED against the live browser by zero-AI replay:",e.completedSteps.map(d=>` \u2713 ${o(d)}`).join(`
|
|
392
|
+
`),"",`The browser currently shows the state after those ${l} step(s) (verify with a snapshot if unsure). Do NOT redo them and do NOT navigate away from the current state.`,o(_i(e)),`Start with saffron_step for step index ${l} and record from there to the end.`)}else c.push("MODE: RECORD. No cache exists for this scenario yet.","Execute every step in order, starting at step 0. Navigate to the base URL first if the scenario implies a starting page.");return c.filter(l=>l!==void 0).join(`
|
|
393
|
+
`)}import{query as xv}from"@anthropic-ai/claude-agent-sdk";var vv="usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET";async function yl(e,t=8e3){let n=e?.[vv];if(typeof n!="function")return;let r;try{let s=await Promise.race([n.call(e,{skipBehaviors:!0}),new Promise(o=>{r=setTimeout(()=>o(void 0),t),r.unref?.()})]);return Sv(s)}catch{return}finally{r&&clearTimeout(r)}}function Sv(e){if(!e||!e.rate_limits_available||!e.subscription_type)return;let t=e.rate_limits?.five_hour;return{subscriptionType:e.subscription_type,utilization:typeof t?.utilization=="number"?t.utilization:void 0,resetsAt:t?.resets_at??void 0}}async function Mg(){let e=()=>{},t=new Promise(s=>e=s);async function*n(){await t}let r;try{let s=xv({prompt:n(),options:{maxTurns:1,tools:[],settingSources:[],persistSession:!1}});r=s;let o=(async()=>{try{for await(let i of s);}catch{}})(),a=await yl(s);return e(),r.close?.(),await o,a}catch{e(),r?.close?.();return}}import zg from"node:fs";import vl from"node:path";import{createRequire as Cv}from"node:module";import{createRequire as Dg}from"node:module";var $v=Dg(import.meta.url),Ii=Dg($v.resolve("playwright/package.json"));import{Client as kv}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as Rv}from"@modelcontextprotocol/sdk/inMemory.js";var Fg=1e4,Tv=5e3,Lg="saffron_connection_check",Av=()=>!0,Ev=()=>!1,Qs=e=>new Promise(t=>{setTimeout(t,e).unref()}),Xs=new Set,bl=0,Bg=e=>{bl===0&&[...Xs].at(-1)?.(e)};function Ov(e){let t=n=>e(n);return Xs.size===0&&process.on("unhandledRejection",Bg),Xs.add(t),()=>{Xs.delete(t)&&Xs.size===0&&process.off("unhandledRejection",Bg)}}async function xl(e,t,n,r){await e.tracing.group(`[saffron:agent:${t.index}] ${t.title}`).catch(()=>{});try{await e.tracing.group(n).catch(()=>{});try{return await r()}finally{await e.tracing.groupEnd().catch(()=>{})}}finally{await e.tracing.groupEnd().catch(()=>{})}}function _v(e,t={}){let n=o=>typeof o=="string"&&o.trim()?o.trim():void 0,r=n(t.element)??"an element",s=(()=>{switch(e){case"browser_snapshot":return"read the page";case"browser_find":return n(t.text)?`find "${n(t.text)}" on the page`:n(t.regex)?`find ${n(t.regex)} on the page`:"search the page";case"browser_click":return`${t.doubleClick?"double-click":"click"} ${r}`;case"browser_hover":return`hover ${r}`;case"browser_type":return`type into ${r}`;case"browser_fill_form":return"fill in the form";case"browser_select_option":return`select in ${r}`;case"browser_press_key":return n(t.key)?`press ${n(t.key)}`:"press a key";case"browser_navigate":return n(t.url)?`go to ${n(t.url)}`:"navigate";case"browser_navigate_back":return"go back";case"browser_wait_for":return n(t.text)?`wait for "${n(t.text)}"`:n(t.textGone)?`wait for "${n(t.textGone)}" to go`:`wait ${t.time??""}s`.replace(" s","");case"browser_tabs":return n(t.action)?`tabs: ${n(t.action)}`:"list the tabs";case"browser_drag":return`drag ${n(t.startElement)??"an element"} to ${n(t.endElement)??"an element"}`;case"browser_file_upload":return"upload files";case"browser_handle_dialog":return`${t.accept?"accept":"dismiss"} the dialog`;case"browser_evaluate":case"browser_run_code":case"browser_run_code_unsafe":return"run a script in the page";case"browser_take_screenshot":return"take a screenshot";case"browser_console_messages":return"read the console";case"browser_network_requests":return"read the network log";default:return}})();return s?`${s} \xB7 ${e}`:e}var br=class extends Error{};async function Ug(e,t,n="none",r=()=>{},s={},o){let{createConnection:a,resolveCLIConfigForMCP:i}=Ii("playwright-core/lib/coreBundle").tools,c=await i?.({},process.env)??{},l={...c,browser:{...c.browser,isolated:!1},sharedBrowserContext:!0,imageResponses:"omit",...s.outputDir?{outputDir:s.outputDir}:{},snapshot:{...c.snapshot,mode:n}},d=Ov(r),u=new Set,p=_=>{u.add(_)},f=async(_,A)=>{let O=_.browser(),j=new Set(O?.listeners("disconnected")??[]),L=Y=>{Y.on("download",p)};for(let Y of _.pages())L(Y);_.on("page",L);let I=Y=>{_.off("page",L);for(let Q of _.pages())Q.off("download",p);for(let Q of O?.listeners("disconnected")??[])j.has(Q)||O.off("disconnected",Q);return Y?y(_):void 0},U,D=new kv({name:"saffron-trace",version:"1"});try{U=await a(l,async()=>_);let[Y,Q]=Rv.createLinkedPair();await U.connect(Q),await D.connect(Y);let M=((await D.callTool({name:Lg,arguments:{}})).content??[]).map(ne=>ne.text??"").join(`
|
|
394
|
+
`);if(!M.includes(Lg))throw new Error(M.replace(/^### Error\s*/,"").trim()||"the browser backend did not start");let B=_.pages().filter(ne=>!ne.isClosed()),J=A?B.indexOf(A):-1;if(J>0&&(await D.callTool({name:"browser_tabs",arguments:{action:"list"}}),(await D.callTool({name:"browser_tabs",arguments:{action:"select",index:J}})).isError))throw new br(`could not start on the session's tab ${J}`)}catch(Y){throw await Promise.allSettled([D.close(),U?.close()]),I(!1),Y}let q=U;return{context:_,client:D,close:async()=>{await Promise.allSettled([D.close()]),await Promise.allSettled([q.close()])},release:I}},g=0,y=_=>{g++;let A=!1,O=()=>{A||(A=!0,clearTimeout(L),_.off("close",j),--g===0&&d())},j=()=>{setTimeout(O,1e3).unref()},L=setTimeout(O,3e5);return L.unref(),_.on("close",j),O},h=new Map,S=new Set,v=!1,x=!1,b=_=>{let A=h.get(_);if(!A){if(v)return Promise.reject(new br("the agent session is over"));A=o?o.pageOf(_).then(O=>f(O.context(),O),O=>{throw new br(`browser session "${ht(_)}" could not open: ${O instanceof Error?O.message:String(O)}`)}):f(e),h.set(_,A),A.then(O=>{x?O.close().finally(()=>O.release(!1)):S.add(O)},()=>{}),A.catch(()=>{h.get(_)===A&&h.delete(_)})}return A},m=()=>o?.keyOf()??"",$;try{$=await b(m())}catch(_){throw d(),_}let T=Promise.resolve(),R,k=(_,A)=>{let O=T.then(async()=>{let j=m(),L=await b(j);R=j;try{return await xl(L.context,t(),_,A)}finally{R=void 0}});return T=O.then(()=>{},()=>{}),O},P=Za({listTools:(..._)=>$.client.listTools(..._),callTool:async(..._)=>(await b(R??m())).client.callTool(..._)},(_,A,O)=>k(_v(_,A),O),s.projectRoot,s.toolHooks),w=async()=>{let _=[...u];if(_.length===0)return;let A=Promise.all(_.map(j=>j.path().then(()=>!0,()=>!0))),O=!await Promise.race([A,Qs(Tv).then(()=>!1)]);O&&bl++;try{O&&(await Promise.allSettled(_.map(j=>j.cancel())),await Promise.allSettled(_.map(j=>j.failure()))),await Qs(0),await Qs(0)}finally{O&&bl--}};return{config:{type:"sdk",name:"playwright",instance:P},close:async()=>{v=!0,await Promise.race([T,Qs(Fg)]),await w().catch(()=>{});let _=Promise.allSettled([...h.values()]);await Promise.race([_.then(Av),Qs(Fg).then(Ev)]);let A=[...S];x=!0;for(let O of A)await O.close();await Promise.allSettled([P.close()]);for(let O of A)O.release(!0)},grouped:(_,A)=>k(_,A)}}var Pv=Cv(import.meta.url),Iv=3e4,qg="This scenario runs in several browser sessions, and the agent needs Playwright's in-process browser tools to act in each of them; they could not start";function jv(){let e=Pv.resolve("@playwright/mcp/package.json");return vl.join(vl.dirname(e),"cli.js")}var Vg=new Set(["mcp__playwright__browser_navigate","mcp__playwright__browser_click","mcp__playwright__browser_type","mcp__playwright__browser_fill_form","mcp__playwright__browser_select_option","mcp__playwright__browser_press_key"]),Nv=new Set([...Vg,"mcp__playwright__browser_press_sequentially","mcp__playwright__browser_check","mcp__playwright__browser_uncheck","mcp__playwright__browser_hover","mcp__playwright__browser_drag","mcp__playwright__browser_file_upload"]),Mv=new Set(["mcp__playwright__browser_network_requests","mcp__playwright__browser_network_request","mcp__playwright__browser_console_messages"]),Hg=e=>e.startsWith("mcp__playwright__")&&!Mv.has(e),Dv=new Set(["mcp__playwright__browser_snapshot","mcp__playwright__browser_find","mcp__playwright__browser_wait_for","mcp__playwright__browser_take_screenshot","mcp__playwright__browser_console_messages","mcp__playwright__browser_network_requests","mcp__playwright__browser_network_request","mcp__saffron__saffron_step","mcp__saffron__saffron_capture","mcp__saffron__saffron_dialog","mcp__saffron__saffron_wait_api","mcp__saffron__saffron_assert","mcp__saffron__saffron_done"]);function ji(e,t){if(Dv.has(e))return!1;if(e==="mcp__playwright__browser_tabs"){let n=t?.action;return!(n==="list"||n==="select"||n==="close")}return!0}var ss=class e{constructor(t,n){this.ctx=t;this.snapshotMode=n;this.state=new Go(t.scenario,{firstStep:ic(t),discardBeforeAnnounce:of(t),startedAt:this.startedAt,uniqueSeed:t.uniqueSeed,lastStep:t.recordOnly?t.recordOnly.to:t.mode==="record"?t.scenario.steps.length-1:void 0})}ctx;snapshotMode;state;usage={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0};resultText="";toolCalls=0;traced;seenNames=new Map;capped;outputDir=Ju();get projectRoot(){return this.ctx.projectRoot??process.cwd()}stopTabWatch;stopDownloadWatch;downloadsHeard=0;heardAt=new Map;startedAt=new Date;static async open(t,n,r){let s=new e(t,n);try{return await e.attach(s,t,n,r)}catch(o){throw zg.rmSync(s.outputDir,{recursive:!0,force:!0}),o}}static async attach(t,n,r,s){let o=Dn(n.scenario.steps)?n.sessionPage:void 0;if(o&&s.traceBridgeUnavailable)throw new Error(qg);if((n.traceContext||o)&&!s.traceBridgeUnavailable){let a=Te(n.scenario),i=n.traceContext??(await o(t.sessionKey())).context();try{let c=o&&{keyOf:()=>t.sessionKey(),pageOf:o};t.traced=await Ug(i,()=>t.currentStep(),r,l=>{let d=l instanceof Error?l.message:String(l);console.warn(`A promise rejected during the agent session and nothing handled it: ${Ge(d,a)}`)},{outputDir:t.outputDir,projectRoot:t.projectRoot,toolHooks:t.browserHooks},c)}catch(c){if(c instanceof br)throw c;let l=Ge(c instanceof Error?c.message:String(c),a);if(o)throw new Error(`${qg} (${l})`);s.traceBridgeUnavailable=!0,console.warn(`Agent tracing could not start (${l}). Continuing through the standard browser connection; agent calls will be absent from these traces.`)}}return t}sessionKey(){let t=this.state.currentStepIndex>=0?this.state.currentStepIndex:ic(this.ctx);return we(this.ctx.scenario.steps[t]?.session)}currentStep(){let t=this.state.currentStepIndex,n=this.ctx.scenario.steps[t];return{index:t,title:n?`${n.keyword} ${n.text}`:"Agent exploration"}}async playwrightServer(){return this.traced?this.traced.config:(this.capped??=await Wu(this.playwrightStdio(),this.projectRoot,this.browserHooks),this.capped.config)}playwrightStdio(){return{command:process.execPath,args:[jv(),"--cdp-endpoint",this.ctx.cdpEndpoint,"--snapshot-mode",this.snapshotMode,"--image-responses","omit","--output-dir",this.outputDir]}}noteThePage(t){let n="note the page for the recording";return this.traced?this.traced.grouped(n,t):this.ctx.traceContext?xl(this.ctx.traceContext,this.currentStep(),n,t):t()}async beforeTool(t,n,r){this.toolCalls++;let s=dc(n,r);if((Nv.has(n)||s?.action==="newTab"||s?.action==="closeTab")&&this.ctx.onBrowserAction?.(this.sessionKey()),this.state.beginToolCall(t),n.startsWith("mcp__playwright__")&&ji(n,r)&&this.heardAt.set(t,this.downloadsHeard),Vg.has(n)&&this.ctx.takeFingerprint&&!this.traced&&!this.state.pendingFingerprint)try{let o=this.ctx.takeFingerprint;this.state.pendingFingerprint=await this.noteThePage(()=>o(this.sessionKey()))}catch{}}afterTool(t,n,r,s){let o=Jg(s),a=this.rawResults.get(o)??s;this.rawResults.delete(o);let i=xf(n,r);i&&this.state.addArmedAction(i);let c=dc(n,r,this.ctx.baseURL);c&&this.state.addActions([c]);let l=this.heardAt.get(t);if(this.heardAt.delete(t),Hg(n)&&this.recordBrowserResult(a,l===void 0?void 0:this.downloadsHeard-l,uf(r)),Hg(n)){let d=this.seenNames.get(this.sessionKey())??new Map;for(let[u,p]of df(a))d.set(u,p);this.seenNames.set(this.sessionKey(),d)}this.state.endToolCall(t,ji(n,r))}browserHooks={beforeAction:()=>this.ctx.onBrowserAction?.(this.sessionKey()),onPartialResult:t=>this.recordBrowserResult(t),secrets:()=>this.secrets(),texts:()=>Or(this.ctx.scenario),onResult:(t,n)=>{this.rawResults.set(Jg(t),n),this.rawResults.size>32&&this.rawResults.delete(this.rawResults.keys().next().value)}};rawResults=new Map;secretValues;secrets(){return this.secretValues??=Te(this.ctx.scenario)}recordBrowserResult(t,n,r=[]){let s=cf(t);s!==void 0&&this.ctx.onActiveTab?.(s,this.sessionKey());let o=pf(t,this.ctx.baseURL);r.length>0&&ff(o,r,this.seenNames.get(this.sessionKey())??new Map),this.state.addActions(o),this.state.pendingFingerprint=void 0;let i=this.stopDownloadWatch!==void 0?n??0:lf(t);i>0&&(this.state.addArmedAction({action:"waitForDownload",...i>1?{downloads:i}:{}}),this.state.downloadUnarmed=!1)}failedTool(t,n,r){this.heardAt.delete(t),n.startsWith("mcp__playwright__")&&(this.state.pendingFingerprint=void 0),this.state.endToolCall(t,ji(n,r))}watchTabs(){this.stopTabWatch=this.ctx.onTabOpened?.(n=>this.state.markTabOpened(n));let t=0;this.stopDownloadWatch=this.ctx.onDownload?.(n=>{this.downloadsHeard++,this.heardAt.size===0&&(this.state.downloadUnarmed=!this.state.creditLateDownload()),this.state.lastDownload=Ec(n,vl.join(this.outputDir,"downloads",String(++t)),Iv).catch(()=>{})})}sessionError(t){if(this.state.done)return;let n=t instanceof Error?t.message:String(t);this.state.done=!0,this.state.success=!1,this.state.narrative=`${Zs}${n}`}async close(){this.stopTabWatch?.(),this.stopTabWatch=void 0,this.stopDownloadWatch?.(),this.stopDownloadWatch=void 0,await this.traced?.close(),await this.capped?.close(),zg.rmSync(this.outputDir,{recursive:!0,force:!0})}result(){let{ctx:t,state:n}=this;if(!n.done){n.success=!1;let r=this.toolCalls===0?" The agent made no browser or Saffron tool call, so its tools did not reach it: check the provider's SDK version and its login.":"";n.narrative=n.narrative||`Agent session ended without finalizing the run.${r} Last output: ${Ge(this.resultText,Te(t.scenario)).slice(0,500)}`}return{success:n.success,narrative:n.narrative,adaptations:[...n.adaptations,...n.attributionNotes()],suggestedFeatureEdit:n.suggestedFeatureEdit,featureEdits:n.featureEdits.map(r=>{let s=Hr(r.text,t.scenario.params),o=t.scenario.steps[r.index];return{index:r.index,text:o?xd(o.text,s):s}}),recordedSteps:yf(n.steps,t.scenario,t.uniqueSeed,this.startedAt),announcedSteps:[...n.announced].sort((r,s)=>r-s),usage:this.usage}}},Jg=e=>cc(e).join("\0");var Ni=class{constructor(t={}){this.opts=t}opts;planBefore;traceBridgeUnavailable=!1;async planUsage(){if(!this.planBefore)return;let t=await this.planBefore;if(!t)return;let n=await Mg();return{subscriptionType:t.subscriptionType,fiveHourBefore:t.utilization,fiveHourAfter:n?.utilization,resetsAt:n?.resetsAt??t.resetsAt}}async run(t){let n=await ss.open(t,this.opts.snapshotMode??"none",this),r;try{r=Fv({prompt:Pi(t,n.startedAt),options:{systemPrompt:Ci({deliberateSnapshots:n.snapshotMode==="none",adaptableMidAssertions:t.assertionPolicy==="adaptable-mid"}),model:t.model??this.opts.model,maxTurns:this.opts.maxTurns??100,tools:[],permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,persistSession:!1,settingSources:[],strictMcpConfig:!0,settings:{disableClaudeAiConnectors:!0},mcpServers:{playwright:await n.playwrightServer(),saffron:Oi(n.state)},hooks:{PreToolUse:[{hooks:[async s=>{let o=s;return await n.beforeTool(o.tool_use_id,o.tool_name,o.tool_input),{continue:!0}}]}],PostToolUse:[{hooks:[async s=>{let o=s;return n.afterTool(o.tool_use_id,o.tool_name,o.tool_input,o.tool_response),{continue:!0}}]}],PostToolUseFailure:[{hooks:[async s=>{let o=s;return n.failedTool(o.tool_use_id,o.tool_name,o.tool_input),{continue:!0}}]}]}}})}catch(s){throw await n.close(),s}this.planBefore||(this.planBefore=yl(r)),n.watchTabs();try{let s;for await(let o of r){let a=o.type==="rate_limit_event"?o.rate_limit_info:void 0;if(a?.status==="rejected"&&!a.isUsingOverage&&a.overageStatus!=="allowed"&&a.overageStatus!=="allowed_warning"){let i=a.resetsAt;s=`Claude usage limit reached${i?`; it resets at ${new Date(i*1e3).toISOString()}`:""}`}o.type==="result"&&o.is_error&&(s??=`Claude: ${"result"in o&&o.result?o.result:o.subtype}`),o.type==="result"&&(n.usage.aiCalls=o.num_turns,n.usage.costUsd=o.total_cost_usd,"modelUsage"in o&&o.modelUsage&&(n.usage.models=Object.keys(o.modelUsage)),"usage"in o&&o.usage&&(n.usage.inputTokens=o.usage.input_tokens??0,n.usage.outputTokens=o.usage.output_tokens??0,n.usage.cacheReadTokens=o.usage.cache_read_input_tokens??0,n.usage.cacheCreationTokens=o.usage.cache_creation_input_tokens??0),o.subtype==="success"&&(n.resultText=o.result))}s&&n.sessionError(new Error(s))}catch(s){n.sessionError(s)}finally{await n.close()}return n.result()}};import Lv from"node:http";import{randomBytes as Bv,randomUUID as Uv,timingSafeEqual as zv}from"node:crypto";import{Client as qv}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as Hv}from"@modelcontextprotocol/sdk/inMemory.js";import{Server as Jv}from"@modelcontextprotocol/sdk/server/index.js";import{StreamableHTTPServerTransport as Vv}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as Wv,ListToolsRequestSchema as Gv}from"@modelcontextprotocol/sdk/types.js";var Kv=5e3;async function Yv(e,t){let n=Bv(16).toString("hex"),r=Buffer.from(`Bearer ${n}`),s=f=>{let g=Buffer.from(f??"");return g.length===r.length&&zv(g,r)},o=Promise.resolve(),a=!1,i=new AbortController,c,l=f=>{let g=o.then(f);return o=g.catch(()=>{}),g},d=(f,g)=>{let y=new Jv({name:f,version:"1"},{capabilities:{tools:{}}});return y.setRequestHandler(Gv,h=>g.listTools(h.params)),y.setRequestHandler(Wv,(h,S)=>l(async()=>{if(a||S.signal.aborted)throw new Error(a?"the agent session is over":"the call was cancelled before its turn came");let v=Uv(),x=`mcp__${f}__${h.params.name}`,b=h.params.arguments??{};await t.beforeTool(v,x,b);try{i.signal.throwIfAborted();let m=await g.callTool(h.params,void 0,{timeout:Ka,signal:i.signal});return m.isError?t.failedTool(v,x,b):t.afterTool(v,x,b,m),m}catch(m){throw t.failedTool(v,x,b),m}})),y},u=Lv.createServer(async(f,g)=>{let y=(f.url??"").split("?")[0].slice(1),h=s(f.headers.authorization)?e[y]:void 0;if(!h)return void g.writeHead(404).end();if(f.method!=="POST")return void g.writeHead(405,{Allow:"POST"}).end();let S=d(y,h),v=new Vv({sessionIdGenerator:void 0,enableJsonResponse:!0});g.on("close",()=>{Promise.allSettled([v.close(),S.close()])});try{await S.connect(v),await v.handleRequest(f,g)}catch{g.headersSent||g.writeHead(500).end()}});u.requestTimeout=0,await new Promise((f,g)=>{u.once("error",g),u.listen(0,"127.0.0.1",()=>f())});let{port:p}=u.address();return{urls:Object.fromEntries(Object.keys(e).map(f=>[f,`http://127.0.0.1:${p}/${f}`])),token:n,close:()=>c??=(async()=>{a=!0,u.closeAllConnections(),await new Promise(g=>u.close(()=>g()));let f;try{await Promise.race([o,new Promise((g,y)=>{f=setTimeout(()=>{let h=new Error("Agent shutdown timed out after 5 seconds waiting for a browser tool; the incomplete recording cannot be used.");i.abort(h),y(h)},Kv),f.unref()})])}finally{clearTimeout(f)}})()}}async function Wg(e){let[t,n]=Hv.createLinkedPair();await e.connect(n);let r=new qv({name:"saffron-gateway",version:"1"});return await r.connect(t),r}async function Gg(e,t=e){let n=[];try{let r=await Wg((await e.playwrightServer()).instance);n.push(r);let s=await Wg(Oi(e.state).instance);n.push(s);let o=await Yv({playwright:r,saffron:s},t);return{urls:o.urls,token:o.token,close:async()=>{try{await o.close()}finally{await Promise.allSettled(n.map(a=>a.close()))}}}}catch(r){throw await Promise.allSettled(n.map(s=>s.close())),r}}var Mi=class{constructor(t,n={},r=()=>{}){this.drive=t;this.opts=n;this.blocker=r}drive;opts;blocker;traceBridgeUnavailable=!1;async run(t){let n=this.blocker();if(n)throw new Error(n);let r=await ss.open(t,this.opts.snapshotMode??"none",this),s=this.opts.maxTurns??100,o=new AbortController,a=0,i;try{i=await Gg(r,{beforeTool:async(l,d,u)=>{if(++a>s)throw o.abort(new Error(xr(s))),o.signal.reason;await r.beforeTool(l,d,u)},afterTool:r.afterTool.bind(r),failedTool:r.failedTool.bind(r)})}catch(l){throw await r.close(),l}r.watchTabs();let c;try{if(await this.drive({systemPrompt:Ci({deliberateSnapshots:r.snapshotMode==="none",adaptableMidAssertions:t.assertionPolicy==="adaptable-mid"}),prompt:Pi(t,r.startedAt),model:t.model??this.opts.model,maxTurns:s,signal:o.signal,mcpServers:i.urls,mcpToken:i.token,usage:r.usage,lastOutput:l=>{r.resultText=l},finished:()=>r.state.done}),o.signal.aborted)throw o.signal.reason}catch(l){c={error:l}}finally{try{try{await i.close()}catch(l){c={error:l},r.state.done=!1}c&&r.sessionError(c.error)}finally{await r.close()}}return r.result()}};async function eo(e,t){try{return await import(e)}catch(n){let r=n.code;throw(r==="ERR_MODULE_NOT_FOUND"||r==="MODULE_NOT_FOUND")&&String(n.message).includes(`'${e}'`)?new Error(`the ${t} provider needs ${e}: npm install --save-dev ${e}`):n}}function xr(e){return`stopped after ${e} tool calls, the session's turn limit: raise maxTurns in saffron.config.json, or look at what the agent kept retrying`}import os from"node:fs";import Sl from"node:os";import fn from"node:path";import{createHash as Zv}from"node:crypto";import{createRequire as Kg}from"node:module";function Qv(){try{let e=Kg(import.meta.resolve("@openai/codex-sdk")).resolve("@openai/codex/package.json"),t=Kg(e).resolve(`@openai/codex-${process.platform}-${process.arch}/package.json`),n=fn.join(fn.dirname(t),"vendor");for(let r of os.readdirSync(n))for(let s of[fn.join(n,r,"bin","codex"),fn.join(n,r,"codex","codex")])if(os.existsSync(s))return s}catch{}}function Di(e=process.platform){return e==="win32"?"the codex provider is not available on Windows yet: Saffron must run Codex without your ~/.codex/config.toml (your own MCP servers, plugins and hooks), and cannot on Windows":void 0}function Xv(e){return`'${e.replaceAll("'","'\\''")}'`}function eS(){let e=Di();if(e)throw new Error(e);let t=Qv();if(!t)throw new Error("the Codex binary is missing from @openai/codex-sdk's install: reinstall it with npm install --save-dev @openai/codex-sdk");let n=fn.join(process.env.XDG_CACHE_HOME||fn.join(Sl.homedir(),".cache"),"saffron");os.mkdirSync(n,{recursive:!0});let r=fn.join(n,`codex-${Zv("sha256").update(t).digest("hex").slice(0,12)}`);return Ue(r,`#!/bin/sh
|
|
394
395
|
sub="$1"; shift
|
|
395
|
-
exec ${
|
|
396
|
-
`,493),r}var
|
|
397
|
-
`,c)}catch(l){let d=l.code;throw!a||!["EACCES","EPERM","EROFS"].includes(d??"")?l:new Error(`${e} links to ${i}, which Saffron cannot write: add ${n.join(" and ")} to permissions.allow there, then run npx saffron login antigravity again`)}return n}function
|
|
398
|
-
`).at(-1)||(t.error?.message??"no answer");throw new Error(`agy could not list your models (${r}): run agy once and sign in with your Google AI Pro or Ultra account`)}let n=
|
|
396
|
+
exec ${Xv(t)} "$sub" --ignore-user-config --ephemeral "$@"
|
|
397
|
+
`,493),r}var Yg="SAFFRON_MCP_TOKEN",tS=["cli_auth_credentials_store","forced_login_method","forced_chatgpt_workspace_id"];function nS(e){let t=e.split(/^\s*\[/m)[0],n={};for(let r of tS){let s=new RegExp(`^\\s*${r}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`,"m").exec(t);s&&(n[r]=s[1]??s[2])}return n}function $l(){try{return nS(os.readFileSync(fn.join(process.env.CODEX_HOME??fn.join(Sl.homedir(),".codex"),"config.toml"),"utf8"))}catch{return{}}}var Zg=async e=>{let{Codex:t}=await eo("@openai/codex-sdk","codex"),n=os.mkdtempSync(fn.join(Sl.tmpdir(),"saffron-codex-"));try{let r=Object.fromEntries(Object.entries(process.env).filter(d=>d[1]!==void 0)),o=new t({codexPathOverride:eS(),env:{...r,[Yg]:e.mcpToken},config:{...$l(),developer_instructions:e.systemPrompt,include_permissions_instructions:!1,include_apps_instructions:!1,include_collaboration_mode_instructions:!1,include_environment_context:!1,project_doc_max_bytes:0,skills:{include_instructions:!1},mcp_servers:Object.fromEntries(Object.entries(e.mcpServers).map(([d,u])=>[d,{url:u,bearer_token_env_var:Yg,required:!0,default_tools_approval_mode:"approve",startup_timeout_sec:30,tool_timeout_sec:600}])),features:{shell_tool:!1,view_image:!1,apps:!1,plugins:!1,hooks:!1,memories:!1,goals:!1,image_generation:!1,tool_suggest:!1,browser_use:!1,computer_use:!1,unified_exec:!1,multi_agent:!1,code_mode_host:!0,in_app_browser:!1,browser_use_external:!1}}}).startThread({model:e.model,workingDirectory:n,skipGitRepoCheck:!0,sandboxMode:"read-only",approvalPolicy:"never",webSearchMode:"disabled"}),a=new AbortController,i=e.signal?AbortSignal.any([a.signal,e.signal]):a.signal,c=0,l;try{let{events:d}=await o.runStreamed(e.prompt,{signal:i});for await(let u of d)if(u.type==="item.started"&&u.item.type==="mcp_tool_call")++c>e.maxTurns&&!i.aborted&&(l=xr(e.maxTurns),a.abort());else if(u.type==="item.completed")(u.item.type==="mcp_tool_call"||u.item.type==="agent_message")&&e.usage.aiCalls++,u.item.type==="agent_message"&&e.lastOutput(u.item.text);else if(u.type==="turn.completed"){let p=u.usage;e.usage.inputTokens=p.input_tokens-p.cached_input_tokens,e.usage.cacheReadTokens=p.cached_input_tokens,e.usage.cacheCreationTokens=p.cache_write_input_tokens??0,e.usage.outputTokens=p.output_tokens}else u.type==="turn.failed"&&!i.aborted?l=u.error.message:u.type==="error"&&!i.aborted&&(l??=u.message)}catch(d){if(!i.aborted&&!l)throw d}if(e.signal?.aborted&&(l=String(e.signal.reason instanceof Error?e.signal.reason.message:e.signal.reason)),e.usage.models=[`codex/${e.model??"default"}`],l&&!e.finished()){let d=/auth|log ?in|401|unauthori[sz]ed/i.test(l)?". Sign in with your ChatGPT plan: npx @openai/codex login":"";throw new Error(`Codex: ${l}${d}`)}}finally{os.rmSync(n,{recursive:!0,force:!0})}};import{spawn as rS,spawnSync as sS}from"node:child_process";import ze from"node:fs";import Li from"node:os";import Je from"node:path";import oS from"node:readline";var Fi="install the Antigravity CLI (curl -fsSL https://antigravity.google/cli/install.sh | bash), then run `agy` once to sign in with your Google account";function Bi(){for(let e of[...(process.env.PATH??"").split(Je.delimiter),Je.join(Li.homedir(),".local","bin")]){let t=Je.join(e,process.platform==="win32"?"agy.exe":"agy");if(e&&ze.existsSync(t))return t}}var is={playwright:"saffron_browser",saffron:"saffron_tools"},Qg=Object.values(is).map(e=>`mcp(${e}/*)`),kl=()=>Je.join(Li.homedir(),".gemini","antigravity-cli","settings.json");function Xg(e){if(!ze.existsSync(e))return{};try{let t=JSON.parse(ze.readFileSync(e,"utf8"));if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}throw new Error(`${e} is not a JSON object Saffron can add to: fix it (or ask agy to rewrite it), then run npx saffron login antigravity again`)}function Ui(e=kl()){let t;try{t=Xg(e).permissions?.allow}catch{return Qg}return Qg.filter(n=>!(Array.isArray(t)&&t.includes(n)))}function iS(e=kl()){let t=Xg(e),n=Ui(e);if(n.length===0)return[];let r=t.permissions&&typeof t.permissions=="object"?t.permissions:{},s=Array.isArray(r.allow)?r.allow:[],o={...t,permissions:{...r,allow:[...s,...n]}},a=ze.lstatSync(e,{throwIfNoEntry:!1})?.isSymbolicLink()??!1,i=aS(e),c=ze.existsSync(i)?ze.statSync(i).mode&4095:void 0;try{Ue(i,JSON.stringify(o,null,2)+`
|
|
398
|
+
`,c)}catch(l){let d=l.code;throw!a||!["EACCES","EPERM","EROFS"].includes(d??"")?l:new Error(`${e} links to ${i}, which Saffron cannot write: add ${n.join(" and ")} to permissions.allow there, then run npx saffron login antigravity again`)}return n}function aS(e){let t=e;for(let n=0;n<40&&ze.lstatSync(t,{throwIfNoEntry:!1})?.isSymbolicLink();n++)t=Je.resolve(ze.realpathSync(Je.dirname(t)),ze.readlinkSync(t));return ze.existsSync(t)?ze.realpathSync(t):t}async function eh(){let e=Bi();if(!e)throw new Error(`the antigravity provider needs the agy command: ${Fi}`);let t=sS(e,["models"],{encoding:"utf8",timeout:6e4});if(t.status!==0){let r=`${t.stderr??""}${t.stdout??""}`.trim().split(`
|
|
399
|
+
`).at(-1)||(t.error?.message??"no answer");throw new Error(`agy could not list your models (${r}): run agy once and sign in with your Google AI Pro or Ultra account`)}let n=iS();console.log(n.length>0?`Antigravity: allowed Saffron's tools in ${kl()}: ${n.join(", ")}. Remove those lines to take it back.`:"Antigravity: Saffron's tools are already allowed.")}var th=Je.join(Li.homedir(),".gemini","antigravity-cli","mcp"),cS=Object.values(is).map(e=>Je.join(th,e)),lS=`const path=require("path");const DIRS=${JSON.stringify(cS)};const SERVERS=${JSON.stringify(Object.values(is))};
|
|
399
400
|
let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{let t={};try{t=JSON.parse(s).toolCall||{}}catch{}const a=t.args||{};
|
|
400
401
|
const file=typeof a.AbsolutePath==="string"?path.resolve(a.AbsolutePath):"";
|
|
401
402
|
const dir=typeof a.DirectoryPath==="string"?path.resolve(a.DirectoryPath):"";
|
|
402
403
|
const ok=(t.name==="call_mcp_tool"&&SERVERS.includes(a.ServerName))||(t.name==="view_file"&&DIRS.includes(path.dirname(file)))||(t.name==="list_dir"&&DIRS.includes(dir));
|
|
403
|
-
process.stdout.write(JSON.stringify(ok?{decision:"allow"}:{decision:"deny",reason:"Only Saffron's browser and saffron tools are available in a Saffron session."}))})`,
|
|
404
|
+
process.stdout.write(JSON.stringify(ok?{decision:"allow"}:{decision:"deny",reason:"Only Saffron's browser and saffron tools are available in a Saffron session."}))})`,dS=(e,t)=>`let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{let i=0;try{i=JSON.parse(s).invocationNum}catch{}
|
|
404
405
|
const stop=i+1>=${e};if(stop)require("fs").writeFileSync(${JSON.stringify(t)},"");
|
|
405
|
-
process.stdout.write(JSON.stringify(stop?{terminationBehavior:"terminate"}:{}))})`,
|
|
406
|
+
process.stdout.write(JSON.stringify(stop?{terminationBehavior:"terminate"}:{}))})`,nh=async e=>{let t=Bi();if(!t)throw new Error(`the antigravity provider needs the agy command: ${Fi}`);if(Object.keys(e.mcpServers).length>0&&Ui().length>0)throw new Error("agy does not allow Saffron's tools yet: run npx saffron login antigravity once");let n=ze.mkdtempSync(Je.join(Li.tmpdir(),"saffron-agy-"));try{let r=Je.join(n,".agents");ze.mkdirSync(Je.join(r,"agents"),{recursive:!0}),ze.writeFileSync(Je.join(r,"agents","saffron.md"),`---
|
|
406
407
|
name: saffron
|
|
407
408
|
description: Saffron's browser test agent.
|
|
408
409
|
mainAgent: true
|
|
@@ -412,15 +413,15 @@ commandExecutionPolicy: off
|
|
|
412
413
|
|
|
413
414
|
${e.systemPrompt}
|
|
414
415
|
|
|
415
|
-
Your tools are MCP tools, called with call_mcp_tool: the browser_* tools are on the ${
|
|
416
|
-
`),
|
|
417
|
-
`).at(-1)||`agy exited with ${
|
|
416
|
+
Your tools are MCP tools, called with call_mcp_tool: the browser_* tools are on the ${is.playwright} server and the saffron_* tools on the ${is.saffron} server. Before a tool's first call, read its parameters with view_file from ${Je.join(th,"<server>","<tool>.json")}. No other tool is available.
|
|
417
|
+
`),ze.writeFileSync(Je.join(r,"mcp_config.json"),JSON.stringify({mcpServers:Object.fromEntries(Object.entries(e.mcpServers).map(([h,S])=>[is[h]??h,{serverUrl:S,headers:{Authorization:`Bearer ${e.mcpToken}`}}]))}));let s=(h,S)=>{let v=Je.join(n,h);return ze.writeFileSync(v,S),`${JSON.stringify(process.execPath)} ${JSON.stringify(v)}`};ze.writeFileSync(Je.join(r,"hooks.json"),JSON.stringify({"saffron-gate":{PreToolUse:[{matcher:"",hooks:[{type:"command",command:s("gate.cjs",lS)}]}]},"saffron-turns":{PostInvocation:[{type:"command",command:s("turns.cjs",dS(e.maxTurns,Je.join(n,"turn-limit")))}]}}));let a=["--output-format","stream-json","--agent","saffron","--print-timeout",`${Math.max(30,2*e.maxTurns)}m`,"--sandbox"];e.model&&a.push("--model",e.model);let i=rS(t,a,{cwd:n,stdio:["pipe","pipe","pipe"]});i.stdin.on("error",()=>{}),i.stdin.end(e.prompt);let c="";i.stderr.on("data",h=>{c=(c+h).slice(-4e3)});let l=new Promise((h,S)=>i.once("error",v=>S(new Error(`Antigravity: could not start ${t}: ${v.message}. ${Fi}`)))),d=new Promise(h=>i.once("close",h)),u="",p,f,g=(async()=>{for await(let h of oS.createInterface({input:i.stdout})){let S;try{S=JSON.parse(h)}catch{continue}let v=S.step_update;v?(v.state==="DONE"&&v.usage&&e.usage.aiCalls++,v.step_type==="agent_response"&&typeof v.text_delta=="string"&&(v.step_index!==p&&([u,p]=["",v.step_index]),u+=v.text_delta,e.lastOutput(u))):S.event==="result"&&(f=S.result)}})();await Promise.race([g,l]);let y=await Promise.race([d,l]);if(f?.usage&&(e.usage.inputTokens+=Math.max(0,(f.usage.input_tokens??0)-(f.usage.cache_read_tokens??0)),e.usage.outputTokens+=f.usage.output_tokens??0,e.usage.cacheReadTokens+=f.usage.cache_read_tokens??0),e.usage.models=[`antigravity/${e.model??"default"}`],f?.response&&e.lastOutput(f.response),!e.finished()&&ze.existsSync(Je.join(n,"turn-limit")))throw new Error(`Antigravity: ${xr(e.maxTurns)}`);if((f?.status!=="SUCCESS"||y!==0)&&!e.finished()){let h=typeof f?.error=="string"?f.error:c.trim().split(`
|
|
418
|
+
`).at(-1)||`agy exited with ${y}`;throw new Error(`Antigravity: ${h}${/auth/i.test(h)?`. ${Fi}`:""}`)}}finally{ze.rmSync(n,{recursive:!0,force:!0})}};import rh from"node:fs";import uS from"node:os";import fS from"node:path";var oh="@cursor/sdk";function to(e=process.versions.node){let[t,n]=e.split(".").map(Number);return t>22||t===22&&n>=13?void 0:`the cursor provider needs Node.js 22.13 or newer (this is ${e})`}var ih=async e=>{let t=to();if(t)throw new Error(t);let{Agent:n,JsonlLocalAgentStore:r}=await eo(oh,"cursor"),s=rh.mkdtempSync(fS.join(uS.tmpdir(),"saffron-cursor-")),o=a=>n.create({model:{id:e.model??"auto"},...a?{systemPrompt:a}:{},tools:["mcp"],mcpServers:Object.fromEntries(Object.entries(e.mcpServers).map(([i,c])=>[i,{type:"http",url:c,headers:{Authorization:`Bearer ${e.mcpToken}`}}])),local:{cwd:s,settingSources:[],store:new r(s)}});try{let a=await sh(await o(e.systemPrompt),e.prompt,e);if(a.status==="error"&&/system.?prompt/i.test(a.error?.message??"")&&(a=await sh(await o(void 0),`${e.systemPrompt}
|
|
418
419
|
|
|
419
420
|
---
|
|
420
421
|
|
|
421
|
-
${e.prompt}`,e)),a.status==="error"&&!e.finished())throw new Error(`Cursor: ${a.error?.message??"the run failed"}${
|
|
422
|
-
`)),{calls:r,order:s,events:o}=
|
|
423
|
-
`)){if(!r.trim())continue;let s;try{s=JSON.parse(r)}catch{continue}if(s.type!=="resource-snapshot"||!s.snapshot)continue;let o=s.snapshot,a=o.request,i=o.response,c=o._monotonicTime;t.push({pageId:
|
|
422
|
+
${e.prompt}`,e)),a.status==="error"&&!e.finished())throw new Error(`Cursor: ${a.error?.message??"the run failed"}${pS(a.error?.message)}`)}finally{rh.rmSync(s,{recursive:!0,force:!0})}};async function sh(e,t,n){try{let r=await e.send(t),s="",o=new Set,a=!1;for await(let c of r.stream())if(c.type==="usage")n.usage.aiCalls++;else if(c.type==="assistant"){for(let l of c.message.content)l.type==="text"&&(s+=l.text);n.lastOutput(s)}else c.type==="tool_call"&&(s="",c.status==="running"&&o.add(c.call_id??`#${o.size}`),o.size>n.maxTurns&&!a&&(a=!0,await r.cancel()));let i=await r.wait();if(i.usage&&(n.usage.inputTokens+=i.usage.inputTokens,n.usage.outputTokens+=i.usage.outputTokens,n.usage.cacheReadTokens+=i.usage.cacheReadTokens,n.usage.cacheCreationTokens+=i.usage.cacheWriteTokens),i.model&&(n.usage.models=[...new Set([...n.usage.models??[],`cursor/${i.model.id}`])]),i.result&&n.lastOutput(i.result),a&&!n.finished())throw new Error(`Cursor: ${xr(n.maxTurns)}`);return i}finally{e.close()}}function pS(e=""){return/api key|unauthenticated|unauthori[sz]ed|logged.?out/i.test(e)?". Sign in once with: npx saffron login cursor":""}async function ah(){let e=to();if(e)throw new Error(e);let{Cursor:t}=await eo(oh,"cursor"),n=await t.auth.status();if(n.status==="logged-in"){console.log(`Cursor: already signed in${n.email?` as ${n.email}`:""}.`);return}await t.auth.login({onLoginUrl:r=>console.log(`Opening ${r}`)}),console.log("Cursor: signed in. Saffron runs will use your Cursor plan.")}var Rl=["claude","codex","antigravity","cursor"];function dh(e){return Rl.includes(e)}var Tl={codex:Zg,antigravity:nh,cursor:ih};function uh(e,t){return e==="claude"?new Ni(t):new Mi(Tl[e],t,()=>{let n=Hi(e);return n.length>0?`${_n[e]} cannot start here: ${n.join("; ")}`:void 0})}var qi=(...e)=>lh.join(gS.homedir(),...e);function ch(e){try{return import.meta.resolve(e),!0}catch{return!1}}function Hi(e){switch(e){case"claude":return[];case"codex":{let t=Di();return t?[t]:ch("@openai/codex-sdk")?[]:["npm install --save-dev @openai/codex-sdk"]}case"antigravity":return Bi()?Ui().length>0?["Saffron's tools allowed in agy, once: npx saffron login antigravity"]:[]:["the Antigravity CLI: curl -fsSL https://antigravity.google/cli/install.sh | bash","then run `agy` once to sign in with your Google AI Pro or Ultra account"];case"cursor":{let t=to();return t?[t]:ch("@cursor/sdk")?[]:["npm install --save-dev @cursor/sdk"]}}}function Al(e){let t=process.env,n=Hi(e);if(e==="claude")t.ANTHROPIC_API_KEY||t.CLAUDE_CODE_OAUTH_TOKEN||t.CLAUDE_CODE_USE_BEDROCK||t.CLAUDE_CODE_USE_VERTEX||zi.existsSync(qi(".claude",".credentials.json"))||zi.existsSync(qi(".claude.json"))||n.push("ANTHROPIC_API_KEY=sk-ant-... (console.anthropic.com \u2192 API keys)","or a Claude Code login on this machine");else if(e==="codex"&&!Di()){let r=lh.join(t.CODEX_HOME??qi(".codex"),"auth.json");!["keyring","auto"].includes($l().cli_auth_credentials_store??"")&&!zi.existsSync(r)&&n.push("a Codex login with your ChatGPT plan: npx @openai/codex login")}else e==="cursor"&&!to()&&!t.CURSOR_API_KEY&&!zi.existsSync(qi(".cursor","sdk","auth.json"))&&n.push("a Cursor sign-in for Saffron (once per machine): npx saffron login cursor");return n}var _n={claude:"Claude",codex:"Codex",antigravity:"Antigravity",cursor:"Cursor"},fh={claude:"@anthropic-ai/claude-agent-sdk",codex:"@openai/codex-sdk",cursor:"@cursor/sdk"};var Qn=(e,t=0)=>typeof e=="number"?e:t,be=e=>typeof e=="string"?e:void 0;function hS(e,t){if(!t)return;let n=be(t.selector);if(n)return mS(n);let r=be(t.url);if(r)return r;if(e==="press"||e==="keyboardPress")return be(t.key)}function mS(e){return e.replace(/internal:role=([a-z]+)\[name="((?:[^"\\]|\\.)*)"[is]?\]/g,(t,n,r)=>`${n} "${r}"`).replace(/internal:role=([a-z]+)/g,"$1").replace(/internal:label="((?:[^"\\]|\\.)*)"[is]?/g,'label "$1"').replace(/internal:text="((?:[^"\\]|\\.)*)"[is]?/g,'text "$1"').replace(/internal:attr=\[placeholder="((?:[^"\\]|\\.)*)"[is]?\]/g,'placeholder "$1"').replace(/internal:testid=\[data-testid="((?:[^"\\]|\\.)*)"s?\]/g,'test id "$1"').replace(/internal:has-text="((?:[^"\\]|\\.)*)"[is]?/g,'with text "$1"').replace(/ >> nth=0$/,"").replace(/ >> /g," \u203A ").replace(/nth=(\d+)/g,"#$1")}function wS(e){let t=new Map,n=[],r=[];for(let s of e){if(!s.trim())continue;let o;try{o=JSON.parse(s)}catch{continue}r.push(o);let a=be(o.callId);switch(o.type){case"before":{if(!a)break;let i=be(o.method)??"",c=o.class==="Tracing"&&i==="tracingGroup",l=i==="__waitInfo__";t.set(a,{callId:a,method:l?be(o.title)??"wait":i,subject:hS(i,o.params),selector:be(o.params?.selector),startTime:Qn(o.startTime),log:[],pageId:be(o.pageId),before:El(o,"beforeSnapshot"),calls:[],parentId:be(o.parentId),isGroup:c,title:be(o.title),isWait:l}),n.push(a);break}case"input":{let i=a?t.get(a):void 0;if(i){i.input=El({...o,pageId:i.pageId},"inputSnapshot");let c=o.point,l=o.box,d=c??(l?{x:l.x+l.width/2,y:l.y+l.height/2}:void 0);i.input&&d?i.input.point=d:d&&(i.inputPoint=d)}break}case"frame-snapshot":{let i=o.snapshot,c=i?.callId?t.get(i.callId):void 0;if(c&&i?.phase&&i.pageId&&i.isMainFrame!==!1){let l=i.phase,d={pageId:i.pageId,name:`${l}@${i.callId}`,callId:i.callId,phase:l};if(c.pageId||(c.pageId=i.pageId),l==="before"&&!c.before)c.before=d;else if(l==="after")c.after=d;else if(l==="action"&&!c.input){let u=c.inputPoint;c.input=u?{...d,point:u}:d}}break}case"log":{let i=a?t.get(a):void 0,c=be(o.message);i&&c&&i.log.push(c);break}case"after":{let i=a?t.get(a):void 0;if(!i)break;i.endTime=Qn(o.endTime,i.startTime);let c=o.error;c?.message&&(i.error=c.message);let l=El({...o,pageId:i.pageId},"afterSnapshot");l&&(i.after=l);break}default:break}}return{calls:t,order:n,events:r}}function El(e,t){let n=be(e[t]),r=be(e.pageId);return n&&r?{pageId:r,name:n}:void 0}function ph(e){return Ol(Rf(e))}function Ol(e){let n=e.filter(x=>x.name.endsWith(".trace")).flatMap(x=>x.data.toString("utf8").split(`
|
|
423
|
+
`)),{calls:r,order:s,events:o}=wS(n),a=new Map;for(let x of o){let b=x.snapshot;if(x.type!=="frame-snapshot"||!b?.isMainFrame||!b.pageId||!b.frameUrl)continue;let m=b.snapshotName??(b.callId&&b.phase?`${b.phase}@${b.callId}`:void 0);m&&a.set(`${b.pageId}/${m}`,b.frameUrl)}for(let x of r.values())for(let b of[x.before,x.input,x.after])b&&(b.url=a.get(`${b.pageId}/${b.name}`));let i=[];for(let x of s){let b=r.get(x),m=b.parentId?r.get(b.parentId):void 0;m?m.calls.push(b):i.push(x)}let c=x=>{let{parentId:b,isGroup:m,title:$,isWait:T,...R}=x;return{...R,calls:R.calls.map(k=>c(k))}},l=x=>x.find(b=>b.error&&!b.isWait)?.error,d=[],u=[];for(let x of i){let b=r.get(x);if(!b.isGroup){u.push(c(b));continue}let m={title:b.title??"",startTime:b.startTime,endTime:b.endTime,error:b.error,actions:[],calls:[]},$=/^\[saffron:(agent|replay|pending):(-?\d+)\] (.*)$/.exec(m.title);$&&(m.phase=$[1],m.stepIndex=Number($[2]),m.title=$[3]);let T=[];for(let R of b.calls)if(R.isGroup){let k={title:R.title??"",startTime:R.startTime,endTime:R.endTime,error:R.error??l(R.calls),calls:R.calls.map(P=>c(P))},C=/^\[saffron:action:(\d+)\] ([\s\S]*)$/.exec(k.title);C&&(k.actionIndex=Number(C[1]),k.title=C[2]),m.actions.push(k)}else T.push(R),m.calls.push(c(R));m.error||(m.error=m.actions.find(R=>R.error)?.error??l(T)),d.push(m)}let p=[],f=new Map,g,y,h,S=Number.POSITIVE_INFINITY,v=0;for(let x of o)if(x.type==="context-options")g=be(x.title),y=be(x.browserName),h=Number(x.version)||void 0,S=Math.min(S,Qn(x.monotonicTime,S));else if(x.type==="screencast-frame"){let b=be(x.file)??(be(x.sha1)?`resources/${be(x.sha1)}`:""),m={pageId:be(x.pageId)??"",file:b,sha1:b.slice(b.lastIndexOf("/")+1),timestamp:Qn(x.timestamp),width:Qn(x.width),height:Qn(x.height)};p.push(m),f.has(m.pageId)||f.set(m.pageId,{pageId:m.pageId})}else if(x.type==="event"&&x.class==="BrowserContext"&&x.method==="page"){let b=be(x.params?.pageId);b&&f.set(b,{...f.get(b),pageId:b,openedAt:Qn(x.time)})}else if(x.type==="event"&&x.class==="BrowserContext"&&x.method==="pageClosed"){let b=be(x.params?.pageId);b&&f.set(b,{...f.get(b),pageId:b,closedAt:Qn(x.time)})}else if(x.type==="frame-snapshot"){let b=x.snapshot;if(b?.pageId){let m=f.get(b.pageId)??{pageId:b.pageId};b.isMainFrame&&b.frameUrl&&(m.url=b.frameUrl),f.set(b.pageId,m)}}for(let x of r.values())S=Math.min(S,x.startTime),v=Math.max(v,x.endTime??x.startTime);for(let x of p)v=Math.max(v,x.timestamp);return Number.isFinite(S)||(S=0),{format:h,title:g,browserName:y,startTime:S,endTime:v,steps:d,calls:u,frames:p,requests:yS(e),pages:[...f.values()],resources:e.filter(x=>x.name.startsWith("resources/")).map(x=>x.name.slice(10))}}function yS(e){let t=[];for(let n of e.filter(r=>r.name.endsWith(".network")))for(let r of n.data.toString("utf8").split(`
|
|
424
|
+
`)){if(!r.trim())continue;let s;try{s=JSON.parse(r)}catch{continue}if(s.type!=="resource-snapshot"||!s.snapshot)continue;let o=s.snapshot,a=o.request,i=o.response,c=o._monotonicTime;t.push({pageId:be(o.pageref),method:be(a?.method)??"GET",url:be(a?.url)??"",status:Number.isFinite(i?.status)?i?.status:void 0,mimeType:be(i?.content?.mimeType),startedAt:Date.parse(be(o.startedDateTime)??"")||0,time:typeof o.time=="number"?o.time:void 0,timestamp:typeof c=="number"?c:void 0})}return t}import as from"node:fs";import{createHash as bS,randomBytes as $h}from"node:crypto";import gh from"node:fs";import Cn from"node:path";var hh="This run has no reviewable proposal identity. Run the scenario again to review from replay.",_l="The proposal does not belong to this replay.",mh=e=>e instanceof Error?e.message:String(e),wh=(e,t)=>`No pending proposal at ${Cn.relative(e,t)}: it has been accepted, rejected or removed since this run.`;function yh(e,t){let n=/ \(example \d+\)$/.exec(t.scenario),r=n?[t.scenario,t.scenario.slice(0,n.index)]:[t.scenario],s=t.proposalFile,o=i=>i.split(/[\\/]/).slice(-2).join("/"),a=Cn.win32.isAbsolute(s)?i=>o(i)===o(s):i=>Cn.resolve(i)===Cn.resolve(e,s);return r.map(i=>dt(e,t.feature,i)).find(a)}function bh(e,t,n){if(jt(n)!==t.proposalRevision)return{available:!1,reason:"The proposal changed since this run. Open the latest run before reviewing it."};let r=i=>({available:!1,reason:i,rejectable:!0}),s;try{s=zr(n)}catch(i){if(i instanceof ke)return r(`The proposal cannot be read: ${Cn.relative(e,n)}: ${i.problem}`);throw i}let{feature:o,scenario:a}=s.cache;if(Cn.resolve(dt(e,o,a))!==Cn.resolve(n)||o!==t.feature||!(t.scenario===a||t.scenario===s.meta.recordedFor||t.scenario.startsWith(a+" (example ")))return{available:!1,reason:_l};try{if(!gh.existsSync(Cn.resolve(e,o)))return r(`STALE: ${o} no longer exists`);let i=mt(e,_e(e),[Cn.resolve(e,o)]),c=At(e,s,i);if(c)return r(`STALE: ${c}`);let l=t.status==="red",d=s.meta.verified===!0&&!l,u=l?t.error??"This run replayed the proposal and it failed.":s.meta.proofError;return{available:!0,verified:d,...!d&&u?{proofError:u}:{},unbound:!s.meta.bound,diff:Hn(Ye(pe(e,o,a)),s.cache),featureEdits:s.meta.featureEdits??[]}}catch(i){return r(mh(i))}}function xh(e,t){if(!t.proposalFile||!t.proposalRevision)return{available:!1,reason:hh};try{let n=yh(e,{...t,proposalFile:t.proposalFile});return n?gh.existsSync(n)?bh(e,t,n):{available:!1,reason:wh(e,n)}:{available:!1,reason:_l}}catch(n){return{available:!1,reason:mh(n)}}}function vh(e,t,n,r=!1){if(!t.proposalFile||!t.proposalRevision)throw new Error(hh);let s=yh(e,{...t,proposalFile:t.proposalFile});if(!s)throw new Error(_l);Fo(s,()=>{let o=bh(e,t,s);if(n==="reject"){if(!o.available&&!o.rejectable)throw new Error(o.reason);Uo(s)}else{if(!o.available)throw new Error(o.reason);if(!o.verified&&!r)throw new Error("Confirm that you want to accept a proposal without successful proof replay.");Bo(e,s)}},()=>{throw new Error(wh(e,s))})}import xS from"node:http";import Sr from"node:path";function Sh(){return`<!DOCTYPE html>
|
|
424
425
|
<html lang="en">
|
|
425
426
|
<head>
|
|
426
427
|
<meta charset="utf-8">
|
|
@@ -507,7 +508,7 @@ ${e.prompt}`,e)),a.status==="error"&&!e.finished())throw new Error(`Cursor: ${a.
|
|
|
507
508
|
</head>
|
|
508
509
|
<body>
|
|
509
510
|
<header>
|
|
510
|
-
${
|
|
511
|
+
${pr(26)}
|
|
511
512
|
<div><div class="name" id="title">Saffron replay</div><div class="sub" id="subtitle"></div></div>
|
|
512
513
|
<span class="status" id="status"></span>
|
|
513
514
|
<label id="scenarioPicker" hidden>Scenario <select id="scenarioSelect" aria-label="Scenario"></select></label>
|
|
@@ -1142,9 +1143,10 @@ ${e.prompt}`,e)),a.status==="error"&&!e.finished())throw new Error(`Cursor: ${a.
|
|
|
1142
1143
|
})();
|
|
1143
1144
|
</script>
|
|
1144
1145
|
</body>
|
|
1145
|
-
</html>`}var gr=class extends Error{},Dg="This trace is gone, or a later run replaced it (one that stopped before writing its report). Run the scenario again to replay it.",$x=4;function sl(e,t){let n=hr.join(e,t.file);try{Yr.accessSync(n,Yr.constants.R_OK)}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return;throw s}if(!_t(hr.join(e,".saffron","artifacts"),n))throw new Error(`${t.file} is not a file under .saffron/artifacts`);let r=Yr.readFileSync(n);return t.sha256&&zt(r)!==t.sha256?void 0:r}function kx(){let e=hi.resolve("playwright-core/package.json");return hr.join(hr.dirname(e),"lib","vite","traceViewer")}var vn={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpeg":"image/jpeg",".jpg":"image/jpeg",".ttf":"font/ttf",".webmanifest":"application/manifest+json",".zip":"application/zip"},Rx=new Set([".png",".jpeg",".jpg"]),rl={"Content-Security-Policy":"sandbox","X-Content-Type-Options":"nosniff"};function Tx(e){let t=/<script>([\s\S]*?)<\/script>/.exec(e)[1];return["default-src 'self'",`script-src 'sha256-${xx("sha256").update(t).digest("base64")}'`,"style-src 'self' 'unsafe-inline'","worker-src 'self'","connect-src 'self'","frame-src 'self'","object-src 'none'","base-uri 'none'","form-action 'none'","frame-ancestors 'none'"].join("; ")}async function Fg(e){let t=e.entries?[...e.entries]:[{scenario:e.scenario,traces:[{file:e.traceFile,data:e.traceData,label:e.label??"Execution",proof:e.proof,steps:e.scenario.steps,uniques:e.scenario.uniques},...(e.additionalTraces??[]).map(y=>({...y,proof:y.proof??!0}))]}],n=e.start??0;if(!t[n])throw new Error("No scenario to replay");let r=y=>{let w=ds(y),v=tl(w.map(x=>({name:x.name,get data(){return x.read()}})));return{zip:y,model:v,resources:new Map(w.filter(x=>x.name.includes("/")).map(x=>[x.name,x.read]))}},s=y=>{try{return y.data?y.data:!y.read&&!Yr.existsSync(y.file)?new gr(Dg):(y.read?y.read():Yr.readFileSync(y.file))??new gr(Dg)}catch(w){return w instanceof gr?w:new gr(`This trace cannot be read: ${w instanceof Error?w.message:String(w)}`)}},o=[];{let y=t[n],w=y.traces.map(s),v=y.traces.map((x,$)=>({t:x,data:w[$]})).filter(({data:x},$)=>$===0||Buffer.isBuffer(x));for(let[x,$]of y.traces.entries()){let E=w[x];x>0&&!Buffer.isBuffer(E)&&o.push({file:$.file,reason:E.message})}t[n]={...y,traces:v.map(({t:x,data:$})=>({...x,data:Buffer.isBuffer($)?$:void 0,read:Buffer.isBuffer($)?void 0:()=>{throw $}}))}}let a=new Map,i=(y,w)=>{let v=`${y}:${w}`,x=a.get(v);if(x)a.delete(v);else{let $=s(t[y].traces[w]);if(!Buffer.isBuffer($))throw $;x=r($);let E=[...a.keys()].filter(R=>{let[k,C]=R.split(":").map(Number),P=t[k].traces[C];return k!==n&&(P.data!==void 0||P.checked===!0)});y!==n&&E.length>=$x&&a.delete(E[0])}return a.set(v,x),x},c=new Map,l=(y,w)=>{let v=t[y].scenario.screenshots?.find(E=>E.file===w);if(!v)return;let x=`${y}:${w}`;if(c.has(x))return c.get(x);let $=Pn(e.projectRoot,v);return(y===n||!v.sha256)&&c.set(x,$),$};try{i(n,0)}catch(y){if(t.length===1)throw y}for(let y of t[n].scenario.screenshots??[])l(n,y.file);let d=kx(),f=jg(),p={"Content-Security-Policy":Tx(f)},u=Mg(32).toString("hex"),h=Mg(8).toString("hex"),b=t.map(y=>({feature:y.scenario.feature,scenario:y.scenario.scenario,status:y.scenario.status,browser:y.scenario.browser})),g=Sx.createServer((y,w)=>{let v=(x,$,E,R={})=>{w.writeHead(x,{"Content-Type":E,"Cache-Control":"no-store",...R}),w.end($)};try{let x=y.headers.host??"";if(!/^(?:127\.0\.0\.1|localhost)(?::\d+)?$/i.test(x))return v(403,"Invalid host","text/plain");let $=new URL(y.url??"/",`http://${x}`),E=Number($.searchParams.get("scenario")??n),R=Number.isInteger(E)?t[E]:void 0,k=Number($.searchParams.get("session")??"0"),C=R&&Number.isInteger(k)?R.traces[k]:void 0,P=()=>v(404,R?"No such trace session":"No such scenario","text/plain");if($.pathname.startsWith("/api/review/")&&!e.viewOnly){if(y.method!=="POST")return v(405,"Use POST","text/plain");if(y.headers.origin!==`http://${x}`||y.headers["x-saffron-review"]!==u)return v(403,"Review must come from this replay page","text/plain");if(!R||!C)return P();let m=$.pathname.slice(12);if(m!=="accept"&&m!=="reject")return v(404,"Unknown decision","text/plain");try{return Ng(e.projectRoot,R.scenario,m,y.headers["x-saffron-unverified"]==="yes"),v(200,JSON.stringify({decision:m}),vn[".json"])}catch(A){return v(409,JSON.stringify({error:A instanceof Error?A.message:String(A)}),vn[".json"])}}if(y.method!=="GET"&&y.method!=="HEAD")return v(405,"Use GET","text/plain");if($.pathname==="/"||$.pathname==="/index.html")return v(200,f,vn[".html"],p);if($.pathname==="/api/replay"){let m=R?E:n,A=C?k:0,O=t[m],T=O.traces[A],_={scenarios:b,scenarioIndex:m,sessions:O.traces.map(I=>I.label),session:A,proof:T.proof===!0,instance:h},N;try{N=i(m,A).model}catch(I){let L=I instanceof gr?I.message:`This trace cannot be read: ${I instanceof Error?I.message:String(I)}`;return v(200,JSON.stringify({..._,scenario:O.scenario,unavailable:L}),vn[".json"])}let F=e.viewOnly?{review:{available:!1,reason:e.viewOnly}}:{review:Ig(e.projectRoot,O.scenario),reviewToken:u};return v(200,JSON.stringify({..._,scenario:{...O.scenario,steps:T.steps,uniques:T.uniques,traceSession:T.browserSession},trace:N,...F}),vn[".json"])}if($.pathname.startsWith("/artifact/")){let m=$.searchParams.get("v");if(m!==null&&m!==h)return v(410,"This replay was restarted. Reload the page.","text/plain");if(!R||!C)return P();if($.pathname==="/artifact/trace.zip")return v(200,i(E,k).zip,vn[".zip"],rl);if($.pathname.startsWith("/artifact/resource/")){let A=decodeURIComponent($.pathname.slice(19)),O=i(E,k).resources,T=(O.get(A)??(A.includes("/")?void 0:O.get(`resources/${A}`)))?.();if(!T)return v(404,"no such resource","text/plain");let _=hr.extname($.pathname).toLowerCase();return v(200,T,Rx.has(_)?vn[_]:"application/octet-stream",rl)}if($.pathname.startsWith("/artifact/screenshot/")){let A=l(E,decodeURIComponent($.pathname.slice(21)));return A?v(200,A,vn[".jpg"],rl):v(404,"no such file","text/plain")}}if($.pathname==="/trace/ping")return v(200,"ok","text/plain");if($.pathname.startsWith("/trace/")){let m=$.pathname.slice(7)||"index.html",A=hr.join(d,m);if(!_t(d,A))return v(404,"not found","text/plain");let O=hr.extname(A).toLowerCase(),T=Yr.readFileSync(A);return w.writeHead(200,{"Content-Type":vn[O]??"application/octet-stream","Service-Worker-Allowed":"/trace/"}),w.end(T)}v(404,"not found","text/plain")}catch{w.headersSent?w.destroy():v(400,"Invalid request","text/plain")}});return await new Promise((y,w)=>{g.once("error",w),g.listen(e.port??0,"127.0.0.1",()=>y())}),{url:`http://127.0.0.1:${g.address().port}/`,skipped:o,close:()=>new Promise(y=>g.close(()=>y()))}}import Lg from"node:fs";import Ai from"node:path";function Ei(e){return JSON.stringify([e.role??null,e.name??null,e.nameRegex??null,e.label??null,e.text??null,e.testId??null,e.placeholder??null,e.frame??null,e.role||e.name||e.nameRegex||e.label||e.text||e.testId||e.placeholder?null:e.fallbackSelectors??[]])}function Bg(e,t){let n=new Map,r=new Set,s=new Map,o=Math.min(e.steps.length,t.steps.length);for(let i=0;i<o;i++){if(e.steps[i].kind==="assertion"||t.steps[i].kind==="assertion"||e.steps[i].gherkin!==t.steps[i].gherkin)continue;let c=e.steps[i].actions,l=t.steps[i].actions;if(c.length===l.length)for(let d=0;d<c.length;d++){let f=c[d],p=l[d];if(f.action!==p.action||Se.has(f.action)||!f.target||!p.target)continue;let u=Ei(f.target),h=JSON.stringify(p.target);s.has(u)&&s.get(u)!==h&&r.add(u),s.set(u,h),u!==Ei(p.target)&&n.set(u,{from:f.target,to:p.target})}}let a=[...n.entries()];return{changes:a.filter(([i])=>!r.has(i)).map(([,i])=>i),ambiguous:a.filter(([i])=>r.has(i)).map(([,i])=>i.from)}}function Ax(e){let t=Ai.join(e,".saffron","cache");if(!Lg.existsSync(t))return[];let n=[];for(let r of Lg.readdirSync(t,{recursive:!0})){let s=String(r);s.endsWith(".json")&&n.push(Ai.join(t,s))}return n}function Ug(e,t,n,r){if(t.length===0)return[];let s=new Map,o=new Set,a=c=>new Set(JSON.stringify(c).match(/<[^<>"]+>/g)??[]);for(let c of t){let l=a(c.from);if([...a(c.to)].some(p=>!l.has(p)))continue;let d=Ei(c.from),f=s.get(d);f&&JSON.stringify(f.to)!==JSON.stringify(c.to)&&o.add(d),s.set(d,c)}for(let c of o)s.delete(c);let i=[];for(let c of Ax(e)){if(Ai.resolve(c)===Ai.resolve(n))continue;let l=Jt(c);if(!l)continue;let d=[],f=!1;for(let p of l.steps){if(p.kind==="assertion")continue;let u=0;for(let h of p.actions){if(!h.target||Se.has(h.action))continue;let b=s.get(Ei(h.target));b&&(u++,r||(h.target=structuredClone(b.to),f=!0))}u>0&&d.push({gherkin:p.gherkin,count:u})}d.length>0&&(f&&Ar(c,l),i.push({file:c,scenario:l.scenario,feature:l.feature,steps:d}))}return i}function _i(e){return e.role?`${e.role} "${e.name??e.nameRegex??""}"`:e.label?`label "${e.label}"`:e.text?`text "${e.text}"`:e.testId?`testId "${e.testId}"`:(e.fallbackSelectors??[]).join(",")||"(empty target)"}import zg from"node:fs";import Oi from"node:path";function Hg(e,t,n,r,s){let o=ft(Oi.join(e,t),e,s).find(c=>c.name===n);if(!o)return`scenario "${n}" is no longer in ${t}`;let a=o.steps.map(c=>c.text);if(a.length!==r.length)return`the scenario has ${a.length} steps now and had ${r.length} when this was recorded`;let i=a.findIndex((c,l)=>c!==r[l]);return i<0?void 0:`step ${i+1} now reads "${a[i]}" and was recorded as "${r[i]}"`}function qg(e,t,n,r,s,o){let a={applied:[],skipped:[],appliedIndices:[]},i=r.filter(u=>u.text.trim()!==""?!0:(a.skipped.push({index:u.index,reason:"the edit has no step text"}),!1)),c=ft(Oi.join(e,t),e,s).find(u=>u.name===n);if(!c){for(let u of i)a.skipped.push({index:u.index,reason:`scenario "${n}" not found in ${t}`});return a}let l=new Map;for(let u of i){let h=c.steps[u.index]?.source;if(!h||h.fromBackground)continue;let b=`${h.file}:${h.line}`;l.set(b,(l.get(b)??new Set).add(u.text))}let d=tt(c),f=new Map,p=new Set;for(let u of i){let h=c.steps[u.index];if(!h?.source){a.skipped.push({index:u.index,reason:`no step at index ${u.index}`});continue}let b=[...Ji([u.text,...es([u.text])])].filter(P=>!d.has(P));if(b.length>0){a.skipped.push({index:u.index,reason:`it would make the scenario name ${b.map(P=>`{env:${P}}`).join(", ")}, which it does not reference now; a recording can only use the environment variables its scenario names, so edit the feature file by hand if you mean it`});continue}if(Lt(u.text)!==Lt(h.text)){a.skipped.push({index:u.index,reason:'it would change which browser session the step runs in (its As "..."); edit the feature file by hand if you mean it'});continue}if(o&&o[u.index]!==h.text){a.skipped.push({index:u.index,reason:`step ${u.index+1} now reads "${h.text}", not the "${o[u.index]??"(nothing)"}" this edit was written for`});continue}let{file:g,line:S,fromStepSet:y,fromBackground:w}=h.source;if(w){a.skipped.push({index:u.index,reason:`"${h.text}" is a Background step shared across scenarios; edit it manually`});continue}let v=`${g}:${S}`,x=l.get(v);if(x.size>1){a.skipped.push({index:u.index,reason:`${v}${y?` (StepSet "${y}")`:""} is reached by several steps and the edits disagree: ${[...x].map(P=>`"${P}"`).join(" vs ")}. Decide the wording in the definition by hand`});continue}let $=c.steps.findIndex((P,m)=>P.source?.file===g&&P.source.line===S&&P.text!==u.text&&!i.some(A=>A.index===m&&A.text===u.text));if($>=0){a.skipped.push({index:u.index,reason:`${v} is also used at step ${$+1}, which has no agreeing edit; edit the shared definition by hand`});continue}if(p.has(v)){a.appliedIndices.push(u.index);continue}let E=f.get(g);E||(E=zg.readFileSync(Oi.join(e,g),"utf8").split(`
|
|
1146
|
-
`),
|
|
1147
|
-
|
|
1146
|
+
</html>`}var vr=class extends Error{},kh="This trace is gone, or a later run replaced it (one that stopped before writing its report). Run the scenario again to replay it.",vS=4;function Pl(e,t){let n=Sr.join(e,t.file);try{as.accessSync(n,as.constants.R_OK)}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return;throw s}if(!It(Sr.join(e,".saffron","artifacts"),n))throw new Error(`${t.file} is not a file under .saffron/artifacts`);let r=as.readFileSync(n);return t.sha256&&Kt(r)!==t.sha256?void 0:r}function SS(){let e=Ii.resolve("playwright-core/package.json");return Sr.join(Sr.dirname(e),"lib","vite","traceViewer")}var Pn={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpeg":"image/jpeg",".jpg":"image/jpeg",".ttf":"font/ttf",".webmanifest":"application/manifest+json",".zip":"application/zip"},$S=new Set([".png",".jpeg",".jpg"]),Cl={"Content-Security-Policy":"sandbox","X-Content-Type-Options":"nosniff"};function kS(e){let t=/<script>([\s\S]*?)<\/script>/.exec(e)[1];return["default-src 'self'",`script-src 'sha256-${bS("sha256").update(t).digest("base64")}'`,"style-src 'self' 'unsafe-inline'","worker-src 'self'","connect-src 'self'","frame-src 'self'","object-src 'none'","base-uri 'none'","form-action 'none'","frame-ancestors 'none'"].join("; ")}async function Rh(e){let t=e.entries?[...e.entries]:[{scenario:e.scenario,traces:[{file:e.traceFile,data:e.traceData,label:e.label??"Execution",proof:e.proof,steps:e.scenario.steps,uniques:e.scenario.uniques},...(e.additionalTraces??[]).map(v=>({...v,proof:v.proof??!0}))]}],n=e.start??0;if(!t[n])throw new Error("No scenario to replay");let r=v=>{let x=Es(v),b=Ol(x.map(m=>({name:m.name,get data(){return m.read()}})));return{zip:v,model:b,resources:new Map(x.filter(m=>m.name.includes("/")).map(m=>[m.name,m.read]))}},s=v=>{try{return v.data?v.data:!v.read&&!as.existsSync(v.file)?new vr(kh):(v.read?v.read():as.readFileSync(v.file))??new vr(kh)}catch(x){return x instanceof vr?x:new vr(`This trace cannot be read: ${x instanceof Error?x.message:String(x)}`)}},o=[];{let v=t[n],x=v.traces.map(s),b=v.traces.map((m,$)=>({t:m,data:x[$]})).filter(({data:m},$)=>$===0||Buffer.isBuffer(m));for(let[m,$]of v.traces.entries()){let T=x[m];m>0&&!Buffer.isBuffer(T)&&o.push({file:$.file,reason:T.message})}t[n]={...v,traces:b.map(({t:m,data:$})=>({...m,data:Buffer.isBuffer($)?$:void 0,read:Buffer.isBuffer($)?void 0:()=>{throw $}}))}}let a=new Map,i=(v,x)=>{let b=`${v}:${x}`,m=a.get(b);if(m)a.delete(b);else{let $=s(t[v].traces[x]);if(!Buffer.isBuffer($))throw $;m=r($);let T=[...a.keys()].filter(R=>{let[k,C]=R.split(":").map(Number),P=t[k].traces[C];return k!==n&&(P.data!==void 0||P.checked===!0)});v!==n&&T.length>=vS&&a.delete(T[0])}return a.set(b,m),m},c=new Map,l=(v,x)=>{let b=t[v].scenario.screenshots?.find(T=>T.file===x);if(!b)return;let m=`${v}:${x}`;if(c.has(m))return c.get(m);let $=qn(e.projectRoot,b);return(v===n||!b.sha256)&&c.set(m,$),$};try{i(n,0)}catch(v){if(t.length===1)throw v}for(let v of t[n].scenario.screenshots??[])l(n,v.file);let d=SS(),u=Sh(),p={"Content-Security-Policy":kS(u)},f=$h(32).toString("hex"),g=$h(8).toString("hex"),y=t.map(v=>({feature:v.scenario.feature,scenario:v.scenario.scenario,status:v.scenario.status,browser:v.scenario.browser})),h=xS.createServer((v,x)=>{let b=(m,$,T,R={})=>{x.writeHead(m,{"Content-Type":T,"Cache-Control":"no-store",...R}),x.end($)};try{let m=v.headers.host??"";if(!/^(?:127\.0\.0\.1|localhost)(?::\d+)?$/i.test(m))return b(403,"Invalid host","text/plain");let $=new URL(v.url??"/",`http://${m}`),T=Number($.searchParams.get("scenario")??n),R=Number.isInteger(T)?t[T]:void 0,k=Number($.searchParams.get("session")??"0"),C=R&&Number.isInteger(k)?R.traces[k]:void 0,P=()=>b(404,R?"No such trace session":"No such scenario","text/plain");if($.pathname.startsWith("/api/review/")&&!e.viewOnly){if(v.method!=="POST")return b(405,"Use POST","text/plain");if(v.headers.origin!==`http://${m}`||v.headers["x-saffron-review"]!==f)return b(403,"Review must come from this replay page","text/plain");if(!R||!C)return P();let w=$.pathname.slice(12);if(w!=="accept"&&w!=="reject")return b(404,"Unknown decision","text/plain");try{return vh(e.projectRoot,R.scenario,w,v.headers["x-saffron-unverified"]==="yes"),b(200,JSON.stringify({decision:w}),Pn[".json"])}catch(E){return b(409,JSON.stringify({error:E instanceof Error?E.message:String(E)}),Pn[".json"])}}if(v.method!=="GET"&&v.method!=="HEAD")return b(405,"Use GET","text/plain");if($.pathname==="/"||$.pathname==="/index.html")return b(200,u,Pn[".html"],p);if($.pathname==="/api/replay"){let w=R?T:n,E=C?k:0,_=t[w],A=_.traces[E],O={scenarios:y,scenarioIndex:w,sessions:_.traces.map(I=>I.label),session:E,proof:A.proof===!0,instance:g},j;try{j=i(w,E).model}catch(I){let U=I instanceof vr?I.message:`This trace cannot be read: ${I instanceof Error?I.message:String(I)}`;return b(200,JSON.stringify({...O,scenario:_.scenario,unavailable:U}),Pn[".json"])}let L=e.viewOnly?{review:{available:!1,reason:e.viewOnly}}:{review:xh(e.projectRoot,_.scenario),reviewToken:f};return b(200,JSON.stringify({...O,scenario:{..._.scenario,steps:A.steps,uniques:A.uniques,traceSession:A.browserSession},trace:j,...L}),Pn[".json"])}if($.pathname.startsWith("/artifact/")){let w=$.searchParams.get("v");if(w!==null&&w!==g)return b(410,"This replay was restarted. Reload the page.","text/plain");if(!R||!C)return P();if($.pathname==="/artifact/trace.zip")return b(200,i(T,k).zip,Pn[".zip"],Cl);if($.pathname.startsWith("/artifact/resource/")){let E=decodeURIComponent($.pathname.slice(19)),_=i(T,k).resources,A=(_.get(E)??(E.includes("/")?void 0:_.get(`resources/${E}`)))?.();if(!A)return b(404,"no such resource","text/plain");let O=Sr.extname($.pathname).toLowerCase();return b(200,A,$S.has(O)?Pn[O]:"application/octet-stream",Cl)}if($.pathname.startsWith("/artifact/screenshot/")){let E=l(T,decodeURIComponent($.pathname.slice(21)));return E?b(200,E,Pn[".jpg"],Cl):b(404,"no such file","text/plain")}}if($.pathname==="/trace/ping")return b(200,"ok","text/plain");if($.pathname.startsWith("/trace/")){let w=$.pathname.slice(7)||"index.html",E=Sr.join(d,w);if(!It(d,E))return b(404,"not found","text/plain");let _=Sr.extname(E).toLowerCase(),A=as.readFileSync(E);return x.writeHead(200,{"Content-Type":Pn[_]??"application/octet-stream","Service-Worker-Allowed":"/trace/"}),x.end(A)}b(404,"not found","text/plain")}catch{x.headersSent?x.destroy():b(400,"Invalid request","text/plain")}});return await new Promise((v,x)=>{h.once("error",x),h.listen(e.port??0,"127.0.0.1",()=>v())}),{url:`http://127.0.0.1:${h.address().port}/`,skipped:o,close:()=>new Promise(v=>h.close(()=>v()))}}import Th from"node:fs";import Ji from"node:path";function Vi(e){return JSON.stringify([e.role??null,e.name??null,e.nameRegex??null,e.label??null,e.text??null,e.testId??null,e.placeholder??null,e.frame??null,e.role||e.name||e.nameRegex||e.label||e.text||e.testId||e.placeholder?null:e.fallbackSelectors??[]])}function Ah(e,t){let n=new Map,r=new Set,s=new Map,o=Math.min(e.steps.length,t.steps.length);for(let i=0;i<o;i++){if(e.steps[i].kind==="assertion"||t.steps[i].kind==="assertion"||e.steps[i].gherkin!==t.steps[i].gherkin)continue;let c=e.steps[i].actions,l=t.steps[i].actions;if(c.length===l.length)for(let d=0;d<c.length;d++){let u=c[d],p=l[d];if(u.action!==p.action||$e.has(u.action)||!u.target||!p.target)continue;let f=Vi(u.target),g=JSON.stringify(p.target);s.has(f)&&s.get(f)!==g&&r.add(f),s.set(f,g),f!==Vi(p.target)&&n.set(f,{from:u.target,to:p.target})}}let a=[...n.entries()];return{changes:a.filter(([i])=>!r.has(i)).map(([,i])=>i),ambiguous:a.filter(([i])=>r.has(i)).map(([,i])=>i.from)}}function RS(e){let t=Ji.join(e,".saffron","cache");if(!Th.existsSync(t))return[];let n=[];for(let r of Th.readdirSync(t,{recursive:!0})){let s=String(r);s.endsWith(".json")&&n.push(Ji.join(t,s))}return n}function Eh(e,t,n,r){if(t.length===0)return[];let s=new Map,o=new Set,a=c=>new Set(JSON.stringify(c).match(/<[^<>"]+>/g)??[]);for(let c of t){let l=a(c.from);if([...a(c.to)].some(p=>!l.has(p)))continue;let d=Vi(c.from),u=s.get(d);u&&JSON.stringify(u.to)!==JSON.stringify(c.to)&&o.add(d),s.set(d,c)}for(let c of o)s.delete(c);let i=[];for(let c of RS(e)){if(Ji.resolve(c)===Ji.resolve(n))continue;let l=tn(c);if(!l)continue;let d=[],u=!1;for(let p of l.steps){if(p.kind==="assertion")continue;let f=0;for(let g of p.actions){if(!g.target||$e.has(g.action))continue;let y=s.get(Vi(g.target));y&&(f++,r||(g.target=structuredClone(y.to),u=!0))}f>0&&d.push({gherkin:p.gherkin,count:f})}d.length>0&&(u&&Dr(c,l),i.push({file:c,scenario:l.scenario,feature:l.feature,steps:d}))}return i}function Wi(e){return e.role?`${e.role} "${e.name??e.nameRegex??""}"`:e.label?`label "${e.label}"`:e.text?`text "${e.text}"`:e.testId?`testId "${e.testId}"`:(e.fallbackSelectors??[]).join(",")||"(empty target)"}import Oh from"node:fs";import Gi from"node:path";function _h(e,t,n,r,s){let o=nt(Gi.join(e,t),e,s).find(c=>c.name===n);if(!o)return`scenario "${n}" is no longer in ${t}`;let a=o.steps.map(c=>c.text);if(a.length!==r.length)return`the scenario has ${a.length} steps now and had ${r.length} when this was recorded`;let i=a.findIndex((c,l)=>c!==r[l]);return i<0?void 0:`step ${i+1} now reads "${a[i]}" and was recorded as "${r[i]}"`}function Ch(e,t,n,r,s,o){let a={applied:[],skipped:[],appliedIndices:[]},i=r.filter(g=>g.text.trim()!==""?!0:(a.skipped.push({index:g.index,reason:"the edit has no step text"}),!1)),c=nt(Gi.join(e,t),e,s).find(g=>g.name===n);if(!c){for(let g of i)a.skipped.push({index:g.index,reason:`scenario "${n}" not found in ${t}`});return a}let l=new Map;for(let g of i){let y=c.steps[g.index]?.source;if(!y||y.fromBackground)continue;let h=`${y.file}:${y.line}`;l.set(h,(l.get(h)??new Set).add(g.text))}let d=ct(c),u=new Map,p=new Set,f=new Set;for(let g of i){let y=c.steps[g.index];if(!y?.source){a.skipped.push({index:g.index,reason:`no step at index ${g.index}`});continue}let h=[...pa([g.text,..._r([g.text])])].filter(w=>!d.has(w));if(h.length>0){a.skipped.push({index:g.index,reason:`it would make the scenario name ${h.map(w=>`{env:${w}}`).join(", ")}, which it does not reference now; a recording can only use the environment variables its scenario names, so edit the feature file by hand if you mean it`});continue}if(Jt(g.text)!==Jt(y.text)){a.skipped.push({index:g.index,reason:'it would change which browser session the step runs in (its As "..."); edit the feature file by hand if you mean it'});continue}if(o&&o[g.index]!==y.text){a.skipped.push({index:g.index,reason:`step ${g.index+1} now reads "${y.text}", not the "${o[g.index]??"(nothing)"}" this edit was written for`});continue}let{file:S,line:v,fromStepSet:x,fromBackground:b}=y.source;if(b){a.skipped.push({index:g.index,reason:`"${y.text}" is a Background step shared across scenarios; edit it manually`});continue}let m=`${S}:${v}`,$=l.get(m);if($.size>1){a.skipped.push({index:g.index,reason:`${m}${x?` (StepSet "${x}")`:""} is reached by several steps and the edits disagree: ${[...$].map(w=>`"${w}"`).join(" vs ")}. Decide the wording in the definition by hand`});continue}let T=c.steps.findIndex((w,E)=>w.source?.file===S&&w.source.line===v&&w.text!==g.text&&!i.some(_=>_.index===E&&_.text===g.text));if(T>=0){a.skipped.push({index:g.index,reason:`${m} is also used at step ${T+1}, which has no agreeing edit; edit the shared definition by hand`});continue}if(f.has(m)){a.appliedIndices.push(g.index);continue}let R=u.get(S);if(!R){let w=Oh.readFileSync(Gi.join(e,S),"utf8");w.includes(`\r
|
|
1147
|
+
`)&&p.add(S),R=w.split(/\r?\n/),u.set(S,R)}let k=R[v-1],C=k?.match(/^(\s*)(\S+)\s+(.*)$/);if(!C||C[3]!==y.text){a.skipped.push({index:g.index,reason:`${S}:${v} no longer matches the recorded step text`});continue}let P=`${C[1]}${C[2]} ${g.text}`;R[v-1]=P,f.add(m),a.appliedIndices.push(g.index),a.applied.push({file:S,line:v,from:k.trim(),to:P.trim(),fromStepSet:x})}for(let[g,y]of u)a.applied.some(h=>h.file===g)&&Oh.writeFileSync(Gi.join(e,g),y.join(p.has(g)?`\r
|
|
1148
|
+
`:`
|
|
1149
|
+
`));return a}import{spawn as TS}from"node:child_process";function Il(e,t){if(e==null)return[];let n=Array.isArray(e)?e:[e];for(let r of n)if(typeof r!="string"||r.trim()==="")throw new Error(`"${t}" in saffron.config.json must be a command, or a list of commands, e.g. "${t}": "npm run seed"`);return n}function AS(e,t,n){let r=Date.now();return new Promise(s=>{let o=process.platform!=="win32",a=TS(t,{cwd:n.cwd,shell:!0,detached:o,env:{...process.env,...n.env},stdio:["ignore",process.stderr,process.stderr]}),i=!1,c=!1,l,d=()=>{try{o&&a.pid?process.kill(-a.pid,"SIGKILL"):a.kill("SIGKILL")}catch{}},u=setTimeout(()=>{i=!0,d()},n.timeoutMs),p=()=>{c=!0,d()};n.signal?.addEventListener("abort",p,{once:!0});let f=g=>{clearTimeout(u),n.signal?.removeEventListener("abort",p),s({phase:e,command:t,exitCode:g,durationMs:Date.now()-r,...i?{timedOut:i}:{},...c?{cancelled:c}:{},...l?{signal:l}:{}})};a.on("error",()=>f(null)),a.on("exit",(g,y)=>{y&&!i&&!c&&(l=y),f(i||c?null:g)})})}var Ki=e=>e.exitCode!==0;async function jl(e,t,n){let r=[];for(let s of t){if(n.signal?.aborted)break;console.error(`saffron ${e}: ${s}`);let o=await AS(e,s,n);if(r.push(o),o.cancelled||Ki(o)&&(console.error(`saffron ${e} failed: ${Nl(o,n.timeoutMs)}`),e==="setup"))break}return r}function Nl(e,t){return e.cancelled?`"${e.command}" was interrupted`:e.timedOut?`"${e.command}" was stopped after ${Math.round(t/1e3)}s (hookTimeoutMs)`:e.signal?`"${e.command}" was killed by ${e.signal}`:e.exitCode===null?`"${e.command}" could not be started`:`"${e.command}" exited with code ${e.exitCode}`}var ES=`
|
|
1148
1150
|
.wrap { max-width: 1180px; }
|
|
1149
1151
|
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 0 14px; align-items: start; }
|
|
1150
1152
|
.panel { min-width: 0; }
|
|
@@ -1186,42 +1188,42 @@ ${e.prompt}`,e)),a.status==="error"&&!e.finished())throw new Error(`Cursor: ${a.
|
|
|
1186
1188
|
details.more summary { padding: 6px 0 0; font-family: var(--mono); font-size: 10.5px; color: var(--muted); }
|
|
1187
1189
|
details.more summary:hover { background: none; color: var(--text); }
|
|
1188
1190
|
@media (max-width: 560px) { .wrap { padding: 14px 12px 40px; } .grid { grid-template-columns: 1fr; } .kpis { grid-template-columns: repeat(2, 1fr); } }
|
|
1189
|
-
`,ae=e=>String(Number(e)),
|
|
1190
|
-
${
|
|
1191
|
-
${
|
|
1192
|
-
${
|
|
1193
|
-
${
|
|
1194
|
-
${
|
|
1195
|
-
${
|
|
1196
|
-
${
|
|
1197
|
-
${
|
|
1198
|
-
</section>`,d=`<div class="panel"><div class="panel-title">suite health \xB7 each scenario's latest result</div>${
|
|
1199
|
-
${
|
|
1200
|
-
${
|
|
1201
|
-
</div>`,p=
|
|
1191
|
+
`,ae=e=>String(Number(e)),Ml=e=>z(st(Number(e))),$r=(e,t)=>`${ae(e)} ${t}${Number(e)===1?"":"s"}`,Dl=e=>new Date(e).toLocaleString("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}),Fl=e=>new Date(e).toLocaleString("en-GB",{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit"});function no(e,t=""){let n=e.name??e.scenario;return`<div class="row-main"><div class="scn" data-f="${z(e.feature)}" data-s="${z(n)}" title="${z(`${e.feature} \u203A ${e.scenario}`)}">${z(e.scenario)}</div><div class="feat">${z(e.feature)}${e.browser?` \xB7 ${z(e.browser)}`:""}</div>${t}</div>`}function In(e,t,n,r,s,o=""){return`<div class="panel${o?` accent-${o}`:""}"><div class="panel-head"><div class="panel-title${n?` ${n}`:""}">${z(e)}</div>${t===void 0?"":`<span class="count${t>0&&n?` ${n}`:""}">${ae(t)}</span>`}</div>${r||`<div class="empty">${z(s)}</div>`}</div>`}function Ph(e){let t=e.reduce((n,[r])=>n+r,0)||1;return`<div class="stack">${e.filter(([n])=>n>0).map(([n,r,s])=>`<span style="width:${(n/t*100).toFixed(2)}%;background:${s??`var(${r})`}"></span>`).join("")}</div>`}function Ih(e,t,n,r){if(e.length===0)return'<div class="empty">No runs yet.</div>';let s=Math.max(1,...e.map(t)),o=10,a=e.map((i,c)=>{let l=Math.max(2,t(i)/s*62);return`<rect x="${c*o+1.5}" y="${(64-l).toFixed(1)}" width="${o-3}" height="${l.toFixed(1)}" rx="1.5" fill="var(${r(i)})"><title>${z(n(i))}</title></rect>`}).join("");return`<svg class="bars" viewBox="0 0 ${e.length*o} 64" preserveAspectRatio="none" aria-hidden="true">${a}</svg><div class="axis"><span>${z(Fl(e[0].startedAt))}</span><span>${z(Fl(e.at(-1).startedAt))}</span></div>`}var ro=e=>e.length?`<ul class="rows">${e.join("")}</ul>`:"";function jh(e,t){let n=e.suite,r=n.green+n.yellow+n.unverified+n.red,s=r===0?void 0:Math.round((n.green+n.yellow)/r*100),o=m=>m>0?` \xB7 ${ae(m)} unverified`:"",a=n.red,i=e.lastRun,c=s===void 0?"":s>=95?"green":s>=80?"gold":"red",l=`<section class="kpis">
|
|
1192
|
+
${Ae("tests",ae(n.tests),`${$r(n.scenarios,"scenario")} \xB7 ${$r(n.features,"feature")}`)}
|
|
1193
|
+
${Ae("passing",s===void 0?"\u2013":`${s}<span class="unit">%</span>`,`${ae(n.green+n.yellow)} of ${ae(r)} \xB7 latest results${o(n.unverified)}`,c,"",Zr(e.trend.map(m=>m.passRate),"var(--green)"))}
|
|
1194
|
+
${Ae("failing",ae(a),a>0?"\u25BC red the last time they ran":"all clear",a>0?"red":"",a>0?"red":"green")}
|
|
1195
|
+
${Ae("flaky",ae(e.flaky.length),e.flaky.length>0?"pass and fail by turns on one base URL":"none in 20 runs",e.flaky.length>0?"gold":"",e.flaky.length>0?"gold":"green")}
|
|
1196
|
+
${Ae("never run",ae(e.neverRun.length),e.neverRun.length>0?"in no recorded run":"every scenario has run",e.neverRun.length>0?"gold":"",e.neverRun.length>0?"gold":"green")}
|
|
1197
|
+
${Ae("last run",i?Ml(i.durationMs):"\u2013",i?`${$r(i.ran,"test")} \xB7 ${ae(i.passRate)}% passed${o(i.unverified)}`:"no run yet","","",Zr(e.trend.map(m=>m.durationMs),"var(--muted)"))}
|
|
1198
|
+
${Ae("zero-ai replay",i?`${ae(i.replayRate)}<span class="unit">%</span>`:"\u2013","replayed from recordings, last run",i&&i.replayRate>=90?"green":"")}
|
|
1199
|
+
${Ae("recorded",n.scenarios?`${Math.round(n.recorded/n.scenarios*100)}<span class="unit">%</span>`:"\u2013",n.scenarios-n.recorded>0?`${ae(n.scenarios-n.recorded)} still need the agent`:"every scenario has a current recording",n.recorded===n.scenarios?"green":"")}
|
|
1200
|
+
</section>`,d=`<div class="panel"><div class="panel-title">suite health \xB7 each scenario's latest result</div>${Ph([[n.green,"--green"],[n.yellow,"--gold"],[n.unverified,"--gold","repeating-linear-gradient(135deg, var(--gold) 0 4px, var(--gold-soft) 4px 8px)"],[n.red,"--red"],[n.neverRun,"--faint"]])}<div class="legend"><span><i class="dot green"></i>${ae(n.green)} passed</span><span><i class="dot gold"></i>${ae(n.yellow)} healed</span>${n.unverified>0?`<span><i class="dot unverified"></i>${ae(n.unverified)} healed, unverified</span>`:""}<span><i class="dot red"></i>${ae(n.red)} failed</span><span><i class="dot faint"></i>${ae(n.neverRun)} never run</span></div></div>`,u=`<div class="grid">
|
|
1201
|
+
${In(`pass rate \xB7 last ${$r(e.trend.length,"run")}`,void 0,"",Ih(e.trend,m=>m.passRate,m=>`${Dl(m.startedAt)}: ${ae(m.passRate)}% of ${ae(m.tests)} passed, ${ae(m.red)} failed`,m=>m.red>0?"--red":"--green"),"")}
|
|
1202
|
+
${In(`execution time \xB7 last ${$r(e.trend.length,"run")}`,void 0,"",Ih(e.trend,m=>m.durationMs,m=>`${Dl(m.startedAt)}: ${st(Number(m.durationMs))} for ${$r(m.tests,"test")}`,()=>"--muted"),"")}
|
|
1203
|
+
</div>`,p=ro(e.recentFailures.map(m=>`<li><i class="dot ${m.stillFailing?"red":"green"}"></i>${no(m,m.error?`<div class="err" title="${z(m.error)}">${z(m.error)}</div>`:"")}<div class="row-side">${m.stillFailing?`<span class="red">${ae(m.streak)} run${Number(m.streak)===1?"":"s"} in a row</span>`:'<span class="green">passed since</span>'}<br>${z(Fl(m.at))}</div></li>`)),f=ro(e.flaky.map(m=>`<li><i class="dot gold"></i>${no(m)}<div class="row-side">flipped ${ae(m.flips)}\xD7 in ${ae(m.runs)} runs<br>${ae(m.reds)} red \xB7 last <span class="${m.last==="red"?"red":"green"}">${m.last==="red"?"failed":"passed"}</span></div></li>`)),g=ro(e.healing.map(m=>`<li><i class="dot gold"></i>${no(m)}<div class="row-side">healed ${ae(m.heals)}\xD7${m.unverified>0?` <span class="gold">(${ae(m.unverified)} unverified)</span>`:""}<br>in ${ae(m.runs)} runs</div></li>`)),y=Math.max(1,...e.slowest.map(m=>m.avgMs)),h=ro(e.slowest.map(m=>`<li>${no(m,`<div class="meter" style="width:${(m.avgMs/y*100).toFixed(1)}%"></div>`)}<div class="row-side">avg ${Ml(m.avgMs)}<br>last ${Ml(m.lastMs)}</div></li>`)),S=e.tags.length?`<table class="tags">${e.tags.map(m=>{let $=m.scenarios-m.neverRun,T=m.red>0?`<span style="color:var(--red)">${ae(m.red)} red</span>`:$===0?"never run":`${Math.round((m.green+m.yellow)/$*100)}%`;return`<tr><td class="tagname">${z(m.tag)}</td><td class="num">${ae(m.scenarios)}</td><td class="stackcell">${Ph([[m.green,"--green"],[m.yellow,"--gold"],[m.unverified,"--gold","repeating-linear-gradient(135deg, var(--gold) 0 4px, var(--gold-soft) 4px 8px)"],[m.red,"--red"],[m.neverRun,"--faint"]])}</td><td class="num">${T}</td></tr>`}).join("")}</table>`:"",v=(m,$)=>ro(m.map(T=>`<li><i class="dot ${$}"></i>${no(T)}</li>`)),x=e.notInLastRun.length?`<details class="more"><summary>left out by tags or paths \xB7 show ${ae(e.notInLastRun.length)}</summary>${v(e.notInLastRun,"idle")}</details>`:"",b=e.historyRuns===0?"no runs recorded yet":`${$r(e.historyRuns,"run")} in .saffron/history.jsonl`;return`<!doctype html>
|
|
1202
1204
|
<html lang="en">
|
|
1203
1205
|
<head>
|
|
1204
1206
|
<meta charset="utf-8"/>
|
|
1205
1207
|
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
|
1206
1208
|
<title>Saffron dashboard</title>
|
|
1207
|
-
${
|
|
1209
|
+
${Us}
|
|
1208
1210
|
<style>
|
|
1209
|
-
${
|
|
1211
|
+
${zs}${ES}</style>
|
|
1210
1212
|
</head>
|
|
1211
1213
|
<body>
|
|
1212
1214
|
<div class="topline"></div>
|
|
1213
1215
|
<div class="wrap">
|
|
1214
1216
|
<header class="top">
|
|
1215
1217
|
<div class="brand">
|
|
1216
|
-
${
|
|
1218
|
+
${pr(38)}
|
|
1217
1219
|
<div>
|
|
1218
1220
|
<div class="brand-name">saffron</div>
|
|
1219
1221
|
<div class="brand-sub">suite quality</div>
|
|
1220
1222
|
</div>
|
|
1221
1223
|
</div>
|
|
1222
1224
|
<div class="run-meta">
|
|
1223
|
-
<span>${
|
|
1224
|
-
${i?`<span>\xB7</span><span>last run ${
|
|
1225
|
+
<span>${z(b)}</span>
|
|
1226
|
+
${i?`<span>\xB7</span><span>last run ${z(Dl(i.startedAt))}</span>`:""}
|
|
1225
1227
|
</div>
|
|
1226
1228
|
</header>
|
|
1227
1229
|
|
|
@@ -1229,24 +1231,24 @@ ${ks}${Ox}</style>
|
|
|
1229
1231
|
${d}
|
|
1230
1232
|
|
|
1231
1233
|
<div class="section-head"><span class="section-title">trends</span></div>
|
|
1232
|
-
${
|
|
1234
|
+
${u}
|
|
1233
1235
|
|
|
1234
1236
|
<div class="section-head"><span class="section-title">stability</span></div>
|
|
1235
1237
|
<div class="grid">
|
|
1236
|
-
${
|
|
1237
|
-
${
|
|
1238
|
-
${
|
|
1239
|
-
${
|
|
1238
|
+
${In("recent failures \xB7 last 10 runs",e.recentFailures.length,"red",p,"Nothing failed in the last 10 runs.",a>0?"red":"")}
|
|
1239
|
+
${In("flaky \xB7 last 20 runs",e.flaky.length,"gold",f,"No scenario passed and failed by turns.",e.flaky.length>0?"gold":"")}
|
|
1240
|
+
${In("healed again and again",e.healing.length,"gold",g?`<div class="note">The page keeps changing under these: review the heals, or fix the step.</div>${g}`:"","No scenario needed the agent twice in the last 20 runs.")}
|
|
1241
|
+
${In("slowest \xB7 average over 20 runs",void 0,"",h,"No timings yet.")}
|
|
1240
1242
|
</div>
|
|
1241
1243
|
|
|
1242
1244
|
<div class="section-head"><span class="section-title">coverage</span></div>
|
|
1243
1245
|
<div class="grid">
|
|
1244
|
-
${
|
|
1245
|
-
${
|
|
1246
|
-
${
|
|
1246
|
+
${In("tags \xB7 latest results",e.tags.length,"",S,"No tags in the feature files.")}
|
|
1247
|
+
${In("never run",e.neverRun.length,"gold",v(e.neverRun,"faint"),"Every scenario has run at least once.")}
|
|
1248
|
+
${In("not in the last run",e.notInLastRun.length,"",x,"The last run ran every scenario that has run before.")}
|
|
1247
1249
|
</div>
|
|
1248
1250
|
|
|
1249
|
-
<footer>${
|
|
1251
|
+
<footer>${Bs(11)} generated by saffron v${z(t)}</footer>
|
|
1250
1252
|
</div>
|
|
1251
1253
|
<script>
|
|
1252
1254
|
if (typeof window.saffronOpen === "function") document.body.classList.add("linked");
|
|
@@ -1257,7 +1259,7 @@ ${ks}${Ox}</style>
|
|
|
1257
1259
|
</script>
|
|
1258
1260
|
</body>
|
|
1259
1261
|
</html>
|
|
1260
|
-
`}import{spawnSync as
|
|
1262
|
+
`}import{spawnSync as Xh}from"node:child_process";import Bt from"node:fs";import tm from"node:os";import Pe from"node:path";import{spawnSync as Mh}from"node:child_process";import je from"node:fs";import ge from"node:path";import OS from"node:fs";import Ll from"node:path";var _S=`
|
|
1261
1263
|
.wrap { max-width: 1060px; }
|
|
1262
1264
|
.acts { display: none; gap: 8px; flex-wrap: wrap; margin-top: 10px; }
|
|
1263
1265
|
.linked .acts { display: flex; }
|
|
@@ -1286,41 +1288,41 @@ ${ks}${Ox}</style>
|
|
|
1286
1288
|
.ok { color: var(--green); } .no { color: var(--muted); }
|
|
1287
1289
|
details.more summary { padding: 2px 0; font-family: var(--mono); font-size: 10.5px; color: var(--muted); cursor: pointer; }
|
|
1288
1290
|
details.more summary:hover { color: var(--text); }
|
|
1289
|
-
`;function
|
|
1290
|
-
`).map(t=>t.trim()).find(Boolean);function
|
|
1291
|
-
<div class="scn">${
|
|
1292
|
-
<div class="feat">${
|
|
1293
|
-
${$.failingStep?`<div class="step">${$.status==="red"?"failed at":"changed at"}: ${
|
|
1294
|
-
${$.error?`<div class="err">${
|
|
1295
|
-
${$.narrative?`<div class="story">${
|
|
1296
|
-
${
|
|
1297
|
-
<div class="acts">${$.trace?
|
|
1298
|
-
</div>`},
|
|
1291
|
+
`;function CS(e,t){if(!(!t||!It(Ll.join(e,".saffron","ci"),Ll.join(e,t))))try{let n=OS.readFileSync(Ll.join(e,t));return n.length<=4*1024**2?`data:image/${/\.png$/i.test(t)?"png":"jpeg"};base64,${n.toString("base64")}`:void 0}catch{return}}var so=(e,t,n,r=!1)=>`<button class="act${r?" primary":""}" data-act="${z(e)}"${n?` data-f="${z(n.feature)}" data-s="${z(n.scenario)}"${n.browser?` data-b="${z(n.browser)}"`:""}`:""}>${z(t)}</button>`,Nh=e=>e?.split(`
|
|
1292
|
+
`).map(t=>t.trim()).find(Boolean);function Yi(e,t,n){let{run:r}=e,s=`${r.name??"CI run"} \xB7 run ${r.id}${r.attempt>1?`, attempt ${r.attempt}`:""}`,o=[r.status==="completed"?r.conclusion??"completed":r.status.replace("_"," "),r.branch&&`${r.branch}${r.commit?` @ ${r.commit.slice(0,7)}`:""}`,r.createdAt&&new Date(r.createdAt).toLocaleString("en-GB",{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit"})].filter(Boolean),a;if(!e.bundle)a=`<div class="panel"><div class="panel-title">no results</div><div class="note">${z(e.reason??"This run has no Saffron results.")}</div></div>`;else{let i=e.scenarios??[],c=e.totals??{green:0,yellow:0,red:0,aiCalls:0,costUsd:0},l=`<div class="kpis">${Ae("passed",String(c.green),"green","green")}${Ae("pending review",String(c.yellow),"healed or recorded",c.yellow?"gold":"")}${Ae("failed",String(c.red),"red",c.red?"red":"")}${Ae("agent",c.costUsd>0?`$${c.costUsd.toFixed(2)}`:String(c.aiCalls),c.costUsd>0?`${c.aiCalls} AI calls`:"AI calls")}</div>`,d=e.warnings.length?`<div class="panel accent-gold"><div class="panel-title gold">warnings</div>${e.warnings.map($=>`<div class="note">${z($)}</div>`).join("")}</div>`:"",u=e.bundle.summaryOnly?'<div class="panel"><div class="note">This run uploaded only a summary (saffron export --report-only): its results and screenshots, no traces to replay and nothing to import.</div></div>':"",p=$=>{let T=CS(t,$.screenshot),R={feature:$.feature,scenario:$.displayName,browser:$.browser},k={feature:$.feature,scenario:$.scenario,browser:$.browser};return`<div class="card ${$.status==="red"?"red":"yellow"}">
|
|
1293
|
+
<div class="scn">${z($.displayName)}</div>
|
|
1294
|
+
<div class="feat">${z($.feature)}${$.browser?` \xB7 ${z($.browser)}`:""} \xB7 ${z(st($.durationMs))}${$.verified===!1?" \xB7 unverified":$.verified?" \xB7 verified":""}</div>
|
|
1295
|
+
${$.failingStep?`<div class="step">${$.status==="red"?"failed at":"changed at"}: ${z(Nh($.failingStep)??"")}</div>`:""}
|
|
1296
|
+
${$.error?`<div class="err">${z($.error)}</div>`:""}
|
|
1297
|
+
${$.narrative?`<div class="story">${z($.narrative)}</div>`:""}
|
|
1298
|
+
${T?`<details class="shot-full"><summary><img class="shot" src="${T}" alt="screenshot of ${z($.displayName)}"></summary></details>`:""}
|
|
1299
|
+
<div class="acts">${$.trace?so("trace","Open trace",R,!0):""}${so("open","Open scenario",k)}</div>
|
|
1300
|
+
</div>`},f=i.filter($=>$.status==="red"),g=i.filter($=>$.status==="yellow"),y=i.filter($=>$.status==="green"),h=($,T)=>T.length?`<div class="section-head"><span class="section-title">${z($)}</span></div><div class="cards">${T.map(p).join("")}</div>`:"",S=y.length?`<div class="section-head"><span class="section-title">passed</span></div><div class="panel"><details class="more"><summary>${y.length} scenario${y.length===1?"":"s"} passed</summary><ul class="rows">${y.map($=>`<li><span class="grow">${z($.displayName)}</span><span class="why">${z($.feature)}${$.browser?` \xB7 ${z($.browser)}`:""}</span></li>`).join("")}</ul></details></div>`:"",v=e.proposals??[],x=v.filter($=>$.importable).length,b=v.length?`<div class="section-head"><span class="section-title">proposals</span></div><div class="panel"><div class="note">${v.length} proposal${v.length===1?"":"s"}, ${x} importable here. Import files them for review in this checkout.</div><ul class="rows">${v.map($=>`<li><span class="${$.importable?"ok":"no"}">${$.importable?"\u2713":"\xB7"}</span><span class="grow">${z($.feature)} \u203A ${z($.scenario)}</span><span class="why">${z($.importable?$.verified?"verified":"unverified":Nh($.reason)??"not importable")}</span></li>`).join("")}</ul>${x?`<div class="acts">${so("import","Import",void 0,!0)}</div>`:""}</div>`:"",m=e.interrupted?`<div class="panel"><p><b>Run interrupted:</b> ${Number(e.notRun??0)} scenario${e.notRun===1?"":"s"} did not run, and count as neither passed nor failed.</p></div>`:"";a=`${l}${m}${d}${u}${h("failed",f)}${h("pending review",g)}${S}${b}`}return`<!doctype html>
|
|
1299
1301
|
<html lang="en">
|
|
1300
1302
|
<head>
|
|
1301
1303
|
<meta charset="utf-8"/>
|
|
1302
1304
|
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
|
1303
|
-
<title>${
|
|
1304
|
-
${
|
|
1305
|
+
<title>${z(s)}</title>
|
|
1306
|
+
${Us}
|
|
1305
1307
|
<style>
|
|
1306
|
-
${
|
|
1308
|
+
${zs}${_S}</style>
|
|
1307
1309
|
</head>
|
|
1308
1310
|
<body>
|
|
1309
1311
|
<div class="topline"></div>
|
|
1310
1312
|
<div class="wrap">
|
|
1311
1313
|
<header class="top">
|
|
1312
1314
|
<div class="brand">
|
|
1313
|
-
${
|
|
1315
|
+
${pr(38)}
|
|
1314
1316
|
<div>
|
|
1315
1317
|
<div class="brand-name">saffron</div>
|
|
1316
|
-
<div class="brand-sub">${
|
|
1318
|
+
<div class="brand-sub">${z(s)}</div>
|
|
1317
1319
|
</div>
|
|
1318
1320
|
</div>
|
|
1319
|
-
<div class="run-meta">${o.map(i=>`<span>${
|
|
1321
|
+
<div class="run-meta">${o.map(i=>`<span>${z(i)}</span>`).join("<span>\xB7</span>")}</div>
|
|
1320
1322
|
</header>
|
|
1321
|
-
<div class="acts">${e.reportHtml?
|
|
1323
|
+
<div class="acts">${e.reportHtml?so("report","Open report"):""}${r.url?so("run","Open run page"):""}</div>
|
|
1322
1324
|
${a}
|
|
1323
|
-
<footer>${
|
|
1325
|
+
<footer>${Bs(11)} generated by saffron v${z(n)}</footer>
|
|
1324
1326
|
</div>
|
|
1325
1327
|
<script>
|
|
1326
1328
|
if (typeof window.saffronAct === "function") document.body.classList.add("linked");
|
|
@@ -1331,64 +1333,97 @@ ${ks}${Px}</style>
|
|
|
1331
1333
|
</script>
|
|
1332
1334
|
</body>
|
|
1333
1335
|
</html>
|
|
1334
|
-
`}var
|
|
1335
|
-
${e.stdout}`,
|
|
1336
|
-
`).map(n=>n.trim()).find(n=>n&&!/^WARNING:/.test(n))??t;function Qr(e){return e.missing?{kind:"missing-tool",message:"the GitHub CLI (gh) is not installed here: install it from cli.github.com and sign in with gh auth login"}:e.timedOut?{kind:"failed",message:"gh did not finish within 10 minutes"}:/gh auth login|not logged in|authentication required/i.test(qs(e))?{kind:"signed-out",message:"gh is not signed in: run gh auth login"}:/none of the git remotes|no git remotes|not a git repository/i.test(qs(e))?{kind:"not-a-repository",message:fl(e,"not a GitHub repository")}:{kind:"failed",message:fl(e,`gh exited with ${e.status}`)}}function wr(e){if(e.missing)return{kind:"missing-tool",message:"the Azure CLI (az) is not installed here: install it, add its azure-devops extension (az extension add --name azure-devops) and sign in (az login, or AZURE_DEVOPS_EXT_PAT)"};if(e.timedOut)return{kind:"failed",message:"az did not finish within 10 minutes"};let t=qs(e);return/azure-devops|'pipelines' is (misspelled|not in)|not in the 'az' command group/i.test(t)&&!/login/i.test(t)?{kind:"missing-tool",message:"the Azure CLI has no azure-devops extension: az extension add --name azure-devops"}:/az login|az devops login|TF400813|not authorized|authentication failed|\b401\b/i.test(t)?{kind:"signed-out",message:"az is not signed in to Azure DevOps: run az login, or set AZURE_DEVOPS_EXT_PAT"}:/--organization|--org\b|--project|must be specified|could not detect/i.test(t)?{kind:"not-a-repository",message:"cannot tell which Azure DevOps organization and project: run this in a clone of an Azure Repos repository, or set ci.organization and ci.project in saffron.config.json"}:{kind:"failed",message:fl(e,`az exited with ${e.status}`)}}function hl(e,t,n){let r=n??t.ci?.provider;if(r!==void 0){if(!Nx.includes(r))throw new W(`unknown CI provider "${r}": use "github" or "azure"`);return r}return ei(e).some(s=>s.startsWith("dev.azure.com/"))?"azure":"github"}var Js=e=>[...e.ci?.organization?["--organization",e.ci.organization]:[],...e.ci?.project?["--project",e.ci.project]:[]];function Mx(e,t){let n=ze("git",["rev-parse","--abbrev-ref","HEAD"],e,t),r=n.status===0?n.stdout.trim():"";return r&&r!=="HEAD"?r:void 0}function Dx(e){let t=new Map;for(let[n,r]of Object.entries(hn(e))){try{if(Ot(le.join(e,n))!==r.revision)continue}catch{continue}r.from.run&&t.set(r.from.run,(t.get(r.from.run)??0)+1)}return t}function Xg(e,t=Date.now()){let n=e?t-Date.parse(e):NaN;if(!(n>=0))return;let r=Math.round(n/6e4);if(r<60)return`${r} min ago`;let s=Math.round(r/60);return s<48?`${s} h ago`:`${Math.round(s/24)} days ago`}var ie=e=>typeof e=="string"&&e?e:void 0,Zg=e=>ie(e)?.replace(/^refs\/(heads|tags)\//,""),Qg="databaseId,number,attempt,displayTitle,workflowName,status,conclusion,event,headBranch,headSha,createdAt,startedAt,url";function Fx(e){let t=e.status==="completed"?"completed":e.status==="in_progress"?"in_progress":"queued";return{id:String(e.databaseId),name:ie(e.workflowName)??"workflow",number:String(e.number??""),title:ie(e.displayTitle),status:t,conclusion:t==="completed"?ie(e.conclusion):void 0,event:ie(e.event),branch:ie(e.headBranch),commit:ie(e.headSha),createdAt:ie(e.createdAt),url:ie(e.url),attempt:typeof e.attempt=="number"?e.attempt:void 0}}var Lx={completed:"completed",inProgress:"in_progress",cancelling:"in_progress"},Bx={succeeded:"success",partiallySucceeded:"partial",failed:"failure",canceled:"cancelled"},Ux={individualCI:"push",batchedCI:"push",pullRequest:"pull_request",schedule:"schedule",manual:"manual"};function eh(e){let t=e.triggerInfo??{};return Zg(t["pr.sourceBranch"])??Zg(e.sourceBranch)}function th(e){let t=e.triggerInfo??{},n=Lx[String(e.status)]??"queued",r=ie(e.result);return{id:String(e.id),name:ie(e.definition?.name)??"pipeline",number:String(e.buildNumber??e.id),status:n,conclusion:n==="completed"&&r?Bx[r]??r:void 0,event:ie(e.reason)?Ux[String(e.reason)]??String(e.reason):void 0,branch:eh(e),commit:ie(t["pr.sourceSha"])??ie(e.sourceVersion),createdAt:ie(e.queueTime),url:ie((e._links??{}).web?.href)}}function Ii(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function ml(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>!!n&&typeof n=="object"):void 0}catch{return}}function zx(e){return new Set(e.map(t=>t.startsWith("dev.azure.com/")?t.slice(t.lastIndexOf("/_git/")+6):t.slice(t.indexOf("/")+1)))}function Hx(e,t,n,r,s,o,a=Math.min(Math.max(o,50),500)){for(let i=a;;i=Math.min(i*2,500)){let c=ze("az",["pipelines","runs","list","--top",String(i),...r,"--output","json",...Js(t)],e,n);if(c.missing||c.status!==0)return wr(c);let l=ml(c.stdout);if(!l)return{kind:"failed",message:"az answered with something other than a list of runs"};let d=l.filter(s);if(d.length>=o||l.length<i||i>=500)return d}}function nh(e,t,n={}){let r=n.env??process.env,s=hl(e,t,n.provider),o=n.branch??Mx(e,r),a=o===void 0?void 0:Zr(o),i=n.limit??20,c,l=new Map;if(s==="github"){let p=b=>ze("gh",["run","list","--limit",String(i),"--json",b,...a?["--branch",a]:[]],e,r),u=p(Qg);if(!u.missing&&u.status!==0&&/startedAt/.test(`${u.stderr??""}${u.stdout??""}`)&&(u=p(Qg.replace(",startedAt",""))),u.missing||u.status!==0)return{provider:s,branch:a,runs:[],problem:Qr(u)};let h=ml(u.stdout);if(!h)return{provider:s,branch:a,runs:[],problem:{kind:"failed",message:"gh answered with something other than a list of runs"}};c=h.map(Fx);for(let b of h)l.set(String(b.databaseId),Date.parse(ie(b.startedAt)??""))}else{let p=zx(ei(e)),u=S=>{let y=ie(S.repository?.name)?.toLowerCase();return p.size===0||!y||p.has(y)},h=S=>u(S)&&(!a||eh(S)===a),b=a?[["--branch",`refs/heads/${a}`],["--branch",`refs/tags/${a}`],["--reason","pullRequest"]]:[[]],g=new Map;for(let S of b){let y=Hx(e,t,r,S,h,i);if(!Array.isArray(y))return{provider:s,branch:a,runs:[],problem:y};for(let w of y)g.set(String(w.id),w)}c=[...g.values()].sort((S,y)=>(Date.parse(ie(y.queueTime)??"")||0)-(Date.parse(ie(S.queueTime)??"")||0)).slice(0,i).map(th)}let d=Dx(e),f=s==="github"?qx(e,r,c,l):new Map;return{provider:s,branch:a,runs:c.map(p=>{let u=f.get(p.id);return{...p,pending:d.get(`${s}:${p.id}`)??0,...u?{results:u}:{}}})}}function qx(e,t,n,r){let s=new Map;for(let d of n)d.status!=="completed"&&s.set(d.id,{kind:"running",label:Yg("running")});let o=n.filter(d=>d.status==="completed");if(o.length===0)return s;let a=Math.min(...o.map(d=>Date.parse(d.createdAt??"")||0)),i=new Map,c=!1;for(let d=1;d<=5&&!c;d++){let f=ze("gh",["api",`repos/{owner}/{repo}/actions/artifacts?per_page=100&page=${d}`],e,t),p=f.missing||f.status!==0?void 0:Ii(f.stdout)?.artifacts;if(!Array.isArray(p))break;for(let u of p.filter(h=>!!h&&typeof h=="object")){let h=String((u.workflow_run??{}).id??"");h&&i.set(h,[...i.get(h)??[],u]);let b=Date.parse(ie(u.created_at)??"");!Number.isNaN(b)&&b<a&&(c=!0)}p.length<100&&(c=!0)}let l=d=>d.reduce((f,p)=>f+(Number(p.size_in_bytes)||0),0);for(let d of o){let f=Vx(i.get(d.id)??[],(d.attempt??1)>1?r.get(d.id):void 0),p=S=>f.filter(y=>typeof y.name=="string"&&S.test(y.name)),u=p(sh),h=p(gl),b=S=>S.filter(y=>y.expired!==!0),g=(S,y)=>s.set(d.id,{kind:S,...y!==void 0?{sizeBytes:y}:{},label:Yg(S,y)});b(u).length>0?g("full",l(b(u))):b(h).length>0?g("summary",l(b(h))):u.length+h.length>0?g("expired"):c&&g("none")}return s}function Vx(e,t){if(t===void 0||Number.isNaN(t))return e;let n=o=>String(o.name).replace(/^saffron-(bundle|summary)/,""),r=o=>Date.parse(ie(o.created_at)??"")>=t,s=new Set(e.filter(r).map(n));return e.filter(o=>r(o)||!s.has(n(o)))}var pl=e=>`run ${e} has no Saffron bundle: none was uploaded, or it expired. Its workflow needs saffron export and an upload of saffron-bundle* (see the guide, section 19)`;function rh(e,t,n,r,s,o){let a,i;if(n==="github"){let c=ze("gh",["api",`repos/{owner}/{repo}/actions/runs/${r}`],e,s);if(c.missing||c.status!==0)throw new W(Qr(c).message,Qr(c).kind);let l=Ii(c.stdout),d=ie(l?.repository?.full_name);if(!l||String(l.id)!==r||!d)throw new W(`gh answered with something other than run ${r}`);let f=ie(l.head_repository?.full_name);f?.toLowerCase()!==d.toLowerCase()&&(a={event:ie(l.event),from:f});let p=l.status==="completed"?"completed":l.status==="in_progress"?"in_progress":"queued";i={provider:n,id:r,attempt:typeof l.run_attempt=="number"?l.run_attempt:1,name:ie(l.name),branch:ie(l.head_branch),commit:ie(l.head_sha),url:ie(l.html_url),status:p,conclusion:p==="completed"?ie(l.conclusion):void 0,createdAt:ie(l.created_at)}}else{let c=ze("az",["pipelines","runs","show","--id",r,"--output","json",...Js(t)],e,s);if(c.missing||c.status!==0)throw new W(wr(c).message,wr(c).kind);let l=Ii(c.stdout);if(!l||String(l.id)!==r)throw new W(`az answered with something other than run ${r}`);let d=th(l);/^true$/i.test(String((l.triggerInfo??{})["pr.isFork"]))&&(a={event:d.event}),i={provider:n,id:r,attempt:1,name:d.name,branch:d.branch,commit:d.commit,url:d.url,status:d.status,conclusion:d.conclusion,createdAt:d.createdAt}}if(a&&!o)throw new W(`run ${r}${a.event?` (${a.event})`:""} comes from ${a.from?`the fork ${a.from}`:"a fork"}: code from outside this repository made its bundle, and could have put anything in it. Read that pull request, then import with --allow-fork if you trust it`,"fork");return i}var sh=/^saffron-bundle[\w.-]*$/,gl=/^saffron-summary[\w.-]*$/;function oh(e,t,n,r,s){let o;if(n==="github"){o=[];for(let a=1;o;a++){let i=ze("gh",["api",`repos/{owner}/{repo}/actions/runs/${r}/artifacts?per_page=100&page=${a}`],e,s);if(i.missing||i.status!==0)throw new W(Qr(i).message,Qr(i).kind);let c=Ii(i.stdout)?.artifacts;if(!Array.isArray(c))o=void 0;else if(o.push(...c.filter(l=>!!l&&typeof l=="object")),c.length<100)break}}else{let a=ze("az",["pipelines","runs","artifact","list","--run-id",r,"--output","json",...Js(t)],e,s);if(a.missing||a.status!==0)throw new W(wr(a).message,wr(a).kind);o=ml(a.stdout)}if(!o)throw new W(`${n==="github"?"gh":"az"} answered with something other than a list of artifacts`);return o.filter(a=>typeof a.name=="string"&&(sh.test(a.name)||gl.test(a.name))).map(a=>({name:a.name,sizeBytes:Number(a.size_in_bytes??((a.resource??{}).properties??{}).artifactsize)||0,expired:a.expired===!0,summary:gl.test(a.name)}))}function ih(e,t,n,r,s,o,a){if(a.length===0)throw new W(pl(r));for(let i of a){let c=n==="github"?ze("gh",["run","download",r,"-n",i,"--dir",le.join(s,i)],e,o):ze("az",["pipelines","runs","artifact","download","--run-id",r,"--artifact-name",i,"--path",le.join(s,i),...Js(t)],e,o);if(c.missing||c.status!==0)throw n==="github"&&/no (valid )?artifact/i.test(qs(c))?new W(pl(r)):new W(`cannot download ${i}: ${(n==="github"?Qr(c):wr(c)).message}`)}}function ah(e,t,n,r={}){ch(n);let s=r.env??process.env,o=hl(e,t,r.provider),a=rh(e,t,o,n,s,r.allowFork===!0),i=lh(e,o,n,a.attempt);if(a.status==="completed"&&Oe.existsSync(i))return{provider:o,dir:le.join(i,"bundles"),remove:()=>{}};let c=oh(e,t,o,n,s).filter(f=>!f.expired).map(f=>f.name);if(c.length===0)throw new W(pl(n));let{dir:l,remove:d}=vc(e);try{return ih(e,t,o,n,l,s,c),{provider:o,dir:l,remove:d}}catch(f){throw d(),f}}function ch(e){if(!/^\d+$/.test(e))throw new W(`--run takes the run's id, a number as saffron runs lists it, not "${e}"`)}var wl=e=>le.join(e,".saffron","ci"),lh=(e,t,n,r)=>le.join(wl(e),`${t}-${n}`,`attempt-${r}`),Jx=10,Wx=1024**3;function Gx(e){let t=0;for(let n of Oe.readdirSync(e,{recursive:!0})){let r=Oe.lstatSync(le.join(e,String(n)),{throwIfNoEntry:!1});r?.isFile()&&(t+=r.size)}return t}function Kx(e,t){let n=wl(e),r=Oe.readdirSync(n,{withFileTypes:!0}).filter(a=>a.isDirectory()).map(a=>le.join(n,a.name)).map(a=>({run:a,mtime:Oe.statSync(a).mtimeMs,bytes:Gx(a)})).sort((a,i)=>+(i.run===t)-+(a.run===t)||i.mtime-a.mtime),s=0,o=0;for(let a of r){if(a.run!==t&&(s+1>Jx||o+a.bytes>Wx)){Oe.rmSync(a.run,{recursive:!0,force:!0});continue}s++,o+=a.bytes}}var Vs=class extends W{constructor(n,r){super(`this run's results are ${Math.ceil(n/1024**2)} MB, over --max-download ${Math.round(r/1024**2)} MB. Run again with a higher --max-download to download them`,"too-large");this.sizeBytes=n}sizeBytes};function yl(e,t,n,r={}){ch(n);let s=r.env??process.env,o=hl(e,t,r.provider),a=rh(e,t,o,n,s,r.allowFork===!0);if(a.status!=="completed")return{run:a,artifacts:[],reasonKind:"running",reason:`run ${n} has not finished: its results are uploaded when it does`};let i=oh(e,t,o,n,s),c=i.filter(S=>!S.expired),l=c.map(({name:S,sizeBytes:y})=>({name:S,sizeBytes:y})),d=lh(e,o,n,a.attempt),f=new Date;if(Oe.existsSync(d))return Oe.utimesSync(le.dirname(d),f,f),{run:a,folder:d,cached:!0,artifacts:l};if(c.length===0)return i.length>0?{run:a,artifacts:l,reasonKind:"expired",reason:`run ${n}'s Saffron bundle expired: the service keeps artifacts for a limited time`}:{run:a,artifacts:l,reasonKind:"none",reason:`run ${n} uploaded no Saffron bundle. The guide's workflow exports only when a run fails; set if: always() on the export and upload steps to keep every run's results`};let p=c.reduce((S,y)=>S+y.sizeBytes,0);if(r.maxDownloadBytes!==void 0&&p>r.maxDownloadBytes)throw new Vs(p,r.maxDownloadBytes);let u=wl(e);Oe.mkdirSync(u,{recursive:!0});let h=le.join(u,".gitignore");Oe.existsSync(h)||Oe.writeFileSync(h,`*
|
|
1337
|
-
`),
|
|
1338
|
-
`).map(t=>t.trim()).find(Boolean);async function
|
|
1339
|
-
`),
|
|
1340
|
-
`).slice(-3).join(" ")}`);return e.stdout}function
|
|
1336
|
+
`}var PS=["github","azure"],Qi={github:"GitHub Actions",azure:"Azure Pipelines"};function Dh(e,t){let n={full:"results",summary:"summary only",expired:"results expired",none:"no results uploaded",running:"still running"}[e];if(!t)return n;let r=t/1024**2;return`${n}, ${r<1?"under 1":Math.round(r)} MB`}function cs(e){if(e.startsWith("@")||/[\x00-\x1f\x7f]/.test(e))throw new G(`${JSON.stringify(e)} is not a branch name Saffron passes on`);return e}function IS(e){let t=e.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\*)$/,"$1$1");return t=`"${t}"`,t=t.replace(/[()%!^"<>&|;, ]/g,"^$&"),t.replace(/[()%!^"<>&|;, ]/g,"^$&")}function Ve(e,t,n,r,s){let o=process.platform==="win32"&&e==="az",a=o?Mh("az.cmd",t.map(IS),{cwd:n,env:r,input:s,encoding:"utf8",shell:!0,windowsVerbatimArguments:!0,timeout:6e5,maxBuffer:64*1024*1024}):Mh(e,t,{cwd:n,env:r,input:s,encoding:"utf8",timeout:6e5,maxBuffer:64*1024*1024}),i=a.error?.code,c=i==="ENOENT"||o&&a.status===9009;return{status:a.status,stdout:(a.stdout??"").trim(),stderr:(a.stderr??"").trim(),missing:c,timedOut:i==="ETIMEDOUT"}}var oo=e=>`${e.stderr}
|
|
1337
|
+
${e.stdout}`,Bl=(e,t)=>oo(e).split(`
|
|
1338
|
+
`).map(n=>n.trim()).find(n=>n&&!/^WARNING:/.test(n))??t;function ls(e){return e.missing?{kind:"missing-tool",message:"the GitHub CLI (gh) is not installed here: install it from cli.github.com and sign in with gh auth login"}:e.timedOut?{kind:"failed",message:"gh did not finish within 10 minutes"}:/gh auth login|not logged in|authentication required/i.test(oo(e))?{kind:"signed-out",message:"gh is not signed in: run gh auth login"}:/none of the git remotes|no git remotes|not a git repository/i.test(oo(e))?{kind:"not-a-repository",message:Bl(e,"not a GitHub repository")}:{kind:"failed",message:Bl(e,`gh exited with ${e.status}`)}}function kr(e){if(e.missing)return{kind:"missing-tool",message:"the Azure CLI (az) is not installed here: install it, add its azure-devops extension (az extension add --name azure-devops) and sign in (az login, or AZURE_DEVOPS_EXT_PAT)"};if(e.timedOut)return{kind:"failed",message:"az did not finish within 10 minutes"};let t=oo(e);return/azure-devops|'pipelines' is (misspelled|not in)|not in the 'az' command group/i.test(t)&&!/login/i.test(t)?{kind:"missing-tool",message:"the Azure CLI has no azure-devops extension: az extension add --name azure-devops"}:/az login|az devops login|TF400813|not authorized|authentication failed|\b401\b/i.test(t)?{kind:"signed-out",message:"az is not signed in to Azure DevOps: run az login, or set AZURE_DEVOPS_EXT_PAT"}:/--organization|--org\b|--project|must be specified|could not detect/i.test(t)?{kind:"not-a-repository",message:"cannot tell which Azure DevOps organization and project: run this in a clone of an Azure Repos repository, or set ci.organization and ci.project in saffron.config.json"}:{kind:"failed",message:Bl(e,`az exited with ${e.status}`)}}function ql(e,t,n){let r=n??t.ci?.provider;if(r!==void 0){if(!PS.includes(r))throw new G(`unknown CI provider "${r}": use "github" or "azure"`);return r}return ki(e).some(s=>s.startsWith("dev.azure.com/"))?"azure":"github"}var ao=e=>[...e.ci?.organization?["--organization",e.ci.organization]:[],...e.ci?.project?["--project",e.ci.project]:[]];function jS(e,t){let n=Ve("git",["rev-parse","--abbrev-ref","HEAD"],e,t),r=n.status===0?n.stdout.trim():"";return r&&r!=="HEAD"?r:void 0}function NS(e){let t=new Map;for(let[n,r]of Object.entries(En(e))){try{if(jt(ge.join(e,n))!==r.revision)continue}catch{continue}r.from.run&&t.set(r.from.run,(t.get(r.from.run)??0)+1)}return t}function Bh(e,t=Date.now()){let n=e?t-Date.parse(e):NaN;if(!(n>=0))return;let r=Math.round(n/6e4);if(r<60)return`${r} min ago`;let s=Math.round(r/60);return s<48?`${s} h ago`:`${Math.round(s/24)} days ago`}var ie=e=>typeof e=="string"&&e?e:void 0,Fh=e=>ie(e)?.replace(/^refs\/(heads|tags)\//,""),Lh="databaseId,number,attempt,displayTitle,workflowName,status,conclusion,event,headBranch,headSha,createdAt,startedAt,url";function MS(e){let t=e.status==="completed"?"completed":e.status==="in_progress"?"in_progress":"queued";return{id:String(e.databaseId),name:ie(e.workflowName)??"workflow",number:String(e.number??""),title:ie(e.displayTitle),status:t,conclusion:t==="completed"?ie(e.conclusion):void 0,event:ie(e.event),branch:ie(e.headBranch),commit:ie(e.headSha),createdAt:ie(e.createdAt),url:ie(e.url),attempt:typeof e.attempt=="number"?e.attempt:void 0}}var DS={completed:"completed",inProgress:"in_progress",cancelling:"in_progress"},FS={succeeded:"success",partiallySucceeded:"partial",failed:"failure",canceled:"cancelled"},LS={individualCI:"push",batchedCI:"push",pullRequest:"pull_request",schedule:"schedule",manual:"manual"};function Uh(e){let t=e.triggerInfo??{};return Fh(t["pr.sourceBranch"])??Fh(e.sourceBranch)}function zh(e){let t=e.triggerInfo??{},n=DS[String(e.status)]??"queued",r=ie(e.result);return{id:String(e.id),name:ie(e.definition?.name)??"pipeline",number:String(e.buildNumber??e.id),status:n,conclusion:n==="completed"&&r?FS[r]??r:void 0,event:ie(e.reason)?LS[String(e.reason)]??String(e.reason):void 0,branch:Uh(e),commit:ie(t["pr.sourceSha"])??ie(e.sourceVersion),createdAt:ie(e.queueTime),url:ie((e._links??{}).web?.href)}}function Zi(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function Hl(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>!!n&&typeof n=="object"):void 0}catch{return}}function BS(e){return new Set(e.map(t=>t.startsWith("dev.azure.com/")?t.slice(t.lastIndexOf("/_git/")+6):t.slice(t.indexOf("/")+1)))}function US(e,t,n,r,s,o,a=Math.min(Math.max(o,50),500)){for(let i=a;;i=Math.min(i*2,500)){let c=Ve("az",["pipelines","runs","list","--top",String(i),...r,"--output","json",...ao(t)],e,n);if(c.missing||c.status!==0)return kr(c);let l=Hl(c.stdout);if(!l)return{kind:"failed",message:"az answered with something other than a list of runs"};let d=l.filter(s);if(d.length>=o||l.length<i||i>=500)return d}}function qh(e,t,n={}){let r=n.env??process.env,s=ql(e,t,n.provider),o=n.branch??jS(e,r),a=o===void 0?void 0:cs(o),i=n.limit??20,c,l=new Map;if(s==="github"){let p=y=>Ve("gh",["run","list","--limit",String(i),"--json",y,...a?["--branch",a]:[]],e,r),f=p(Lh);if(!f.missing&&f.status!==0&&/startedAt/.test(`${f.stderr??""}${f.stdout??""}`)&&(f=p(Lh.replace(",startedAt",""))),f.missing||f.status!==0)return{provider:s,branch:a,runs:[],problem:ls(f)};let g=Hl(f.stdout);if(!g)return{provider:s,branch:a,runs:[],problem:{kind:"failed",message:"gh answered with something other than a list of runs"}};c=g.map(MS);for(let y of g)l.set(String(y.databaseId),Date.parse(ie(y.startedAt)??""))}else{let p=BS(ki(e)),f=S=>{let v=ie(S.repository?.name)?.toLowerCase();return p.size===0||!v||p.has(v)},g=S=>f(S)&&(!a||Uh(S)===a),y=a?[["--branch",`refs/heads/${a}`],["--branch",`refs/tags/${a}`],["--reason","pullRequest"]]:[[]],h=new Map;for(let S of y){let v=US(e,t,r,S,g,i);if(!Array.isArray(v))return{provider:s,branch:a,runs:[],problem:v};for(let x of v)h.set(String(x.id),x)}c=[...h.values()].sort((S,v)=>(Date.parse(ie(v.queueTime)??"")||0)-(Date.parse(ie(S.queueTime)??"")||0)).slice(0,i).map(zh)}let d=NS(e),u=s==="github"?zS(e,r,c,l):new Map;return{provider:s,branch:a,runs:c.map(p=>{let f=u.get(p.id);return{...p,pending:d.get(`${s}:${p.id}`)??0,...f?{results:f}:{}}})}}function zS(e,t,n,r){let s=new Map;for(let d of n)d.status!=="completed"&&s.set(d.id,{kind:"running",label:Dh("running")});let o=n.filter(d=>d.status==="completed");if(o.length===0)return s;let a=Math.min(...o.map(d=>Date.parse(d.createdAt??"")||0)),i=new Map,c=!1;for(let d=1;d<=5&&!c;d++){let u=Ve("gh",["api",`repos/{owner}/{repo}/actions/artifacts?per_page=100&page=${d}`],e,t),p=u.missing||u.status!==0?void 0:Zi(u.stdout)?.artifacts;if(!Array.isArray(p))break;for(let f of p.filter(g=>!!g&&typeof g=="object")){let g=String((f.workflow_run??{}).id??"");g&&i.set(g,[...i.get(g)??[],f]);let y=Date.parse(ie(f.created_at)??"");!Number.isNaN(y)&&y<a&&(c=!0)}p.length<100&&(c=!0)}let l=d=>d.reduce((u,p)=>u+(Number(p.size_in_bytes)||0),0);for(let d of o){let u=qS(i.get(d.id)??[],(d.attempt??1)>1?r.get(d.id):void 0),p=S=>u.filter(v=>typeof v.name=="string"&&S.test(v.name)),f=p(Jh),g=p(zl),y=S=>S.filter(v=>v.expired!==!0),h=(S,v)=>s.set(d.id,{kind:S,...v!==void 0?{sizeBytes:v}:{},label:Dh(S,v)});y(f).length>0?h("full",l(y(f))):y(g).length>0?h("summary",l(y(g))):f.length+g.length>0?h("expired"):c&&h("none")}return s}function qS(e,t){if(t===void 0||Number.isNaN(t))return e;let n=o=>String(o.name).replace(/^saffron-(bundle|summary)/,""),r=o=>Date.parse(ie(o.created_at)??"")>=t,s=new Set(e.filter(r).map(n));return e.filter(o=>r(o)||!s.has(n(o)))}var Ul=e=>`run ${e} has no Saffron bundle: none was uploaded, or it expired. Its workflow needs saffron export and an upload of saffron-bundle* (see the guide, section 19)`;function Hh(e,t,n,r,s,o){let a,i;if(n==="github"){let c=Ve("gh",["api",`repos/{owner}/{repo}/actions/runs/${r}`],e,s);if(c.missing||c.status!==0)throw new G(ls(c).message,ls(c).kind);let l=Zi(c.stdout),d=ie(l?.repository?.full_name);if(!l||String(l.id)!==r||!d)throw new G(`gh answered with something other than run ${r}`);let u=ie(l.head_repository?.full_name);u?.toLowerCase()!==d.toLowerCase()&&(a={event:ie(l.event),from:u});let p=l.status==="completed"?"completed":l.status==="in_progress"?"in_progress":"queued";i={provider:n,id:r,attempt:typeof l.run_attempt=="number"?l.run_attempt:1,name:ie(l.name),branch:ie(l.head_branch),commit:ie(l.head_sha),url:ie(l.html_url),status:p,conclusion:p==="completed"?ie(l.conclusion):void 0,createdAt:ie(l.created_at)}}else{let c=Ve("az",["pipelines","runs","show","--id",r,"--output","json",...ao(t)],e,s);if(c.missing||c.status!==0)throw new G(kr(c).message,kr(c).kind);let l=Zi(c.stdout);if(!l||String(l.id)!==r)throw new G(`az answered with something other than run ${r}`);let d=zh(l);/^true$/i.test(String((l.triggerInfo??{})["pr.isFork"]))&&(a={event:d.event}),i={provider:n,id:r,attempt:1,name:d.name,branch:d.branch,commit:d.commit,url:d.url,status:d.status,conclusion:d.conclusion,createdAt:d.createdAt}}if(a&&!o)throw new G(`run ${r}${a.event?` (${a.event})`:""} comes from ${a.from?`the fork ${a.from}`:"a fork"}: code from outside this repository made its bundle, and could have put anything in it. Read that pull request, then import with --allow-fork if you trust it`,"fork");return i}var Jh=/^saffron-bundle[\w.-]*$/,zl=/^saffron-summary[\w.-]*$/;function Vh(e,t,n,r,s){let o;if(n==="github"){o=[];for(let a=1;o;a++){let i=Ve("gh",["api",`repos/{owner}/{repo}/actions/runs/${r}/artifacts?per_page=100&page=${a}`],e,s);if(i.missing||i.status!==0)throw new G(ls(i).message,ls(i).kind);let c=Zi(i.stdout)?.artifacts;if(!Array.isArray(c))o=void 0;else if(o.push(...c.filter(l=>!!l&&typeof l=="object")),c.length<100)break}}else{let a=Ve("az",["pipelines","runs","artifact","list","--run-id",r,"--output","json",...ao(t)],e,s);if(a.missing||a.status!==0)throw new G(kr(a).message,kr(a).kind);o=Hl(a.stdout)}if(!o)throw new G(`${n==="github"?"gh":"az"} answered with something other than a list of artifacts`);return o.filter(a=>typeof a.name=="string"&&(Jh.test(a.name)||zl.test(a.name))).map(a=>({name:a.name,sizeBytes:Number(a.size_in_bytes??((a.resource??{}).properties??{}).artifactsize)||0,expired:a.expired===!0,summary:zl.test(a.name)}))}function Wh(e,t,n,r,s,o,a){if(a.length===0)throw new G(Ul(r));for(let i of a){let c=n==="github"?Ve("gh",["run","download",r,"-n",i,"--dir",ge.join(s,i)],e,o):Ve("az",["pipelines","runs","artifact","download","--run-id",r,"--artifact-name",i,"--path",ge.join(s,i),...ao(t)],e,o);if(c.missing||c.status!==0)throw n==="github"&&/no (valid )?artifact/i.test(oo(c))?new G(Ul(r)):new G(`cannot download ${i}: ${(n==="github"?ls(c):kr(c)).message}`)}}function Gh(e,t,n,r={}){Kh(n);let s=r.env??process.env,o=ql(e,t,r.provider),a=Hh(e,t,o,n,s,r.allowFork===!0),i=Yh(e,o,n,a.attempt);if(a.status==="completed"&&je.existsSync(i))return{provider:o,dir:ge.join(i,"bundles"),remove:()=>{}};let c=Vh(e,t,o,n,s).filter(u=>!u.expired).map(u=>u.name);if(c.length===0)throw new G(Ul(n));let{dir:l,remove:d}=ol(e);try{return Wh(e,t,o,n,l,s,c),{provider:o,dir:l,remove:d}}catch(u){throw d(),u}}function Kh(e){if(!/^\d+$/.test(e))throw new G(`--run takes the run's id, a number as saffron runs lists it, not "${e}"`)}var Jl=e=>ge.join(e,".saffron","ci"),Yh=(e,t,n,r)=>ge.join(Jl(e),`${t}-${n}`,`attempt-${r}`),HS=10,JS=1024**3;function VS(e){let t=0;for(let n of je.readdirSync(e,{recursive:!0})){let r=je.lstatSync(ge.join(e,String(n)),{throwIfNoEntry:!1});r?.isFile()&&(t+=r.size)}return t}function WS(e,t){let n=Jl(e),r=je.readdirSync(n,{withFileTypes:!0}).filter(a=>a.isDirectory()).map(a=>ge.join(n,a.name)).map(a=>({run:a,mtime:je.statSync(a).mtimeMs,bytes:VS(a)})).sort((a,i)=>+(i.run===t)-+(a.run===t)||i.mtime-a.mtime),s=0,o=0;for(let a of r){if(a.run!==t&&(s+1>HS||o+a.bytes>JS)){je.rmSync(a.run,{recursive:!0,force:!0});continue}s++,o+=a.bytes}}var io=class extends G{constructor(n,r){super(`this run's results are ${Math.ceil(n/1024**2)} MB, over --max-download ${Math.round(r/1024**2)} MB. Run again with a higher --max-download to download them`,"too-large");this.sizeBytes=n}sizeBytes};function Vl(e,t,n,r={}){Kh(n);let s=r.env??process.env,o=ql(e,t,r.provider),a=Hh(e,t,o,n,s,r.allowFork===!0);if(a.status!=="completed")return{run:a,artifacts:[],reasonKind:"running",reason:`run ${n} has not finished: its results are uploaded when it does`};let i=Vh(e,t,o,n,s),c=i.filter(S=>!S.expired),l=c.map(({name:S,sizeBytes:v})=>({name:S,sizeBytes:v})),d=Yh(e,o,n,a.attempt),u=new Date;if(je.existsSync(d))return je.utimesSync(ge.dirname(d),u,u),{run:a,folder:d,cached:!0,artifacts:l};if(c.length===0)return i.length>0?{run:a,artifacts:l,reasonKind:"expired",reason:`run ${n}'s Saffron bundle expired: the service keeps artifacts for a limited time`}:{run:a,artifacts:l,reasonKind:"none",reason:`run ${n} uploaded no Saffron bundle. The guide's workflow exports only when a run fails; set if: always() on the export and upload steps to keep every run's results`};let p=c.reduce((S,v)=>S+v.sizeBytes,0);if(r.maxDownloadBytes!==void 0&&p>r.maxDownloadBytes)throw new io(p,r.maxDownloadBytes);let f=Jl(e);je.mkdirSync(f,{recursive:!0});let g=ge.join(f,".gitignore");je.existsSync(g)||je.writeFileSync(g,`*
|
|
1339
|
+
`),je.mkdirSync(ge.dirname(d),{recursive:!0});let y=je.mkdtempSync(`${d}.partial-`);try{Wh(e,t,o,n,ge.join(y,"bundles"),s,c.map(S=>S.name));try{je.renameSync(y,d)}catch(S){if(!je.existsSync(d))throw S;return je.utimesSync(ge.dirname(d),u,u),{run:a,folder:d,cached:!0,artifacts:l}}}finally{je.rmSync(y,{recursive:!0,force:!0})}let h=Date.now()-1440*60*1e3;for(let S of je.readdirSync(ge.dirname(d))){let v=ge.join(ge.dirname(d),S),x=/^attempt-(\d+)$/.exec(S),b=/^attempt-\d+\.partial$/.test(S)||/^attempt-\d+\.partial-/.test(S)&&(je.statSync(v,{throwIfNoEntry:!1})?.mtimeMs??1/0)<h;(x&&Number(x[1])<a.attempt||b)&&je.rmSync(v,{recursive:!0,force:!0})}return je.utimesSync(ge.dirname(d),u,u),WS(e,ge.dirname(d)),{run:a,folder:d,cached:!1,artifacts:l}}async function Wl(e,t,n){let{run:r,folder:s}=t;return Wp(e,s,[ge.join(s,"bundles")],n,{run:`${r.provider}:${r.id}`,describe:o=>`${Qi[r.provider]} run ${r.id} (${ge.basename(ge.dirname(o))})`})}var GS=e=>e?.split(`
|
|
1340
|
+
`).map(t=>t.trim()).find(Boolean);async function Zh(e,t,n,r,s={}){let o=Vl(e,t,r,s);if(!o.folder)return{results:{run:o.run,bundle:null,reasonKind:o.reasonKind,reason:o.reason,warnings:[]}};let a=o.folder,i=await Wl(e,{...o,folder:a},n),c=f=>He(e,ge.join(a,f)),l={run:o.run,bundle:{folder:He(e,a),cached:o.cached===!0,artifacts:o.artifacts,...i.summaryOnly?{summaryOnly:!0}:{}},warnings:i.warnings},{report:d}=i;if(d){let{green:f,yellow:g,red:y,aiCalls:h,costUsd:S}=d.totals;l.totals={green:f,yellow:g,red:y,aiCalls:h,costUsd:S},d.interrupted&&Object.assign(l,{interrupted:!0,notRun:d.notRun??0}),d.browsers?.length&&(l.browsers=d.browsers),l.scenarios=d.scenarios.map(v=>{let x=(v.evidence??[]).filter(R=>R.kind==="trace"?It(ge.join(a,".saffron","artifacts"),ge.join(a,R.file)):qn(a,R)!==void 0),b=x.filter(R=>R.kind!=="trace"),m=b.find(R=>R.kind==="failure")??b.find(R=>R.kind==="before-heal")??b[0],$=x.filter(R=>R.kind==="trace"),T=$.find(R=>!R.proof)??$[0];return{feature:v.feature,scenario:ur(v),displayName:v.scenario,tags:v.tags,status:v.status,durationMs:v.durationMs,verified:v.verified,failingStep:v.steps.find(R=>R.status==="failed")?.gherkin,error:GS(v.error),narrative:v.narrative,screenshot:m&&c(m.file),trace:T&&c(T.file),...v.browser?{browser:v.browser}:{}}}),Ue(ge.join(a,"report.json"),`${JSON.stringify(d,null,2)}
|
|
1341
|
+
`),Ue(ge.join(a,"report.html"),Gn(d,a)),l.reportHtml=c("report.html")}else l.scenarios=[];l.proposals=i.proposals,Ue(ge.join(a,"panel.html"),Yi(l,e,ut())),l.panelHtml=c("panel.html");let{warnings:u,...p}=l;return{results:{...p,warnings:u},report:d}}function Qh(e,t,n,r){let s=Ve("az",["repos","pr","create","--draft","true","--source-branch",`refs/heads/${cs(n.branch)}`,"--target-branch",`refs/heads/${cs(n.base)}`,"--title",n.title,"--description",`@${n.bodyFile}`,"--output","json",...ao(t)],e,r);if(s.missing||s.status!==0)return{problem:`az repos pr create failed: ${kr(s).message}`};try{let o=JSON.parse(s.stdout),a=o.repository?.webUrl;return{url:a&&o.pullRequestId!==void 0?`${a}/pullrequest/${o.pullRequestId}`:void 0}}catch{return{}}}function em(e,t,n){if(e.missing)throw new G(`${n}: ${t} is not installed here`);if(e.timedOut)throw new G(`${n}: ${t} did not finish within 10 minutes`);if(e.status!==0)throw new G(`${n}: ${(e.stderr||e.stdout||`exit ${e.status}`).split(`
|
|
1342
|
+
`).slice(-3).join(" ")}`);return e.stdout}function KS(e,t){let n=a=>Ve("git",["config",a],e,t).stdout,r=t.GIT_AUTHOR_NAME||n("user.name"),s=t.GIT_AUTHOR_EMAIL||n("user.email"),o=t.GITHUB_ACTIONS==="true"?{name:"github-actions[bot]",email:"41898282+github-actions[bot]@users.noreply.github.com"}:{name:"Saffron",email:"saffron@localhost"};return{...t,GIT_AUTHOR_NAME:r||o.name,GIT_AUTHOR_EMAIL:s||o.email,GIT_COMMITTER_NAME:t.GIT_COMMITTER_NAME||r||o.name,GIT_COMMITTER_EMAIL:t.GIT_COMMITTER_EMAIL||s||o.email}}var Xi=(e,t)=>`${e} ${t}${e===1?"":"s"}`,co=e=>`\`${e.replaceAll("`","'")}\``,Gl=e=>{let t=e.startsWith("-")?`./${e}`:e;return/^[\w./-]+$/.test(t)?t:`'${t.replaceAll("'","'\\''")}'`};function Kl(e,t=""){let n=Math.max(0,...[...e.matchAll(/`+/g)].map(s=>s[0].length)),r="`".repeat(Math.max(3,n+1));return`${r}${t}
|
|
1341
1343
|
${e}
|
|
1342
|
-
${r}`}var
|
|
1343
|
-
`),"bash"),"","Then mark this pull request ready for review. `accept --all` leaves UNVERIFIED proposals out: read one, and accept it by file if it is right. `saffron accept` refuses a proposal whose scenario or recording changed since it was filed."],
|
|
1344
|
-
`).length;for(let[p,{proposal:
|
|
1345
|
-
`),
|
|
1346
|
-
`);if(
|
|
1344
|
+
${r}`}var nm={github:6e4,azure:3800};function YS(e,t,n,r="",s=nm.github){let{manifest:o,proposals:a}=t,i=o.run?o.url&&/^https?:\/\//i.test(o.url)?`[run ${o.run}](${o.url})`:`run ${co(o.run)}`:"a run",c=o.headCommit??o.commit,l=[o.branch&&`on ${co(o.branch)}`,c&&`at ${co(c.slice(0,7))}`].filter(Boolean).join(" "),d=[`Saffron filed ${Xi(a.length,"proposal")} in ${i}${l?` ${l}`:""}. This pull request carries ${a.length===1?"the proposal, not the recording":"the proposals, not the recordings"}: nothing is accepted until you accept it.`,"","**To review and accept** (no agent runs on your machine):","",Kl([`git fetch origin ${Gl(n)} && git switch ${Gl(n)}`,...r?[`cd ${Gl(r.replace(/\/$/,""))}`]:[],"npx -y -p saffron-ai saffron diff","npx -y -p saffron-ai saffron accept --all",'git add -A .saffron/cache && git add -u .saffron/proposals && git commit -m "Accept Saffron proposals" && git push'].join(`
|
|
1345
|
+
`),"bash"),"","Then mark this pull request ready for review. `accept --all` leaves UNVERIFIED proposals out: read one, and accept it by file if it is right. `saffron accept` refuses a proposal whose scenario or recording changed since it was filed."],u=d.join(`
|
|
1346
|
+
`).length;for(let[p,{proposal:f}]of a.entries()){let{feature:g,scenario:y}=f.cache,{mode:h,verified:S,proofError:v,narrative:x,adaptations:b}=f.meta,m=S===!0?"**verified \u2713**: a zero-AI proof replay passed":S===!1?"**UNVERIFIED \u2717**: its proof replay failed":"not verified: proof replays were off",$=[x,...b.map(k=>`\u26A0 ${k}`),...S===!1&&v?[`Proof replay: ${v}`]:[]].filter(Boolean).join(`
|
|
1347
|
+
`),T=Wo(Hn(tn(pe(e,g,y)),f.cache,f.meta.featureEdits)),R=["",`### ${co(g)} \u203A ${co(y)}`,"",`${h==="heal"?"Heal":"First recording"}, ${m}`,"",...$?[Kl($,"text"),""]:[],Kl(T,"diff")].join(`
|
|
1348
|
+
`);if(u+R.length>s){d.push("",`\u2026and ${Xi(a.length-p,"more proposal")}: run \`saffron diff\` on the branch to see ${a.length-p===1?"it":"them"}.`);break}d.push(R),u+=R.length+1}return`${d.join(`
|
|
1347
1349
|
`)}
|
|
1348
|
-
`}var
|
|
1349
|
-
`)[0]:String(
|
|
1350
|
-
`)}function
|
|
1351
|
-
`).slice(-2).join(" ")}`,failed:!0}:{...
|
|
1352
|
-
`).pop()}}import X from"node:fs";import re from"node:path";var
|
|
1353
|
-
`)}function
|
|
1350
|
+
`}var Yl=e=>e.split(/[\\/]/).join("/");function ZS(e,t,n,r,s,o){let a=Bt.mkdtempSync(Pe.join(tm.tmpdir(),"saffron-head-")),i=g=>{let y=Xh("git",["show",`${n}:${r}${Yl(g)}`],{cwd:e,env:s,timeout:6e5,maxBuffer:67108864});return y.status===0?y.stdout:void 0},c=g=>{let y=Pe.relative(e,Pe.resolve(e,g));return!y.startsWith("..")&&!Pe.isAbsolute(y)?Yl(y):void 0},l=c(o.features??"features"),d=c(o.dataDir??"data"),u=Xh("git",["ls-tree","-r","-z","--full-tree","--name-only",n,"--",...[l,d].flatMap(g=>g===void 0?[]:[`${r}${g}`||"."])],{cwd:e,env:s,encoding:"utf8",timeout:6e5,maxBuffer:64*1024*1024}),p=it(),f=[];try{for(let y of(l!==void 0||d!==void 0)&&u.status===0?u.stdout.split("\0").filter(Boolean):[]){let h=y.slice(r.length);if(!(d!==void 0&&(d===""||h.startsWith(`${d}/`)))&&!h.endsWith(".saffron"))continue;let v=i(h);v!==void 0&&(Bt.mkdirSync(Pe.dirname(Pe.join(a,h)),{recursive:!0}),Bt.writeFileSync(Pe.join(a,h),v))}d!==void 0&&Ut(a,d,p.env);let g;try{g=mt(a,o,[])}catch(y){let h=`cannot be checked: the StepSets at ${n.slice(0,7)} do not parse: ${y instanceof Error?y.message.split(`
|
|
1351
|
+
`)[0]:String(y)}`;return t.proposals.map(({file:S})=>({file:S,reason:h}))}for(let{file:y,proposal:h}of t.proposals){let{feature:S,scenario:v}=h.cache,x=i(S);if(!x){f.push({file:y,reason:`is for ${S}, which is not in ${n.slice(0,7)}`});continue}Bt.mkdirSync(Pe.dirname(Pe.join(a,S)),{recursive:!0}),Bt.writeFileSync(Pe.join(a,S),x);let b=Yl(Pe.relative(e,pe(e,S,v))),m=i(b);Bt.rmSync(Pe.join(a,b),{force:!0}),m&&(Bt.mkdirSync(Pe.dirname(Pe.join(a,b)),{recursive:!0}),Bt.writeFileSync(Pe.join(a,b),m));let $;try{$=At(a,h,g)}catch(T){$=`cannot be checked: ${T instanceof Error?T.message:String(T)}`}$&&f.push({file:y,reason:`does not fit ${n.slice(0,7)}: ${$}`})}}finally{d!==void 0&&Ut(e,p.dir,p.env),Bt.rmSync(a,{recursive:!0,force:!0})}return f}function QS(e){let{manifest:t,proposals:n}=e;return[`Saffron: ${Xi(n.length,"proposal")} to review${t.run?` from run ${t.run}`:""}`,"",...n.map(({proposal:r})=>`${r.cache.feature} \u203A ${r.cache.scenario} (${r.meta.mode}${r.meta.verified===!0?", verified":r.meta.verified===!1?", UNVERIFIED":""})`),"","Proposals only: nothing is accepted until someone runs saffron accept."].join(`
|
|
1352
|
+
`)}function lo(e,t){if(t!==void 0&&/[$`;|&<>()\s'"\\]/.test(t))throw new G(`${e} ${JSON.stringify(t)}: a branch name with a space, a quote or any of $ \` ; | & < > ( ) \\ is not accepted, as the pull request gives it to a shell`)}function rm(e,t,n,r={}){let s=r.env??process.env,o=($,T,R={})=>em(Ve("git",T,e,R.env??s,R.input),"git",$),{manifest:a}=t;if(t.proposals.length===0)throw new G("there are no pending proposals to push");let i=r.base??a.branch;if(!i)throw new G("cannot tell which branch the pull request is for: pass --base <branch>");if(cs(i),cs(n),lo("--branch",n),lo("--base",r.base),n===i)throw new G(`--branch ${n} is the branch the proposals are for: name a new one, e.g. saffron/heal-<run id>`);if(n.startsWith("-"))throw new G(`${n} is not a branch name git accepts`);o(`${n} is not a branch name git accepts`,["check-ref-format","--branch",n]);let c=a.headCommit??a.commit;if(!c||!/^[0-9a-f]{40}([0-9a-f]{24})?$/i.test(c))throw new G("cannot tell which commit the run tested: run it in a git checkout");let l=o("not a git checkout",["rev-parse","HEAD"]);if(c!==l&&!rl(e,l).includes(c)&&Ve("git",["merge-base","--is-ancestor",c,l],e,s).status!==0)throw new G(`${c.slice(0,7)}, the commit the branch would start on, is not this checkout's HEAD, a commit it merged or one it descends from: run export --branch in the checkout the run tested`);Ve("git",["cat-file","-e",`${c}^{commit}`],e,s).status!==0&&o(`the commit to build on, ${c.slice(0,7)}, is not in this clone and could not be fetched`,["fetch","--quiet","--no-tags","--depth=1","origin",c]);let d=Ve("git",["ls-remote","--exit-code","--heads","origin",`refs/heads/${n}`],e,s);if(d.status===0)throw new G(`branch ${n} already exists on origin: give each run its own, e.g. saffron/heal-<run id>-<attempt>`);d.status!==2&&em(d,"git","cannot reach origin");let u=o("not a git checkout",["rev-parse","--show-prefix"]),p=ZS(e,t,c,u,s,r.config??{}),f={...t,proposals:t.proposals.filter($=>!p.some(T=>T.file===$.file))};if(f.proposals.length===0)throw new G(`no proposal fits ${c.slice(0,7)}, the commit the branch would start on: ${p.map($=>`${Pe.relative(e,$.file)} ${$.reason}`).join("; ")}`);let g=Bt.mkdtempSync(Pe.join(tm.tmpdir(),"saffron-index-")),y={...s,GIT_INDEX_FILE:Pe.join(g,"index")},h;try{o("cannot read the tested commit",["read-tree",c],{env:y});for(let{file:T,bytes:R}of f.proposals){let k=o("cannot store a proposal",["hash-object","-w","--stdin"],{input:R}),C=`${u}${Pe.relative(e,T).split(Pe.sep).join("/")}`;o("cannot stage a proposal",["update-index","--add","--cacheinfo",`100644,${k},${C}`],{env:y})}let $=o("cannot write the tree",["write-tree"],{env:y});h=o("cannot commit the proposals",["commit-tree",$,"-p",c,"-m",QS(f)],{env:KS(e,s)})}finally{Bt.rmSync(g,{recursive:!0,force:!0})}o(`cannot push ${n} to origin`,["push","--quiet","origin",`${h}:refs/heads/${n}`]);let S=a.repository?.startsWith("github.com/")?"github":a.repository?.startsWith("dev.azure.com/")?"azure":s.GITHUB_ACTIONS==="true"?"github":s.TF_BUILD==="True"?"azure":void 0,v=Pe.join(Pe.dirname(f.file),"saffron-pull-request.md");Bt.writeFileSync(v,YS(e,f,n,u,nm[S??"github"]));let x={branch:n,base:i,commit:h,parent:c,bodyFile:v,leftOut:p};if(!S)return{...x,noPullRequest:`${a.repository??"this repository"} is not on GitHub or Azure DevOps`};let b=`Saffron: ${Xi(f.proposals.length,"proposal")} to review for ${i}`;if(S==="azure"){let $=Qh(e,r.config??{},{branch:n,base:i,title:b,bodyFile:v},s);return $.problem?{...x,noPullRequest:$.problem,failed:!0}:$.url?{...x,pullRequest:$.url}:{...x,noPullRequest:"az created it but did not say where",failed:!0}}let m=Ve("gh",["pr","create","--draft","--base",i,"--head",n,"--title",b,"--body-file",v],e,s);return m.missing?{...x,noPullRequest:"the gh CLI is not installed here",failed:!0}:m.status!==0?{...x,noPullRequest:`gh pr create failed: ${(m.stderr||m.stdout).split(`
|
|
1353
|
+
`).slice(-2).join(" ")}`,failed:!0}:{...x,pullRequest:m.stdout.split(`
|
|
1354
|
+
`).pop()}}import X from"node:fs";import re from"node:path";var uo={claude:".claude/skills",agents:".agents/skills",copilot:".github/skills",cursor:".cursor/skills"},XS=["claude","agents"],im="<!-- saffron:start -->",Ql="<!-- saffron:end -->";function e$(){return[im,"## Saffron end-to-end tests","","UI tests are plain-language `.feature` / `.saffron` files under `features/`,","run by Saffron (`npx saffron run`). No step definitions exist: an AI agent","records each scenario once; later runs replay at zero tokens.","","- Exact step text is the recording's identity: run `npx saffron steps` and"," reuse recorded wordings instead of inventing synonyms.","- `Then` steps are never healed: write them as the verdict, last.","- Never hand-edit `.saffron/cache/` or `.saffron/proposals/`; change the"," scenario text and re-run. Review with `npx saffron accept` / `reject`.","- Secrets only as `{env:VAR}` tokens, never in files or `data/`.","","When asked to create, translate, or edit Saffron scenarios in `.saffron`","or `.feature` files, load the `saffron` skill and follow its authoring","workflow: inspect the relevant UI, reuse recorded vocabulary, name","captures explicitly, and use observable waits and final assertions.","A working test requires reviewing its verified proposal and passing","the affected scenarios with `--no-agent`. For draft-only requests or","unavailable execution, report the validation still needed.","","This authoring workflow does not apply to ordinary application changes","or requests only to run tests, inspect reports, review proposals, or","configure Saffron. Never hand-edit generated caches or proposals to","make a test pass.",Ql,""].join(`
|
|
1355
|
+
`)}function sm(e,t){if(!X.existsSync(e))return X.writeFileSync(e,t),"created";let n=X.readFileSync(e,"utf8"),r=n.indexOf(im),s=n.indexOf(Ql);if(r!==-1&&s!==-1&&s>r){let a=n.slice(0,r)+t.trimEnd()+n.slice(s+Ql.length);return a===n?"unchanged":(X.writeFileSync(e,a),"updated")}let o=n.endsWith(`
|
|
1354
1356
|
`)?`
|
|
1355
1357
|
`:`
|
|
1356
1358
|
|
|
1357
|
-
`;return X.writeFileSync(e,n+o+t),"updated"}var
|
|
1358
|
-
`),s?"updated":"created")}function
|
|
1359
|
-
`),n.scaffolded.push("saffron.config.json"));let{features:o}=
|
|
1360
|
-
`).some(p=>p.trim()===
|
|
1359
|
+
`;return X.writeFileSync(e,n+o+t),"updated"}var Zl={command:"npx",args:["saffron","mcp"]},t$={claude:{file:".mcp.json",key:"mcpServers",entry:Zl},cursor:{file:".cursor/mcp.json",key:"mcpServers",entry:Zl},copilot:{file:".vscode/mcp.json",key:"servers",entry:{type:"stdio",...Zl}}},om={agents:"codex mcp add saffron -- npx saffron mcp (Codex; other hosts: see their MCP settings)"};function n$(e,t){let n=re.join(e,t.file),r={},s=X.existsSync(n);if(s)try{r=JSON.parse(X.readFileSync(n,"utf8"))}catch{throw new Error(`${t.file} is not valid JSON: fix it or remove it, then re-run`)}let o=r[t.key]??{};return JSON.stringify(o.saffron)===JSON.stringify(t.entry)?"unchanged":(o.saffron=t.entry,r[t.key]=o,X.mkdirSync(re.dirname(n),{recursive:!0}),X.writeFileSync(n,JSON.stringify(r,null,2)+`
|
|
1360
|
+
`),s?"updated":"created")}function am(e,t){X.mkdirSync(t,{recursive:!0});for(let n of X.readdirSync(e,{withFileTypes:!0})){let r=re.join(e,n.name),s=re.join(t,n.name);n.isDirectory()?am(r,s):X.copyFileSync(r,s)}}function cm(e){let t=re.join(e.packageRoot,"skills","saffron");if(!X.existsSync(re.join(t,"SKILL.md")))throw new Error(`bundled skill not found at ${t}`);let n={skillDirs:[],instructionFiles:[],scaffolded:[],mcpFiles:[],mcpHints:[]},r=e.targets??XS;for(let s of r){let o=re.join(e.projectRoot,uo[s],"saffron");X.existsSync(o)&&X.rmSync(o,{recursive:!0,force:!0}),am(t,o),n.skillDirs.push(re.relative(e.projectRoot,o))}if(e.mcp!==!1)for(let s of r){let o=t$[s];o?n.mcpFiles.push({file:o.file,outcome:n$(e.projectRoot,o)}):om[s]&&n.mcpHints.push(om[s])}if(e.instructions!==!1){let s=e$(),o=re.join(e.projectRoot,"AGENTS.md");n.instructionFiles.push({file:"AGENTS.md",outcome:sm(o,s)});let a=re.join(e.projectRoot,"CLAUDE.md");X.existsSync(a)&&n.instructionFiles.push({file:"CLAUDE.md",outcome:sm(a,s)})}if(e.examples){n.examples=r$(e.projectRoot,e.packageRoot,ea(e.projectRoot));for(let s of n.examples.files)n.scaffolded.push(s)}if(e.scaffold!==!1){let s=re.join(e.projectRoot,"saffron.config.json");X.existsSync(s)||(X.writeFileSync(s,JSON.stringify({baseURL:"http://localhost:3000",features:"features"},null,2)+`
|
|
1361
|
+
`),n.scaffolded.push("saffron.config.json"));let{features:o}=ea(e.projectRoot),a=re.resolve(e.projectRoot,o);!X.existsSync(a)&&lm(e.projectRoot,a)&&(X.mkdirSync(a,{recursive:!0}),n.scaffolded.push(`${o}/`));let i=re.join(e.projectRoot,".gitignore"),c=[".saffron/reports/",".saffron/artifacts/",".saffron/ci/",...e.examples?[".env"]:[]],l=X.existsSync(i)?X.readFileSync(i,"utf8"):"",d=[];for(let u of c)l.split(`
|
|
1362
|
+
`).some(p=>p.trim()===u)||(l+=(l&&!l.endsWith(`
|
|
1361
1363
|
`)?`
|
|
1362
|
-
`:"")+
|
|
1363
|
-
`,d.push(
|
|
1364
|
-
`),n.push(`saffron.config.json (+ ${a.map(i=>`${i} ${String(s[i])}`).join(", ")})`)}import
|
|
1365
|
-
`)}import{
|
|
1366
|
-
`))}function kh(e,t){let n=e.provider??"claude";return t===n?{model:e.model,healModel:e.healModel}:((e.model||e.healModel)&&console.error(`note: model and healModel in saffron.config.json name ${yn[n]??n} models; this ${yn[t]} run uses its default models (--model and --heal-model pick others).`),{})}function Al(e,t){let n=e??t??"claude";return $g(n)||(console.error(`invalid provider "${n}": use ${Zc.map(r=>`"${r}"`).join(", ")}`),process.exit(2)),n}async function pS(e){let t=dS.createInterface({input:process.stdin,output:process.stdout});try{let n=await new Promise(r=>t.question(e,r));return/^y(es)?$/i.test(n.trim())}finally{t.close()}}function Di(e){console.error(`saffron: ${e.message}`),process.exit(2)}function Tl(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${(e/1e3).toFixed(1)}k`:e.toLocaleString()}var gS={green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m"},hS="\x1B[0m",te=new uS().name("saffron").description("AI-fallback test runner for end-to-end tests written in plain language: zero-token cached replay, runtime AI healing.").version(ot()).option("-p, --project-root <dir>","project root",process.cwd());te.command("run").description("Run feature files (cached replay; AI records/heals on demand)").argument("[paths...]",'feature files or directories (default: features/); file:line runs the scenario at that line, Cucumber-style (login.saffron:12, or :12:30 for two); file:name the scenario of that name ("login.saffron:Successful login")').option("--base-url <url>","base URL of the app under test").option("--env <name>","data environment: data/<file>.<name>.json is laid over data/<file>.json (also SAFFRON_ENV, or env in the config)").option("--headed","run the browser headed").option("--filter <tags>",'only run scenarios whose @tags match: a list ("@smoke,@WA-TC1" runs either) or an expression ("@e2e and not @wip", parentheses allowed); repeat the flag for "or"',Zf).option("--no-agent","disable AI fallback (cache misses/failures go red)").option("--rerecord","discard the committed caches of the selected scenarios and let the agent record them fresh, over a pending proposal this machine did not file too (the honest fix for a wrong recording)").option("--provider <name>",'whose agent records and heals: "claude" (default), "codex", "antigravity" or "cursor", on its login on this machine').option("--model <model>","model for the agent").option("--storage-state <file>","Playwright storageState JSON for authenticated sessions").option("--strict","treat passed-with-adaptation (yellow) as failure until its proposal is reviewed").option("--no-verify","skip the zero-AI proof replay of agent recordings before filing proposals").option("--no-reuse","disable Level-1 step reuse (seeding new recordings from existing step recordings)").option("--browser <name>",'browser: "chromium" (default), "chrome", "msedge", "firefox" or "webkit". Recording and healing need one of the first three. A list ("chromium,firefox,webkit") runs the suite in each, into one report').option("--device <name>",'run under a Playwright device profile, e.g. "iPhone 15" or "Pixel 7"').option("--viewport <size>","viewport as WIDTHxHEIGHT, e.g. 1280x720 (over the device's)").option("--heal-model <model>","cheaper model for heal sessions").option("--workers <n>","parallel replay workers").option("--agent-workers <n>","agent sessions (recording, healing) that may run at once, each in a browser of its own (default 1)").option("--shard <index/total>","run one part of the suite, e.g. 2/4 on the second of four CI machines; combine the parts with `saffron report --merge`").option("--shard-by <mode>",'how --shard splits the suite: "scenario" (default, spreads every file) or "file" (each feature file stays on one machine)').option("--no-hooks","skip the setup and teardown commands from the config").option("--trace <mode>",'execution trace per scenario: "off" (default), "on" or "retain-on-failure"; open one with saffron trace').option("--assertion-policy <policy>",'assertion adaptability: "strict" (default) or "adaptable-mid" (mid-scenario assertions may be adapted; the final assertion block never is)').action(async(e,t)=>{let n=G.resolve(te.opts().projectRoot),r=Ee(n);t.env&&Mt(n,r.dataDir,t.env);let s=t.baseUrl??r.baseURL,o=Qf(e),a=e.length===0?Rl(n,r.features?[r.features]:[]):o.plain.length>0?Rl(n,o.plain):[],i=[...o.picks.keys()].map(D=>G.resolve(n,D)),c=[...o.plain,...o.picks.keys()].find(D=>!Fe.existsSync(G.resolve(n,D)));c!==void 0&&(console.error(`${c} does not exist (in ${n}).`),process.exit(2));let l=[...new Set([...a,...i])].sort();l.length===0&&(console.error("No .feature/.saffron files found."),process.exit(2));let d=l.find(D=>{let q=G.relative(n,D);return q.split(/[\\/]/)[0]===".."||G.isAbsolute(q)});d&&(console.error(`${d} is outside the project (${n}). Run saffron from the project that holds it, or point --project-root at it.`),process.exit(2));let f=Al(t.provider,r.provider),p=kh(r,f);t.agent!==!1&&fS(f);let u;try{let D=ut(n,r,l);u=l.flatMap(q=>ft(q,n,D))}catch(D){throw D instanceof Le&&Di(D),D}let h=u;if(e.length===0){let D=new Set(h.flatMap(q=>q.steps.flatMap(Y=>Y.session===void 0?[]:[Y.session])));for(let q of Object.keys(r.sessions??{}))q===Ft?console.warn(`saffron.config.json sets up the browser session "${Ft}", which takes storageState (or --storage-state) like every scenario: "sessions" is for named sessions.`):D.has(q)||console.warn(`saffron.config.json sets up the browser session "${q}", and no step names it with As "${q}". Check the spelling.`)}let b=ql(h.flatMap(D=>D.steps.flatMap(q=>q.session===void 0?[]:[q.session])),Object.keys(r.sessions??{}),t.storageState??r.storageState);if(b&&console.warn(b),o.picks.size>0)try{u=tp(u,n,o.picks,new Set(a))}catch(D){if(!(D instanceof dr))throw D;console.error(D.message),process.exit(2)}let g;try{g=Kf(t.filter)}catch(D){if(!(D instanceof Cs))throw D;console.error(`${D.message}. Write tags joined with and, or, not and parentheses: "@smoke and not @wip".`),process.exit(2)}if(g&&(u=Yf(u,g),u.length===0&&(console.error(`No scenarios match --filter "${g.text}" in ${l.length} feature file(s).`),process.exit(2))),t.agent!==!1){let D=J=>{try{let de=st(me(n,J.featurePath,J.name));return!!de&&(Mr(J,de)||Fn(J,de)!==void 0)}catch{return!1}},q=u.filter(J=>t.rerecord||!D(J)),Y=Xf(q,h).filter(J=>!u.includes(J));Y.length>0&&(console.log(`${Y.length} more Examples row(s) share a recording this run ${t.rerecord?"replaces":"records"}, and run to replay it`),u=[...u,...Y])}let S=(()=>{let D=t.browser??r.browser??"chromium",q=(Array.isArray(D)?D:String(D).split(",")).map(J=>String(J).trim()).filter(Boolean),Y=q.find(J=>!Up(J));return(Y!==void 0||q.length===0)&&(console.error(`invalid --browser "${Y??""}": use ${zc.map(J=>`"${J}"`).join(", ")}, or a list of them`),process.exit(2)),[...new Set(q)].sort((J,de)=>+!ur(J)-+!ur(de))})(),y=S.length>1,w;if(t.shardBy!==void 0&&t.shard===void 0&&(console.error("saffron: --shard-by needs --shard, e.g. --shard 2/4 --shard-by file"),process.exit(2)),t.shard!==void 0){try{let D=wf(String(t.shardBy??r.shardBy??"scenario")),q=yf(u,{...mf(String(t.shard)),by:D});if(u=q.scenarios,y)throw new Error("saffron: a browser matrix and --shard do not mix: give each shard job one --browser (a CI matrix runs them side by side)");w={...q.info,ciRun:Ko(),attempt:Yo(),browser:S[0]}}catch(D){console.error(D instanceof Error?D.message:String(D)),process.exit(2)}if(console.log(`shard ${w.index}/${w.total}${w.by==="file"?" (by file)":""}: ${u.length} of ${w.suiteSize} scenario(s)`),u.length===0){let D=new Date,q=cc([],D,s),Y=nc([],D,Wt(n).divergent.length,s);console.log(`report: ${gc(n,{...q,shard:w,history:Y})}`),process.exit(0)}}t.rerecord&&t.agent===!1&&(console.error("saffron: --rerecord needs the agent; drop --no-agent"),process.exit(2)),t.rerecord&&!S.some(ur)&&(console.error(`saffron: --rerecord needs a browser that can record (chromium, chrome or msedge); ${S.join(", ")} only replay`),process.exit(2));let v=t.rerecord?Ti(f):[];v.length>0&&(console.error(`saffron: --rerecord needs the agent, and ${yn[f]} cannot start here: ${v.join("; ")}`),process.exit(2));{let D=u;try{let Y=[...new Set([...Rl(n,r.features?[r.features]:[]),...l])],J=ut(n,r,Y);D=Y.flatMap(de=>{try{return ft(de,n,J)}catch{return[]}})}catch{}let q=jd(n,D);if(q.length>0){console.error("cache path collision:");for(let Y of q)console.error(` ${Y}`);process.exit(2)}}let x=[],$=[];if(t.hooks!==!1)try{x=ol(r.setup,"setup"),$=ol(r.teardown,"teardown")}catch(D){console.error(D instanceof Error?D.message:String(D)),process.exit(2)}let E=t.device??r.device,R=E===void 0?void 0:String(E);if(R!==void 0&&(typeof E!="string"||!Hc.includes(R))){let D=Hc.filter(q=>q.toLowerCase().includes(R.toLowerCase().split(" ")[0])).slice(0,8);console.error(`unknown --device "${R}". ${D.length>0?`Close: ${D.map(q=>`"${q}"`).join(", ")}`:'Use a Playwright device name, e.g. "iPhone 15", "Pixel 7" or "Desktop Chrome"'}`),process.exit(2)}let k=t.viewport??r.viewport,C=k===void 0?void 0:zp(String(k));k!==void 0&&!C&&(console.error(`invalid --viewport "${k}": use WIDTHxHEIGHT, e.g. 1280x720`),process.exit(2));let P=D=>Math.max(1,Number.parseInt(String(D??1),10)||1),m=P(t.workers??r.workers),A=P(t.agentWorkers??r.agentWorkers),O=t.agent?kg(f,{model:t.model??p.model,maxTurns:r.maxTurns,snapshotMode:r.snapshotMode}):void 0,T=(D,q)=>D!==void 0?{name:D,source:"flag"}:q!==void 0?{name:q,source:"config"}:void 0,_=Rg[f],N=_&&Gd(_),F=O?{provider:f,model:T(t.model,p.model),healModel:T(t.healModel,p.healModel),..._&&N?{sdk:{name:_,version:N}}:{}}:{},I=(()=>{let D=t.trace??r.trace??"off";return _a.includes(D)||(console.error(`invalid --trace "${D}": use ${_a.map(q=>`"${q}"`).join(", ")}`),process.exit(2)),D})(),L=(()=>{let D=t.assertionPolicy??r.assertionPolicy??"strict";return D!=="strict"&&D!=="adaptable-mid"&&(console.error(`invalid --assertion-policy "${D}": use "strict" or "adaptable-mid"`),process.exit(2)),D})(),j=new Map,H={},Z=D=>new di({filedThisRun:j,agentHalt:H,projectRoot:n,baseURL:s,headed:t.headed,actionTimeoutMs:r.actionTimeoutMs,pollIntervalMs:r.pollIntervalMs,screenshot:r.screenshot,trace:I,retries:r.retries,storageState:t.storageState??r.storageState,sessions:r.sessions,browser:D,device:R,viewport:C,timezone:r.timezone,artifactsPerBrowser:y,healModel:t.healModel??p.healModel,rerecord:t.rerecord===!0,verifyProposals:t.verify===!1?!1:r.verifyProposals,reuseSteps:t.reuse===!1?!1:r.reuseSteps,assertionPolicy:L,agent:O}),Q=new AbortController,M=()=>new Promise(()=>{}),U=new Set,z=async D=>{if(Q.signal.aborted)return M();let q=Z(D);return U.add(q),await q.start(),q},V=async D=>{for(let q of[...D])U.delete(q),await q.stop()},ee=new Date,Ie=[],Ke=new Map,Ne=new Map,Te=async(D,q,Y,J,de)=>{if(Q.signal.aborted)return M();let At=y?`${q} \xB7 ${Y}`:Y,Xe=Date.now(),oe;try{oe=await D.runScenario(J,de)}catch(zi){if(Q.signal.aborted)return M();throw zi}if(Q.signal.aborted)return M();let He=Date.now(),je=Ke.get(At)??{worker:At,runs:0,busyMs:0,spanMs:0,browser:q};Ke.set(At,je),je.runs++,je.busyMs+=He-Xe;let ye=Ne.get(q)??{first:Xe,last:He};return Ne.set(q,{first:Math.min(ye.first,Xe),last:Math.max(ye.last,He)}),oe.worker=At,oe.browser=q,oe},qt=D=>{let q=D.scenario,Y=gS[D.status],J=D.usage.inputTokens+D.usage.outputTokens,de=D.usage.cacheReadTokens+D.usage.cacheCreationTokens,At=de>0?`, ${Tl(de)} cache traffic`:"";console.log(`${Y}${D.status.toUpperCase().padEnd(7)}${hS}${q.displayName}${y?` [${D.browser}]`:""} (${D.source}, ${D.durationMs}ms, ${D.usage.aiCalls} AI calls, ${J} tokens${At})`);for(let oe of D.adaptations)console.log(` \u26A0 ${oe}`);D.status==="yellow"&&D.usage.aiCalls===0&&D.narrative&&console.log(` ${D.narrative}`),D.seededSteps&&console.log(` \u26A1 ${D.seededSteps}/${D.stepResults.length} steps seeded from existing recordings (zero AI)`);let Xe=D.stepResults.reduce((oe,He)=>oe+(He.retries??0),0);Xe&&console.log(` \u21BB ${Xe} action ${Xe===1?"retry":"retries"} absorbed before settling (retries: ${r.retries??1} per action)`),D.verified===!0?console.log(" \u2713 proposal verified by zero-AI proof replay"):D.verified===!1&&console.log(` \u2717 proposal UNVERIFIED, proof replay failed: ${D.proofError?.split(`
|
|
1367
|
-
`)
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
${
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
`)
|
|
1374
|
-
${
|
|
1375
|
-
`)
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1364
|
+
`:"")+u+`
|
|
1365
|
+
`,d.push(u));d.length>0&&(X.writeFileSync(i,l),n.scaffolded.push(`.gitignore (+ ${d.join(", ")})`))}return n}function ea(e){let t={};try{t=JSON.parse(X.readFileSync(re.join(e,"saffron.config.json"),"utf8"))}catch{}let n=(r,s)=>typeof r=="string"&&r.trim()?r.trim().replace(/(.)[\\/]+$/,"$1"):s;return{features:n(t?.features,"features"),data:n(t?.dataDir,"data")}}function lm(e,t){let n=re.relative(re.resolve(e),re.resolve(t));return n===""||n!==".."&&!n.startsWith(".."+re.sep)&&!re.isAbsolute(n)}function r$(e,t,n={features:"features",data:"data"}){let r=re.join(t,"templates","saucedemo");if(!X.existsSync(re.join(r,"features")))return{installed:!1,files:[],reason:`bundled examples not found at ${r}`};let s=re.resolve(e,n.features),o=re.resolve(e,n.data);for(let[u,p]of[[s,n.features],[o,n.data]]){if(!lm(e,u))return{installed:!1,files:[],reason:`${p} is outside the project; examples are only installed inside it`};if(X.existsSync(u)&&!X.statSync(u).isDirectory())return{installed:!1,files:[],reason:`${p} is a file, not a folder; examples are installed into a folder`}}if(X.existsSync(s)&&X.readdirSync(s).length>0)return{installed:!1,files:[],reason:`${n.features}/ is not empty; examples are only installed into an empty features directory`};let a=[];X.mkdirSync(s,{recursive:!0});for(let u of X.readdirSync(re.join(r,"features")))X.copyFileSync(re.join(r,"features",u),re.join(s,u)),a.push(`${n.features}/${u}`);let i=re.join(r,"data");if(X.existsSync(i)){X.mkdirSync(o,{recursive:!0});for(let u of X.readdirSync(i)){let p=re.join(o,u);X.existsSync(p)||(X.copyFileSync(re.join(i,u),p),a.push(`${n.data}/${u}`))}}let c=re.join(e,"saffron.config.json"),l;X.existsSync(c)?l=s$(c,re.join(r,"saffron.config.json"),a):(X.copyFileSync(re.join(r,"saffron.config.json"),c),a.push("saffron.config.json (baseURL https://www.saucedemo.com, retries 1)"));let d=re.join(e,".env.example");return X.existsSync(d)||(X.copyFileSync(re.join(r,".env.example"),d),a.push(".env.example")),{installed:!0,files:a,...l?{note:l}:{}}}function s$(e,t,n){let r;try{r=JSON.parse(X.readFileSync(e,"utf8"))}catch{return}if(!r||typeof r!="object"||Array.isArray(r))return;let s=JSON.parse(X.readFileSync(t,"utf8")),o=s.baseURL;if(r.baseURL!==void 0)return r.baseURL===o?void 0:`the examples target ${o}, but saffron.config.json keeps your baseURL ${String(r.baseURL)}; set "baseURL": "${o}" to run them`;let a=Object.keys(s).filter(i=>i!=="features"&&!(i in r));for(let i of a)r[i]=s[i];X.writeFileSync(e,JSON.stringify(r,null,2)+`
|
|
1366
|
+
`),n.push(`saffron.config.json (+ ${a.map(i=>`${i} ${String(s[i])}`).join(", ")})`)}import o$ from"node:path";function dm(e){return["saffron lsp is a language server: it speaks LSP over stdio and is meant","to be launched by your editor, not run by hand (nothing happens here).","","JetBrains (IntelliJ, WebStorm, PyCharm, Rider, incl. Community):"," Easiest: install the Saffron plugin from the JetBrains Marketplace"," (https://plugins.jetbrains.com/plugin/34240-saffron): highlighting,"," this language server, run configurations and the Saffron tool window,"," in one click. Manual setup instead:"," 1. Completion, diagnostics, hover, go-to-definition: install the free"," LSP4IJ plugin, then Settings \u2192 Languages & Frameworks \u2192 Language"," Servers \u2192 +: command `npx saffron lsp`, working dir = project root,"," file patterns *.saffron and *.feature."," 2. Syntax highlighting comes from a TextMate bundle, not the LSP:"," Settings \u2192 Editor \u2192 TextMate Bundles \u2192 + and pick this folder:",` ${e?o$.join(e,"textmate","saffron"):"node_modules/saffron-ai/textmate/saffron"}`,"","Neovim / other LSP editors: cmd = { 'npx', 'saffron', 'lsp' },","filetypes = { 'saffron', 'feature' }.","","VS Code: install the extension instead:"," code --install-extension ChathurangaJayasinghe.saffron-vscode"].join(`
|
|
1367
|
+
`)}import{execFileSync as i$}from"node:child_process";import{createHash as a$}from"node:crypto";import Xn from"node:fs";import Xe from"node:path";var ta={goto:{class:"exact"},click:{class:"exact"},fill:{class:"exact"},press:{class:"exact"},selectOption:{class:"exact"},check:{class:"exact"},uncheck:{class:"exact"},hover:{class:"exact"},waitFor:{class:"exact"},captureText:{class:"exact"},handleDialog:{class:"exact"},uploadFile:{class:"exact"},dragTo:{class:"exact"},waitForResponse:{class:"exact"},switchTab:{class:"exact"},closeTab:{class:"exact"},newTab:{class:"exact"},waitForDownload:{class:"exact"},expectVisible:{class:"stricter",why:"a hidden first match is not passed over for a displayed one"},expectNotVisible:{class:"exact"},expectText:{class:"stricter",why:"the text is read from the first match only"},expectUrl:{class:"exact"},expectValue:{class:"exact"},expectDiffers:{class:"exact"},expectMatches:{class:"exact"},expectAttribute:{class:"exact"},expectResponse:{class:"exact"},expectEach:{class:"stricter",why:"each value must be a whole line of the container's text, in the case written"},expectDownload:{class:"exact"},expectAmount:{class:"refused",why:"amount checks are not exported yet"}};var ra="Generated by `saffron eject`",c$="Written by `saffron eject`",de=class extends Error{},l$=new Set(["click","fill","press","selectOption","check","uncheck","hover","dragTo","uploadFile"]),d$=new Set(["action","target","value","url","saveAs","compareTo","each","pattern","attribute","toTarget","promptText","opensTab","urlPattern","method","status","json","pageFingerprint","clickCount","downloads","button","modifiers","clearSelection"]),u$=new Set(["role","name","nameRegex","label","text","testId","placeholder","fallbackSelectors","frame"]),na=String.raw`(?:<[^<>]+>|\{(?:data|env|unique|date)[^{}]*\})`,f$=new RegExp(`${Fn.source}|${Se.source}|${Ho.source}`,"g"),ce=e=>JSON.stringify(e),Xl=e=>e.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g," "),um=e=>a$("sha256").update(e).digest("hex").slice(0,16),fm=(e,t)=>{let n=Xe.relative(e,t);return n!==""&&!n.startsWith("..")&&!Xe.isAbsolute(n)};function pm(e,t,n){let r=Xe.resolve(e,t.features??"features"),s=Xe.resolve(e,n.out??"playwright");if(!fm(e,s))throw new Error(`--out ${n.out} is outside the project (${e})`);let o=Vt(yn(r),e),a=n.files?.map(g=>Xe.resolve(e,g))??Gt(r,Wt),i=a.find(g=>!fm(e,g));if(i)throw new Error(`${i} is outside the project (${e})`);let c=p$(e),l={written:[],kept:[],tests:[]},d=(g,y,h)=>{let[S,...v]=y.split(`
|
|
1368
|
+
`),x=v.join(`
|
|
1369
|
+
`);if(Xn.existsSync(g)&&!n.force){let[b,...m]=Xn.readFileSync(g,"utf8").split(`
|
|
1370
|
+
`);if(!b.includes(h)||!b.endsWith(`(${um(m.join(`
|
|
1371
|
+
`))})`)){l.kept.push(Xe.relative(e,g));return}}Xn.mkdirSync(Xe.dirname(g),{recursive:!0}),Xn.writeFileSync(g,`${S} (${um(x)})
|
|
1372
|
+
${x}`),l.written.push(Xe.relative(e,g))},u=new Map,p=[];for(let g of a.sort()){let y=nt(g,e,o);if(y.length===0)continue;let h=y[0].featurePath,S=[];for(let m of y){let $={feature:h,test:m.displayName,outcome:"exported",notes:[],stricterChecks:[]},T;try{T=w$(e,m,$),($.notes.length>0||$.stricterChecks.length>0)&&($.outcome="stricter")}catch(k){if(!(k instanceof de))throw k;$.outcome="fixme",$.notes=[gm(k.message)],$.stricterChecks=[],T=` // ${Xl(k.message)}
|
|
1373
|
+
test.fixme();
|
|
1374
|
+
`}let R=$.outcome==="stricter"?$.notes.map(k=>` // Stricter than replay: ${Xl(k)}.
|
|
1375
|
+
`).join(""):"";S.push(`test(${ce(m.displayName)}, async ({ page, browser, baseURL }) => {
|
|
1376
|
+
${R}${T}});
|
|
1377
|
+
`),l.tests.push($)}let v=Xe.join(s,`${ys(h)}.spec.ts`),x=u.get(v);if(x)throw new Error(`${x} and ${h} would both be written to ${Xe.relative(e,v)}; eject them separately with --out`);u.set(v,h);let b=`// ${ra} from ${Xl(h)}${c?` at ${c}`:""}.
|
|
1378
|
+
// Saffron does not maintain this file: edit it freely.
|
|
1379
|
+
import { expect, test } from "@playwright/test";
|
|
1380
|
+
import * as s from "./saffron-helpers";
|
|
1381
|
+
|
|
1382
|
+
`;p.push([v,`${b}test.describe(${ce(y[0].featureName)}, () => {
|
|
1383
|
+
${g$(S.join(`
|
|
1384
|
+
`))}});
|
|
1385
|
+
`])}for(let[g,y]of p)d(g,y,ra);return d(Xe.join(s,"saffron-helpers.ts"),h$(e,s,t,n.packageRoot),c$),["ts","js","mjs","cjs"].some(g=>Xn.existsSync(Xe.join(e,`playwright.config.${g}`)))||d(Xe.join(e,"playwright.config.ts"),m$(e,s,t),ra),l}function p$(e){try{return i$("git",["rev-parse","--short","HEAD"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}var g$=e=>e.replace(/^(?=.)/gm," ");function h$(e,t,n,r){let s=Xn.readFileSync(Xe.join(r,"templates","playwright","saffron-helpers.ts"),"utf8"),o={locale:n.dateLocale??"en-US",...n.timezone?{timeZone:n.timezone}:{},projectRoot:Xe.relative(t,e)||".",sessions:n.sessions??{},...n.storageState?{storageState:n.storageState}:{},timeoutMs:n.actionTimeoutMs??5e3};return s.replace(/\/\*SETTINGS\*\/[\s\S]*?\/\*END\*\//,()=>`/*SETTINGS*/ ${ce(o)} /*END*/`).replace(/\/\*DRAWN_TEXT\*\/[\s\S]*?\/\*END\*\//,()=>`/*DRAWN_TEXT*/ ${JSON.stringify(Rn.toString())} /*END*/`)}function m$(e,t,n){let r=n.actionTimeoutMs??5e3,s=[`baseURL: process.env.BASE_URL ?? ${ce(n.baseURL??"http://localhost:3000")}`,`actionTimeout: ${r}`];n.trace&&n.trace!=="off"&&s.push(`trace: ${ce(n.trace)}`),n.screenshot==="full-page"?s.push('screenshot: { mode: "only-on-failure", fullPage: true }'):n.screenshot!=="off"&&s.push('screenshot: "only-on-failure"'),n.storageState&&s.push(`storageState: ${ce(n.storageState)}`),n.timezone&&s.push(`timezoneId: ${ce(n.timezone)}`),n.device&&s.unshift(`...devices[${ce(n.device)}]`);let o=/^(\d+)x(\d+)$/.exec(n.viewport??"");return o&&s.push(`viewport: { width: ${o[1]}, height: ${o[2]} }`),`// ${ra}: settings taken from saffron.config.json.
|
|
1386
|
+
import { defineConfig${n.device?", devices":""} } from "@playwright/test";
|
|
1387
|
+
|
|
1388
|
+
export default defineConfig({
|
|
1389
|
+
testDir: ${ce(`./${Xe.relative(e,t).split(Xe.sep).join("/")}`)},
|
|
1390
|
+
expect: { timeout: ${r} },
|
|
1391
|
+
use: {
|
|
1392
|
+
${s.map(a=>` ${a},
|
|
1393
|
+
`).join("")} },
|
|
1394
|
+
});
|
|
1395
|
+
`}function w$(e,t,n){let r=pe(e,t.featurePath,t.name);if(!Xn.existsSync(r))throw new de("This scenario has never been recorded. Run it with saffron run first.");let s;try{s=Ye(r)}catch(a){throw new de(`The recording cannot be read: ${a instanceof ke?a.problem:String(a)}`)}if(!s)throw new de("The recording cannot be read.");if(Xn.existsSync(dt(e,t.featurePath,t.name)))throw new de("A proposal for this scenario is pending. Accept or reject it (saffron accept | saffron reject), then eject again.");let o=ln(t,s);if(o!==void 0)throw new de(`Replay refuses this row: ${gm(o)}`);if(!Wn(t,s))throw new de("The recording is stale: the feature changed since it was recorded. Run it with saffron run, then eject again.");return new ed(t,s,n).body()}var gm=e=>e.replace(/\s+/g," ").trim(),ed=class{constructor(t,n,r){this.row=t;this.cache=n;this.ejected=r;let s=n.steps.flatMap(o=>o.actions);this.usesTabs=s.some(o=>o.opensTab||o.action==="switchTab"||o.action==="newTab"||o.action==="closeTab"),this.marksSteps=s.some(o=>o.action==="waitForResponse"),this.marksActions=s.some(o=>o.action==="expectResponse"),this.envNames=ct(t)}row;cache;ejected;lines=[];P="run.page";usesTabs;marksSteps;marksActions;envNames;params={};downloads;files;dropped=0;captured=new Map;body(){let t=[],n;for(let[o,a]of this.cache.steps.entries()){let i=this.row.steps[o];if(this.params=Ms(this.row,o),this.lines=[],i.session!==n&&(this.lines.push(`await run.use(${i.session===void 0?"":ce(i.session)});`),n=i.session),this.marksSteps&&this.lines.push("run.step();"),a.kind==="assertion"&&!a.actions.some(c=>$e.has(c.action)))throw new de(`"${i.resolvedText}" is a check, and its recording checks nothing; replay fails it.`);for(let c of a.actions)this.action(c);t.push(`await test.step(${ce(`${a.keyword} ${i.resolvedText}`)}, async () => {`,...this.lines.map(c=>` ${c}`),"});")}if(this.downloads!==void 0)throw new de("The recording waits for a download that no later action starts.");if(this.files!==void 0)throw new de("The recording arms a file chooser that no later action opens.");this.dropped>0&&this.ejected.notes.push(`${this.dropped} action(s) use the first of the locators replay would try, without the fallbacks`);let r="const run = await s.Run.start({ page, browser, baseURL });";return(this.row.steps.some(o=>o.session!==void 0)?[r,"try {",...t.map(o=>` ${o}`),"} finally {"," await run.close();","}"]:[r,...t]).map(o=>` ${o}
|
|
1396
|
+
`).join("")}action(t){let n=[...Object.keys(t).filter(i=>!d$.has(i)),...[t.target,t.toTarget].flatMap(i=>Object.keys(i??{}).filter(c=>!u$.has(c)))];if(n.length>0)throw new de(`${t.action} carries ${n.join(", ")}, which saffron eject does not export yet.`);let r=ta[t.action];if(r.class==="refused")throw new de(`${t.action}: ${r.why}.`);r.class==="stricter"&&!this.ejected.stricterChecks.includes(t.action)&&this.ejected.stricterChecks.push(t.action);let s=this.P,o=(i="act")=>{if(!t.target)throw new de(`${t.action} has no target.`);let c=this.candidates(t.target,i);return c.length>1&&this.dropped++,c[0]},a=i=>this.interaction(t,i);switch(t.action){case"goto":return a(`await ${s}.goto(run.url(${this.value(t.url??"",!0)}));`);case"click":{let i={...t.clickCount!==void 0?{clickCount:t.clickCount}:{},...t.button?{button:t.button}:{},...t.modifiers?.length?{modifiers:t.modifiers}:{}};return a(`await ${o("act")}.first().click(${Object.keys(i).length?ce(i):""});`)}case"fill":return a(`await ${o("act")}.first().fill(${this.value(t.value??"")});`);case"press":return a(t.target?`await ${o("act")}.first().press(${this.value(t.value??"")});`:`await ${s}.keyboard.press(${this.value(t.value??"")});`);case"selectOption":{if(t.clearSelection)return a(`await ${o("act")}.first().selectOption([]);`);let i=(t.value??"").split(`
|
|
1397
|
+
`).map(c=>this.value(c));return a(`await ${o("act")}.first().selectOption(${i.length>1?`[${i.join(", ")}]`:i[0]});`)}case"check":case"uncheck":case"hover":return a(`await ${o("act")}.first().${t.action}();`);case"dragTo":{if(!t.toTarget)throw new de("dragTo has no destination.");let i=this.candidates(t.toTarget,"act");return i.length>1&&this.dropped++,a(`await ${o("act")}.first().dragTo(${i[0]}.first());`)}case"uploadFile":{let i=(t.value??"").split(`
|
|
1398
|
+
`).filter(Boolean).map(c=>this.value(c,!0));if(i.length===0)throw new de("uploadFile names no file.");if(!t.target){this.files=i,this.marksActions&&this.lines.push("run.act();");return}return a(`await ${o("act")}.first().setInputFiles([${i.map(c=>`s.projectFile(${c})`).join(", ")}]);`)}case"waitFor":return t.target?void this.lines.push(`await ${o("loose")}.first().waitFor({ state: "visible" });`):void this.lines.push(`await ${s}.waitForTimeout(${Math.max(0,Number(t.value??"0"))||0});`);case"captureText":return this.captured.set(t.saveAs??"",ce(t.target)),void this.lines.push(`await run.capture(${ce(t.saveAs)}, ${o("loose")});`);case"handleDialog":{let i=(t.value??"accept")!=="dismiss";return void this.lines.push(`run.dialog(${i}${i&&t.promptText?`, ${this.value(t.promptText)}`:""});`)}case"waitForDownload":this.downloads=t.downloads??1;return;case"waitForResponse":case"expectResponse":{if(t.json!==void 0)throw new de("JSON response field checks are not exported yet.");let i=[`url: ${this.pattern(t.urlPattern??"","urlPattern")}`,...t.method!==void 0?[`method: ${this.value(t.method,!0)}`]:[],...t.status!==void 0?[`status: ${this.value(t.status,!0)}`]:[],...t.pattern!==void 0?[`body: ${this.pattern(t.pattern,"pattern")}`]:[]];return void this.lines.push(`await run.response(${ce(t.action==="waitForResponse"?"wait":"check")}, { ${i.join(", ")} });`)}case"switchTab":return void this.lines.push(`await run.switchTab(${Number.parseInt(t.value??"",10)});`);case"closeTab":return void this.lines.push(`await run.closeTab(${t.value===void 0?"":Number.parseInt(t.value,10)});`);case"newTab":return a(`await run.newTab(${t.url!==void 0?this.value(t.url,!0):""});`);case"expectVisible":return void this.lines.push(`await expect(${o()}.first()).toBeVisible();`);case"expectNotVisible":return void this.lines.push(`await s.expectNotVisible(${this.candidates(t.target,"negative").join(", ")});`);case"expectText":return void this.lines.push(`await s.expectText(${o()}, ${this.text(t.value??"")});`);case"expectValue":{let i=o();return void this.lines.push(`await expect(${i}.first()).toBeVisible();`,`await expect(${i}.first()).toHaveValue(${this.value(t.value??"")});`)}case"expectUrl":return void this.lines.push(`await s.expectUrl(${s}, ${this.text(t.url??t.value??"")});`);case"expectDiffers":return t.target?void this.lines.push(`await run.expectDiffers(${ce(t.compareTo)}, ${o()}${this.captured.get(t.compareTo??"")===ce(t.target)?", undefined, true":""});`):void this.lines.push(`await run.expectDiffers(${ce(t.compareTo)}, undefined, ${ce(t.value??"")});`);case"expectMatches":return void this.lines.push(`await s.expectMatches(${o()}, ${this.pattern(t.pattern??"","pattern")});`);case"expectAttribute":return void this.lines.push(`await s.expectAttribute(${o()}, ${this.value(t.attribute??"",!0)}, ${this.pattern(t.pattern??"","pattern")});`);case"expectEach":{let i=qt(t.each??"",this.params).match(/^\{data:([^}]+)\}$/)?.[1];if(!i)throw new de(`expectEach needs a {data:...} list, not ${t.each}.`);return void this.lines.push(`await s.expectEach(${o()}, ${ce(en(i))});`)}case"expectDownload":{if(!t.value&&!t.pattern)throw new de("expectDownload checks nothing.");let i=t.value?this.text(t.value):"undefined";return void this.lines.push(`await run.expectDownload(${i}${t.pattern?`, ${this.pattern(t.pattern,"pattern")}`:""});`)}default:throw new de(`${t.action} is not exported yet.`)}}interaction(t,n){let r=n,s=l$.has(t.action)&&!(t.action==="uploadFile"&&!t.target);this.files&&s&&t.action!=="uploadFile"&&(r=`await run.chooseFiles([${this.files.join(", ")}], async () => { ${r} });`,this.files=void 0),this.downloads!==void 0&&(s||t.action==="goto"||t.action==="newTab")&&(r=`await run.downloads(${this.downloads}, async () => { ${r} });`,this.downloads=void 0),this.marksActions&&t.action!=="newTab"&&this.lines.push("run.act();"),this.lines.push(r),t.action==="click"&&((t.modifiers?.length??0)>0||t.button==="middle")?this.lines.push("await run.tabs(false, true);"):this.usesTabs&&(s||t.action==="goto")&&this.lines.push(`await run.tabs(${t.opensTab===!0});`)}candidates(t,n){for(let o of["name","label","text","placeholder","testId"])t[o]!==void 0&&this.refuseBlank(t[o],`the target's ${o}`);let r=t.frame!==void 0?`${this.P}.frameLocator(${this.selector(t.frame)})`:this.P,s=[];if(t.role){let o=ce(t.role),a=t.nameRegex!==void 0?`s.pattern(${this.pattern(t.nameRegex,"nameRegex")}, "i")`:t.name?this.value(t.name):void 0;a===void 0&&!!(t.label||t.placeholder||t.text||t.testId||t.fallbackSelectors?.length)?t.text&&s.push(`${r}.getByRole(${o}).filter({ hasText: ${this.text(t.text,"i")} })`):t.nameRegex===void 0&&a!==void 0?(s.push(`${r}.getByRole(${o}, { name: ${a}, exact: true })`),n==="loose"&&s.push(`${r}.getByRole(${o}, { name: ${this.text(t.name,"i")} })`)):s.push(a===void 0?`${r}.getByRole(${o})`:`${r}.getByRole(${o}, { name: ${a} })`)}t.label&&s.push(`${r}.getByLabel(${this.text(t.label,"i")})`),t.placeholder&&s.push(`${r}.getByPlaceholder(${this.text(t.placeholder,"i")})`),t.text&&!t.role&&s.push(`${r}.getByText(${this.text(t.text,"i")})`),t.testId&&s.push(`${r}.getByTestId(${this.value(t.testId)})`);for(let o of t.fallbackSelectors??[])s.push(`${r}.locator(${this.selector(o)})`);if(s.length===0)throw new de("A target has neither a role nor a selector.");return s}selector(t){if(new RegExp(na).test(t))throw new de(`A selector holds a row or data value (${t}); selectors like this are not exported yet.`);return ce(t)}pattern(t,n){if([...t.matchAll(new RegExp(na,"g"))].filter(s=>{let o=t.slice(Math.max(0,s.index-2),s.index);return!(s[0].startsWith("<")&&(o==="(?"||o==="\\k"))}).length>0)throw new de(`The ${n} /${t}/ holds a row or data value; patterns like this are not exported yet.`);return ce(t)}refuseBlank(t,n){for(let r of t.matchAll(/<([^<>]+)>/g))if(Object.hasOwn(this.params,r[1])&&this.params[r[1]].trim()==="")throw new de(`${n} holds <${r[1]}>, which is blank on this row; replay refuses such a check.`);for(let r of qt(t,this.params).matchAll(ve))if(this.data(r[1]).trim()==="")throw new de(`${n} holds {data:${r[1]}}, which is blank; replay refuses such a check.`)}data(t){try{return Le(t)}catch(n){throw new de(n instanceof Error?n.message:String(n))}}text(t,n){this.refuseBlank(t,"the expected text");let r=this.value(t);if(/^"(?:\s|\\[nrt])*"$/.test(r))throw new de("An expected text is blank.");let s=new RegExp(`^\\s*${na}`).test(t),o=new RegExp(`${na}\\s*$`).test(t);return!s&&!o?r:`s.bounded(${r}, ${ce(s&&o?"both":s?"start":"end")}${n?`, ${ce(`${n}u`)}`:""})`}value(t,n=!1){n&&this.refuseBlank(t,"a value");let r=qt(t,this.params);r=r.replace(ve,(a,i)=>this.data(i));let s=[],o=0;for(let a of r.matchAll(f$)){a.index>o&&s.push(ce(us(r.slice(o,a.index))));let i=a[0],c=/^\{env:(.+)\}$/.exec(i)?.[1];if(c!==void 0&&!this.envNames.has(c))throw new de(`{env:${c}} is not named by this scenario, and replay refuses to read it.`);c!==void 0?s.push(`s.env(${ce(c)})`):i.startsWith("{unique:")?s.push(`run.unique(${ce(i)})`):s.push(`run.date(${ce(i)})`),o=a.index+i.length}return o<r.length&&s.push(ce(us(r.slice(o)))),s.length===0?'""':s.join(" + ")}};import{spawn as y$}from"node:child_process";function b$(e,t=process.platform){return t==="win32"?{command:'start "" "%SAFFRON_BROWSER_TARGET%"',args:[],options:{detached:!0,stdio:"ignore",shell:!0,windowsHide:!0,env:{...process.env,SAFFRON_BROWSER_TARGET:e}}}:{command:t==="darwin"?"open":"xdg-open",args:[e],options:{detached:!0,stdio:"ignore"}}}function fo(e){let{command:t,args:n,options:r}=b$(e),s=t.split(" ")[0],o=y$(t,n,r);o.on("error",()=>console.error(`Could not open a browser (${s} is not available here). Open the address above yourself.`)),o.unref()}function sa(e,t){let n=t.length>0?t:["features"],r=[];for(let s of n){let o=V.isAbsolute(s)?s:V.join(e,s);Ne.existsSync(o)&&(Ne.statSync(o).isDirectory()?r.push(...Gt(o,Wt)):Wt(o)&&r.push(o))}return r.sort()}function S$(e){let t=Al(e);t.length!==0&&console.error([`note: the ${_n[e]} agent is not set up here. Cached scenarios replay fine`,"without AI, but recording and healing need:",...t.map(n=>` \xB7 ${n}`),"Replay-only runs: add --no-agent to silence this note.",""].join(`
|
|
1399
|
+
`))}function hm(e,t){let n=e.provider??"claude";return t===n?{model:e.model,healModel:e.healModel}:((e.model||e.healModel)&&console.error(`note: model and healModel in saffron.config.json name ${_n[n]??n} models; this ${_n[t]} run uses its default models (--model and --heal-model pick others).`),{})}function nd(e,t){let n=e??t??"claude";return dh(n)||(console.error(`invalid provider "${n}": use ${Rl.map(r=>`"${r}"`).join(", ")}`),process.exit(2)),n}async function $$(e){let t=x$.createInterface({input:process.stdin,output:process.stdout});try{let n=await new Promise(r=>t.question(e,r));return/^y(es)?$/i.test(n.trim())}finally{t.close()}}function oa(e){console.error(`saffron: ${e.message}`),process.exit(2)}function td(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${(e/1e3).toFixed(1)}k`:e.toLocaleString()}var k$={green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m"},R$="\x1B[0m",te=new v$().name("saffron").description("AI-fallback test runner for end-to-end tests written in plain language: zero-token cached replay, runtime AI healing.").version(ut()).option("-p, --project-root <dir>","project root",process.cwd());te.command("run").description("Run feature files (cached replay; AI records/heals on demand)").argument("[paths...]",'feature files or directories (default: features/); file:line runs the scenario at that line, Cucumber-style (login.saffron:12, or :12:30 for two); file:name the scenario of that name ("login.saffron:Successful login")').option("--base-url <url>","base URL of the app under test").option("--env <name>","data environment: data/<file>.<name>.json is laid over data/<file>.json (also SAFFRON_ENV, or env in the config)").option("--headed","run the browser headed").option("--filter <tags>",'only run scenarios whose @tags match: a list ("@smoke,@WA-TC1" runs either) or an expression ("@e2e and not @wip", parentheses allowed); repeat the flag for "or"',sg).option("--no-agent","disable AI fallback (cache misses/failures go red)").option("--rerecord","discard the committed caches of the selected scenarios and let the agent record them fresh, over a pending proposal this machine did not file too (the honest fix for a wrong recording)").option("--provider <name>",'whose agent records and heals: "claude" (default), "codex", "antigravity" or "cursor", on its login on this machine').option("--model <model>","model for the agent").option("--storage-state <file>","Playwright storageState JSON for authenticated sessions").option("--strict","treat passed-with-adaptation (yellow) as failure until its proposal is reviewed").option("--no-verify","skip the zero-AI proof replay of agent recordings before filing proposals").option("--no-reuse","disable Level-1 step reuse (seeding new recordings from existing step recordings)").option("--browser <name>",'browser: "chromium" (default), "chrome", "msedge", "firefox" or "webkit". Recording and healing need one of the first three. A list ("chromium,firefox,webkit") runs the suite in each, into one report').option("--device <name>",'run under a Playwright device profile, e.g. "iPhone 15" or "Pixel 7"').option("--viewport <size>","viewport as WIDTHxHEIGHT, e.g. 1280x720 (over the device's)").option("--heal-model <model>","cheaper model for heal sessions").option("--workers <n>","parallel replay workers").option("--agent-workers <n>","agent sessions (recording, healing) that may run at once, each in a browser of its own (default 1)").option("--shard <index/total>","run one part of the suite, e.g. 2/4 on the second of four CI machines; combine the parts with `saffron report --merge`").option("--shard-by <mode>",'how --shard splits the suite: "scenario" (default, spreads every file) or "file" (each feature file stays on one machine)').option("--no-hooks","skip the setup and teardown commands from the config").option("--trace <mode>",'execution trace per scenario: "off" (default), "on" or "retain-on-failure"; open one with saffron trace').option("--assertion-policy <policy>",'assertion adaptability: "strict" (default) or "adaptable-mid" (mid-scenario assertions may be adapted; the final assertion block never is)').action(async(e,t)=>{let n=V.resolve(te.opts().projectRoot),r=_e(n);t.env&&Ut(n,r.dataDir,t.env);let s=t.baseUrl??r.baseURL,o=og(e),a=e.length===0?sa(n,r.features?[r.features]:[]):o.plain.length>0?sa(n,o.plain):[],i=[...o.picks.keys()].map(F=>V.resolve(n,F)),c=[...o.plain,...o.picks.keys()].find(F=>!Ne.existsSync(V.resolve(n,F)));c!==void 0&&(console.error(`${c} does not exist (in ${n}).`),process.exit(2));let l=[...new Set([...a,...i])].sort();l.length===0&&(console.error("No .feature/.saffron files found."),process.exit(2));let d=l.find(F=>{let H=V.relative(n,F);return H.split(/[\\/]/)[0]===".."||V.isAbsolute(H)});d&&(console.error(`${d} is outside the project (${n}). Run saffron from the project that holds it, or point --project-root at it.`),process.exit(2));let u=nd(t.provider,r.provider),p=hm(r,u);t.agent!==!1&&S$(u);let f;try{let F=mt(n,r,l);f=l.flatMap(H=>nt(H,n,F))}catch(F){throw F instanceof Be&&oa(F),F}let g=f;if(g.length===0&&(console.error(`No scenario to run in ${l.length===1?V.relative(n,l[0]):`${l.length} feature files`}: a feature file needs a Scenario or a Scenario Outline.`),process.exit(2)),e.length===0){let F=new Set(g.flatMap(H=>H.steps.flatMap(Z=>Z.session===void 0?[]:[Z.session])));for(let H of Object.keys(r.sessions??{}))H===Ht?console.warn(`saffron.config.json sets up the browser session "${Ht}", which takes storageState (or --storage-state) like every scenario: "sessions" is for named sessions.`):F.has(H)||console.warn(`saffron.config.json sets up the browser session "${H}", and no step names it with As "${H}". Check the spelling.`)}let y=Sd(g.flatMap(F=>F.steps.flatMap(H=>H.session===void 0?[]:[H.session])),Object.keys(r.sessions??{}),t.storageState??r.storageState);if(y&&console.warn(y),o.picks.size>0)try{f=cg(f,n,o.picks,new Set(a))}catch(F){if(!(F instanceof wr))throw F;console.error(F.message),process.exit(2)}let h;try{h=ng(t.filter)}catch(F){if(!(F instanceof Ks))throw F;console.error(`${F.message}. Write tags joined with and, or, not and parentheses: "@smoke and not @wip".`),process.exit(2)}if(h&&(f=rg(f,h),f.length===0&&(console.error(`No scenarios match --filter "${h.text}" in ${l.length} feature file(s).`),process.exit(2))),t.agent!==!1){let F=W=>{try{let he=Ye(pe(n,W.featurePath,W.name));return!!he&&(Wn(W,he)||ln(W,he)!==void 0)}catch{return!1}},H=f.filter(W=>t.rerecord||!F(W)),Z=ig(H,g).filter(W=>!f.includes(W));Z.length>0&&(console.log(`${Z.length} more Examples row(s) share a recording this run ${t.rerecord?"replaces":"records"}, and run to replay it`),f=[...f,...Z])}let S=(()=>{let F=t.browser??r.browser??"chromium",H=(Array.isArray(F)?F:String(F).split(",")).map(W=>String(W).trim()).filter(Boolean),Z=H.find(W=>!Tg(W));return(Z!==void 0||H.length===0)&&(console.error(`invalid --browser "${Z??""}": use ${ml.map(W=>`"${W}"`).join(", ")}, or a list of them`),process.exit(2)),[...new Set(H)].sort((W,he)=>+!yr(W)-+!yr(he))})(),v=S.length>1,x;if(t.shardBy!==void 0&&t.shard===void 0&&(console.error("saffron: --shard-by needs --shard, e.g. --shard 2/4 --shard-by file"),process.exit(2)),t.shard!==void 0){try{let F=kp(String(t.shardBy??r.shardBy??"scenario")),H=Rp(f,{...$p(String(t.shard)),by:F});if(f=H.scenarios,v)throw new Error("saffron: a browser matrix and --shard do not mix: give each shard job one --browser (a CI matrix runs them side by side)");x={...H.info,ciRun:bi(),attempt:xi(),browser:S[0]}}catch(F){console.error(F instanceof Error?F.message:String(F)),process.exit(2)}if(console.log(`shard ${x.index}/${x.total}${x.by==="file"?" (by file)":""}: ${f.length} of ${x.suiteSize} scenario(s)`),f.length===0){let F=new Date,H=Wc([],F,s),Z=Uc([],F,nn(n).divergent.length,s);console.log(`report: ${Xc(n,{...H,shard:x,history:Z})}`),process.exit(0)}}t.rerecord&&t.agent===!1&&(console.error("saffron: --rerecord needs the agent; drop --no-agent"),process.exit(2)),t.rerecord&&!S.some(yr)&&(console.error(`saffron: --rerecord needs a browser that can record (chromium, chrome or msedge); ${S.join(", ")} only replay`),process.exit(2));let b=t.rerecord?Hi(u):[];b.length>0&&(console.error(`saffron: --rerecord needs the agent, and ${_n[u]} cannot start here: ${b.join("; ")}`),process.exit(2));{let F=f;try{let Z=[...new Set([...sa(n,r.features?[r.features]:[]),...l])],W=mt(n,r,Z);F=Z.flatMap(he=>{try{return nt(he,n,W)}catch{return[]}})}catch{}let H=hu(n,F);if(H.length>0){console.error("cache path collision:");for(let Z of H)console.error(` ${Z}`);process.exit(2)}}let m=[],$=[];if(t.hooks!==!1)try{m=Il(r.setup,"setup"),$=Il(r.teardown,"teardown")}catch(F){console.error(F instanceof Error?F.message:String(F)),process.exit(2)}let T=t.device??r.device,R=T===void 0?void 0:String(T);if(R!==void 0&&(typeof T!="string"||!wl.includes(R))){let F=wl.filter(H=>H.toLowerCase().includes(R.toLowerCase().split(" ")[0])).slice(0,8);console.error(`unknown --device "${R}". ${F.length>0?`Close: ${F.map(H=>`"${H}"`).join(", ")}`:'Use a Playwright device name, e.g. "iPhone 15", "Pixel 7" or "Desktop Chrome"'}`),process.exit(2)}let k=t.viewport??r.viewport,C=k===void 0?void 0:Ag(String(k));k!==void 0&&!C&&(console.error(`invalid --viewport "${k}": use WIDTHxHEIGHT, e.g. 1280x720`),process.exit(2));let P=F=>Math.max(1,Number.parseInt(String(F??1),10)||1),w=P(t.workers??r.workers),E=P(t.agentWorkers??r.agentWorkers),_=t.agent?uh(u,{model:t.model??p.model,maxTurns:r.maxTurns,snapshotMode:r.snapshotMode}):void 0,A=(F,H)=>F!==void 0?{name:F,source:"flag"}:H!==void 0?{name:H,source:"config"}:void 0,O=fh[u],j=O&&Eu(O),L=_?{provider:u,model:A(t.model,p.model),healModel:A(t.healModel,p.healModel),...O&&j?{sdk:{name:O,version:j}}:{}}:{},I=(()=>{let F=t.trace??r.trace??"off";return fc.includes(F)||(console.error(`invalid --trace "${F}": use ${fc.map(H=>`"${H}"`).join(", ")}`),process.exit(2)),F})(),U=(()=>{let F=t.assertionPolicy??r.assertionPolicy??"strict";return F!=="strict"&&F!=="adaptable-mid"&&(console.error(`invalid --assertion-policy "${F}": use "strict" or "adaptable-mid"`),process.exit(2)),F})(),D=new Map,q={},Y=F=>new Ei({filedThisRun:D,agentHalt:q,projectRoot:n,baseURL:s,headed:t.headed,actionTimeoutMs:r.actionTimeoutMs,pollIntervalMs:r.pollIntervalMs,screenshot:r.screenshot,trace:I,retries:r.retries,storageState:t.storageState??r.storageState,sessions:r.sessions,browser:F,device:R,viewport:C,timezone:r.timezone,artifactsPerBrowser:v,healModel:t.healModel??p.healModel,rerecord:t.rerecord===!0,verifyProposals:t.verify===!1?!1:r.verifyProposals,reuseSteps:t.reuse===!1?!1:r.reuseSteps,assertionPolicy:U,agent:_}),Q=new AbortController,N=()=>new Promise(()=>{}),M=new Set,B=async F=>{if(Q.signal.aborted)return N();let H=Y(F);return M.add(H),await H.start(),H},J=async F=>{for(let H of[...F])M.delete(H),await H.stop()},ne=new Date,Me=[],et=new Map,De=new Map,Ie=async(F,H,Z,W,he)=>{if(Q.signal.aborted)return N();let Ct=v?`${H} \xB7 ${Z}`:Z,ot=Date.now(),oe;try{oe=await F.runScenario(W,he)}catch(da){if(Q.signal.aborted)return N();throw da}if(Q.signal.aborted)return N();let We=Date.now(),Fe=et.get(Ct)??{worker:Ct,runs:0,busyMs:0,spanMs:0,browser:H};et.set(Ct,Fe),Fe.runs++,Fe.busyMs+=We-ot;let Re=De.get(H)??{first:ot,last:We};return De.set(H,{first:Math.min(Re.first,ot),last:Math.max(Re.last,We)}),oe.worker=Ct,oe.browser=H,oe},Qt=F=>{let H=F.scenario,Z=k$[F.status],W=F.usage.inputTokens+F.usage.outputTokens,he=F.usage.cacheReadTokens+F.usage.cacheCreationTokens,Ct=he>0?`, ${td(he)} cache traffic`:"";console.log(`${Z}${F.status.toUpperCase().padEnd(7)}${R$}${H.displayName}${v?` [${F.browser}]`:""} (${F.source}, ${F.durationMs}ms, ${F.usage.aiCalls} AI calls, ${W} tokens${Ct})`);for(let oe of F.adaptations)console.log(` \u26A0 ${oe}`);F.status==="yellow"&&F.usage.aiCalls===0&&F.narrative&&console.log(` ${F.narrative}`),F.seededSteps&&console.log(` \u26A1 ${F.seededSteps}/${F.stepResults.length} steps seeded from existing recordings (zero AI)`);let ot=F.stepResults.reduce((oe,We)=>oe+(We.retries??0),0);ot&&console.log(` \u21BB ${ot} action ${ot===1?"retry":"retries"} absorbed before settling (retries: ${r.retries??1} per action)`),F.verified===!0?console.log(" \u2713 proposal verified by zero-AI proof replay"):F.verified===!1&&console.log(` \u2717 proposal UNVERIFIED, proof replay failed: ${F.proofError?.split(`
|
|
1400
|
+
`)[0]}`),F.error&&console.log(` ${F.error}`)};console.log(`saffron-ai ${ut()} \xB7 ${pi(L,_n[u])}`);let pt={cwd:n,timeoutMs:r.hookTimeoutMs??Fr.hookTimeoutMs,env:{SAFFRON_BASE_URL:s,SAFFRON_ENV:it().env,SAFFRON_SHARD:x?`${x.index}/${x.total}`:void 0}},jn=[],$m,Rr=()=>$m??=jl("teardown",$,pt).then(F=>{jn.push(...F)}),ia=Promise.resolve([]),rd=!1,aa=o.picks.size>0,sd=async F=>{rd=!0;let H=F.flat().filter(xe=>xe!==void 0),Z=f.length*S.length-H.length,W=Wc(H,ne,s);if(Z>0&&Object.assign(W,{interrupted:!0,notRun:Z}),W.provenance=L,jn.length>0&&(W.hooks=jn),et.size>0){let xe=[...De.values()];W.timing={wallMs:Math.max(...xe.map(gt=>gt.last))-Math.min(...xe.map(gt=>gt.first)),workers:[...et.values()].sort((gt,pn)=>S.indexOf(gt.browser)-S.indexOf(pn.browser)||gt.worker.localeCompare(pn.worker,void 0,{numeric:!0})).map(({browser:gt,...pn})=>({...pn,spanMs:De.get(gt).last-De.get(gt).first}))}}v&&(W.browsers=S);let he=nn(n).divergent.length,Ct=aa||Z>0,ot={...Uc(H,ne,he,s),...Ct?{partial:!0}:{}};x||(Ct||(W.trends=qc(Fs(n),ot)),zc(n,ot)),W.totals.aiCalls>0&&(W.totals.plan=await _?.planUsage?.());let oe,We=!1,Fe=0;if(x){let xe=x.positions.filter((I$,Tm)=>F[0]?.[Tm]!==void 0),gt=Xc(n,{...W,shard:{...x,positions:xe},history:ot}),pn=gt.replace(/\.json$/,".html");Ne.writeFileSync(pn,Gn(W,n)),oe=`${pn}
|
|
1401
|
+
${gt}`}else{let xe=aa?Zc(Yc(n),W):W;We=xe!==W,Fe=xe.scenarios.length-W.scenarios.length;let{html:gt,json:pn}=Hs(n,xe);oe=`${gt}
|
|
1402
|
+
${pn}`}let Re=W.totals,da=Re.cacheReadTokens+Re.cacheCreationTokens;console.log(`
|
|
1403
|
+
${Re.green} passed, ${up(Re.yellow,W.scenarios.filter(lr).length)}, ${Re.red} failed \xB7 ${Re.aiCalls} AI calls \xB7 ${(Re.inputTokens+Re.outputTokens).toLocaleString()} tokens in+out${da>0?` \xB7 ${td(Re.cacheReadTokens)} cache read \xB7 ${td(Re.cacheCreationTokens)} cache written`:""}${Nc(Re)}${Re.models?.length?` \xB7 ${Re.models.join(", ")}`:""}`);let ds=W.timing;ds&&ds.workers.length>1&&ds.wallMs>0&&console.log(`workers over ${st(ds.wallMs)}: ${ds.workers.map(xe=>`${xe.worker} ${Jc(xe)} busy`).join(" \xB7 ")}`),W.scenarios.length>3&&console.log(`slowest: ${Hc(W,3).map(xe=>`${xe.scenario}${W.browsers&&xe.browser?` [${xe.browser}]`:""} ${st(xe.durationMs)}`).join(" \xB7 ")}`);let ua=W.trends;ua?.prev&&console.log(Mc(ua.prev));for(let xe of ua?.chronic??[])console.log(`\u26A0 chronic: ${xe.feature} \u203A ${xe.scenario}: ${xe.heals} heal(s), ${xe.reds} red(s) in last ${xe.runs} run(s); re-record or fix the feature text instead of paying for more heals`);return Z>0&&console.log(`interrupted: the report is partial. ${H.length} scenario(s) finished; ${Z} did not run, and count as neither passed nor failed`),console.log(`report: ${oe}`),aa&&!x&&console.log(ym(We,Fe)),x&&console.log(`shard report, not a whole run: history and trends wait for \`saffron report --merge\` over all ${x.total} shard-*-of-${x.total}.json files`),W};process.on("SIGINT",()=>{if(rd){console.error(`
|
|
1404
|
+
the report is being written, then Saffron exits`);return}if(Q.signal.aborted){console.error($.length>0?"still cleaning up: teardown finishes, then Saffron exits":"still stopping: Saffron writes the report, then exits");return}let F=Me.map(H=>Array.from(H));console.error(`
|
|
1405
|
+
interrupted: stopping${$.length>0?", then running teardown":""}, then writing the report of what finished`),Q.abort(),ia.then(()=>J(M)).catch(()=>{}).then(Rr).then(async()=>{F.flat().some(H=>H!==void 0)?await sd(F):console.log("interrupted before any scenario finished: the last report and history were kept as they were")}).catch(H=>console.error(`saffron: the report was not written: ${H instanceof Error?H.message:String(H)}`)).finally(()=>process.exit(130))}),m.length>0&&(ia=jl("setup",m,{...pt,signal:Q.signal}),jn.push(...await ia),Q.signal.aborted&&await N(),jn.some(Ki)&&(console.error("No scenario was run: the application is not in the state the suite expects."),await Rr(),process.exit(2)));let ca=it();Ut(ca.root,ca.dir,ca.env);{let F=new Map;for(let Z of f)for(let W of ct(Z))process.env[W]===void 0&&!F.has(W)&&F.set(W,Z.displayName);let H=new Map;for(let Z of f){for(let W of hn(at(Z)))if(!H.has(W))try{wo(W)}catch(he){H.set(W,`${he instanceof Error?he.message:String(he)} (used by "${Z.displayName}")`)}for(let W of at(Z).flatMap(he=>Dd(he))){let he=H.has(W)?void 0:Eo(W);he&&H.set(W,`${he} (used by "${Z.displayName}")`)}}if(H.size>0){for(let Z of H.values())console.error(Z);await Rr(),process.exit(2)}if(F.size>0){for(let[Z,W]of F)console.error(`missing environment variable ${Z} (referenced as {env:${Z}} by "${W}")`);console.error("set the variable(s), or add them to a git-ignored .env in the project root"),await Rr(),process.exit(2)}}let go=new Map;try{for(let F of S)go.set(F,await B(F))}catch(F){throw await J(M).catch(()=>{}),await Rr(),F instanceof _t&&(console.error(F.message),process.exit(2)),F}let km=async F=>{let H=go.get(F),Z=new Array(f.length);if(Me.push(Z),w===1&&E===1||f.length===1){for(let oe=0;oe<f.length;oe++)Z[oe]=await Ie(H,F,"1",f[oe]),Qt(Z[oe]);return Z}let W=_!==void 0&&yr(F),he=[];await ul(f.map((oe,We)=>[{s:oe,i:We}]),w,async(oe,We)=>{let Fe=await Ie(H,F,String(We+1),oe.s,{agentDisabled:!0});Fe.status==="red"&&W?he.push(oe):(Z[oe.i]=Fe,Qt(Fe))});let Ct=vg(he.sort((oe,We)=>oe.i-We.i),oe=>pe(n,oe.s.featurePath,oe.s.name)),ot=[];try{for(let Fe=1;Fe<Math.min(E,Ct.length);Fe++)try{ot.push(await B(F))}catch(Re){console.log(` \u26A0 agent worker ${Fe+1} could not start a browser (${(Re instanceof Error?Re.message:String(Re)).split(`
|
|
1406
|
+
`)[0]}); going on with ${Fe}`);break}let oe=[H,...ot],We=oe.length;await ul(Ct,We,async(Fe,Re)=>{Z[Fe.i]=await Ie(oe[Re],F,We>1?`agent ${Re+1}`:"agent",Fe.s),Qt(Z[Fe.i])})}finally{await J(ot)}return Z};try{if(t.rerecord){let F=0;for(let H of f){let Z=pe(n,H.featurePath,H.name);Ne.existsSync(Z)&&(Ne.rmSync(Z),F++)}console.log(`rerecord: removed ${F} cache file(s) for ${f.length} scenario(s); the agent records them fresh (seeded from the other recordings). Restore with git if needed.`)}for(let F of S)v&&console.log(`
|
|
1407
|
+
${F}${yr(F)?"":" (replay only: recording and healing need a Chromium-family browser)"}`),await km(F),await J([go.get(F)]),go.delete(F)}finally{Q.signal.aborted&&await N(),await J(M),await Rr()}Q.signal.aborted&&await N();let ho=(await sd(Me)).totals,od=sn(V.resolve(te.opts().projectRoot),po);od.length>0&&console.log(`${od.length} cache proposal(s) pending. Review with: saffron accept | saffron reject. Until a proposal is accepted, other scenarios do not reuse its steps: accept a shared setup before recording more scenarios that use it.`);let id=t.strict??r.strict??!1;id&&ho.yellow>0&&console.log(`strict mode: ${ho.yellow} scenario(s) pending review treated as failure. Review proposals to go green.`);let Rm=ho.red>0||id&&ho.yellow>0,la=jn.filter(F=>F.phase==="teardown"&&Ki(F));la.length>0&&console.log(`teardown failed: ${la.map(F=>Nl(F,pt.timeoutMs)).join("; ")}. The environment may hold data from this run.`),process.exit(Rm?1:la.length>0?2:0)});te.command("accept").description("Promote pending cache proposals to committed caches").argument("[files...]","proposal file(s) (default with --all: every pending proposal, less those --all leaves out)").option("--all","accept every pending proposal that is verified and was not imported from a CI run (see --include-unverified, --include-imported)").option("--with-feature-edit","also apply the proposal's suggested .feature step rewrites").option("--propagate","apply the same locator fixes to every other cache using the same locator").option("--include-unverified","with --all: also accept proposals that are unverified or not checked (their proof replay failed, or did not run)").option("--include-imported","with --all: also accept proposals imported from a CI run (saffron import), which --all leaves for review by file").action((e,t)=>{let n=V.resolve(te.opts().projectRoot),r=_e(n),s=t.all&&!t.includeImported?En(n):{},o=0,a=e.length>0?e.map(Ua).map(i=>({...i,file:V.resolve(i.file)})):t.all?sn(n,po).map(i=>({file:i.file,revision:void 0})):[];if(a.length===0){Sm(n);return}try{for(let{file:i,revision:c}of a){let l=x=>{console.log(`not accepted: ${V.basename(i)} ${qe(x)}`),process.exitCode=1},d=vm(n,i,c!==void 0,()=>{if(c&&jt(i)!==c)return l(xm);let x=s[V.relative(n,i).split(V.sep).join("/")];if(x&&jt(i)===x.revision){o++;return}let b;try{b=zr(i)}catch(T){if(!(T instanceof ke))throw T;return l(`cannot be read: ${T.problem}`)}if(b.meta.bound){let T=At(n,b,mt(n,r,[]));if(T)return l(`is stale: ${T}. Run the scenario again for a proposal made against what is there now, or reject this one.`)}else console.log(`\u26A0 ${V.basename(i)} is ${ui}; accepting as it is.`);if(b.meta.verified!==!0&&t.all&&!t.includeUnverified){let T=b.meta.verified===!1?b.meta.proofError?.split(`
|
|
1408
|
+
`)[0]:"not checked: no proof replay ran";console.log(`skipped UNVERIFIED ${V.basename(i)} (${qe(T)}). Re-record it (saffron run --rerecord), or accept it explicitly by file, or pass --include-unverified.`);return}b.meta.verified===!1&&console.log(`\u26A0 accepting UNVERIFIED proposal (proof replay failed: ${qe(b.meta.proofError?.split(`
|
|
1409
|
+
`)[0])}): expect a heal or red on the next run.`);let m=b.cache.steps.map(T=>T.gherkin);if(t.withFeatureEdit&&(b.meta.featureEdits??[]).length>0){let T=_h(n,b.cache.feature,b.cache.scenario,m,mt(n,r,[]));if(T)return l(`carries feature edits, and ${T}. Run the scenario again for a fresh proposal, or accept this one without --with-feature-edit.`)}let $=Ye(pe(n,b.cache.feature,b.cache.scenario));return{proposal:b,recordedSteps:m,oldCache:$,cacheFile:Bo(n,i)}},l);if(!d)continue;let{proposal:u,recordedSteps:p,oldCache:f,cacheFile:g}=d;console.log(`accepted \u2192 ${g}`);let y=f?Ah(f,u.cache):{changes:[],ambiguous:[]},h=y.changes;for(let x of y.ambiguous)console.log(` locator fix for ${qe(Wi(x))} not propagated: this heal sent it to more than one place, so other caches are left alone.`);if(h.length>0){let x=Eh(n,h,g,!t.propagate);for(let b of h)console.log(` locator fix: ${qe(Wi(b.from))} \u2192 ${qe(Wi(b.to))}`);if(x.length===0)console.log(" no other caches use this locator.");else if(t.propagate)for(let b of x)console.log(` propagated \u2192 ${b.feature} \u203A ${b.scenario} (${b.steps.map(m=>`"${m.gherkin}"`).join(", ")})`);else{console.log(` ${x.length} other cache(s) use the same locator: re-run with --propagate to fix them too:`);for(let b of x)console.log(` \xB7 ${b.feature} \u203A ${b.scenario}`)}}let S=u.meta.featureEdits??[];if(!t.withFeatureEdit||S.length===0)continue;let v=Ch(n,u.cache.feature,u.cache.scenario,S,mt(n,r,[]),p);for(let x of v.applied){let b=x.fromStepSet?`${x.file}:${x.line} (StepSet "${x.fromStepSet}", fixes every invoking scenario)`:`${x.file}:${x.line}`;console.log(` feature edit ${b}:`),console.log(` - ${x.from}`),console.log(` + ${qe(x.to)}`)}for(let x of v.skipped)console.log(` skipped edit [${x.index}]: ${qe(x.reason)}`);if(v.appliedIndices.length>0){let x=new Set(v.appliedIndices),b=Ye(g);for(let m of S)x.has(m.index)&&m.text.trim()!==""&&b.steps[m.index]&&(b.steps[m.index].gherkin=m.text);Dr(g,b)}}}catch(i){throw i instanceof Be&&oa(i),i}o>0&&console.log(`skipped ${o} proposal${o===1?"":"s"} imported from a CI run: review ${o===1?"it":"them"} (saffron diff) and accept by file, or pass --include-imported.`)});te.command("steps").description("List/search the project's step vocabulary (files + caches): what exists, what's recorded, what to reuse").argument("[search]","case-insensitive substring filter").option("--json","machine-readable vocabulary").option("--snippets","write .vscode/saffron.code-snippets for native VS Code completion").action((e,t)=>{let n=V.resolve(te.opts().projectRoot),r=_e(n),s;try{s=rn(n,r.features??"features")}catch(a){throw a instanceof Be&&oa(a),a}if(e&&(s=Mo(s,e)),t.json){console.log(JSON.stringify(s,null,2));return}if(t.snippets){let a=V.join(n,".vscode","saffron.code-snippets");Ne.mkdirSync(V.dirname(a),{recursive:!0}),Ne.writeFileSync(a,$u(s)),console.log(`wrote ${s.steps.length} step + ${s.stepSets.length} StepSet snippet(s) \u2192 ${a}`),console.log("re-run after recording sessions to keep completions current");return}let o={recorded:"\x1B[32m\u25CF\x1B[0m",divergent:"\x1B[33m\u25CF\x1B[0m",unrecorded:"\u25CB"};if(s.stepSets.length>0){console.log("step sets:");for(let a of s.stepSets)console.log(` ${a.name} (${a.steps.length} steps, ${a.usage} scenario(s)), ${a.file}:${a.line}`);console.log("")}for(let a of s.steps){let i=a.fromStepSet?` [${a.fromStepSet}]`:"";console.log(`${o[a.status]} ${a.keyword} ${a.text} \xD7${a.usage}${i}`)}console.log(`
|
|
1410
|
+
${s.steps.length} step(s) across ${s.scannedFiles} file(s) \xB7 ${s.scannedCaches} cache(s) \xB7 \x1B[32m\u25CF\x1B[0m recorded (replays free) \xB7 \x1B[33m\u25CF\x1B[0m divergent \xB7 \u25CB unrecorded`)});te.command("author").description("Draft a feature file from plain-paragraph requirements, reusing the project's step vocabulary (AI)").argument("<prose-file>","text/markdown file with the requirements").option("-o, --out <file>","output path (default: features/<name>.saffron)").option("--provider <name>",'whose agent writes the draft: "claude" (default), "codex", "antigravity" or "cursor"').option("--model <model>","model for authoring").action(async(e,t)=>{let n=V.resolve(te.opts().projectRoot),r=_e(n),s=nd(t.provider,r.provider),o=Ne.readFileSync(V.resolve(e),"utf8"),a;try{a=rn(n,r.features??"features")}catch(d){throw d instanceof Be&&oa(d),d}console.log(`authoring with ${a.steps.length} known step(s) and ${a.stepSets.length} step set(s) as vocabulary\u2026`);let i=await eg(o,a,t.model??hm(r,s).model,s==="claude"?void 0:Tl[s]),c=t.out?V.resolve(t.out):V.join(n,r.features??"features",`${V.basename(e).replace(/\.[^.]+$/,"")}.saffron`);Ne.existsSync(c)&&(console.error(`refusing to overwrite ${c}: pass --out for a new path`),process.exit(1)),Ne.mkdirSync(V.dirname(c),{recursive:!0}),Ne.writeFileSync(c,i.content);let l=i.content.split(`
|
|
1411
|
+
`).map(d=>d.trim().replace(/^(Given|When|Then|And|But|\*)\s+/,"")).filter(d=>a.steps.some(u=>u.text===me(d))).length;console.log(`wrote ${c}`),console.log(`${l} step line(s) reuse the existing vocabulary (seedable)${i.usage.costUsd?` \xB7 $${i.usage.costUsd.toFixed(4)}`:""}`),console.log("draft only: browser behavior and replay have not been validated."),console.log("inspect the relevant UI, resolve assumptions, then record affected scenarios: saffron run "+V.relative(process.cwd(),c)+":<line>"),console.log("review with saffron diff; accept only faithful, verified proposals, then replay the affected scenarios with --no-agent.")});te.command("login").description("Check or set up an AI provider's login on this machine (Cursor: a one-time sign-in for Saffron; Antigravity: allows Saffron's tools in agy)").argument("[provider]",'"claude", "codex", "antigravity" or "cursor" (default: the configured provider)').action(async e=>{let t=V.resolve(te.opts().projectRoot),n=nd(e,_e(t).provider),r=n==="cursor"?ah:n==="antigravity"?eh:void 0;if(r)try{await r()}catch(o){console.error(o instanceof Error?o.message:String(o)),process.exit(1)}let s=Al(n);if(s.length===0){console.log(`${_n[n]}: ready to record and heal.`);return}console.log([`${_n[n]} still needs:`,...s.map(o=>` \xB7 ${o}`)].join(`
|
|
1412
|
+
`)),process.exit(1)});te.command("mcp").description("Serve the step vocabulary to AI assistants over stdio MCP (search_steps, list_step_sets)").action(async()=>{let e=V.resolve(te.opts().projectRoot),t=_e(e);await Yp(e,t.features??"features")});te.command("lsp").description("Run the Saffron language server over stdio (completion, go-to-definition, hover, diagnostics). For JetBrains (LSP4IJ / Ultimate LSP API), Neovim, and any LSP-capable editor").action(()=>{process.stdin.isTTY&&(console.error(dm(bs())),process.exit(2));let e=V.resolve(te.opts().projectRoot),t=_e(e),n=process.argv.includes("-p")||process.argv.some(r=>r.startsWith("--project-root"));bg(e,t.features??"features",{rootFromClient:!n})});te.command("reject").description("Discard pending cache proposals (AI will retry next run)").argument("[files...]","proposal file(s)").option("--all","reject all pending proposals").action((e,t)=>{let n=V.resolve(te.opts().projectRoot),r=e.length>0?e.map(Ua).map(s=>({...s,file:V.resolve(s.file)})):t.all?sn(n,po).map(s=>({file:s.file,revision:void 0})):[];if(r.length===0){Sm(n);return}for(let{file:s,revision:o}of r){let a=vm(n,s,o!==void 0,()=>{if(o&&jt(s)!==o)return xm;Uo(s)},i=>i);if(a){console.log(`not rejected: ${V.basename(s)} ${a}`),process.exitCode=1;continue}console.log(`rejected ${s}`)}});te.command("init").description("Make the project agent-ready: install the bundled Saffron skill into agent directories, add instructions to AGENTS.md, scaffold config").option("--agents <list>",`comma-separated targets: ${Object.keys(uo).join(", ")} (default: claude,agents)`).option("--no-instructions","do not touch AGENTS.md / CLAUDE.md").option("--no-scaffold","do not create saffron.config.json, features/, .gitignore entry").option("--no-mcp","do not register `saffron mcp` in project MCP configs (.mcp.json, .cursor/mcp.json, .vscode/mcp.json)").option("--examples","install the Saucedemo example suite (features, config, .env.example) for a guided first run").option("--no-examples","never install the example suite (skips the prompt)").action(async e=>{let t=V.resolve(te.opts().projectRoot),n=bs();n||(console.error("saffron: cannot locate the installed package root"),process.exit(2));let r=e.agents?String(e.agents).split(",").map(a=>a.trim()).filter(Boolean):void 0;for(let a of r??[])a in uo||(console.error(`saffron: unknown agent target "${a}" (expected one of ${Object.keys(uo).join(", ")})`),process.exit(2));let s=e.examples===!0;e.examples===void 0&&process.stdin.isTTY&&process.stdout.isTTY&&(s=await $$(`Install the Saucedemo example tests (login, cart, checkout) into ${ea(t).features}/ for a guided first run? [y/N] `));let o=cm({projectRoot:t,packageRoot:n,targets:r,instructions:e.instructions,scaffold:e.scaffold,mcp:e.mcp,examples:s});for(let a of o.skillDirs)console.log(`skill \u2192 ${a}/`);for(let a of o.mcpFiles)console.log(`${a.outcome.padEnd(9)} \u2192 ${a.file} (saffron mcp server)`);for(let a of o.mcpHints)console.log(`mcp hint \u2192 ${a}`);for(let a of o.instructionFiles)console.log(`${a.outcome.padEnd(9)} \u2192 ${a.file} (managed Saffron block)`);for(let a of o.scaffolded)console.log(`created \u2192 ${a}`);o.examples&&!o.examples.installed&&console.log(`examples \u2192 not installed: ${o.examples.reason}`),o.examples?.note&&console.log(`examples \u2192 note: ${o.examples.note}`),console.log("\nAgents now load the saffron skill when writing tests. Re-run after `npm update saffron-ai` to refresh it."),o.examples?.installed&&console.log(["","Your guided first run (recording needs Claude credentials; replays never do):"," cp .env.example .env # public demo credentials, resolved at replay"," npx playwright install chromium"," npx saffron run --filter @smoke # the agent records two scenarios (about $3 of AI usage), files proposals"," npx saffron accept --all # review, then promote them to caches"," npx saffron run --filter @smoke # replays at zero tokens","Then try the rest: npx saffron run (login errors outline, checkout with a data table)"].join(`
|
|
1413
|
+
`))});te.command("export").description("Pack the pending proposals, the last run's report and its screenshots and traces into one bundle, for review on another checkout (CI uploads it as an artifact)").option("-o, --out <file>","where to write the bundle (default: .saffron/reports/saffron-bundle.zip)").option("--branch <name>","also commit the pending proposals (not the caches) onto the commit the run tested as a new branch, push it to origin, and open a draft pull request (GitHub through gh, Azure DevOps through az)").option("--base <branch>","with --branch: the branch the pull request is for (default: the branch the run tested)").option("--report-only","a summary instead: the last run's report and screenshots, no proposals and no traces (default: .saffron/reports/saffron-summary.zip). Small enough to upload on every run, so editors can show any run's results; a run that left only summaries has nothing to import").action(e=>{let t=V.resolve(te.opts().projectRoot);e.base!==void 0&&e.branch===void 0&&(console.error("saffron export: --base needs --branch"),process.exit(2)),e.reportOnly&&e.branch!==void 0&&(console.error("saffron export: --report-only holds no proposals, so there is nothing for --branch to push"),process.exit(2));try{lo("--branch",e.branch),lo("--base",e.base)}catch(i){console.error(`saffron export: ${i.message}`),process.exit(2)}let n;try{n=Np(t,{out:e.out?V.resolve(e.out):void 0,summary:e.reportOnly===!0})}catch(i){console.error(`saffron export: ${i instanceof Error?i.message:String(i)}`),process.exit(2)}for(let i of n.unreadable)console.error(`\u26A0 proposal ${i.file} cannot be read: ${qe(i.problem)}. Left out of the bundle.`);let r=n.manifest;if(console.log(`${r.summary?"summary":"bundle"}: ${n.file}`),console.log(r.summary?` the run's report \xB7 ${r.evidence.length} screenshot(s)${r.shard?` \xB7 shard ${r.shard.index}/${r.shard.total}`:""}`:` ${r.proposals.length} proposal(s) \xB7 ${r.evidence.length} screenshot and trace file(s) \xB7 ${r.report?"the run's report":"no run report"}${r.shard?` \xB7 shard ${r.shard.index}/${r.shard.total}`:""}`),console.log(` from ${Ws(r)}`),n.missing.length>0&&console.log(` ${n.missing.length} file(s) the report names are gone, or were replaced by a later run: left out`),n.dropped.length>0&&console.log(` ${n.dropped.length} trace(s) of green scenarios left out: with them the bundle would be over the 4 GB one bundle holds`),r.summary){console.log("Upload it as a saffron-summary* artifact: saffron runs marks the run, and saffron report --run <id> shows its results.");return}if(console.log("Review it in a checkout of this repository with: saffron import <bundle>"),e.branch===void 0)return;if(n.proposals.length===0){console.log("No pending proposals: no branch to push.");return}let s;try{let i=_e(t);s=rm(t,n,String(e.branch),{base:e.base,config:i})}catch(i){console.error(`saffron export: the bundle is written, but no branch was pushed: ${i instanceof Error?i.message:String(i)}`),process.exit(2)}for(let i of s.leftOut)console.error(`\u26A0 left out of the branch: ${V.relative(t,i.file)} ${i.reason}`);let o=n.proposals.length-s.leftOut.length,a=o===1?"the proposal":`${o} proposals`;console.log(`branch: ${s.branch} pushed to origin (${s.commit.slice(0,7)}: ${a} on top of ${s.parent.slice(0,7)})`),s.pullRequest?console.log(`draft pull request: ${s.pullRequest}`):(console.log(`no pull request: ${s.noPullRequest}. Open one from ${s.branch} to ${s.base}; its description is in ${s.bodyFile}`),s.failed&&(process.exitCode=1))});te.command("eject").description("Write the committed recordings as Playwright Test specs you own from then on: one spec per feature file, a helper file beside them, and playwright.config.ts when there is none. Never looser than replay: what has no faithful form is written as test.fixme with the reason").argument("[files...]","feature files (default: the features folder)").option("-o, --out <dir>","folder for the specs, in the project (default: playwright)").option("--force","replace files saffron eject did not write").option("--json","machine-readable output").action((e,t)=>{let n=V.resolve(te.opts().projectRoot),r=e.find(a=>!Ne.existsSync(V.resolve(n,a)));r!==void 0&&(console.error(`${r} does not exist (in ${n}).`),process.exit(2));let s=bs();s||(console.error("saffron: cannot locate the installed package root"),process.exit(2));let o;try{o=pm(n,_e(n),{out:t.out,files:e.length>0?sa(n,e):void 0,force:t.force===!0,packageRoot:s})}catch(a){console.error(`saffron eject: ${a instanceof Error?a.message:String(a)}`),process.exit(2)}if(t.json)console.log(JSON.stringify(o,null,2));else{let a={exported:"\u2713",stricter:"~",fixme:"\u2717"};for(let l of o.tests){console.log(`${a[l.outcome]} ${l.feature}: ${l.test}`);for(let d of l.notes)console.log(` ${l.outcome==="fixme"?"fixme":"stricter"}: ${d}`)}let i=l=>o.tests.filter(d=>d.outcome===l).length,c=[...new Set(o.tests.flatMap(l=>l.stricterChecks))];if(c.length>0){console.log(`
|
|
1414
|
+
Stricter than replay wherever they appear:`);for(let l of c)console.log(` ${l}: ${ta[l].why}`)}console.log(`
|
|
1415
|
+
${i("exported")} exported, ${i("stricter")} stricter than replay, ${i("fixme")} written as test.fixme`);for(let l of o.written)console.log(`wrote ${l}`);for(let l of o.kept)console.log(`kept ${l}: saffron eject did not write it (replace it with --force)`);console.log("Run them with: npx playwright test")}o.tests.some(a=>a.outcome!=="fixme")||(process.exitCode=1)});te.command("runs").description("List the CI runs of the checkout's branch (GitHub Actions through gh, Azure Pipelines through az), with how many of each run's proposals are pending here; import one with saffron import --run <id>").option("--branch <name>","another branch (default: the checkout's; every branch on a detached HEAD)").option("--limit <n>","how many runs (default 20)").option("--provider <name>",`"github" or "azure" (default: ci.provider in the config, else the repository's host)`).option("--json","machine-readable output").action(e=>{let t=V.resolve(te.opts().projectRoot),n=e.limit===void 0?void 0:Number(e.limit);n!==void 0&&!(Number.isInteger(n)&&n>0)&&(console.error(`invalid --limit "${e.limit}": use a whole number above 0`),process.exit(2));let r;try{r=qh(t,_e(t),{provider:e.provider,branch:e.branch,limit:n})}catch(a){let i=a instanceof Error?a.message:String(a);e.json?console.log(JSON.stringify({error:i},null,2)):console.error(`saffron runs: ${i}`),process.exit(2)}if(r.problem&&(process.exitCode=2),e.json){console.log(JSON.stringify(r.problem?{...r,error:r.problem.message}:r,null,2));return}if(r.problem){console.error(`saffron runs: ${r.problem.message}`);return}let s=`${Qi[r.provider]} runs ${r.branch?`on ${r.branch}`:"on every branch"}`;if(r.runs.length===0){console.log(`No ${s}.`);return}let o=a=>a.status!=="completed"?"\u25CF":a.conclusion==="success"?"\u2713":a.conclusion==="failure"?"\u2717":"\u25CB";console.log(`${s}:`);for(let a of r.runs){let i=[`${a.name} #${a.number}`,a.status==="completed"?a.conclusion:a.status.replace("_"," "),Bh(a.createdAt),a.commit?.slice(0,7),a.pending?`${a.pending} proposal${a.pending===1?"":"s"} pending here`:void 0,a.results?.kind==="running"?void 0:a.results?.label].filter(Boolean);console.log(` ${a.id.padStart(12)} ${o(a)} ${i.join(" \xB7 ")}`)}console.log("Import one with: saffron import --run <id>")});te.command("import").description("Bring a bundle from `saffron export` (a CI run) into this checkout: its proposals, each checked against the files here, and the run's report, screenshots and traces. Then review and accept as usual").argument("[bundles...]","bundle files, folders holding saffron-bundle*.zip (a CI artifact download), or http(s) URLs").option("--run <id>","instead: download the bundles of this CI run (an id from saffron runs) through gh or az, and import them").option("--provider <name>",`with --run: "github" or "azure" (default: ci.provider in the config, else the repository's host)`).option("--allow-fork","with --run: import a run a fork's pull request started (code from outside this repository made its bundle); read that pull request first").option("--overwrite","replace a different proposal already pending here for the same scenario").option("--allow-unknown-repository","import a bundle that does not say which repository it comes from (made outside a git checkout); its proposals are still checked by their bindings").option("--json","machine-readable output").action(async(e,t)=>{let n=V.resolve(te.opts().projectRoot);function r(d,u=!1){t.json?console.log(JSON.stringify({error:d},null,2)):console.error(`saffron import: ${d}${u?"":". Nothing was imported."}`),process.exit(2)}t.run===void 0==(e.length===0)&&r("give bundle files, folders or URLs, or --run <id>, and not both"),t.provider!==void 0&&t.run===void 0&&r("--provider goes with --run"),t.allowFork&&t.run===void 0&&r("--allow-fork goes with --run");let s,o,a;try{let d=_e(n),u=mt(n,d,[]);t.run!==void 0&&(a=Gh(n,d,String(t.run),{provider:t.provider,allowFork:t.allowFork===!0}));let p=a?[a.dir]:e.map(g=>/^https?:\/\//i.test(g)?g:V.resolve(g)),f=a;s=await Bp(n,p,u,{overwrite:t.overwrite===!0,allowUnknownRepository:t.allowUnknownRepository===!0,describe:f?g=>`${Qi[f.provider]} run ${t.run} (${V.basename(V.dirname(g))})`:void 0,run:f?`${f.provider}:${t.run}`:void 0})}catch(d){o=d}finally{a?.remove()}if((o instanceof G||o instanceof Be)&&r(o.message),(o!==void 0||!s)&&r(o instanceof Error?o.message:String(o),!0),s.proposals.some(d=>d.outcome==="refused")&&(process.exitCode=1),t.json){console.log(JSON.stringify(a?{run:{provider:a.provider,id:String(t.run)},...s}:s,null,2));return}for(let d of s.bundles)console.log(`bundle: ${d.source}`),console.log(` from ${Ws(d.origin)}${d.shard?` \xB7 shard ${d.shard.index}/${d.shard.total}`:""} \xB7 saffron-ai ${d.runner}`);for(let d of s.warnings)console.log(`\u26A0 ${d}`);for(let d of s.proposals){let u=d.feature?`${d.feature} \u203A ${d.scenario}`:d.file;d.outcome==="imported"?console.log(`imported \u2192 ${d.file} (${u})`):d.outcome==="unchanged"?console.log(`unchanged: ${u}: ${d.reason??"already pending here"}`):console.log(`not imported: ${u} ${d.reason}`)}let{written:i,unchanged:c}=s.evidence;i>0&&console.log(`evidence: ${i} screenshot and trace file(s) written${c?`, ${c} already here`:""}`),s.report==="written"&&console.log("report: .saffron/reports/latest.html now shows the imported run (saffron report, saffron trace)");let l=s.proposals.filter(d=>d.outcome==="imported").length;l===0&&i===0&&s.report!=="written"&&!s.proposals.some(d=>d.outcome==="refused")?console.log("Nothing changed: this was already imported."):l>0&&console.log("Review with: saffron diff \xB7 accept with: saffron accept <file> | --all --include-imported \xB7 then commit the caches with your git tools")});te.command("diff").description("Show what a pending proposal changes in the committed recording: the action list a reviewer is approving, not just the narrative, and the feature file edits it would apply").argument("[files...]","proposal file(s); default: every pending proposal").option("--json","machine-readable output").action((e,t)=>{let n=V.resolve(te.opts().projectRoot),r=e.length>0?e.map(o=>V.resolve(o)):sn(n,po).map(o=>o.file);if(r.length===0){console.log("No pending proposals.");return}let s=r.map(o=>{let a=zr(o),i=Ye(pe(n,a.cache.feature,a.cache.scenario));return{file:V.relative(n,o),verified:a.meta.verified,stale:a.meta.bound?bm(n,a):ui,...Hn(i,a.cache,a.meta.featureEdits)}});if(t.json){console.log(JSON.stringify(s.length===1?s[0]:s,null,2));return}console.log(s.map(o=>`${Wo(o)}${o.stale?`
|
|
1381
1416
|
|
|
1382
|
-
STALE: ${
|
|
1417
|
+
STALE: ${qe(o.stale)}`:""}`).join(`
|
|
1383
1418
|
|
|
1384
|
-
`))});te.command("trace").description("Open the execution replay of a scenario from the last run: its Given / When / Then, the page at every action, the network alongside, and what the agent changed").argument("[scenario]","scenario name, feature path, or feature:scenario; default: every traced scenario, opening on a red one, else a yellow one").option("--port <n>","listen on a fixed port (default: a free one)").option("--no-open","print the URL without opening a browser").option("--json","print the parsed trace as JSON instead of serving it").option("--run <startedAt|id>","only if the last run is this one (its startedAt): an editor's row names the run it lists. Or a CI run's id (from saffron runs): replay that run's traces without importing it, view only").option("--provider <name>",`with a CI run's id: "github" or "azure" (default: ci.provider in the config, else the repository's host)`).option("--allow-fork","with a CI run's id: view a run a fork's pull request started").option("--max-download <MB>","with a CI run's id: refuse to download more than this many megabytes (default: no limit)").action(async(e,t)=>{let n=t.port===void 0?void 0:Number(t.port);n!==void 0&&(!Number.isInteger(n)||n<0||n>65535)&&(console.error(`invalid --port "${t.port}": use a whole number from 0 to 65535`),process.exit(2));let r=
|
|
1385
|
-
${
|
|
1386
|
-
Press Ctrl-C to stop.`),t.open!==!1&&
|
|
1387
|
-
`)),process.exit(2));let s=e.yes&&!e.check?
|
|
1388
|
-
`))}e.check&&r.orphans.length>0&&process.exit(1),e.yes&&!e.check&&s.length<r.orphans.length&&process.exit(1)});te.command("status").description("Project overview for dashboards and IDE panels: feature files and scenarios with cache state, tags, pending proposals, last run, history, vocabulary health, effective config").option("--json","machine-readable output").action(e=>{let t=
|
|
1389
|
-
${
|
|
1390
|
-
`)[0]:String(n)}`}}var
|
|
1391
|
-
`);for(let{file:n,proposal:r}of t){console.log(` ${n}`);let s=r.meta.verified===!0?" \xB7 verified \u2713":r.meta.verified===!1?" \xB7 UNVERIFIED \u2717":"";console.log(` ${
|
|
1419
|
+
`))});te.command("trace").description("Open the execution replay of a scenario from the last run: its Given / When / Then, the page at every action, the network alongside, and what the agent changed").argument("[scenario]","scenario name, feature path, or feature:scenario; default: every traced scenario, opening on a red one, else a yellow one").option("--port <n>","listen on a fixed port (default: a free one)").option("--no-open","print the URL without opening a browser").option("--json","print the parsed trace as JSON instead of serving it").option("--run <startedAt|id>","only if the last run is this one (its startedAt): an editor's row names the run it lists. Or a CI run's id (from saffron runs): replay that run's traces without importing it, view only").option("--provider <name>",`with a CI run's id: "github" or "azure" (default: ci.provider in the config, else the repository's host)`).option("--allow-fork","with a CI run's id: view a run a fork's pull request started").option("--max-download <MB>","with a CI run's id: refuse to download more than this many megabytes (default: no limit)").action(async(e,t)=>{let n=t.port===void 0?void 0:Number(t.port);n!==void 0&&(!Number.isInteger(n)||n<0||n>65535)&&(console.error(`invalid --port "${t.port}": use a whole number from 0 to 65535`),process.exit(2));let r=V.resolve(te.opts().projectRoot),s=typeof t.run=="string"&&/^\d+$/.test(t.run)?t.run:void 0,o=s?`CI run ${s}`:"the last run",a=r,i,c;if(s){let $=mm("trace",t.json===!0),T=wm(t.maxDownload,$);try{let R=_e(r),k=Vl(r,R,s,{provider:t.provider,allowFork:t.allowFork===!0,maxDownloadBytes:T});if(!k.folder)throw new G(k.reason??`run ${s} has no Saffron bundle`);let C=await Wl(r,{...k,folder:k.folder},mt(r,R,[]));if(!C.report)throw new G(`run ${s}'s bundle holds no run report`);a=k.folder,i=C.report}catch(R){return $(R)}c=`Viewed from CI run ${s}: nothing is filed here, so there is nothing to accept or reject. To review its proposals, import the run (saffron import --run ${s}).`}else{(t.provider!==void 0||t.allowFork||t.maxDownload!==void 0)&&(console.error("saffron trace: --provider, --allow-fork and --max-download go with --run <CI run id>"),process.exit(2));let $=V.join(r,".saffron","reports","latest.json");Ne.existsSync($)||(console.error("No report found. Run `saffron run` first."),process.exit(2)),i=JSON.parse(Ne.readFileSync($,"utf8")),t.run!==void 0&&i.startedAt!==t.run&&(console.error(`The last run changed since this was listed: it is now the run of ${i.startedAt}. Refresh the panel to replay it.`),process.exit(2))}let l=i.scenarios.filter($=>$.evidence?.some(T=>T.kind==="trace"));l.length===0&&(console.error(`${s?o:"The last run"} kept no execution trace. Set "trace": "retain-on-failure" (or "on") in saffron.config.json, or run with --trace retain-on-failure, then run again.`),process.exit(2));let d=e?.trim(),u=l;if(d){let $=l.filter(T=>T.scenario===d||T.feature===d||`${T.feature}:${T.scenario}`===d||`${T.feature}:${T.scenario}@${T.browser}`===d||`${T.scenario}@${T.browser}`===d);u=$.length>0?$:l.filter(T=>T.scenario.toLowerCase().includes(d.toLowerCase()))}if(u.length===0||t.json&&d&&u.length>1){console.error(u.length===0?`No traced scenario matches "${d}". Traced in ${o}:`:`--json prints one trace. Traced in ${o}:`);for(let $ of l)console.error(` ${le($.status).padEnd(6)} ${le($.feature)}:${le($.scenario)}${i.browsers&&$.browser?`@${le($.browser)}`:""}`);console.error('Name one: saffron trace "<scenario name>", or "<feature>:<scenario name>" as listed'),process.exit(2)}let p=u.findIndex($=>$.status==="red"),f=u.findIndex($=>$.status==="yellow"),g=p>=0?p:f>=0?f:0,y=u[g],h=$=>V.basename($,".zip").split(".")[0].replace("proof-","Proof replay "),S=$=>{let T=$.evidence.filter(C=>C.kind==="trace"),R=$.sessions?.[$.steps.findIndex(C=>C.status==="failed")],k=T.find(C=>!C.proof&&R!==void 0&&C.session===R)??T.find(C=>!C.proof)??T[0];return[k,...T.filter(C=>C!==k)]},[v]=S(y),x;if(u.length===1||t.json){let $=V.join(a,v.file);try{x=Pl(a,v)}catch(T){console.error(`The trace cannot be read: ${T instanceof Error?T.message:String(T)}`),process.exit(2)}if(x||(console.error(Ne.existsSync($)?"The trace on disk is from a later run than the last report (a run that stopped before writing its report). Run the scenario again to replay it.":`The trace file is gone: ${$}. Run the scenario again.`),process.exit(2)),t.json){console.log(JSON.stringify({...ph(x),...v.session?{session:v.session}:{}},null,2));return}}let b=u.map(($,T)=>{let[R,...k]=S($);return{scenario:{feature:$.feature,scenario:$.scenario,status:$.status,error:$.error,adaptations:$.adaptations,narrative:$.narrative,proposalDiff:$.proposalDiff,proposalFile:$.proposalFile,proposalRevision:$.proposalRevision,screenshots:$.evidence?.filter(C=>C.kind!=="trace"),ranAt:$.ranAt??i.startedAt,source:["cache","agent-record","agent-heal"].find(C=>C===$.source),proposalReplay:$.proposalReplay===!0?!0:void 0,usage:$.usage,browser:i.browsers?$.browser:void 0,stepSessions:$.sessions},traces:[R,...k].map((C,P)=>({file:V.join(a,C.file),data:T===g&&P===0?x:void 0,read:()=>Pl(a,C),checked:C.sha256!==void 0,label:`${C.proof?h(C.file):"Execution"}${C.session?` \xB7 session "${C.session}"`:""}`,proof:C.proof===!0,steps:C.proof?C.traceSteps:C.traceSteps??$.steps,uniques:C.proof?C.traceUniques:$.uniques,browserSession:C.session}))}}),m;try{m=await Rh({entries:b,start:g,projectRoot:a,port:n,viewOnly:c})}catch($){console.error(`Could not start the replay: ${$ instanceof Error?$.message:String($)}`),process.exit(2)}for(let{file:$,reason:T}of m.skipped)console.error(`Skipping ${V.relative(a,$)}. ${T}`);console.log(`Saffron replay: ${u.length===1?`${le(y.feature)} \u203A ${le(y.scenario)}`:`${u.length} scenarios, opening on ${le(y.scenario)}`}
|
|
1420
|
+
${m.url}
|
|
1421
|
+
Press Ctrl-C to stop.`),t.open!==!1&&fo(m.url),await new Promise($=>{process.once("SIGINT",()=>{m.close().finally($)})}),process.exit(0)});te.command("prune").description("List (and with --yes remove) recordings whose scenario no longer exists: caches and pending proposals left behind by a deleted scenario or feature file").option("--json","machine-readable output").option("--yes","actually delete the files listed").option("--check","exit 1 when anything is orphaned, delete nothing (for CI)").action(e=>{let t=V.resolve(te.opts().projectRoot),n=_e(t),r=qo(t,n.features??"features");r.unreadable.length>0&&(e.json?console.log(JSON.stringify({...r,removed:[]},null,2)):console.error(["saffron: cannot tell what is orphaned while a feature file fails to parse.",...r.unreadable.map(o=>` ${o}`),"Fix these first: a syntax error hides every scenario in the file."].join(`
|
|
1422
|
+
`)),process.exit(2));let s=e.yes&&!e.check?Fu(t,r.orphans):[];if(e.json)console.log(JSON.stringify({...r,removed:s},null,2));else if(r.orphans.length===0)console.log(`Nothing to prune. All ${r.kept} recordings belong to a scenario.`);else{let o=r.orphans.filter(c=>c.kind==="cache").length,a=r.orphans.filter(c=>c.kind==="proposal").length,i=r.orphans.length-o-a;console.log([`${r.orphans.length} orphaned ${r.orphans.length===1?"file":"files"} (${o} cache, ${a} proposal, ${i} screenshot ${i===1?"folder":"folders"}), ${r.kept} still owned:`,"",...r.orphans.map(c=>` ${e.yes&&!e.check?s.includes(c.file)?"removed ":"NOT removed ":""}${Lu(c)}`),"",s.length===0?e.yes&&!e.check?"Nothing could be deleted: check the files' permissions.":"Nothing was deleted. Run `saffron prune --yes` to remove them.":s.length<r.orphans.length?`Deleted ${s.length} of ${r.orphans.length}; the others could not be removed (check their permissions).`:"Deleted. Re-record by running the scenarios again if you deleted something by mistake."].join(`
|
|
1423
|
+
`))}e.check&&r.orphans.length>0&&process.exit(1),e.yes&&!e.check&&s.length<r.orphans.length&&process.exit(1)});te.command("status").description("Project overview for dashboards and IDE panels: feature files and scenarios with cache state, tags, pending proposals, last run, history, vocabulary health, effective config").option("--json","machine-readable output").action(e=>{let t=V.resolve(te.opts().projectRoot),n=_e(t),r=Gs(t,n);if(e.json){console.log(JSON.stringify(r,null,2));return}Kp(r)});te.command("report").description("Open the latest HTML report, or merge shard reports into it, or view a CI run's results without importing them (--run)").argument("[paths...]","with --merge: shard report files or folders to search (default: .saffron)").option("--open","open in the default browser",!0).option("--merge","combine the shard-<i>-of-<n>.json reports of one sharded run into latest.json, latest.html and one history line").option("--run <id>","view a CI run's results (an id from saffron runs): downloaded once into .saffron/ci/, checked like an import, nothing filed. Import it with saffron import --run").option("--provider <name>",`with --run: "github" or "azure" (default: ci.provider in the config, else the repository's host)`).option("--allow-fork","with --run: view a run a fork's pull request started").option("--max-download <MB>","with --run: refuse to download more than this many megabytes (default: no limit)").option("--json","with --run: machine-readable output").option("--panel","with --run: print the run's results as one page (what the editors' CI results panel shows); a failure is {error} as with --json").action(async(e,t)=>{let n=V.resolve(te.opts().projectRoot);if(t.run!==void 0){t.json&&t.panel&&(console.error("saffron report: --json and --panel print different things: pick one"),process.exit(2)),await T$(n,String(t.run),t);return}for(let s of["provider","allowFork","maxDownload","json","panel"])t[s]!==void 0&&(console.error(`saffron report: --${s.replace(/[A-Z]/g,o=>`-${o.toLowerCase()}`)} goes with --run`),process.exit(2));if(t.merge){A$(n,e);return}e.length>0&&(console.error("saffron report: paths are only read with --merge"),process.exit(2));let r=V.join(n,".saffron","reports","latest.html");Ne.existsSync(r)||(console.error("No report found. Run `saffron run` first."),process.exit(2)),console.log(r),fo(r)});function mm(e,t){return n=>{let r=n instanceof Error?n.message:String(n);if(t){let s=n instanceof G?n.kind:void 0;console.log(JSON.stringify({error:r,...s?{kind:s}:{},...n instanceof io?{sizeBytes:n.sizeBytes}:{}},null,2))}else console.error(`saffron ${e}: ${r}`);process.exit(2)}}function wm(e,t){let n=e===void 0?void 0:Number(e);return n!==void 0&&!(n>0)&&t(`invalid --max-download "${e}": use a number of megabytes above 0`),n===void 0?void 0:n*1024**2}async function T$(e,t,n){let r=mm("report",n.json===!0||n.panel===!0),s=wm(n.maxDownload,r),o;try{let l=_e(e);o=await Zh(e,l,mt(e,l,[]),t,{provider:n.provider,allowFork:n.allowFork===!0,maxDownloadBytes:s})}catch(l){return r(l)}let{results:a}=o;if(n.json){console.log(JSON.stringify(a,null,2));return}if(n.panel){process.stdout.write(Yi(a,e,ut()));return}if(!a.bundle){console.log(a.reason);return}for(let l of a.warnings)console.log(`\u26A0 ${l}`);a.bundle.summaryOnly&&console.log(`run ${t} uploaded only a summary: its results and screenshots, no traces to replay and nothing to import`);let i=a.proposals??[];if(i.length>0&&console.log(`${i.length} proposal${i.length===1?"":"s"}, ${i.filter(l=>l.importable).length} importable: saffron import --run ${t}`),!a.reportHtml){console.log(`run ${t}'s bundle holds no run report`);return}let c=V.join(e,a.reportHtml);console.log(c),fo(c)}te.command("dashboard").description("Open the suite's quality dashboard: tests, failing, flaky and never-run scenarios, healing, timing and tags, from the run history").option("--stdout","print the page instead of writing and opening it (what the IDE panels read)").option("--no-open","write the page without opening a browser").action(e=>{let t=V.resolve(te.opts().projectRoot),n=Gs(t,_e(t)),r=jh(n.quality,n.version);if(e.stdout){process.stdout.write(r);return}let s=V.join(t,".saffron","reports","dashboard.html");Ne.mkdirSync(V.dirname(s),{recursive:!0}),Ne.writeFileSync(s,r),console.log(s),e.open!==!1&&fo(s)});function ym(e,t=0){return`named scenarios only: ${e?`the report shows them in place of their last results, beside ${t} row(s) kept from earlier runs, each marked with the time it ran`:"the report holds just them: the last report was missing, imported from CI, interrupted, for another base URL or billed another way"}; their history line counts for them, not as a run of the suite`}function A$(e,t){let n=t.length>0?t.map(y=>V.resolve(y)):[V.join(e,".saffron")],r;try{r=vi(Tp(n))}catch(y){console.error(`saffron report --merge: ${y instanceof Error?y.message:String(y)}`),process.exit(2)}let{report:s,history:o,replaced:a}=r;for(let y of a)console.log(`\u26A0 ${y} is a shard a later attempt of the run ran again: left out`);let i=Fs(e),c=i.find(y=>y.runId===o.runId),l=c?i.filter(y=>y.runId!==o.runId):i;o.partial||(s.trends=qc(l,o));let d=c!==void 0&&JSON.stringify(c)===JSON.stringify(o);d||gp(e,o);let u=o.partial?Zc(Yc(e),s):s,{html:p,json:f}=Hs(e,u),g=s.totals;console.log(`merged ${s.shards} shard(s): ${g.scenarios} scenario(s) \xB7 ${g.green} passed, ${g.yellow} pending review, ${g.red} failed \xB7 ${g.aiCalls} AI calls${Nc(g)}`),d?console.log("history already holds this run: not appended again"):c&&console.log("history already held this run: its line is replaced with these results"),s.trends?.prev&&console.log(Mc(s.trends.prev));for(let y of s.trends?.chronic??[])console.log(`\u26A0 chronic: ${y.feature} \u203A ${y.scenario}: ${y.heals} heal(s), ${y.reds} red(s) in last ${y.runs} run(s)`);o.partial&&console.log(ym(u!==s,u.scenarios.length-s.scenarios.length)),console.log(`report: ${p}
|
|
1424
|
+
${f}`)}function bm(e,t){try{return At(e,t,mt(e,_e(e),[]))}catch(n){return`cannot check: ${n instanceof Error?n.message.split(`
|
|
1425
|
+
`)[0]:String(n)}`}}var qe=e=>le(String(e??""),1/0),po=(e,t)=>console.error(`\u26A0 proposal ${e} cannot be read: ${qe(t)}`),E$="is no longer pending: it was accepted, rejected or removed since it was listed.",O$="is not a pending proposal.",_$="is not a proposal file under .saffron/proposals.",xm="changed since it was listed. Refresh and review it again.",C$="is being decided by another process. Try again.";function vm(e,t,n,r,s){if(!t.endsWith(".json")||Ne.existsSync(t)&&!It(V.join(e,".saffron","proposals"),t))return s(_$);try{return Fo(t,r,()=>s(n?E$:O$))}catch(o){if(!(o instanceof cr))throw o;return s(C$)}}function Sm(e){let t=sn(e,po);if(t.length===0){console.log("No pending proposals.");return}console.log(`Pending proposals:
|
|
1426
|
+
`);for(let{file:n,proposal:r}of t){console.log(` ${n}`);let s=r.meta.verified===!0?" \xB7 verified \u2713":r.meta.verified===!1?" \xB7 UNVERIFIED \u2717":"";console.log(` ${qe(r.cache.feature)} \u203A ${qe(r.cache.scenario)} (${qe(r.meta.mode)}, ${qe(r.meta.createdAt)}${s})`);let o=r.meta.bound?bm(e,r):ui;o&&console.log(` \u2717 STALE: ${qe(o)}`),console.log(` ${qe(r.meta.narrative)}`);for(let a of r.meta.adaptations)console.log(` \u26A0 ${qe(a)}`);r.meta.suggestedFeatureEdit&&console.log(` suggested .feature edit:
|
|
1392
1427
|
${r.meta.suggestedFeatureEdit.split(`
|
|
1393
|
-
`).map(a=>` ${
|
|
1428
|
+
`).map(a=>` ${qe(a)}`).join(`
|
|
1394
1429
|
`)}`),console.log()}console.log("Accept with: saffron accept <file> | --all")}te.parseAsync().catch(e=>{process.env.SAFFRON_DEBUG?console.error(e):console.error(`saffron: ${e instanceof Error?e.message:String(e)}`),process.exit(2)});
|