@curl-runner/cli 1.21.0 → 1.23.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/dist/cli.js ADDED
@@ -0,0 +1,528 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ var Y3=Object.create;var{getPrototypeOf:z3,defineProperty:w9,getOwnPropertyNames:H3}=Object;var K3=Object.prototype.hasOwnProperty;var A1=(Z,X,J)=>{J=Z!=null?Y3(z3(Z)):{};let W=X||!Z||!Z.__esModule?w9(J,"default",{value:Z,enumerable:!0}):J;for(let $ of H3(Z))if(!K3.call(W,$))w9(W,$,{get:()=>Z[$],enumerable:!0});return W};var q9=(Z,X)=>()=>(X||Z((X={exports:{}}).exports,X),X.exports);var K1=import.meta.require;var $9=q9((Z8,W9)=>{var o1=process||{},U4=o1.argv||[],n1=o1.env||{},O2=!(!!n1.NO_COLOR||U4.includes("--no-color"))&&(!!n1.FORCE_COLOR||U4.includes("--color")||o1.platform==="win32"||(o1.stdout||{}).isTTY&&n1.TERM!=="dumb"||!!n1.CI),_2=(Z,X,J=Z)=>(W)=>{let $=""+W,G=$.indexOf(X,Z.length);return~G?Z+M2($,X,J,G)+X:Z+$+X},M2=(Z,X,J,W)=>{let $="",G=0;do $+=Z.substring(G,W)+J,G=W+X.length,W=Z.indexOf(X,G);while(~W);return $+Z.substring(G)},O4=(Z=O2)=>{let X=Z?_2:()=>String;return{isColorSupported:Z,reset:X("\x1B[0m","\x1B[0m"),bold:X("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:X("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:X("\x1B[3m","\x1B[23m"),underline:X("\x1B[4m","\x1B[24m"),inverse:X("\x1B[7m","\x1B[27m"),hidden:X("\x1B[8m","\x1B[28m"),strikethrough:X("\x1B[9m","\x1B[29m"),black:X("\x1B[30m","\x1B[39m"),red:X("\x1B[31m","\x1B[39m"),green:X("\x1B[32m","\x1B[39m"),yellow:X("\x1B[33m","\x1B[39m"),blue:X("\x1B[34m","\x1B[39m"),magenta:X("\x1B[35m","\x1B[39m"),cyan:X("\x1B[36m","\x1B[39m"),white:X("\x1B[37m","\x1B[39m"),gray:X("\x1B[90m","\x1B[39m"),bgBlack:X("\x1B[40m","\x1B[49m"),bgRed:X("\x1B[41m","\x1B[49m"),bgGreen:X("\x1B[42m","\x1B[49m"),bgYellow:X("\x1B[43m","\x1B[49m"),bgBlue:X("\x1B[44m","\x1B[49m"),bgMagenta:X("\x1B[45m","\x1B[49m"),bgCyan:X("\x1B[46m","\x1B[49m"),bgWhite:X("\x1B[47m","\x1B[49m"),blackBright:X("\x1B[90m","\x1B[39m"),redBright:X("\x1B[91m","\x1B[39m"),greenBright:X("\x1B[92m","\x1B[39m"),yellowBright:X("\x1B[93m","\x1B[39m"),blueBright:X("\x1B[94m","\x1B[39m"),magentaBright:X("\x1B[95m","\x1B[39m"),cyanBright:X("\x1B[96m","\x1B[39m"),whiteBright:X("\x1B[97m","\x1B[39m"),bgBlackBright:X("\x1B[100m","\x1B[49m"),bgRedBright:X("\x1B[101m","\x1B[49m"),bgGreenBright:X("\x1B[102m","\x1B[49m"),bgYellowBright:X("\x1B[103m","\x1B[49m"),bgBlueBright:X("\x1B[104m","\x1B[49m"),bgMagentaBright:X("\x1B[105m","\x1B[49m"),bgCyanBright:X("\x1B[106m","\x1B[49m"),bgWhiteBright:X("\x1B[107m","\x1B[49m")}};W9.exports=O4();W9.exports.createColors=O4});var Q9=q9((X8,_4)=>{var G9={to(Z,X){if(!X)return`\x1B[${Z+1}G`;return`\x1B[${X+1};${Z+1}H`},move(Z,X){let J="";if(Z<0)J+=`\x1B[${-Z}D`;else if(Z>0)J+=`\x1B[${Z}C`;if(X<0)J+=`\x1B[${-X}A`;else if(X>0)J+=`\x1B[${X}B`;return J},up:(Z=1)=>`\x1B[${Z}A`,down:(Z=1)=>`\x1B[${Z}B`,forward:(Z=1)=>`\x1B[${Z}C`,backward:(Z=1)=>`\x1B[${Z}D`,nextLine:(Z=1)=>"\x1B[E".repeat(Z),prevLine:(Z=1)=>"\x1B[F".repeat(Z),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},D2={up:(Z=1)=>"\x1B[S".repeat(Z),down:(Z=1)=>"\x1B[T".repeat(Z)},F2={screen:"\x1B[2J",up:(Z=1)=>"\x1B[1J".repeat(Z),down:(Z=1)=>"\x1B[J".repeat(Z),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(Z){let X="";for(let J=0;J<Z;J++)X+=this.line+(J<Z-1?G9.up():"");if(Z)X+=G9.left;return X}};_4.exports={cursor:G9,scroll:D2,erase:F2,beep:"\x07"}});var{Glob:U7}=globalThis.Bun;var x9={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",underscore:"\x1B[4m",black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m"};function D(Z,X){return`${x9[X]}${Z}${x9.reset}`}var B3=[`${process.env.HOME}/.local/bin/curl-runner`,`${process.env.USERPROFILE}\\.local\\bin\\curl-runner.exe`];function b9(){let Z=process.execPath,X=process.argv[0];if(U3(Z))return{source:"bun",path:Z,canAutoUpgrade:!0};if(O3(Z,X))return{source:"npm",path:Z,canAutoUpgrade:!0};if(_3(Z))return{source:"curl",path:Z,canAutoUpgrade:!0};return{source:"standalone",path:Z,canAutoUpgrade:!0}}function U3(Z){if(Z.includes(".bun"))return!0;if(process.env.BUN_INSTALL&&Z.includes(process.env.BUN_INSTALL))return!0;return["/bun/install/","/.bun/bin/","/bun/bin/"].some((J)=>Z.includes(J))}function O3(Z,X){if(Z.includes("node_modules"))return!0;if(X.includes("node_modules"))return!0;if(process.env.npm_config_prefix)return!0;if(process.env.npm_execpath)return!0;return["/lib/node_modules/","/node_modules/.bin/"].some((W)=>Z.includes(W)||X.includes(W))}function _3(Z){return B3.some((X)=>Z===X||Z.startsWith(X))}function y9(Z){switch(Z){case"bun":return"bun install -g @curl-runner/cli@latest";case"npm":return"npm install -g @curl-runner/cli@latest";case"curl":return"curl -fsSL https://www.curl-runner.com/install.sh | bash";case"standalone":return"curl -fsSL https://www.curl-runner.com/install.sh | bash"}}function v9(Z){switch(Z){case"bun":return"bun install -g @curl-runner/cli@latest";case"npm":return"npm install -g @curl-runner/cli@latest";case"curl":case"standalone":return"irm https://www.curl-runner.com/install.ps1 | iex"}}function Q0(){return process.platform==="win32"}function n(){if(typeof BUILD_VERSION<"u")return BUILD_VERSION;if(process.env.CURL_RUNNER_VERSION)return process.env.CURL_RUNNER_VERSION;try{let Z=["../package.json","./package.json","../../package.json"];for(let X of Z)try{let J=K1(X);if(J.name==="@curl-runner/cli"&&J.version)return J.version}catch{}return"0.0.0"}catch{return"0.0.0"}}var M3="https://registry.npmjs.org/@curl-runner/cli/latest",D3="https://api.github.com/repos/alexvcasillas/curl-runner/releases/latest";class Y0{async run(Z){let X=this.parseArgs(Z);console.log(),console.log(D("curl-runner upgrade","bright")),console.log();let J=b9();console.log(`${D("Installation:","cyan")} ${this.formatSource(J.source)}`),console.log(`${D("Current version:","cyan")} ${n()}`);let W=await this.fetchLatestVersion(J.source);if(!W)console.log(D("Failed to fetch latest version","red")),process.exit(1);console.log(`${D("Latest version:","cyan")} ${W}`),console.log();let $=n();if(!X.force&&!this.isNewerVersion($,W)){console.log(D("Already up to date!","green"));return}let G=Q0()?v9(J.source):y9(J.source);if(X.dryRun){console.log(D("Dry run - would execute:","yellow")),console.log(` ${D(G,"cyan")}`);return}console.log(`${D("Upgrading...","yellow")}`),console.log(),await this.executeUpgrade(J,G)}parseArgs(Z){let X={};for(let J of Z)if(J==="--dry-run"||J==="-n")X.dryRun=!0;else if(J==="--force"||J==="-f")X.force=!0;return X}formatSource(Z){switch(Z){case"bun":return"bun (global)";case"npm":return"npm (global)";case"curl":return"curl installer";case"standalone":return"standalone binary"}}async fetchLatestVersion(Z){try{if(Z==="bun"||Z==="npm"){let G=await fetch(M3,{signal:AbortSignal.timeout(5000)});if(!G.ok)return null;return(await G.json()).version}let X=await fetch(D3,{signal:AbortSignal.timeout(5000),headers:{Accept:"application/vnd.github.v3+json"}});if(!X.ok)return null;let W=(await X.json()).tag_name,$=W.match(/(\d+\.\d+\.\d+)/);return $?$[1]:W.replace(/^v/,"")}catch{return null}}isNewerVersion(Z,X){let J=Z.replace(/^v/,""),W=X.replace(/^v/,""),$=J.split(".").map(Number),G=W.split(".").map(Number);for(let Q=0;Q<Math.max($.length,G.length);Q++){let Y=$[Q]||0,z=G[Q]||0;if(z>Y)return!0;if(z<Y)return!1}return!1}async executeUpgrade(Z,X){let{source:J}=Z;try{if(J==="bun")await this.runBunUpgrade();else if(J==="npm")await this.runNpmUpgrade();else await this.runShellUpgrade(X)}catch(W){let $=W instanceof Error?W.message:String(W);if($.includes("EACCES")||$.includes("permission"))console.log(),console.log(D("Permission denied. Try running with sudo:","yellow")),console.log(` ${D(`sudo ${X}`,"cyan")}`),process.exit(1);console.log(D(`Upgrade failed: ${$}`,"red")),console.log(),console.log(D("Manual upgrade:","yellow")),console.log(` ${D(X,"cyan")}`),process.exit(1)}}async runBunUpgrade(){let X=await Bun.spawn(["bun","install","-g","@curl-runner/cli@latest"],{stdout:"inherit",stderr:"inherit"}).exited;if(X!==0)throw Error(`bun install failed with exit code ${X}`);this.showSuccess()}async runNpmUpgrade(){let X=await Bun.spawn(["npm","install","-g","@curl-runner/cli@latest"],{stdout:"inherit",stderr:"inherit"}).exited;if(X!==0)throw Error(`npm install failed with exit code ${X}`);this.showSuccess()}async runShellUpgrade(Z){let X;if(Q0())X=Bun.spawn(["powershell","-Command",Z],{stdout:"inherit",stderr:"inherit"});else X=Bun.spawn(["bash","-c",Z],{stdout:"inherit",stderr:"inherit"});let J=await X.exited;if(J!==0)throw Error(`Upgrade script failed with exit code ${J}`);this.showSuccess()}showSuccess(){console.log(),console.log(D("Upgrade complete!","green")),console.log(),console.log("Run `curl-runner --version` to verify.")}}function m9(){console.log(`
4
+ ${D("curl-runner upgrade","bright")}
5
+
6
+ Automatically upgrade curl-runner to the latest version.
7
+ Detects installation source (bun, npm, curl) and uses appropriate method.
8
+
9
+ ${D("USAGE:","yellow")}
10
+ curl-runner upgrade [options]
11
+
12
+ ${D("OPTIONS:","yellow")}
13
+ -n, --dry-run Show what would be executed without running
14
+ -f, --force Force upgrade even if already on latest version
15
+ -h, --help Show this help message
16
+
17
+ ${D("EXAMPLES:","yellow")}
18
+ curl-runner upgrade # Upgrade to latest
19
+ curl-runner upgrade --dry-run # Preview upgrade command
20
+ curl-runner upgrade --force # Force reinstall latest
21
+ `)}var{Glob:p9}=globalThis.Bun;var F3=["DATE","TIME","UUID","RANDOM"];function B1(Z,X={}){let{variables:J={},storeContext:W,resolveEnv:$=!0}=X;if(typeof Z==="string")return T3(Z,J,W,$);if(Array.isArray(Z))return Z.map((G)=>B1(G,X));if(Z&&typeof Z==="object"){let G={};for(let[Q,Y]of Object.entries(Z))G[Q]=B1(Y,X);return G}return Z}function T3(Z,X,J,W=!0){let $=f9(Z);if($.length===0)return Z;if($.length===1&&$[0].start===0&&$[0].end===Z.length){let Y=U1($[0].name,X,J,W);return Y!==null?Y:Z}let G="",Q=0;for(let Y of $){G+=Z.slice(Q,Y.start);let z=U1(Y.name,X,J,W);G+=z!==null?z:Z.slice(Y.start,Y.end),Q=Y.end}return G+=Z.slice(Q),G}function U1(Z,X,J,W=!0){if(Z.startsWith("store.")&&J){let Y=Z.slice(6);if(Y in J)return J[Y];return null}let $=Z.match(/^([^:]+):(upper|lower)$/);if($){let[,Y,z]=$,H=X[Y]??(W?process.env[Y]:void 0);if(H)return z==="upper"?H.toUpperCase():H.toLowerCase();return null}let G=Z.indexOf(":");if(G!==-1){let Y=Z.slice(0,G),z=Z.slice(G+1);if(!F3.includes(Y)){let H=U1(Y,X,J,W);if(H!==null)return H;if(z.startsWith("${")){let K=z.endsWith("}")?z.slice(2,-1):z.slice(2),U=U1(K,X,J,W);return U!==null?U:z}return z}}let Q=h9(Z);if(Q!==null)return Q;if(Z in X)return X[Z];if(W&&Z in process.env)return process.env[Z];return null}function h9(Z){if(Z==="UUID")return crypto.randomUUID();if(Z==="UUID:short")return crypto.randomUUID().split("-")[0];let X=Z.match(/^RANDOM:(\d+)-(\d+)$/);if(X){let W=Number(X[1]),$=Number(X[2]);return String(Math.floor(Math.random()*($-W+1))+W)}let J=Z.match(/^RANDOM:string:(\d+)$/);if(J){let W=Number(J[1]),$="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";return Array.from({length:W},()=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(Math.random()*62))).join("")}if(Z==="CURRENT_TIME"||Z==="TIMESTAMP")return Date.now().toString();if(Z.startsWith("DATE:"))return g9(new Date,Z.slice(5));if(Z.startsWith("TIME:"))return d9(new Date,Z.slice(5));return null}function g9(Z,X){let J=Z.getFullYear(),W=String(Z.getMonth()+1).padStart(2,"0"),$=String(Z.getDate()).padStart(2,"0");return X.replace("YYYY",J.toString()).replace("MM",W).replace("DD",$)}function d9(Z,X){let J=String(Z.getHours()).padStart(2,"0"),W=String(Z.getMinutes()).padStart(2,"0"),$=String(Z.getSeconds()).padStart(2,"0");return X.replace("HH",J).replace("mm",W).replace("ss",$)}function f9(Z){let X=[],J=0;while(J<Z.length)if(Z[J]==="$"&&Z[J+1]==="{"){let W=J;J+=2;let $=1,G=J;while(J<Z.length&&$>0){if(Z[J]==="{")$++;else if(Z[J]==="}")$--;J++}if($===0)X.push({start:W,end:J,name:Z.slice(G,J-1)})}else J++;return X}class y{static async parseFile(Z){let J=await Bun.file(Z).text();return Bun.YAML.parse(J)}static parse(Z){return Bun.YAML.parse(Z)}static interpolateVariables(Z,X,J){return B1(Z,{variables:X,storeContext:J})}static mergeConfigs(Z,X){return{...Z,...X,headers:{...Z.headers,...X.headers},params:{...Z.params,...X.params},variables:{...Z.variables,...X.variables}}}}var z0=["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],H0=["basic","bearer","digest","ntlm","oauth2"],K0=["sequential","parallel"],B0=["json","pretty","raw"],U0=["minimal","standard","detailed"],O0=["==","!=",">","<",">=","<=","contains","matches","exists","not-exists"],c9=["none","all","failing"],u9=["terminal","json","markdown"],I3={htpp:"http",htps:"https",htp:"http","http:/":"http://","https:/":"https://",locahost:"localhost",localhsot:"localhost",loaclhost:"localhost",localost:"localhost","127.0.0.0":"127.0.0.1"},N3={"content-type":"Content-Type","content-length":"Content-Length","content-encoding":"Content-Encoding","content-language":"Content-Language","content-disposition":"Content-Disposition",accept:"Accept","accept-encoding":"Accept-Encoding","accept-language":"Accept-Language","accept-charset":"Accept-Charset",authorization:"Authorization","cache-control":"Cache-Control",connection:"Connection",cookie:"Cookie","set-cookie":"Set-Cookie",host:"Host",origin:"Origin",referer:"Referer","user-agent":"User-Agent","x-requested-with":"X-Requested-With","x-forwarded-for":"X-Forwarded-For","x-forwarded-proto":"X-Forwarded-Proto","x-api-key":"X-API-Key","x-auth-token":"X-Auth-Token","x-csrf-token":"X-CSRF-Token","x-request-id":"X-Request-ID","x-correlation-id":"X-Correlation-ID",etag:"ETag","if-match":"If-Match","if-none-match":"If-None-Match","if-modified-since":"If-Modified-Since","if-unmodified-since":"If-Unmodified-Since","last-modified":"Last-Modified",location:"Location",pragma:"Pragma","proxy-authorization":"Proxy-Authorization",range:"Range","content-range":"Content-Range",te:"TE",trailer:"Trailer","transfer-encoding":"Transfer-Encoding",upgrade:"Upgrade",vary:"Vary",via:"Via",warning:"Warning","www-authenticate":"WWW-Authenticate","access-control-allow-origin":"Access-Control-Allow-Origin","access-control-allow-methods":"Access-Control-Allow-Methods","access-control-allow-headers":"Access-Control-Allow-Headers","access-control-allow-credentials":"Access-Control-Allow-Credentials","access-control-expose-headers":"Access-Control-Expose-Headers","access-control-max-age":"Access-Control-Max-Age","strict-transport-security":"Strict-Transport-Security","x-content-type-options":"X-Content-Type-Options","x-frame-options":"X-Frame-Options","x-xss-protection":"X-XSS-Protection"},L3=["name","url","method","headers","params","body","formData","timeout","followRedirects","maxRedirects","auth","proxy","insecure","ssl","output","http2","retry","variables","store","when","expect","snapshot","diff","sourceOutputConfig","sourceFile"],R3=["execution","maxConcurrency","continueOnError","dryRun","http2","connectionPool","ci","ssl","watch","profile","snapshot","diff","variables","output","defaults"],j3=["name","description","variables","defaults","requests"],l9=[/^(password|passwd|pwd|secret|api[_-]?key|apikey|token|auth|credential|private[_-]?key)$/i,/Bearer\s+[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+/i,/^[A-Fa-f0-9]{32,}$/,/^sk[-_]live[-_]/i,/^AKIA[0-9A-Z]{16}$/i];class _0{issues=[];currentFile="";definedVariables=new Set;storedVariables=new Set;requestNames=new Set;async run(Z){let X=this.parseArgs(Z),J=Z.filter((Y)=>!Y.startsWith("-"));if(J.length===0)J.push("*.yaml","*.yml");console.log(),console.log(D("curl-runner validate","bright")),console.log();let W=await this.findYamlFiles(J);if(W.length===0){console.log(D("No YAML files found","yellow"));return}console.log(`${D("Files:","cyan")} ${W.length} found`),console.log();let $=0,G=0,Q=0;for(let Y of W){let z=await this.validateFile(Y,X),H=z.issues.filter((M)=>M.severity==="error"),K=z.issues.filter((M)=>M.severity==="warning"),U=z.issues.filter((M)=>M.severity==="info");if(!z.valid||X.strict&&K.length>0){Q++,$+=z.issues.length,console.log(`${D("\u2717","red")} ${Y}`);for(let R of z.issues){let _=R.severity==="error"?D("\u25CF","red"):R.severity==="warning"?D("\u25CF","yellow"):D("\u25CF","blue");if(console.log(` ${_} ${R.path}: ${R.message}`),R.fix&&!X.fix)console.log(` ${D("fix:","cyan")} ${R.fix.description}`)}if(X.fix&&z.fixedContent){await Bun.write(Y,z.fixedContent);let R=z.issues.filter((_)=>_.fix).length;G+=R,console.log(` ${D("\u2713","green")} Fixed ${R} issue(s)`)}let M=[];if(H.length>0)M.push(`${H.length} error(s)`);if(K.length>0)M.push(`${K.length} warning(s)`);if(U.length>0)M.push(`${U.length} info`);if(M.length>0)console.log(` ${D("\u2192","dim")} ${M.join(", ")}`);console.log()}else if(!X.quiet)console.log(`${D("\u2713","green")} ${Y}`)}if(console.log(),Q===0)console.log(D("All files valid!","green"));else{if(console.log(`${D("Summary:","cyan")} ${Q} file(s) with ${$} issue(s)`),X.fix)console.log(`${D("Fixed:","green")} ${G} issue(s)`);process.exit(1)}}parseArgs(Z){let X={};for(let J of Z)if(J==="--fix"||J==="-f")X.fix=!0;else if(J==="--quiet"||J==="-q")X.quiet=!0;else if(J==="--strict"||J==="-s")X.strict=!0;return X}async findYamlFiles(Z){let X=new Set,J=await import("fs/promises");for(let W of Z)try{let $=await J.stat(W);if($.isDirectory()){let G=new p9(`${W}/**/*.{yaml,yml}`);for await(let Q of G.scan("."))X.add(Q)}else if($.isFile()&&(W.endsWith(".yaml")||W.endsWith(".yml")))X.add(W)}catch{let $=new p9(W);for await(let G of $.scan("."))if(G.endsWith(".yaml")||G.endsWith(".yml"))X.add(G)}return Array.from(X).sort()}async validateFile(Z,X){this.issues=[],this.currentFile=Z,this.definedVariables=new Set,this.storedVariables=new Set,this.requestNames=new Set;let J;try{J=await y.parseFile(Z)}catch(G){let Q=G instanceof Error?G.message:String(G);return this.addIssue("","error",`Failed to parse YAML: ${Q}`),{file:Z,valid:!1,issues:this.issues}}if(this.collectDefinedVariables(J),this.validateYamlStructure(J),J.global)this.validateGlobalConfig(J.global,"global");if(J.collection)this.validateCollection(J.collection,"collection");if(J.request)this.validateRequest(J.request,"request");if(J.requests)if(!Array.isArray(J.requests))this.addIssue("requests","error","Must be an array");else J.requests.forEach((G,Q)=>{this.validateRequest(G,`requests[${Q}]`)});this.checkDuplicateRequestNames();let W;if(X.fix&&this.issues.some((G)=>G.fix)){let G=JSON.parse(JSON.stringify(J));for(let Q of this.issues)if(Q.fix){let Y=Q.fix.apply();this.applyFix(G,Q.path,Y)}W=this.toYaml(G)}let $=this.issues.filter((G)=>G.severity==="error");return{file:Z,valid:$.length===0,issues:this.issues,fixedContent:W}}collectDefinedVariables(Z){if(Z.global?.variables)for(let J of Object.keys(Z.global.variables))this.definedVariables.add(J);if(Z.collection?.variables)for(let J of Object.keys(Z.collection.variables))this.definedVariables.add(J);this.definedVariables.add("env");let X=[...Z.requests||[],...Z.collection?.requests||[],Z.request].filter(Boolean);for(let J of X){if(J.variables)for(let W of Object.keys(J.variables))this.definedVariables.add(W);if(J.store)for(let W of Object.keys(J.store))this.storedVariables.add(W)}}validateYamlStructure(Z){let X="request"in Z,J="requests"in Z,W="collection"in Z;if(!X&&!J&&!W)this.addIssue("","error",'Missing request(s). Must have "request", "requests", or "collection"');if(X&&J)this.addIssue("","warning",'Both "request" and "requests" defined; both will be executed');if(W&&(X||J))this.addIssue("","warning","Collection mixed with request/requests; may cause confusion");let $=["version","global","collection","requests","request"];for(let G of Object.keys(Z))if(!$.includes(G))this.addIssue(G,"warning",`Unknown top-level key "${G}"`,{description:`Remove unknown key "${G}"`,apply:()=>{return}});if(Z.version!==void 0){if(typeof Z.version!=="string")this.addIssue("version","warning","Version should be a string")}}validateGlobalConfig(Z,X){if(this.checkUnknownKeys(Z,R3,X),Z.execution&&!K0.includes(Z.execution)){let W=this.findClosestMatch(Z.execution,[...K0]);this.addIssue(`${X}.execution`,"error",`Invalid execution mode "${Z.execution}". Must be: ${K0.join(", ")}`,W?{description:`Change to "${W}"`,apply:()=>W}:void 0)}if(Z.maxConcurrency!==void 0){if(typeof Z.maxConcurrency!=="number"||Z.maxConcurrency<1)this.addIssue(`${X}.maxConcurrency`,"error","Must be a positive number");if(Z.execution==="sequential")this.addIssue(`${X}.maxConcurrency`,"warning","maxConcurrency has no effect with sequential execution")}let J=Z;if(this.validateBooleanField(J,"continueOnError",X),this.validateBooleanField(J,"dryRun",X),this.validateBooleanField(J,"http2",X),Z.output)this.validateOutputConfig(Z.output,`${X}.output`);if(Z.connectionPool)this.validateConnectionPool(Z.connectionPool,`${X}.connectionPool`);if(Z.ci)this.validateCIConfig(Z.ci,`${X}.ci`);if(Z.ssl)this.validateSSLConfig(Z.ssl,`${X}.ssl`);if(Z.watch)this.validateWatchConfig(Z.watch,`${X}.watch`);if(Z.profile)this.validateProfileConfig(Z.profile,`${X}.profile`);if(Z.snapshot)this.validateSnapshotConfig(Z.snapshot,`${X}.snapshot`);if(Z.diff)this.validateDiffConfig(Z.diff,`${X}.diff`);if(Z.variables)this.validateVariables(Z.variables,`${X}.variables`);if(Z.defaults)this.validateRequestConfig(Z.defaults,`${X}.defaults`,!0)}validateBooleanField(Z,X,J){if(Z[X]!==void 0&&typeof Z[X]!=="boolean"){let W=String(Z[X]).toLowerCase();if(W==="true"||W==="false")this.addIssue(`${J}.${X}`,"warning",`Should be boolean, not string "${Z[X]}"`,{description:`Convert to ${W}`,apply:()=>W==="true"});else this.addIssue(`${J}.${X}`,"error","Must be a boolean")}}validateVariables(Z,X){if(typeof Z!=="object"||Array.isArray(Z)){this.addIssue(X,"error","Must be an object");return}for(let[J,W]of Object.entries(Z)){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(J))this.addIssue(`${X}.${J}`,"warning","Variable names should use alphanumeric characters and underscores");if(typeof W==="string"&&this.isSensitiveValue(J,W))this.addIssue(`${X}.${J}`,"warning",'Potentially sensitive value hardcoded. Consider using environment variables like "${env.VAR}"')}}validateOutputConfig(Z,X){let J=["verbose","showHeaders","showBody","showMetrics","format","prettyLevel","saveToFile","dryRun"];if(this.checkUnknownKeys(Z,J,X),Z.format&&!B0.includes(Z.format)){let W=this.findClosestMatch(Z.format,[...B0]);this.addIssue(`${X}.format`,"error",`Invalid format "${Z.format}". Must be: ${B0.join(", ")}`,W?{description:`Change to "${W}"`,apply:()=>W}:void 0)}if(Z.prettyLevel&&!U0.includes(Z.prettyLevel)){let W=this.findClosestMatch(Z.prettyLevel,[...U0]);this.addIssue(`${X}.prettyLevel`,"error",`Invalid prettyLevel "${Z.prettyLevel}". Must be: ${U0.join(", ")}`,W?{description:`Change to "${W}"`,apply:()=>W}:void 0)}this.validateBooleanField(Z,"verbose",X),this.validateBooleanField(Z,"showHeaders",X),this.validateBooleanField(Z,"showBody",X),this.validateBooleanField(Z,"showMetrics",X)}validateConnectionPool(Z,X){let J=["enabled","maxStreamsPerHost","keepaliveTime","connectTimeout"];if(this.checkUnknownKeys(Z,J,X),this.validateBooleanField(Z,"enabled",X),Z.maxStreamsPerHost!==void 0){if(typeof Z.maxStreamsPerHost!=="number"||Z.maxStreamsPerHost<1)this.addIssue(`${X}.maxStreamsPerHost`,"error","Must be a positive number");else if(Z.maxStreamsPerHost>100)this.addIssue(`${X}.maxStreamsPerHost`,"warning","Very high stream count may cause issues with some servers")}if(Z.keepaliveTime!==void 0){if(typeof Z.keepaliveTime!=="number"||Z.keepaliveTime<0)this.addIssue(`${X}.keepaliveTime`,"error","Must be a non-negative number")}if(Z.connectTimeout!==void 0){if(typeof Z.connectTimeout!=="number"||Z.connectTimeout<0)this.addIssue(`${X}.connectTimeout`,"error","Must be a non-negative number")}}validateCIConfig(Z,X){let J=["strictExit","failOn","failOnPercentage"];if(this.checkUnknownKeys(Z,J,X),this.validateBooleanField(Z,"strictExit",X),Z.failOn!==void 0&&(typeof Z.failOn!=="number"||Z.failOn<0))this.addIssue(`${X}.failOn`,"error","Must be a non-negative number");if(Z.failOnPercentage!==void 0){if(typeof Z.failOnPercentage!=="number"||Z.failOnPercentage<0||Z.failOnPercentage>100)this.addIssue(`${X}.failOnPercentage`,"error","Must be a number between 0 and 100")}if(Z.failOn!==void 0&&Z.failOnPercentage!==void 0)this.addIssue(X,"info","Both failOn and failOnPercentage are set; failOn takes precedence")}validateSSLConfig(Z,X){let J=["verify","ca","cert","key"];if(this.checkUnknownKeys(Z,J,X),this.validateBooleanField(Z,"verify",X),Z.ca&&typeof Z.ca!=="string")this.addIssue(`${X}.ca`,"error","Must be a string path");if(Z.cert&&typeof Z.cert!=="string")this.addIssue(`${X}.cert`,"error","Must be a string path");if(Z.key&&typeof Z.key!=="string")this.addIssue(`${X}.key`,"error","Must be a string path");if(Z.cert&&!Z.key)this.addIssue(`${X}`,"warning","cert provided without key; mTLS may fail");if(Z.key&&!Z.cert)this.addIssue(`${X}`,"warning","key provided without cert; mTLS may fail");if(Z.ca&&typeof Z.ca==="string")this.validateFilePath(Z.ca,`${X}.ca`);if(Z.cert&&typeof Z.cert==="string")this.validateFilePath(Z.cert,`${X}.cert`);if(Z.key&&typeof Z.key==="string")this.validateFilePath(Z.key,`${X}.key`)}validateFilePath(Z,X){if(Z.includes("${"))return;if(Z.includes(".."))this.addIssue(X,"info",'Path contains ".."; ensure this is intentional')}validateWatchConfig(Z,X){let J=["enabled","debounce","clear"];if(this.checkUnknownKeys(Z,J,X),Z.debounce!==void 0){if(typeof Z.debounce!=="number"||Z.debounce<0)this.addIssue(`${X}.debounce`,"error","Must be a non-negative number")}this.validateBooleanField(Z,"enabled",X),this.validateBooleanField(Z,"clear",X)}validateProfileConfig(Z,X){let J=["iterations","warmup","concurrency","percentiles"];if(this.checkUnknownKeys(Z,J,X),Z.iterations!==void 0){if(typeof Z.iterations!=="number"||Z.iterations<1)this.addIssue(`${X}.iterations`,"error","Must be a positive number");else if(Z.iterations>1e4)this.addIssue(`${X}.iterations`,"warning","Very high iteration count may take long")}if(Z.warmup!==void 0){if(typeof Z.warmup!=="number"||Z.warmup<0)this.addIssue(`${X}.warmup`,"error","Must be a non-negative number")}if(Z.concurrency!==void 0){if(typeof Z.concurrency!=="number"||Z.concurrency<1)this.addIssue(`${X}.concurrency`,"error","Must be a positive number")}}validateSnapshotConfig(Z,X){let J=["updateMode","dir","ignoreFields","ignoreHeaders"];if(this.checkUnknownKeys(Z,J,X),Z.updateMode&&!c9.includes(Z.updateMode))this.addIssue(`${X}.updateMode`,"error",`Invalid updateMode "${Z.updateMode}". Must be: ${c9.join(", ")}`);if(Z.dir&&typeof Z.dir!=="string")this.addIssue(`${X}.dir`,"error","Must be a string")}validateDiffConfig(Z,X){let J=["outputFormat","dir","ignoreFields","ignoreHeaders","baselineUrl"];if(this.checkUnknownKeys(Z,J,X),Z.outputFormat&&!u9.includes(Z.outputFormat))this.addIssue(`${X}.outputFormat`,"error",`Invalid outputFormat "${Z.outputFormat}". Must be: ${u9.join(", ")}`);if(Z.dir&&typeof Z.dir!=="string")this.addIssue(`${X}.dir`,"error","Must be a string")}validateCollection(Z,X){if(this.checkUnknownKeys(Z,j3,X),!Z.name)this.addIssue(`${X}.name`,"warning","Collection name is recommended");if(!Z.requests||!Array.isArray(Z.requests))this.addIssue(`${X}.requests`,"error","Collection must have a requests array");else{if(Z.requests.length===0)this.addIssue(`${X}.requests`,"warning","Collection has no requests");Z.requests.forEach((J,W)=>{this.validateRequest(J,`${X}.requests[${W}]`)})}if(Z.variables)this.validateVariables(Z.variables,`${X}.variables`);if(Z.defaults)this.validateRequestConfig(Z.defaults,`${X}.defaults`,!0)}validateRequest(Z,X){this.validateRequestConfig(Z,X,!1)}validateRequestConfig(Z,X,J){if(this.checkUnknownKeys(Z,L3,X),Z.name)this.requestNames.add(`${X}:${Z.name}`);if(!J&&!Z.url)this.addIssue(`${X}.url`,"error","URL is required");if(Z.url)this.validateURL(Z.url,`${X}.url`);if(Z.method)this.validateMethod(Z.method,`${X}.method`);if(Z.headers)this.validateHeaders(Z.headers,`${X}.headers`,Z);if(Z.params){if(typeof Z.params!=="object"||Array.isArray(Z.params))this.addIssue(`${X}.params`,"error","Params must be an object")}if(Z.body!==void 0&&Z.formData!==void 0)this.addIssue(`${X}`,"error",'Cannot use both "body" and "formData"');if(Z.body!==void 0)this.validateBody(Z.body,`${X}.body`,Z);if(Z.formData)this.validateFormData(Z.formData,`${X}.formData`);if(Z.timeout!==void 0)this.validateTimeout(Z.timeout,`${X}.timeout`);if(Z.auth)this.validateAuth(Z.auth,`${X}.auth`);if(Z.ssl)this.validateSSLConfig(Z.ssl,`${X}.ssl`);if(Z.insecure!==void 0){if(this.validateBooleanField(Z,"insecure",X),Z.insecure===!0)this.addIssue(`${X}.insecure`,"warning","Insecure mode disables SSL verification")}if(Z.proxy)this.validateProxyURL(Z.proxy,`${X}.proxy`);if(Z.retry)this.validateRetry(Z.retry,`${X}.retry`,Z.method);if(Z.when)this.validateWhenCondition(Z.when,`${X}.when`);if(Z.expect)this.validateExpect(Z.expect,`${X}.expect`);if(Z.store)this.validateStore(Z.store,`${X}.store`);if(Z.maxRedirects!==void 0){if(typeof Z.maxRedirects!=="number"||Z.maxRedirects<0)this.addIssue(`${X}.maxRedirects`,"error","Must be a non-negative number");else if(Z.maxRedirects>50)this.addIssue(`${X}.maxRedirects`,"warning","Very high redirect limit")}if(this.validateBooleanField(Z,"followRedirects",X),this.validateBooleanField(Z,"http2",X),Z.snapshot!==void 0&&typeof Z.snapshot==="object")this.validateSnapshotConfig(Z.snapshot,`${X}.snapshot`);if(Z.diff!==void 0&&typeof Z.diff==="object")this.validateDiffConfig(Z.diff,`${X}.diff`)}validateURL(Z,X){if(typeof Z!=="string"){this.addIssue(X,"error","URL must be a string");return}let J=Z.includes("${"),W=Z,$=!1;for(let[G,Q]of Object.entries(I3))if(Z.toLowerCase().includes(G)){W=Z.replace(new RegExp(G,"gi"),Q),$=!0,this.addIssue(X,"error",`URL contains typo "${G}"`,{description:`Fix to "${Q}"`,apply:()=>W});break}if(!$&&!Z.startsWith("http")&&!J)this.addIssue(X,"warning","URL should start with http:// or https://",{description:"Prepend https://",apply:()=>`https://${Z}`});if(!J&&Z.match(/https?:\/\/[^/]+\/\/+/)){let G=Z.replace(/(https?:\/\/[^/]+)(\/+)/g,"$1/");this.addIssue(X,"warning","URL contains double slashes in path",{description:"Remove extra slashes",apply:()=>G})}if(Z.includes(" ")){let G=Z.replace(/ /g,"%20");this.addIssue(X,"error","URL contains spaces",{description:"Encode spaces as %20",apply:()=>G})}if(Z.startsWith("http://")&&!Z.includes("localhost")&&!Z.includes("127.0.0.1"))this.addIssue(X,"info","Using HTTP instead of HTTPS; consider using HTTPS for security");if(!J){let G=Z.match(/:(\d+)/);if(G){let Q=parseInt(G[1],10);if(Q<1||Q>65535)this.addIssue(X,"error",`Invalid port number ${Q}. Must be 1-65535`)}}}validateProxyURL(Z,X){if(typeof Z!=="string"){this.addIssue(X,"error","Proxy must be a string URL");return}if(!Z.includes("${")&&!Z.match(/^(https?|socks[45]?):\/\//i))this.addIssue(X,"error","Proxy URL should start with http://, https://, socks4://, or socks5://")}validateMethod(Z,X){let J=Z.toUpperCase();if(!z0.includes(J)){let W=this.findClosestMatch(J,[...z0]);this.addIssue(X,"error",`Invalid method "${Z}". Must be: ${z0.join(", ")}`,W?{description:`Change to "${W}"`,apply:()=>W}:void 0)}else if(Z!==J)this.addIssue(X,"warning",`Method should be uppercase: "${J}"`,{description:`Change to "${J}"`,apply:()=>J})}validateHeaders(Z,X,J){if(typeof Z!=="object"||Array.isArray(Z)){this.addIssue(X,"error","Headers must be an object");return}let W=new Map;for(let[Q,Y]of Object.entries(Z)){let z=Q.toLowerCase(),H=N3[z];if(H&&Q!==H)this.addIssue(`${X}.${Q}`,"info",`Header "${Q}" should be "${H}" for consistency`,{description:`Rename to "${H}"`,apply:()=>({rename:H,value:Y})});if(W.has(z))this.addIssue(`${X}.${Q}`,"warning",`Duplicate header "${Q}" (case-insensitive match with "${W.get(z)}")`);if(W.set(z,Q),typeof Y!=="string"&&typeof Y!=="number")this.addIssue(`${X}.${Q}`,"error","Header value must be a string or number");if(typeof Y==="string"&&this.isSensitiveValue(Q,Y))this.addIssue(`${X}.${Q}`,"warning",'Potentially sensitive header value. Consider using variables like "${env.TOKEN}"')}let $=this.getHeaderValue(Z,"content-type");if(J.body!==void 0&&!$)this.addIssue(X,"info","Body present but no Content-Type header; consider adding one");let G=this.getHeaderValue(Z,"authorization");if(J.auth&&G)this.addIssue(X,"warning","Both auth block and Authorization header present; auth block may be ignored")}getHeaderValue(Z,X){let J=X.toLowerCase();for(let[W,$]of Object.entries(Z))if(W.toLowerCase()===J)return $;return}validateBody(Z,X,J){let W=(J.method||"GET").toUpperCase();if(["GET","HEAD","OPTIONS"].includes(W))this.addIssue(X,"warning",`Body with ${W} method may be ignored by some servers`);if(typeof Z==="string"){let $=Z.trim();if($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]"))try{JSON.parse($)}catch{this.addIssue(X,"warning","Body looks like JSON but is invalid; check syntax")}}}validateFormData(Z,X){if(typeof Z!=="object"||Array.isArray(Z)){this.addIssue(X,"error","FormData must be an object");return}for(let[J,W]of Object.entries(Z))if(typeof W==="object"&&W!==null&&"file"in W){if(typeof W.file!=="string")this.addIssue(`${X}.${J}.file`,"error","File path must be a string");else this.validateFilePath(W.file,`${X}.${J}.file`);if(W.contentType&&typeof W.contentType!=="string")this.addIssue(`${X}.${J}.contentType`,"error","contentType must be a string");if(W.filename&&typeof W.filename!=="string")this.addIssue(`${X}.${J}.filename`,"error","filename must be a string")}}validateTimeout(Z,X){if(typeof Z!=="number"){if(typeof Z==="string"){let J=parseInt(Z,10);if(!Number.isNaN(J)&&J>0){this.addIssue(X,"warning","Timeout should be a number, not string",{description:`Convert to ${J}`,apply:()=>J});return}}this.addIssue(X,"error","Timeout must be a positive number");return}if(Z<=0)this.addIssue(X,"error","Timeout must be a positive number");else if(Z<100)this.addIssue(X,"warning","Very short timeout (<100ms) may cause failures");else if(Z>300000)this.addIssue(X,"warning","Very long timeout (>5min) - is this intentional?")}validateAuth(Z,X){let J=["type","username","password","token"];if(this.checkUnknownKeys(Z,J,X),!Z.type){this.addIssue(`${X}.type`,"error","Auth type is required");return}if(!H0.includes(Z.type)){let W=this.findClosestMatch(Z.type,[...H0]);this.addIssue(`${X}.type`,"error",`Invalid auth type "${Z.type}". Must be: ${H0.join(", ")}`,W?{description:`Change to "${W}"`,apply:()=>W}:void 0);return}if(Z.type==="basic"){if(!Z.username)this.addIssue(`${X}.username`,"error","Username required for basic auth");if(!Z.password)this.addIssue(`${X}.password`,"warning","Password missing for basic auth");if(Z.password&&typeof Z.password==="string"&&!Z.password.includes("${"))this.addIssue(`${X}.password`,"warning",'Hardcoded password. Consider using "${env.PASSWORD}"')}if(Z.type==="bearer"){if(!Z.token)this.addIssue(`${X}.token`,"error","Token required for bearer auth");if(Z.token&&typeof Z.token==="string"&&!Z.token.includes("${"))this.addIssue(`${X}.token`,"warning",'Hardcoded token. Consider using "${env.TOKEN}"')}}validateRetry(Z,X,J){let W=["count","delay","backoff"];if(this.checkUnknownKeys(Z,W,X),Z.count===void 0)this.addIssue(`${X}.count`,"error","Retry count is required");else if(typeof Z.count!=="number"||Z.count<0)this.addIssue(`${X}.count`,"error","Retry count must be a non-negative number");else if(Z.count>10)this.addIssue(`${X}.count`,"warning","High retry count (>10) may cause long delays");if(Z.delay!==void 0){if(typeof Z.delay!=="number"||Z.delay<0)this.addIssue(`${X}.delay`,"error","Retry delay must be a non-negative number")}if(Z.backoff!==void 0){if(typeof Z.backoff!=="number"||Z.backoff<1)this.addIssue(`${X}.backoff`,"error","Retry backoff must be >= 1");else if(Z.backoff>5)this.addIssue(`${X}.backoff`,"warning","High backoff multiplier may cause very long delays")}if(J&&["POST","PATCH"].includes(J.toUpperCase())&&Z.count&&Z.count>0)this.addIssue(X,"info",`Retrying ${J} requests may cause duplicate operations`)}validateWhenCondition(Z,X){if(typeof Z==="string"){this.validateWhenString(Z,X);return}let J="all"in Z&&Z.all,W="any"in Z&&Z.any,$="left"in Z;if(!J&&!W&&!$){this.addIssue(X,"error",'When condition must have "all", "any", or "left"');return}if(J&&W||J&&$||W&&$)this.addIssue(X,"warning","When condition has multiple forms; behavior may be unexpected");if(J)if(!Array.isArray(Z.all))this.addIssue(`${X}.all`,"error","Must be an array");else{if(Z.all.length===0)this.addIssue(`${X}.all`,"warning",'Empty "all" array - condition always true');Z.all.forEach((G,Q)=>{this.validateConditionExpression(G,`${X}.all[${Q}]`)})}if(W)if(!Array.isArray(Z.any))this.addIssue(`${X}.any`,"error","Must be an array");else{if(Z.any.length===0)this.addIssue(`${X}.any`,"warning",'Empty "any" array - condition always false');Z.any.forEach((G,Q)=>{this.validateConditionExpression(G,`${X}.any[${Q}]`)})}if($)this.validateConditionExpression(Z,X)}validateWhenString(Z,X){if(!Z.includes("store.")&&!Z.includes("env."))this.addIssue(X,"warning","When string should reference store.* or env.* values");if(!/\s*(==|!=|>=|<=|>|<|contains|matches|exists|not-exists)\s*/.test(Z))this.addIssue(X,"warning","When string should contain a valid operator (==, !=, >, <, >=, <=, contains, matches, exists)")}validateConditionExpression(Z,X){if(!Z.left)this.addIssue(`${X}.left`,"error","Left operand is required");else if(!Z.left.startsWith("store.")&&!Z.left.startsWith("env."))this.addIssue(`${X}.left`,"warning",'Left operand should start with "store." or "env."');if(!Z.operator)this.addIssue(`${X}.operator`,"error","Operator is required");else if(!O0.includes(Z.operator)){let J=this.findClosestMatch(Z.operator,[...O0]);this.addIssue(`${X}.operator`,"error",`Invalid operator "${Z.operator}". Must be: ${O0.join(", ")}`,J?{description:`Change to "${J}"`,apply:()=>J}:void 0)}if(Z.operator!=="exists"&&Z.operator!=="not-exists"){if(Z.right===void 0)this.addIssue(`${X}.right`,"error","Right operand is required")}}validateExpect(Z,X){let J=["failure","status","headers","body","responseTime"];if(this.checkUnknownKeys(Z,J,X),this.validateBooleanField(Z,"failure",X),Z.status!==void 0)this.validateExpectStatus(Z.status,`${X}.status`);if(Z.headers){if(typeof Z.headers!=="object"||Array.isArray(Z.headers))this.addIssue(`${X}.headers`,"error","Expected headers must be an object")}if(Z.responseTime!==void 0)this.validateResponseTime(Z.responseTime,`${X}.responseTime`)}validateExpectStatus(Z,X){if(Array.isArray(Z)){if(Z.length===0)this.addIssue(X,"warning","Empty status array - no status will match");for(let J of Z)if(typeof J!=="number"||J<100||J>599){this.addIssue(X,"error","Status codes must be numbers between 100-599");break}}else if(typeof Z==="string"){let J=parseInt(Z,10);if(!Number.isNaN(J)&&J>=100&&J<=599)this.addIssue(X,"warning","Status should be a number, not string",{description:`Convert to ${J}`,apply:()=>J});else this.addIssue(X,"error","Status code must be a number between 100-599")}else if(typeof Z!=="number"||Z<100||Z>599)this.addIssue(X,"error","Status code must be a number between 100-599")}validateResponseTime(Z,X){if(typeof Z!=="string"){this.addIssue(X,"error",'Response time must be a string (e.g., "< 1000")');return}let J=/^[<>]=?\s*(\d+|\$\{[^}]+\})(\s*,\s*[<>]=?\s*(\d+|\$\{[^}]+\}))?$/;if(!Z.match(J))this.addIssue(X,"warning",'Response time should be like "< 1000", "> 500, < 2000"')}validateStore(Z,X){if(typeof Z!=="object"||Array.isArray(Z)){this.addIssue(X,"error","Store must be an object");return}for(let[J,W]of Object.entries(Z)){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(J))this.addIssue(`${X}.${J}`,"warning","Store variable names should use alphanumeric characters and underscores");if(typeof W!=="string")this.addIssue(`${X}.${J}`,"error","Store path must be a string");else{let $=["body","status","headers","responseTime"],G=W.split(".")[0];if(!$.includes(G))this.addIssue(`${X}.${J}`,"warning",`Store path should start with: ${$.join(", ")}`)}}}checkDuplicateRequestNames(){let Z=new Map;for(let X of this.requestNames){let[J,W]=X.split(":");if(!Z.has(W))Z.set(W,[]);Z.get(W).push(J)}for(let[X,J]of Z)if(J.length>1)this.addIssue(J[1],"warning",`Duplicate request name "${X}" (also at ${J[0]})`)}checkUnknownKeys(Z,X,J){for(let W of Object.keys(Z))if(!X.includes(W)){let $=this.findClosestMatch(W,X);this.addIssue(`${J}.${W}`,"warning",`Unknown key "${W}"`,$?{description:`Did you mean "${$}"?`,apply:()=>({rename:$})}:void 0)}}findClosestMatch(Z,X){let J=Z.toLowerCase(),W=null,$=3;for(let G of X){let Q=G.toLowerCase();if(J===Q)return G;if(Q.startsWith(J)||J.startsWith(Q))return G;let Y=this.editDistance(J,Q);if(Y<$)$=Y,W=G}return W}editDistance(Z,X){if(Z.length===0)return X.length;if(X.length===0)return Z.length;let J=[];for(let W=0;W<=X.length;W++)J[W]=[W];for(let W=0;W<=Z.length;W++)J[0][W]=W;for(let W=1;W<=X.length;W++)for(let $=1;$<=Z.length;$++)if(X.charAt(W-1)===Z.charAt($-1))J[W][$]=J[W-1][$-1];else J[W][$]=Math.min(J[W-1][$-1]+1,J[W][$-1]+1,J[W-1][$]+1);return J[X.length][Z.length]}isSensitiveValue(Z,X){if(X.includes("${"))return!1;for(let J of l9)if(J.test(Z))return!0;for(let J of l9)if(J.test(X))return!0;return!1}addIssue(Z,X,J,W){this.issues.push({file:this.currentFile,path:Z||"(root)",severity:X,message:J,fix:W})}applyFix(Z,X,J){if(!X||X==="(root)")return;let W=X.split(".").flatMap((G)=>{let Q=G.match(/^(\w+)\[(\d+)\]$/);return Q?[Q[1],Number(Q[2])]:G}),$=Z;for(let G=0;G<W.length-1;G++){let Q=W[G];if(typeof $==="object"&&$!==null)$=$[Q]}if(typeof $==="object"&&$!==null){let G=W[W.length-1];if(typeof J==="object"&&J!==null&&"rename"in J){let Q=J,Y=Q.value??$[G];delete $[G],$[Q.rename]=Y}else if(J===void 0)delete $[G];else $[G]=J}}toYaml(Z){return this.serializeYaml(Z)}serializeYaml(Z,X=0){let J=" ".repeat(X);if(Z===null||Z===void 0)return"null";if(typeof Z==="string"){if(Z.includes(`
22
+ `)||Z.includes(":")||Z.includes("#")||Z.startsWith("$")||Z.match(/^[0-9]/)||Z===""||Z==="true"||Z==="false"||Z==="null")return JSON.stringify(Z);return Z}if(typeof Z==="number"||typeof Z==="boolean")return String(Z);if(Array.isArray(Z)){if(Z.length===0)return"[]";return Z.map((W)=>{if(typeof W==="object"&&W!==null){let G=this.serializeYaml(W,X+1).split(`
23
+ `);return`${J}- ${G[0]}
24
+ ${G.slice(1).map((Q)=>`${J} ${Q}`).join(`
25
+ `)}`.trimEnd()}return`${J}- ${this.serializeYaml(W,X)}`}).join(`
26
+ `)}if(typeof Z==="object"){let W=Object.entries(Z).filter(([,$])=>$!==void 0);if(W.length===0)return"{}";return W.map(([$,G])=>{if(typeof G==="object"&&G!==null&&!Array.isArray(G)){let Q=this.serializeYaml(G,X+1);return`${J}${$}:
27
+ ${Q.split(`
28
+ `).map((Y)=>` ${Y}`).join(`
29
+ `)}`}if(Array.isArray(G))return`${J}${$}:
30
+ ${this.serializeYaml(G,X+1)}`;return`${J}${$}: ${this.serializeYaml(G,X)}`}).join(`
31
+ `)}return String(Z)}}function n9(){console.log(`
32
+ ${D("curl-runner validate","bright")}
33
+
34
+ Validate YAML files against curl-runner schema and curl options.
35
+ Discovers issues and proposes fixes, or auto-fixes with --fix.
36
+
37
+ ${D("USAGE:","yellow")}
38
+ curl-runner validate [files...] [options]
39
+
40
+ ${D("OPTIONS:","yellow")}
41
+ -f, --fix Auto-fix issues where possible
42
+ -q, --quiet Only show files with issues
43
+ -s, --strict Treat warnings as errors
44
+ -h, --help Show this help message
45
+
46
+ ${D("ARGUMENTS:","yellow")}
47
+ files File paths or glob patterns (default: *.yaml, *.yml)
48
+
49
+ ${D("EXAMPLES:","yellow")}
50
+ curl-runner validate # Validate all YAML in current dir
51
+ curl-runner validate api.yaml # Validate single file
52
+ curl-runner validate "tests/**/*.yaml" # Validate with glob pattern
53
+ curl-runner validate --fix # Validate and auto-fix issues
54
+ curl-runner validate -fq # Fix quietly (only show errors)
55
+ curl-runner validate --strict # Fail on warnings too
56
+
57
+ ${D("VALIDATION CATEGORIES:","yellow")}
58
+
59
+ ${D("Structure","cyan")}
60
+ \u2022 YAML syntax and parsing
61
+ \u2022 Required fields (url, auth.type, etc.)
62
+ \u2022 Unknown/misspelled keys with suggestions
63
+ \u2022 Duplicate request names
64
+
65
+ ${D("URLs","cyan")}
66
+ \u2022 Valid URL syntax
67
+ \u2022 Common typos (htpp, localhsot, etc.)
68
+ \u2022 Double slashes in paths
69
+ \u2022 Missing protocol (http/https)
70
+ \u2022 Valid port numbers (1-65535)
71
+ \u2022 Spaces in URLs
72
+
73
+ ${D("HTTP","cyan")}
74
+ \u2022 Valid methods (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS)
75
+ \u2022 Method casing (lowercase \u2192 UPPERCASE)
76
+ \u2022 Headers casing (content-type \u2192 Content-Type)
77
+ \u2022 Content-Type consistency with body
78
+ \u2022 Duplicate headers
79
+
80
+ ${D("Auth & Security","cyan")}
81
+ \u2022 Valid auth types (basic, bearer)
82
+ \u2022 Required auth fields (username, password, token)
83
+ \u2022 Hardcoded credentials warning
84
+ \u2022 Insecure mode warnings
85
+ \u2022 HTTP vs HTTPS warnings
86
+
87
+ ${D("Configuration","cyan")}
88
+ \u2022 Boolean string values ("true" \u2192 true)
89
+ \u2022 Numeric string values
90
+ \u2022 Valid execution modes
91
+ \u2022 Valid output formats
92
+ \u2022 SSL certificate consistency
93
+
94
+ ${D("Timeouts & Retries","cyan")}
95
+ \u2022 Positive timeout values
96
+ \u2022 Reasonable timeout ranges
97
+ \u2022 Retry count limits
98
+ \u2022 Non-idempotent retry warnings
99
+
100
+ ${D("Conditions & Expectations","cyan")}
101
+ \u2022 When condition operators
102
+ \u2022 Store path references
103
+ \u2022 Status code ranges (100-599)
104
+ \u2022 Response time format
105
+
106
+ ${D("AUTO-FIXABLE ISSUES:","yellow")}
107
+ \u2022 Lowercase HTTP methods \u2192 UPPERCASE
108
+ \u2022 Missing https:// prefix on URLs
109
+ \u2022 URL typos (htpp \u2192 http, localhsot \u2192 localhost)
110
+ \u2022 Double slashes in URL paths
111
+ \u2022 Spaces in URLs (\u2192 %20)
112
+ \u2022 Header casing (content-type \u2192 Content-Type)
113
+ \u2022 Boolean strings ("true" \u2192 true)
114
+ \u2022 Numeric strings (timeout: "5000" \u2192 5000)
115
+ \u2022 Status code strings ("200" \u2192 200)
116
+ \u2022 Execution mode typos
117
+ \u2022 Unknown keys (with suggestions)
118
+ `)}function M0(Z){let X=[],J=Z.split(`
119
+ `),W=0;while(W<J.length){let $=J[W].trim();if(!$||$.startsWith("#")||$.startsWith("//")){W++;continue}let G=S3($);if(G>=0){let Q=$.slice(G);while(Q.endsWith("\\")&&W+1<J.length)Q=Q.slice(0,-1),W++,Q+=` ${J[W].trim()}`;let Y=E3(Q);if(Y>0)Q=Q.slice(0,Y).trim();if(Q=Q.replace(/;\s*$/,"").trim(),Q.length>4)X.push(Q)}W++}return X}function S3(Z){if(Z.startsWith("curl ")||Z==="curl")return 0;let X=[/(?:^|&&\s*|;\s*|\|\|\s*|\$\(\s*|`\s*)curl\s/];for(let J of X){let W=J.exec(Z);if(W){let $=Z.indexOf("curl",W.index);if($>=0)return $}}return-1}function E3(Z){let X=!1,J=!1;for(let W=0;W<Z.length;W++){let $=Z[W];if($==="\\"&&!X){W++;continue}if($==="'"&&!J){X=!X;continue}if($==='"'&&!X){J=!J;continue}if($==="|"&&!X&&!J)return W}return-1}function D0(Z){let X=["curl"];if(Z.method!=="GET"||Z.body||Z.formData)X.push(`-X ${Z.method}`);for(let[W,$]of Object.entries(Z.headers))X.push(`-H ${x(`${W}: ${$}`)}`);if(Z.auth){if(Z.auth.type==="basic")X.push(`-u ${x(`${Z.auth.username||""}:${Z.auth.password||""}`)}`);else if(Z.auth.type==="bearer")X.push(`-H ${x(`Authorization: Bearer ${Z.auth.token||""}`)}`)}if(Z.formData)for(let[W,$]of Object.entries(Z.formData))if(typeof $==="string")X.push(`--form-string ${x(`${W}=${$}`)}`);else{let G=`@${$.file}`;if($.filename)G+=`;filename=${$.filename}`;if($.contentType)G+=`;type=${$.contentType}`;X.push(`-F ${x(`${W}=${G}`)}`)}else if(Z.body)if(Z.body.type==="json"){if(X.push(`-d ${x(JSON.stringify(Z.body.content))}`),!Z.headers["Content-Type"])X.push(`-H ${x("Content-Type: application/json")}`)}else if(Z.body.type==="urlencoded")X.push(`--data-urlencode ${x(String(Z.body.content))}`);else if(Z.body.type==="binary")X.push(`--data-binary ${x(String(Z.body.content))}`);else X.push(`-d ${x(String(Z.body.content))}`);if(Z.timeout!==void 0)X.push(`--max-time ${Math.ceil(Z.timeout/1000)}`);if(Z.followRedirects)X.push("-L");if(Z.maxRedirects!==void 0)X.push(`--max-redirs ${Z.maxRedirects}`);if(Z.proxy)X.push(`-x ${x(Z.proxy)}`);if(Z.insecure)X.push("-k");if(Z.http2)X.push("--http2");if(Z.output)X.push(`-o ${x(Z.output)}`);if(Z.ssl){if(Z.ssl.ca)X.push(`--cacert ${x(Z.ssl.ca)}`);if(Z.ssl.cert)X.push(`--cert ${x(Z.ssl.cert)}`);if(Z.ssl.key)X.push(`--key ${x(Z.ssl.key)}`)}let J=Z.url;if(Z.params&&Object.keys(Z.params).length>0){let W=new URLSearchParams(Z.params).toString();J+=(J.includes("?")?"&":"?")+W}return X.push(x(J)),X.join(" \\\n ")}function x(Z){if(Z.includes("'"))return`"${Z.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\$/g,"\\$").replace(/`/g,"\\`")}"`;if(/[^a-zA-Z0-9_./:@=,+%-]/.test(Z))return`'${Z}'`;return Z}function O1(Z){let X=[],J="",W=0,$=Z.length;while(W<$){let G=Z[W];if(G==="\\"&&W+1<$&&(Z[W+1]===`
120
+ `||Z[W+1]==="\r")){if(W+=2,W<$&&Z[W]===`
121
+ `)W++;while(W<$&&(Z[W]===" "||Z[W]==="\t"))W++;continue}if(G===" "||G==="\t"||G===`
122
+ `||G==="\r"){if(J.length>0)X.push(J),J="";W++;continue}if(G==="'"){W++;while(W<$&&Z[W]!=="'")J+=Z[W],W++;if(W<$)W++;continue}if(G==='"'){W++;while(W<$&&Z[W]!=='"'){if(Z[W]==="\\"&&W+1<$){let Q=Z[W+1];if(Q==='"'||Q==="\\"||Q==="$"||Q==="`"||Q===`
123
+ `){if(Q===`
124
+ `){W+=2;continue}J+=Q,W+=2;continue}}J+=Z[W],W++}if(W<$)W++;continue}if(G==="\\"&&W+1<$){J+=Z[W+1],W+=2;continue}J+=G,W++}if(J.length>0)X.push(J);return X}var F0=new Set(["-X","--request","-H","--header","-d","--data","--data-raw","--data-binary","--data-ascii","--data-urlencode","-F","--form","--form-string","-u","--user","-o","--output","-x","--proxy","--max-time","-m","--max-redirs","--cacert","--cert","--key","-b","--cookie","-c","--cookie-jar","-A","--user-agent","-e","--referer","--connect-timeout","--retry","--retry-delay","-w","--write-out","--resolve","--interface","--local-port","--limit-rate","--ciphers","--proto","--tlsv1.2","--tlsv1.3"]),o9=new Set(["-G","--get","-I","--head","-L","--location","-k","--insecure","-s","--silent","-S","--show-error","-v","--verbose","--compressed","--http2","--http2-prior-knowledge","--http1.1","-N","--no-buffer","--raw","-f","--fail","--fail-early","--globoff","-#","--progress-bar","--tr-encoding","--tcp-nodelay","--tcp-fastopen"]);function k1(Z){let X=O1(Z.trim());return i9(X)}function i9(Z){let X={url:"",headers:[],unsupportedFlags:[]},J=[],W=[],$=[],G=[],Q=[],Y=[],z=0;if(Z.length>0&&Z[0]==="curl")z=1;while(z<Z.length){let H=Z[z];if(!H.startsWith("-")){if(!X.url)X.url=H;z++;continue}if(H.startsWith("-")&&!H.startsWith("--")&&H.length>2){let K=`-${H[1]}`;if(F0.has(K)){let M=H.slice(2);z=V1(K,M,Z,z,X,J,W,$,G,Q,Y);continue}let U=!0;for(let M=1;M<H.length;M++){let R=`-${H[M]}`;if(!o9.has(R)){U=!1;break}}if(U){for(let M=1;M<H.length;M++)z=V1(`-${H[M]}`,void 0,Z,z,X,J,W,$,G,Q,Y);z++;continue}}if(F0.has(H)){let K=Z[z+1];z=V1(H,K,Z,z,X,J,W,$,G,Q,Y);continue}if(o9.has(H)){z=V1(H,void 0,Z,z,X,J,W,$,G,Q,Y);continue}if(H.startsWith("-")){let K=Z[z+1];if(K&&!K.startsWith("-"))X.unsupportedFlags.push({flag:H,value:K}),z+=2;else X.unsupportedFlags.push({flag:H}),z++;continue}z++}if(J.length>0)X.data=J;if(W.length>0)X.dataRaw=W;if($.length>0)X.dataBinary=$;if(G.length>0)X.dataUrlencode=G;if(Q.length>0)X.form=Q;if(Y.length>0)X.formString=Y;return X}function V1(Z,X,J,W,$,G,Q,Y,z,H,K){switch(Z){case"-X":case"--request":return $.method=X?.toUpperCase(),W+2;case"-H":case"--header":{if(X){let U=X.indexOf(":");if(U>0)$.headers.push({key:X.slice(0,U).trim(),value:X.slice(U+1).trim()})}return W+2}case"-d":case"--data":case"--data-ascii":if(X!==void 0)G.push(X);return W+2;case"--data-raw":if(X!==void 0)Q.push(X);return W+2;case"--data-binary":if(X!==void 0)Y.push(X);return W+2;case"--data-urlencode":if(X!==void 0)z.push(X);return W+2;case"-F":case"--form":if(X!==void 0)H.push(X);return W+2;case"--form-string":if(X!==void 0)K.push(X);return W+2;case"-u":case"--user":return $.user=X,W+2;case"-o":case"--output":return $.output=X,W+2;case"-x":case"--proxy":return $.proxy=X,W+2;case"--max-time":case"-m":if(X)$.maxTime=Number(X);return W+2;case"--max-redirs":if(X)$.maxRedirs=Number(X);return W+2;case"--cacert":return $.cacert=X,W+2;case"--cert":return $.cert=X,W+2;case"--key":return $.key=X,W+2;case"-b":case"--cookie":return $.cookie=X,W+2;case"-c":case"--cookie-jar":return $.cookieJar=X,W+2;case"-A":case"--user-agent":return $.userAgent=X,W+2;case"-e":case"--referer":return $.referer=X,W+2;case"-G":case"--get":return $.get=!0,W+1;case"-I":case"--head":return $.head=!0,W+1;case"-L":case"--location":return $.location=!0,W+1;case"-k":case"--insecure":return $.insecure=!0,W+1;case"--compressed":return $.compressed=!0,W+1;case"--http2":return $.http2=!0,W+1;case"-s":case"--silent":return $.silent=!0,W+1;case"-v":case"--verbose":return $.verbose=!0,W+1;default:if(F0.has(Z))return W+2;return W+1}}function P1(Z){let X=[],{url:J,params:W}=A3(Z.url),$=V3(Z),G=P3(Z,$),{body:Q,formData:Y}=C3(Z,X),z=x3(Z,Q,Y),H=b3(Z);for(let U of Z.unsupportedFlags)X.push(`Unsupported curl flag: ${U.flag}${U.value?` ${U.value}`:""}`);if(Z.compressed)X.push("Flag --compressed has no YAML equivalent; curl handles decompression natively");if(Z.cookie)X.push(`Cookie flag (-b ${Z.cookie}) stored as header; manual review recommended`),$.Cookie=Z.cookie;if(Z.cookieJar)X.push(`Cookie jar flag (-c ${Z.cookieJar}) has no YAML equivalent`);if(Z.userAgent&&!$["User-Agent"])$["User-Agent"]=Z.userAgent;if(Z.referer&&!$.Referer)$.Referer=Z.referer;let K={method:z,url:J,headers:$,metadata:{source:"curl",warnings:X,unsupportedFlags:Z.unsupportedFlags.length>0?Z.unsupportedFlags:void 0}};if(Object.keys(W).length>0)K.params=W;if(Q)K.body=Q;if(Y)K.formData=Y;if(G)K.auth=G;if(Z.insecure)K.insecure=!0;if(Z.location)K.followRedirects=!0;if(Z.maxRedirs!==void 0)K.maxRedirects=Z.maxRedirs;if(Z.maxTime!==void 0)K.timeout=Z.maxTime*1000;if(Z.proxy)K.proxy=Z.proxy;if(Z.output)K.output=Z.output;if(Z.http2)K.http2=!0;if(H)K.ssl=H;return K}function A3(Z){let X={};if(!Z)return{url:"",params:X};let J=Z.indexOf("?");if(J===-1)return{url:Z,params:X};let W=Z.slice(0,J),$=Z.slice(J+1);for(let G of $.split("&")){let Q=G.indexOf("=");if(Q>0){let Y=decodeURIComponent(G.slice(0,Q)),z=decodeURIComponent(G.slice(Q+1));X[Y]=z}else if(G.length>0)X[decodeURIComponent(G)]=""}return{url:W,params:X}}function V3(Z){let X={};for(let J of Z.headers){if(J.key.toLowerCase()==="authorization")continue;X[k3(J.key)]=J.value}return X}function k3(Z){return Z.split("-").map((X)=>X.charAt(0).toUpperCase()+X.slice(1).toLowerCase()).join("-")}function P3(Z,X){if(Z.user){let J=Z.user.indexOf(":");if(J>0)return{type:"basic",username:Z.user.slice(0,J),password:Z.user.slice(J+1)};return{type:"basic",username:Z.user,password:""}}for(let J of Z.headers)if(J.key.toLowerCase()==="authorization"){let W=J.value.trim();if(W.toLowerCase().startsWith("bearer "))return{type:"bearer",token:W.slice(7).trim()};if(W.toLowerCase().startsWith("basic "))try{let $=atob(W.slice(6).trim()),G=$.indexOf(":");if(G>0)return{type:"basic",username:$.slice(0,G),password:$.slice(G+1)}}catch{X.Authorization=W}else X.Authorization=W}return}function C3(Z,X){if(Z.form&&Z.form.length>0){let W={};for(let $ of Z.form)w3($,W);if(Z.formString)for(let $ of Z.formString){let G=$.indexOf("=");if(G>0)W[$.slice(0,G)]=$.slice(G+1)}return{formData:W}}if(Z.dataUrlencode&&Z.dataUrlencode.length>0)return{body:{type:"urlencoded",content:Z.dataUrlencode.map(($)=>encodeURIComponent($)).join("&")}};if(Z.dataBinary&&Z.dataBinary.length>0){if(Z.dataBinary[0].startsWith("@"))return{body:{type:"binary",content:Z.dataBinary[0]}};return{body:{type:"raw",content:Z.dataBinary.join("")}}}let J=[...Z.data||[],...Z.dataRaw||[]];if(J.length>0){let W=J.join("&");try{return{body:{type:"json",content:JSON.parse(W)}}}catch{if(q3(W))return{body:{type:"urlencoded",content:W}};return{body:{type:"raw",content:W}}}}return{}}function w3(Z,X){let J=Z.indexOf("=");if(J<=0)return;let W=Z.slice(0,J),$=Z.slice(J+1);if($.startsWith("@")){let G=$.slice(1).split(";"),Q={file:G[0]};for(let Y=1;Y<G.length;Y++){let[z,H]=G[Y].split("=");if(z==="filename")Q.filename=H;else if(z==="type")Q.contentType=H}X[W]=Q}else X[W]=$}function q3(Z){return/^[^=&]+=[^&]*(&[^=&]+=[^&]*)*$/.test(Z)}function x3(Z,X,J){if(Z.method)return Z.method;if(Z.head)return"HEAD";if(Z.get)return"GET";if(X||J)return"POST";return"GET"}function b3(Z){if(!Z.cacert&&!Z.cert&&!Z.key)return;let X={};if(Z.cacert)X.ca=Z.cacert;if(Z.cert)X.cert=Z.cert;if(Z.key)X.key=Z.key;return X}function C1(Z,X){let J=[],W=X?.pretty??!0;if((X?.lossReport??!0)&&Z.metadata.warnings.length>0){for(let G of Z.metadata.warnings)J.push(`# Warning: ${G}`);J.push("")}if(J.push("request:"),Z.name)J.push(` name: ${S(Z.name)}`);if(J.push(` method: ${Z.method}`),J.push(` url: ${S(Z.url)}`),Z.params&&Object.keys(Z.params).length>0){J.push(" params:");for(let[G,Q]of Y1(Z.params))J.push(` ${d(G)}: ${S(Q)}`)}if(Object.keys(Z.headers).length>0){J.push(" headers:");for(let[G,Q]of Y1(Z.headers))J.push(` ${d(G)}: ${S(Q)}`)}if(Z.auth){if(J.push(" auth:"),J.push(` type: ${Z.auth.type}`),Z.auth.type==="basic")J.push(` username: ${S(Z.auth.username||"")}`),J.push(` password: ${S(Z.auth.password||"")}`);else if(Z.auth.type==="bearer")J.push(` token: ${S(Z.auth.token||"")}`)}if(Z.body)if(J.push(" body:"),Z.body.type==="json")if(W){let G=a9(Z.body.content,4);J.push(...G)}else J.push(` json: ${JSON.stringify(Z.body.content)}`);else if(Z.body.type==="urlencoded")J.push(` form: ${S(String(Z.body.content))}`);else if(Z.body.type==="binary")J.push(` binary: ${S(String(Z.body.content))}`);else J.push(` raw: ${S(String(Z.body.content))}`);if(Z.formData&&Object.keys(Z.formData).length>0){J.push(" formData:");for(let[G,Q]of Y1(Z.formData))if(typeof Q==="string")J.push(` ${d(G)}: ${S(Q)}`);else{if(J.push(` ${d(G)}:`),J.push(` file: ${S(Q.file)}`),Q.filename)J.push(` filename: ${S(Q.filename)}`);if(Q.contentType)J.push(` contentType: ${S(Q.contentType)}`)}}if(Z.timeout!==void 0)J.push(` timeout: ${Z.timeout}`);if(Z.followRedirects)J.push(" followRedirects: true");if(Z.maxRedirects!==void 0)J.push(` maxRedirects: ${Z.maxRedirects}`);if(Z.proxy)J.push(` proxy: ${S(Z.proxy)}`);if(Z.insecure)J.push(" insecure: true");if(Z.http2)J.push(" http2: true");if(Z.output)J.push(` output: ${S(Z.output)}`);if(Z.ssl){if(J.push(" ssl:"),Z.ssl.ca)J.push(` ca: ${S(Z.ssl.ca)}`);if(Z.ssl.cert)J.push(` cert: ${S(Z.ssl.cert)}`);if(Z.ssl.key)J.push(` key: ${S(Z.ssl.key)}`)}return`${J.join(`
125
+ `)}
126
+ `}function T0(Z,X){let J=[],W=X?.pretty??!0;if(X?.lossReport??!0){let G=Z.flatMap((Q)=>Q.metadata.warnings);if(G.length>0){for(let Q of G)J.push(`# Warning: ${Q}`);J.push("")}}J.push("requests:");for(let G=0;G<Z.length;G++){let Q=Z[G];if(G>0)J.push("");if(Q.name)J.push(` - name: ${S(Q.name)}`);else J.push(` - name: request_${G+1}`);if(J.push(` method: ${Q.method}`),J.push(` url: ${S(Q.url)}`),Q.params&&Object.keys(Q.params).length>0){J.push(" params:");for(let[Y,z]of Y1(Q.params))J.push(` ${d(Y)}: ${S(z)}`)}if(Object.keys(Q.headers).length>0){J.push(" headers:");for(let[Y,z]of Y1(Q.headers))J.push(` ${d(Y)}: ${S(z)}`)}if(Q.auth){if(J.push(" auth:"),J.push(` type: ${Q.auth.type}`),Q.auth.type==="basic")J.push(` username: ${S(Q.auth.username||"")}`),J.push(` password: ${S(Q.auth.password||"")}`);else if(Q.auth.type==="bearer")J.push(` token: ${S(Q.auth.token||"")}`)}if(Q.body)if(J.push(" body:"),Q.body.type==="json")if(W){let Y=a9(Q.body.content,6);J.push(...Y)}else J.push(` json: ${JSON.stringify(Q.body.content)}`);else if(Q.body.type==="urlencoded")J.push(` form: ${S(String(Q.body.content))}`);else if(Q.body.type==="binary")J.push(` binary: ${S(String(Q.body.content))}`);else J.push(` raw: ${S(String(Q.body.content))}`);if(Q.formData&&Object.keys(Q.formData).length>0){J.push(" formData:");for(let[Y,z]of Y1(Q.formData))if(typeof z==="string")J.push(` ${d(Y)}: ${S(z)}`);else{if(J.push(` ${d(Y)}:`),J.push(` file: ${S(z.file)}`),z.filename)J.push(` filename: ${S(z.filename)}`);if(z.contentType)J.push(` contentType: ${S(z.contentType)}`)}}if(Q.timeout!==void 0)J.push(` timeout: ${Q.timeout}`);if(Q.followRedirects)J.push(" followRedirects: true");if(Q.maxRedirects!==void 0)J.push(` maxRedirects: ${Q.maxRedirects}`);if(Q.proxy)J.push(` proxy: ${S(Q.proxy)}`);if(Q.insecure)J.push(" insecure: true");if(Q.http2)J.push(" http2: true");if(Q.output)J.push(` output: ${S(Q.output)}`);if(Q.ssl){if(J.push(" ssl:"),Q.ssl.ca)J.push(` ca: ${S(Q.ssl.ca)}`);if(Q.ssl.cert)J.push(` cert: ${S(Q.ssl.cert)}`);if(Q.ssl.key)J.push(` key: ${S(Q.ssl.key)}`)}}return`${J.join(`
127
+ `)}
128
+ `}function a9(Z,X){let J=" ".repeat(X);if(Z===null||Z===void 0)return[`${J}json: null`];if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")return[`${J}json: ${JSON.stringify(Z)}`];if(Array.isArray(Z)){if(Z.length===0)return[`${J}json: []`];if(Z.every((W)=>typeof W!=="object"||W===null))return[`${J}json: [${Z.map((W)=>JSON.stringify(W)).join(", ")}]`];return[`${J}json: ${JSON.stringify(Z)}`]}if(typeof Z==="object"){let W=Z,$=Object.keys(W);if($.length===0)return[`${J}json: {}`];let G=[];G.push(`${J}json:`);for(let Q of $){let Y=W[Q];if(Y===null)G.push(`${J} ${d(Q)}: null`);else if(typeof Y==="object"&&!Array.isArray(Y))G.push(`${J} ${d(Q)}: ${JSON.stringify(Y)}`);else if(Array.isArray(Y))G.push(`${J} ${d(Q)}: ${JSON.stringify(Y)}`);else G.push(`${J} ${d(Q)}: ${y3(Y)}`)}return G}return[`${J}json: ${JSON.stringify(Z)}`]}function S(Z){if(Z==="")return'""';if(v3(Z))return`"${Z.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return Z}function d(Z){if(/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(Z))return Z;return`"${Z.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function y3(Z){if(typeof Z==="string")return S(Z);if(typeof Z==="number"||typeof Z==="boolean")return String(Z);return JSON.stringify(Z)}function v3(Z){if(/[{}[\],&*?|>!%#@`]/.test(Z))return!0;if(/: /.test(Z)||Z.endsWith(":"))return!0;if(Z.startsWith("'")||Z.startsWith('"'))return!0;let X=Z.toLowerCase();if(["true","false","null","yes","no","on","off"].includes(X))return!0;if(/^-?\d+(\.\d+)?$/.test(Z))return!0;if(Z.startsWith(" ")||Z.endsWith(" "))return!0;return!1}function Y1(Z){return Object.entries(Z).sort(([X],[J])=>X.localeCompare(J))}function I0(Z){let X=[],J={};if(Z.headers)for(let[$,G]of Object.entries(Z.headers))J[$]=G;let W={method:Z.method||"GET",url:Z.url,headers:J,metadata:{source:"yaml",warnings:X}};if(Z.name)W.name=Z.name;if(Z.params)W.params={...Z.params};if(Z.auth)W.auth={type:Z.auth.type,username:Z.auth.username,password:Z.auth.password,token:Z.auth.token};if(Z.body!==void 0)if(typeof Z.body==="object"&&Z.body!==null&&!Array.isArray(Z.body)){let $=Z.body;if("json"in $)W.body={type:"json",content:$.json};else if("form"in $)W.body={type:"urlencoded",content:String($.form)};else if("raw"in $)W.body={type:"raw",content:String($.raw)};else if("binary"in $)W.body={type:"binary",content:String($.binary)};else W.body={type:"json",content:Z.body}}else W.body={type:"json",content:Z.body};if(Z.formData){let $={};for(let[G,Q]of Object.entries(Z.formData))if(typeof Q==="object"&&Q!==null&&"file"in Q)$[G]={file:Q.file,filename:Q.filename,contentType:Q.contentType};else $[G]=String(Q);W.formData=$}if(Z.timeout)W.timeout=Z.timeout;if(Z.followRedirects!==void 0)W.followRedirects=Z.followRedirects;if(Z.maxRedirects)W.maxRedirects=Z.maxRedirects;if(Z.proxy)W.proxy=Z.proxy;if(Z.insecure)W.insecure=!0;if(Z.http2)W.http2=!0;if(Z.output)W.output=Z.output;if(Z.ssl){if(W.ssl={},Z.ssl.ca)W.ssl.ca=Z.ssl.ca;if(Z.ssl.cert)W.ssl.cert=Z.ssl.cert;if(Z.ssl.key)W.ssl.key=Z.ssl.key}if(Z.expect)X.push("expect block has no curl equivalent");if(Z.store)X.push("store block has no curl equivalent");if(Z.when)X.push("when condition has no curl equivalent");if(Z.retry)X.push("retry config simplified in curl output");if(Z.snapshot)X.push("snapshot config has no curl equivalent");if(Z.diff)X.push("diff config has no curl equivalent");return W}function N0(Z,X){let J=k1(Z),W=P1(J),G={output:C1(W,{pretty:X?.pretty??!0,lossReport:X?.lossReport??!0}),warnings:W.metadata.warnings};if(X?.debug)G.debug={tokens:O1(Z.trim()),ast:J,ir:W};return G}async function L0(Z,X){let J=await Bun.file(Z).text(),W=M0(J);if(W.length===0)return{output:"",warnings:["No curl commands found in file"]};let $=[],G=[];for(let z=0;z<W.length;z++){let H=k1(W[z]),K=P1(H);K.name=`request_${z+1}`,$.push(K),G.push(...K.metadata.warnings)}if($.length===1){let H={output:C1($[0],{pretty:X?.pretty??!0,lossReport:X?.lossReport??!0}),warnings:G};if(X?.debug)H.debug={ir:$[0]};return H}let Y={output:T0($,{pretty:X?.pretty??!0,lossReport:X?.lossReport??!0}),warnings:G};if(X?.debug)Y.debug={ir:$};return Y}async function R0(Z,X){let J=await Bun.file(Z).text(),W=Bun.YAML.parse(J),$=[];if(W.request)$.push(W.request);if(W.requests)$.push(...W.requests);if(W.collection?.requests)$.push(...W.collection.requests);if($.length===0)return{output:"",warnings:["No requests found in YAML file"]};let G=[],Q=[];for(let z of $){let H=I0(z);G.push(...H.metadata.warnings),Q.push(D0(H))}return{output:Q.join(`
129
+
130
+ `),warnings:G}}function j0(Z){if(Z.length<3)return null;let X=Z[1];if(X!=="curl"&&X!=="file"&&X!=="yaml")return null;let J=Z[2],W={};for(let $=3;$<Z.length;$++)switch(Z[$]){case"--output":case"-o":W.output=Z[++$];break;case"--pretty":W.pretty=!0;break;case"--normalize":W.normalize=!0;break;case"--loss-report":W.lossReport=!0;break;case"--batch":W.batch=!0;break;case"--env-detect":W.envDetect=!0;break;case"--debug":W.debug=!0;break}return{subcommand:X,input:J,options:W}}function S0(Z){let X={files:[]};for(let J=0;J<Z.length;J++){let W=Z[J],$=Z[J+1],G=$!==void 0&&!$.startsWith("-");if(W.startsWith("--"))J+=m3(W.slice(2),$,G,X);else if(W.startsWith("-"))J+=h3(W.slice(1),$,G,X);else X.files.push(W)}return X}function m3(Z,X,J,W){switch(Z){case"help":return W.help=!0,0;case"version":return W.version=!0,0;case"all":return W.all=!0,0;case"dry-run":return W.dryRun=!0,0;case"http2":return W.http2=!0,0;case"connection-pool":return W.connectionPool=!0,0;case"quiet":return W.quiet=!0,0;case"show-headers":return W.showHeaders=!0,0;case"show-body":return W.showBody=!0,0;case"show-metrics":return W.showMetrics=!0,0;case"no-retry":return W.noRetry=!0,0;case"watch":return W.watch=!0,0;case"watch-clear":return W.watchClear=!0,0;case"no-watch-clear":return W.watchClear=!1,0;case"profile-histogram":return W.profileHistogram=!0,0;case"snapshot":return W.snapshot=!0,0;case"update-snapshots":return W.snapshotUpdate="all",0;case"update-failing":return W.snapshotUpdate="failing",0;case"ci-snapshot":return W.snapshotCi=!0,0;case"diff":return W.diff=!0,0;case"diff-save":return W.diffSave=!0,0;case"strict-exit":return W.strictExit=!0,0;case"no-redact":return W.noRedact=!0,0}if(!J){if(Z==="verbose")return W.verbose=!0,0;if(Z==="continue-on-error")return W.continueOnError=!0,0;return 0}switch(Z){case"env":return W.env=X,1;case"execution":if(X==="sequential"||X==="parallel")W.execution=X;return 1;case"max-concurrent":{let $=Number.parseInt(X,10);if($>0)W.maxConcurrency=$;return 1}case"max-streams":{let $=Number.parseInt(X,10);if($>0)W.maxStreams=$;return 1}case"keepalive-time":return W.keepaliveTime=Number.parseInt(X,10),1;case"connect-timeout":return W.connectTimeout=Number.parseInt(X,10),1;case"verbose":return W.verbose=X==="true",1;case"output":return W.output=X,1;case"output-format":if(["json","pretty","raw"].includes(X))W.outputFormat=X;return 1;case"pretty-level":if(["minimal","standard","detailed"].includes(X))W.prettyLevel=X;return 1;case"timeout":return W.timeout=Number.parseInt(X,10),1;case"retries":return W.retries=Number.parseInt(X,10),1;case"retry-delay":return W.retryDelay=Number.parseInt(X,10),1;case"continue-on-error":return W.continueOnError=X==="true",1;case"watch-debounce":return W.watchDebounce=Number.parseInt(X,10),1;case"profile":return W.profile=Number.parseInt(X,10),1;case"profile-warmup":return W.profileWarmup=Number.parseInt(X,10),1;case"profile-concurrency":return W.profileConcurrency=Number.parseInt(X,10),1;case"profile-export":return W.profileExport=X,1;case"snapshot-dir":return W.snapshotDir=X,1;case"diff-label":return W.diffLabel=X,1;case"diff-compare":return W.diffCompare=X,1;case"diff-dir":return W.diffDir=X,1;case"diff-output":if(["terminal","json","markdown"].includes(X))W.diffOutput=X;return 1;case"fail-on":return W.failOn=Number.parseInt(X,10),1;case"fail-on-percentage":{let $=Number.parseFloat(X);if($>=0&&$<=100)W.failOnPercentage=$;return 1}default:return 1}}function h3(Z,X,J,W){let $=0;for(let G of Z)switch(G){case"h":W.help=!0;break;case"v":W.verbose=!0;break;case"p":W.execution="parallel";break;case"c":break;case"q":W.quiet=!0;break;case"w":W.watch=!0;break;case"s":W.snapshot=!0;break;case"u":W.snapshotUpdate="all";break;case"d":W.diff=!0;break;case"n":W.dryRun=!0;break;case"o":if(J)W.output=X,$=1;break;case"P":if(J)W.profile=Number.parseInt(X,10),$=1;break;case"e":if(J)W.env=X,$=1;break}return $}function E0(Z){if(Z[0]==="upgrade")return"upgrade";if(Z[0]==="validate")return"validate";if(Z[0]==="convert")return"convert";if(Z[0]==="diff"&&Z.length>=3)return"diff-subcommand";if(Z[0]==="init")return"init";if(Z[0]==="edit")return"edit";return null}function A0(Z){let X={};for(let J=1;J<Z.length;J++){let W=Z[J],$=Z[J+1];if(W==="--wizard"||W==="-w")X.wizard=!0;else if(W==="-o"||W==="--output"){if($&&!$.startsWith("-"))X.outputPath=$,J++}else if(!W.startsWith("-")&&!X.url)X.url=W}return X}function V0(Z){let X={file:""};for(let J=1;J<Z.length;J++){let W=Z[J],$=Z[J+1];if(W==="-o"||W==="--output"){if($&&!$.startsWith("-"))X.outputPath=$,J++}else if(!W.startsWith("-")&&!X.file)X.file=W}return X}function k0(Z){if(Z.help)return"help";if(Z.version)return"version";return null}import{join as w1}from"path";function g3(Z){let X={},J=Z.split(`
131
+ `);for(let W of J){let $=W.trim();if(!$||$.startsWith("#"))continue;let G=$.indexOf("=");if(G===-1)continue;let Q=$.slice(0,G).trim(),Y=$.slice(G+1).trim();if(Y.startsWith('"')&&Y.endsWith('"')||Y.startsWith("'")&&Y.endsWith("'"))Y=Y.slice(1,-1);if($.slice(G+1).trim().startsWith('"'))Y=Y.replace(/\\n/g,`
132
+ `).replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\\\/g,"\\");if(Q)X[Q]=Y}return X}async function d3(Z){let X=Bun.file(Z);if(!await X.exists())return{};try{let J=await X.text();return g3(J)}catch{return{}}}function f3(Z){return Object.keys(Z).filter((X)=>X.startsWith("SECRET_"))}async function P0(Z=process.cwd(),X){let J=[w1(Z,".env"),w1(Z,".env.local")];if(X)J.push(w1(Z,`.env.${X}`),w1(Z,`.env.${X}.local`));let W={};for(let $ of J){let G=await d3($);W={...W,...G}}return{variables:W,secretKeys:f3(W)}}function C0(){let Z={};return p3(Z),c3(Z),u3(Z),l3(Z),n3(Z),o3(Z),i3(Z),a3(Z),r3(Z),Z}function p3(Z){if(process.env.CURL_RUNNER_EXECUTION)Z.execution=process.env.CURL_RUNNER_EXECUTION;if(process.env.CURL_RUNNER_CONTINUE_ON_ERROR)Z.continueOnError=process.env.CURL_RUNNER_CONTINUE_ON_ERROR.toLowerCase()==="true";if(process.env.CURL_RUNNER_DRY_RUN)Z.dryRun=process.env.CURL_RUNNER_DRY_RUN.toLowerCase()==="true";if(process.env.CURL_RUNNER_HTTP2)Z.http2=process.env.CURL_RUNNER_HTTP2.toLowerCase()==="true";if(process.env.CURL_RUNNER_MAX_CONCURRENCY){let X=Number.parseInt(process.env.CURL_RUNNER_MAX_CONCURRENCY,10);if(X>0)Z.maxConcurrency=X}}function c3(Z){if(process.env.CURL_RUNNER_CONNECTION_POOL)Z.connectionPool={...Z.connectionPool,enabled:process.env.CURL_RUNNER_CONNECTION_POOL.toLowerCase()==="true"};if(process.env.CURL_RUNNER_MAX_STREAMS_PER_HOST)Z.connectionPool={...Z.connectionPool,maxStreamsPerHost:Number.parseInt(process.env.CURL_RUNNER_MAX_STREAMS_PER_HOST,10)};if(process.env.CURL_RUNNER_KEEPALIVE_TIME)Z.connectionPool={...Z.connectionPool,keepaliveTime:Number.parseInt(process.env.CURL_RUNNER_KEEPALIVE_TIME,10)};if(process.env.CURL_RUNNER_CONNECT_TIMEOUT)Z.connectionPool={...Z.connectionPool,connectTimeout:Number.parseInt(process.env.CURL_RUNNER_CONNECT_TIMEOUT,10)}}function u3(Z){if(process.env.CURL_RUNNER_VERBOSE)Z.output={...Z.output,verbose:process.env.CURL_RUNNER_VERBOSE.toLowerCase()==="true"};if(process.env.CURL_RUNNER_OUTPUT_FORMAT){let X=process.env.CURL_RUNNER_OUTPUT_FORMAT;if(["json","pretty","raw"].includes(X))Z.output={...Z.output,format:X}}if(process.env.CURL_RUNNER_PRETTY_LEVEL){let X=process.env.CURL_RUNNER_PRETTY_LEVEL;if(["minimal","standard","detailed"].includes(X))Z.output={...Z.output,prettyLevel:X}}if(process.env.CURL_RUNNER_OUTPUT_FILE)Z.output={...Z.output,saveToFile:process.env.CURL_RUNNER_OUTPUT_FILE}}function l3(Z){if(process.env.CURL_RUNNER_STRICT_EXIT)Z.ci={...Z.ci,strictExit:process.env.CURL_RUNNER_STRICT_EXIT.toLowerCase()==="true"};if(process.env.CURL_RUNNER_FAIL_ON)Z.ci={...Z.ci,failOn:Number.parseInt(process.env.CURL_RUNNER_FAIL_ON,10)};if(process.env.CURL_RUNNER_FAIL_ON_PERCENTAGE){let X=Number.parseFloat(process.env.CURL_RUNNER_FAIL_ON_PERCENTAGE);if(X>=0&&X<=100)Z.ci={...Z.ci,failOnPercentage:X}}}function n3(Z){if(process.env.CURL_RUNNER_WATCH)Z.watch={...Z.watch,enabled:process.env.CURL_RUNNER_WATCH.toLowerCase()==="true"};if(process.env.CURL_RUNNER_WATCH_DEBOUNCE)Z.watch={...Z.watch,debounce:Number.parseInt(process.env.CURL_RUNNER_WATCH_DEBOUNCE,10)};if(process.env.CURL_RUNNER_WATCH_CLEAR)Z.watch={...Z.watch,clear:process.env.CURL_RUNNER_WATCH_CLEAR.toLowerCase()!=="false"}}function o3(Z){if(process.env.CURL_RUNNER_PROFILE){let X=Number.parseInt(process.env.CURL_RUNNER_PROFILE,10);if(X>0)Z.profile={...Z.profile,iterations:X}}if(process.env.CURL_RUNNER_PROFILE_WARMUP)Z.profile={...Z.profile,iterations:Z.profile?.iterations??10,warmup:Number.parseInt(process.env.CURL_RUNNER_PROFILE_WARMUP,10)};if(process.env.CURL_RUNNER_PROFILE_CONCURRENCY)Z.profile={...Z.profile,iterations:Z.profile?.iterations??10,concurrency:Number.parseInt(process.env.CURL_RUNNER_PROFILE_CONCURRENCY,10)};if(process.env.CURL_RUNNER_PROFILE_HISTOGRAM)Z.profile={...Z.profile,iterations:Z.profile?.iterations??10,histogram:process.env.CURL_RUNNER_PROFILE_HISTOGRAM.toLowerCase()==="true"};if(process.env.CURL_RUNNER_PROFILE_EXPORT)Z.profile={...Z.profile,iterations:Z.profile?.iterations??10,exportFile:process.env.CURL_RUNNER_PROFILE_EXPORT}}function i3(Z){if(process.env.CURL_RUNNER_SNAPSHOT)Z.snapshot={...Z.snapshot,enabled:process.env.CURL_RUNNER_SNAPSHOT.toLowerCase()==="true"};if(process.env.CURL_RUNNER_SNAPSHOT_UPDATE){let X=process.env.CURL_RUNNER_SNAPSHOT_UPDATE.toLowerCase();if(["none","all","failing"].includes(X))Z.snapshot={...Z.snapshot,updateMode:X}}if(process.env.CURL_RUNNER_SNAPSHOT_DIR)Z.snapshot={...Z.snapshot,dir:process.env.CURL_RUNNER_SNAPSHOT_DIR};if(process.env.CURL_RUNNER_SNAPSHOT_CI)Z.snapshot={...Z.snapshot,ci:process.env.CURL_RUNNER_SNAPSHOT_CI.toLowerCase()==="true"}}function a3(Z){if(process.env.CURL_RUNNER_DIFF)Z.diff={...Z.diff,enabled:process.env.CURL_RUNNER_DIFF.toLowerCase()==="true"};if(process.env.CURL_RUNNER_DIFF_SAVE)Z.diff={...Z.diff,save:process.env.CURL_RUNNER_DIFF_SAVE.toLowerCase()==="true"};if(process.env.CURL_RUNNER_DIFF_LABEL)Z.diff={...Z.diff,label:process.env.CURL_RUNNER_DIFF_LABEL};if(process.env.CURL_RUNNER_DIFF_COMPARE)Z.diff={...Z.diff,compareWith:process.env.CURL_RUNNER_DIFF_COMPARE};if(process.env.CURL_RUNNER_DIFF_DIR)Z.diff={...Z.diff,dir:process.env.CURL_RUNNER_DIFF_DIR};if(process.env.CURL_RUNNER_DIFF_OUTPUT){let X=process.env.CURL_RUNNER_DIFF_OUTPUT.toLowerCase();if(["terminal","json","markdown"].includes(X))Z.diff={...Z.diff,outputFormat:X}}}function r3(Z){if(process.env.CURL_RUNNER_TIMEOUT)Z.defaults={...Z.defaults,timeout:Number.parseInt(process.env.CURL_RUNNER_TIMEOUT,10)};if(process.env.CURL_RUNNER_RETRIES)Z.defaults={...Z.defaults,retry:{...Z.defaults?.retry,count:Number.parseInt(process.env.CURL_RUNNER_RETRIES,10)}};if(process.env.CURL_RUNNER_RETRY_DELAY)Z.defaults={...Z.defaults,retry:{...Z.defaults?.retry,delay:Number.parseInt(process.env.CURL_RUNNER_RETRY_DELAY,10)}}}var r9=["curl-runner.yaml","curl-runner.yml",".curl-runner.yaml",".curl-runner.yml"];async function w0(Z,X){for(let J of r9)try{if(await Bun.file(J).exists()){let G=(await y.parseFile(J)).global||{};return Z?.(`Loaded configuration from ${J}`),{config:G,path:J}}}catch(W){X?.(`Failed to load configuration from ${J}: ${W}`)}return{config:{},path:null}}var s3=[/sk_live_[a-zA-Z0-9]{24,}/g,/sk_test_[a-zA-Z0-9]{24,}/g,/pk_live_[a-zA-Z0-9]{24,}/g,/pk_test_[a-zA-Z0-9]{24,}/g,/rk_live_[a-zA-Z0-9]{24,}/g,/rk_test_[a-zA-Z0-9]{24,}/g,/AKIA[0-9A-Z]{16}/g,/ghp_[a-zA-Z0-9]{36,}/g,/gho_[a-zA-Z0-9]{36,}/g,/ghu_[a-zA-Z0-9]{36,}/g,/ghs_[a-zA-Z0-9]{36,}/g,/ghr_[a-zA-Z0-9]{36,}/g,/npm_[a-zA-Z0-9]{36,}/g,/xox[baprs]-[a-zA-Z0-9-]{10,}/g,/pdl_[a-zA-Z0-9]{20,}/g,/sk-[a-zA-Z0-9]{48,}/g,/sk-ant-[a-zA-Z0-9-]{40,}/g,/Bearer [a-zA-Z0-9_-]{40,}/g];class s9{secrets=new Map;sortedSecrets=[];patternRedaction=!0;addSecrets(Z){for(let[X,J]of Object.entries(Z))if(J&&J.length>0)this.secrets.set(X,J);this.updateSortedSecrets()}addSecret(Z,X){if(X&&X.length>0)this.secrets.set(Z,X),this.updateSortedSecrets()}setPatternRedaction(Z){this.patternRedaction=Z}clear(){this.secrets.clear(),this.sortedSecrets=[]}updateSortedSecrets(){this.sortedSecrets=Array.from(this.secrets.values()).filter((Z)=>Z.length>0).sort((Z,X)=>X.length-Z.length)}redact(Z){let X=Z;for(let J of this.sortedSecrets)X=X.split(J).join("[REDACTED]");if(this.patternRedaction)for(let J of s3)J.lastIndex=0,X=X.replace(J,"[REDACTED]");return X}hasSecrets(){return this.secrets.size>0}get secretCount(){return this.secrets.size}}var q0=null;function q1(){if(!q0)q0=new s9;return q0}async function x0(Z,X){let J=E0(Z);if(J==="upgrade")return{config:{},cliOptions:{files:[]},files:[],mode:"upgrade",rawArgs:Z,secretKeys:[]};if(J==="init")return{config:{},cliOptions:{files:[]},files:[],mode:"init",rawArgs:Z,secretKeys:[]};if(J==="edit")return{config:{},cliOptions:{files:[]},files:[],mode:"edit",rawArgs:Z,secretKeys:[]};if(J==="validate")return{config:{},cliOptions:{files:[]},files:[],mode:"validate",rawArgs:Z,secretKeys:[]};if(J==="convert")return{config:{},cliOptions:{files:[]},files:[],mode:"convert",rawArgs:Z,secretKeys:[]};let W=S0(Z),$=k0(W);if($)return{config:{},cliOptions:W,files:W.files,mode:$,rawArgs:Z,secretKeys:[]};if(J==="diff-subcommand")return{config:{},cliOptions:W,files:Z.slice(1),mode:"diff-subcommand",rawArgs:Z,secretKeys:[]};let G=C0(),{config:Q}=await w0(X?.onInfo,X?.onWarning),Y=x1(Q,G);Y=t3(Y,W);let z=W.env??Y.env?.environment,{variables:H,secretKeys:K}=await P0(process.cwd(),z);if(Y.variables={...H,...Y.variables},!W.noRedact&&Y.env?.redactSecrets!==!1&&K.length>0){let R=q1(),_={};for(let O of K)if(Y.variables?.[O])_[O]=Y.variables[O];R.addSecrets(_)}let M=e3(W,Y);return{config:Y,cliOptions:W,files:W.files,mode:M,rawArgs:Z,secretKeys:K}}function x1(Z,X){return{...Z,...X,env:{...Z.env,...X.env},variables:{...Z.variables,...X.variables},output:{...Z.output,...X.output},defaults:{...Z.defaults,...X.defaults},ci:{...Z.ci,...X.ci},watch:{...Z.watch,...X.watch},snapshot:{...Z.snapshot,...X.snapshot},diff:{...Z.diff,...X.diff},connectionPool:{...Z.connectionPool,...X.connectionPool}}}function t3(Z,X){let J={...Z};if(X.env)J.env={...J.env,environment:X.env};if(X.noRedact)J.env={...J.env,redactSecrets:!1};if(X.execution)J.execution=X.execution;if(X.maxConcurrency!==void 0)J.maxConcurrency=X.maxConcurrency;if(X.continueOnError!==void 0)J.continueOnError=X.continueOnError;if(X.dryRun!==void 0)J.dryRun=X.dryRun,J.output={...J.output,dryRun:X.dryRun};if(X.http2!==void 0)J.http2=X.http2,J.defaults={...J.defaults,http2:X.http2};if(X.connectionPool!==void 0)J.connectionPool={...J.connectionPool,enabled:X.connectionPool};if(X.maxStreams!==void 0)J.connectionPool={...J.connectionPool,enabled:!0,maxStreamsPerHost:X.maxStreams};if(X.keepaliveTime!==void 0)J.connectionPool={...J.connectionPool,enabled:!0,keepaliveTime:X.keepaliveTime};if(X.connectTimeout!==void 0)J.connectionPool={...J.connectionPool,enabled:!0,connectTimeout:X.connectTimeout};if(X.verbose!==void 0)J.output={...J.output,verbose:X.verbose};if(X.quiet)J.output={...J.output,verbose:!1};if(X.output)J.output={...J.output,saveToFile:X.output};if(X.outputFormat)J.output={...J.output,format:X.outputFormat};if(X.prettyLevel)J.output={...J.output,prettyLevel:X.prettyLevel};if(X.showHeaders!==void 0)J.output={...J.output,showHeaders:X.showHeaders};if(X.showBody!==void 0)J.output={...J.output,showBody:X.showBody};if(X.showMetrics!==void 0)J.output={...J.output,showMetrics:X.showMetrics};if(X.timeout)J.defaults={...J.defaults,timeout:X.timeout};if(X.retries||X.noRetry){let W=X.noRetry?0:X.retries||0;J.defaults={...J.defaults,retry:{...J.defaults?.retry,count:W}}}if(X.retryDelay)J.defaults={...J.defaults,retry:{...J.defaults?.retry,delay:X.retryDelay}};if(X.strictExit!==void 0)J.ci={...J.ci,strictExit:X.strictExit};if(X.failOn!==void 0)J.ci={...J.ci,failOn:X.failOn};if(X.failOnPercentage!==void 0)J.ci={...J.ci,failOnPercentage:X.failOnPercentage};if(X.snapshot!==void 0)J.snapshot={...J.snapshot,enabled:X.snapshot};if(X.snapshotUpdate!==void 0)J.snapshot={...J.snapshot,enabled:!0,updateMode:X.snapshotUpdate};if(X.snapshotDir!==void 0)J.snapshot={...J.snapshot,dir:X.snapshotDir};if(X.snapshotCi!==void 0)J.snapshot={...J.snapshot,ci:X.snapshotCi};if(X.diff!==void 0)J.diff={...J.diff,enabled:X.diff};if(X.diffSave!==void 0)J.diff={...J.diff,enabled:!0,save:X.diffSave};if(X.diffLabel!==void 0)J.diff={...J.diff,label:X.diffLabel};if(X.diffCompare!==void 0)J.diff={...J.diff,enabled:!0,compareWith:X.diffCompare};if(X.diffDir!==void 0)J.diff={...J.diff,dir:X.diffDir};if(X.diffOutput!==void 0)J.diff={...J.diff,outputFormat:X.diffOutput};return J}function e3(Z,X){let J=Z.watch||X.watch?.enabled,W=Z.profile??X.profile?.iterations;if(W&&W>0)return"profile";if(J)return"watch";return"normal"}function b0(Z,X){return{iterations:Z.profile??X.profile?.iterations??10,warmup:Z.profileWarmup??X.profile?.warmup??1,concurrency:Z.profileConcurrency??X.profile?.concurrency??1,histogram:Z.profileHistogram??X.profile?.histogram??!1,exportFile:Z.profileExport??X.profile?.exportFile}}function y0(Z,X){return{enabled:!0,debounce:Z.watchDebounce??X.watch?.debounce??300,clear:Z.watchClear??X.watch?.clear??!0}}import*as o from"fs/promises";import*as v from"path";var Z2=1,X2="__baselines__";class z1{baselineDir;writeLocks=new Map;constructor(Z={}){this.baselineDir=Z.dir||X2}getBaselinePath(Z,X){let J=v.dirname(Z),W=v.basename(Z,v.extname(Z));return v.join(J,this.baselineDir,`${W}.${X}.baseline.json`)}getBaselineDir(Z){return v.join(v.dirname(Z),this.baselineDir)}async load(Z,X){let J=this.getBaselinePath(Z,X);try{let W=Bun.file(J);if(!await W.exists())return null;let $=await W.text();return JSON.parse($)}catch{return null}}async save(Z,X,J){let W=this.getBaselinePath(Z,X),$=this.writeLocks.get(W),G=(async()=>{if($)await $;let Q=v.dirname(W);await o.mkdir(Q,{recursive:!0});let Y=JSON.stringify(J,null,2);await Bun.write(W,Y)})();this.writeLocks.set(W,G),await G,this.writeLocks.delete(W)}async get(Z,X,J){return(await this.load(Z,X))?.baselines[J]||null}async listLabels(Z){let X=this.getBaselineDir(Z),J=v.basename(Z,v.extname(Z));try{let W=await o.readdir(X),$=[];for(let G of W){let Q=G.match(new RegExp(`^${J}\\.(.+)\\.baseline\\.json$`));if(Q)$.push(Q[1])}return $.sort()}catch{return[]}}createBaseline(Z,X){let J={hash:"",capturedAt:new Date().toISOString()};if(Z.status!==void 0)J.status=Z.status;if(Z.headers)J.headers=this.normalizeHeaders(Z.headers);if(Z.body!==void 0)J.body=Z.body;if(X.includeTimings&&Z.metrics?.duration!==void 0)J.timing=Z.metrics.duration;return J.hash=this.hash(J),J}normalizeHeaders(Z){let X={},J=Object.keys(Z).sort();for(let W of J)X[W.toLowerCase()]=Z[W];return X}hash(Z){let X=JSON.stringify(Z),J=new Bun.CryptoHasher("md5");return J.update(X),J.digest("hex").slice(0,8)}async saveBaseline(Z,X,J,W){let $={};for(let Q of J){if(Q.skipped||!Q.success)continue;let Y=Q.request.name||Q.request.url;$[Y]=this.createBaseline(Q,W)}let G={version:Z2,label:X,capturedAt:new Date().toISOString(),baselines:$};await this.save(Z,X,G)}async cleanOldBaselines(Z,X){let J=this.getBaselineDir(Z),W=Date.now()-X*24*60*60*1000,$=0;try{let G=await o.readdir(J);for(let Q of G){if(!Q.endsWith(".baseline.json"))continue;let Y=v.join(J,Q);if((await o.stat(Y)).mtimeMs<W)await o.unlink(Y),$++}}catch{}return $}static mergeConfig(Z,X){if(!X&&!Z?.enabled)return null;if(X===!0)return{enabled:!0,exclude:Z?.exclude||[],match:Z?.match||{},includeTimings:Z?.includeTimings||!1};if(typeof X==="object"&&X.enabled!==!1)return{enabled:!0,exclude:[...Z?.exclude||[],...X.exclude||[]],match:{...Z?.match||{},...X.match||{}},includeTimings:X.includeTimings??Z?.includeTimings??!1};if(Z?.enabled&&X===void 0)return{enabled:!0,exclude:Z.exclude||[],match:Z.match||{},includeTimings:Z.includeTimings||!1};return null}}var _1={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",underscore:"\x1B[4m",black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m"};function i(Z,X){return`${_1[X]}${Z}${_1.reset}`}function u(Z){if(Z<1000)return`${Z.toFixed(0)}ms`;return`${(Z/1000).toFixed(2)}s`}function e(Z){if(Z<1)return`${(Z*1000).toFixed(0)}\xB5s`;if(Z<1000)return`${Z.toFixed(1)}ms`;return`${(Z/1000).toFixed(2)}s`}function b1(Z){if(!Z)return"0 B";let X=["B","KB","MB","GB"],J=Math.floor(Math.log(Z)/Math.log(1024));return`${(Z/1024**J).toFixed(2)} ${X[J]}`}function y1(Z,X="pretty"){if(X==="raw")return typeof Z==="string"?Z:JSON.stringify(Z);if(X==="json")return JSON.stringify(Z);return JSON.stringify(Z,null,2)}function v0(Z){return Z.replace(/.*\//,"").replace(".yaml","")}class H1{color(Z,X){if(!X||!(X in _1))return Z;return i(Z,X)}render(Z,X=" "){Z.forEach((J,W)=>{let $=W===Z.length-1,G=$?`${X}\u2514\u2500`:`${X}\u251C\u2500`;if(J.label&&J.value){let Q=J.color?this.color(J.value,J.color):J.value,Y=Q.split(`
133
+ `);if(Y.length===1)console.log(`${G} ${J.label}: ${Q}`);else{console.log(`${G} ${J.label}:`);let z=$?`${X} `:`${X}\u2502 `;for(let H of Y)console.log(`${z}${H}`)}}else if(J.label&&!J.value)console.log(`${G} ${J.label}:`);else if(!J.label&&J.value){let Q=$?`${X} `:`${X}\u2502 `;console.log(`${Q}${J.value}`)}if(J.children&&J.children.length>0){let Q=$?`${X} `:`${X}\u2502 `;this.render(J.children,Q)}})}}class M1{outputFormat;constructor(Z="terminal"){this.outputFormat=Z}color(Z,X){if(this.outputFormat!=="terminal")return Z;return i(Z,X)}formatSummary(Z,X,J){switch(this.outputFormat){case"json":return this.formatSummaryJson(Z);case"markdown":return this.formatSummaryMarkdown(Z,X,J);default:return this.formatSummaryTerminal(Z,X,J)}}formatSummaryTerminal(Z,X,J){let W=[];W.push(""),W.push(`${this.color("Response Diff:","bright")} ${this.color(X,"cyan")} \u2192 ${this.color(J,"cyan")}`),W.push("");for(let $ of Z.results)W.push(this.formatResultTerminal($)),W.push("");return W.push(this.formatStatsSummary(Z)),W.join(`
134
+ `)}formatSummaryJson(Z){return JSON.stringify({summary:{total:Z.totalRequests,unchanged:Z.unchanged,changed:Z.changed,newBaselines:Z.newBaselines},results:Z.results.map((X)=>({request:X.requestName,status:X.hasDifferences?"changed":X.isNewBaseline?"new":"unchanged",differences:X.differences,timingDiff:X.timingDiff}))},null,2)}formatSummaryMarkdown(Z,X,J){let W=[];if(W.push(`# Response Diff: ${X} \u2192 ${J}`),W.push(""),W.push("| Metric | Count |"),W.push("|--------|-------|"),W.push(`| Total Requests | ${Z.totalRequests} |`),W.push(`| Unchanged | ${Z.unchanged} |`),W.push(`| Changed | ${Z.changed} |`),W.push(`| New Baselines | ${Z.newBaselines} |`),W.push(""),Z.changed>0){W.push("## Changes"),W.push("");for(let $ of Z.results)if($.hasDifferences)W.push(this.formatResultMarkdown($))}if(Z.newBaselines>0){W.push("## New Requests"),W.push("");for(let $ of Z.results)if($.isNewBaseline)W.push(`- \`${$.requestName}\``);W.push("")}return W.join(`
135
+ `)}formatResultTerminal(Z){let X=[];if(Z.isNewBaseline)return X.push(` ${this.color("NEW","cyan")} ${this.color(Z.requestName,"bright")}`),X.join(`
136
+ `);if(!Z.hasDifferences)return X.push(` ${this.color("\u2713","green")} ${this.color(Z.requestName,"bright")} ${this.color("(no changes)","dim")}`),X.join(`
137
+ `);X.push(` ${this.color("\u2717","red")} ${this.color(Z.requestName,"bright")}`);for(let J of Z.differences)X.push(this.formatDifferenceTerminal(J));if(Z.timingDiff){let{baseline:J,current:W,changePercent:$}=Z.timingDiff,G=$>=0?"+":"",Q=$>20?"red":$<-20?"green":"yellow";X.push(` ${this.color("timing:","cyan")} ${J}ms \u2192 ${W}ms ${this.color(`(${G}${$.toFixed(0)}%)`,Q)}`)}return X.join(`
138
+ `)}formatDifferenceTerminal(Z){let X=[],J=Z.path||"(root)";switch(Z.type){case"added":X.push(` ${this.color(J,"cyan")}:`),X.push(` ${this.color(`+ ${this.stringify(Z.current)}`,"green")}`);break;case"removed":X.push(` ${this.color(J,"cyan")}:`),X.push(` ${this.color(`- ${this.stringify(Z.baseline)}`,"red")}`);break;case"changed":X.push(` ${this.color(J,"cyan")}:`),X.push(` ${this.color(`- ${this.stringify(Z.baseline)}`,"red")}`),X.push(` ${this.color(`+ ${this.stringify(Z.current)}`,"green")}`);break;case"type_mismatch":X.push(` ${this.color(J,"cyan")} (type mismatch):`),X.push(` ${this.color(`- ${this.stringify(Z.baseline)} (${typeof Z.baseline})`,"red")}`),X.push(` ${this.color(`+ ${this.stringify(Z.current)} (${typeof Z.current})`,"green")}`);break}return X.join(`
139
+ `)}formatResultMarkdown(Z){let X=[];X.push(`### \`${Z.requestName}\``),X.push(""),X.push("```diff");for(let J of Z.differences)X.push(this.formatDifferenceMarkdown(J));if(X.push("```"),Z.timingDiff){let{baseline:J,current:W,changePercent:$}=Z.timingDiff,G=$>=0?"+":"";X.push(""),X.push(`**Timing:** ${J}ms \u2192 ${W}ms (${G}${$.toFixed(0)}%)`)}return X.push(""),X.join(`
140
+ `)}formatDifferenceMarkdown(Z){let X=[],J=Z.path||"(root)";switch(Z.type){case"added":X.push(`# ${J}:`),X.push(`+ ${this.stringify(Z.current)}`);break;case"removed":X.push(`# ${J}:`),X.push(`- ${this.stringify(Z.baseline)}`);break;case"changed":X.push(`# ${J}:`),X.push(`- ${this.stringify(Z.baseline)}`),X.push(`+ ${this.stringify(Z.current)}`);break;case"type_mismatch":X.push(`# ${J} (type mismatch):`),X.push(`- ${this.stringify(Z.baseline)} (${typeof Z.baseline})`),X.push(`+ ${this.stringify(Z.current)} (${typeof Z.current})`);break}return X.join(`
141
+ `)}formatStatsSummary(Z){let X=[];if(Z.unchanged>0)X.push(this.color(`${Z.unchanged} unchanged`,"green"));if(Z.changed>0)X.push(this.color(`${Z.changed} changed`,"red"));if(Z.newBaselines>0)X.push(this.color(`${Z.newBaselines} new`,"cyan"));return`Summary: ${X.join(", ")} (${Z.totalRequests} total)`}stringify(Z){if(Z===void 0)return"undefined";if(Z===null)return"null";if(typeof Z==="string")return`"${Z}"`;if(typeof Z==="object"){let X=JSON.stringify(Z);if(X.length>80)return`${X.slice(0,77)}...`;return X}return String(Z)}}class v1{excludePaths;matchRules;includeTimings;constructor(Z){this.excludePaths=new Set(Z.exclude||[]),this.matchRules=new Map(Object.entries(Z.match||{})),this.includeTimings=Z.includeTimings||!1}compare(Z,X,J,W,$){let G=[];if(Z.status!==void 0||X.status!==void 0){if(Z.status!==X.status&&!this.isExcluded("status"))G.push({path:"status",baseline:Z.status,current:X.status,type:"changed"})}if(Z.headers||X.headers){let Y=this.compareObjects(Z.headers||{},X.headers||{},"headers");G.push(...Y)}if(Z.body!==void 0||X.body!==void 0){let Y=this.deepCompare(Z.body,X.body,"body");G.push(...Y)}let Q={requestName:$,hasDifferences:G.length>0,isNewBaseline:!1,baselineLabel:J,currentLabel:W,differences:G};if(this.includeTimings&&Z.timing!==void 0&&X.timing!==void 0){let Y=(X.timing-Z.timing)/Z.timing*100;Q.timingDiff={baseline:Z.timing,current:X.timing,changePercent:Y}}return Q}deepCompare(Z,X,J){if(this.isExcluded(J))return[];if(this.matchesRule(J,X))return[];if(Z===null&&X===null)return[];if(Z===void 0&&X===void 0)return[];let W=this.getType(Z),$=this.getType(X);if(W!==$)return[{path:J,baseline:Z,current:X,type:"type_mismatch"}];if(W!=="object"&&W!=="array"){if(Z!==X)return[{path:J,baseline:Z,current:X,type:"changed"}];return[]}if(W==="array")return this.compareArrays(Z,X,J);return this.compareObjects(Z,X,J)}compareArrays(Z,X,J){let W=[],$=Math.max(Z.length,X.length);for(let G=0;G<$;G++){let Q=`${J}[${G}]`;if(G>=Z.length){if(!this.isExcluded(Q))W.push({path:Q,baseline:void 0,current:X[G],type:"added"})}else if(G>=X.length){if(!this.isExcluded(Q))W.push({path:Q,baseline:Z[G],current:void 0,type:"removed"})}else{let Y=this.deepCompare(Z[G],X[G],Q);W.push(...Y)}}return W}compareObjects(Z,X,J){let W=[],$=new Set([...Object.keys(Z),...Object.keys(X)]);for(let G of $){let Q=J?`${J}.${G}`:G,Y=G in Z,z=G in X;if(!Y&&z){if(!this.isExcluded(Q))W.push({path:Q,baseline:void 0,current:X[G],type:"added"})}else if(Y&&!z){if(!this.isExcluded(Q))W.push({path:Q,baseline:Z[G],current:void 0,type:"removed"})}else{let H=this.deepCompare(Z[G],X[G],Q);W.push(...H)}}return W}isExcluded(Z){if(this.excludePaths.has(Z))return!0;for(let X of this.excludePaths){if(X.startsWith("*.")){let J=X.slice(2);if(Z.endsWith(`.${J}`))return!0;if(Z.split(".").pop()===J)return!0}if(X.includes("[*]")){if(new RegExp(`^${X.replace(/\[\*\]/g,"\\[\\d+\\]").replace(/\./g,"\\.")}$`).test(Z))return!0}}return!1}matchesRule(Z,X){let J=this.matchRules.get(Z);if(!J)return!1;if(J==="*")return!0;if(J.startsWith("regex:")){let W=J.slice(6);try{return new RegExp(W).test(String(X))}catch{return!1}}return!1}getType(Z){if(Z===null)return"null";if(Z===void 0)return"undefined";if(Array.isArray(Z))return"array";return typeof Z}}class D1{manager;constructor(Z={}){this.manager=new z1(Z)}async compareWithBaseline(Z,X,J,W,$){let G=await this.manager.load(Z,W),Q=[];for(let Y of X){if(Y.skipped||!Y.success)continue;let z=Y.request.name||Y.request.url,H=this.manager.createBaseline(Y,$);if(!G){Q.push({requestName:z,hasDifferences:!1,isNewBaseline:!0,baselineLabel:W,currentLabel:J,differences:[]});continue}let K=G.baselines[z];if(!K){Q.push({requestName:z,hasDifferences:!1,isNewBaseline:!0,baselineLabel:W,currentLabel:J,differences:[]});continue}let M=new v1($).compare(K,H,W,J,z);Q.push(M)}return{totalRequests:Q.length,unchanged:Q.filter((Y)=>!Y.hasDifferences&&!Y.isNewBaseline).length,changed:Q.filter((Y)=>Y.hasDifferences).length,newBaselines:Q.filter((Y)=>Y.isNewBaseline).length,results:Q}}async compareTwoBaselines(Z,X,J,W){let $=await this.manager.load(Z,X),G=await this.manager.load(Z,J);if(!$)throw Error(`Baseline '${X}' not found`);if(!G)throw Error(`Baseline '${J}' not found`);let Q=new Set([...Object.keys($.baselines),...Object.keys(G.baselines)]),Y=[],z=new v1(W);for(let H of Q){let K=$.baselines[H],U=G.baselines[H];if(!K){Y.push({requestName:H,hasDifferences:!0,isNewBaseline:!1,baselineLabel:X,currentLabel:J,differences:[{path:"",baseline:void 0,current:"exists",type:"added"}]});continue}if(!U){Y.push({requestName:H,hasDifferences:!0,isNewBaseline:!1,baselineLabel:X,currentLabel:J,differences:[{path:"",baseline:"exists",current:void 0,type:"removed"}]});continue}let M=z.compare(K,U,X,J,H);Y.push(M)}return{totalRequests:Y.length,unchanged:Y.filter((H)=>!H.hasDifferences).length,changed:Y.filter((H)=>H.hasDifferences).length,newBaselines:0,results:Y}}async saveBaseline(Z,X,J,W){await this.manager.saveBaseline(Z,X,J,W)}async listLabels(Z){return this.manager.listLabels(Z)}getManager(){return this.manager}}function m0(Z){return typeof Z==="object"&&Z!==null&&"file"in Z}var J2=`
142
+ __CURL_METRICS_START__%{json}__CURL_METRICS_END__`;function F1(Z,X={}){let{writeOutMarker:J=J2,includeSilentFlags:W=!0,includeHttp2Flag:$=!0,includeOutputFlag:G=!0}=X,Q=[];if(Q.push("-X",Z.method||"GET"),Q.push("-w",J),Z.headers)for(let[z,H]of Object.entries(Z.headers))Q.push("-H",`${z}: ${H}`);if(Z.auth){if(Z.auth.type==="basic"&&Z.auth.username&&Z.auth.password)Q.push("-u",`${Z.auth.username}:${Z.auth.password}`);else if(Z.auth.type==="bearer"&&Z.auth.token)Q.push("-H",`Authorization: Bearer ${Z.auth.token}`)}if(Z.formData)for(let[z,H]of Object.entries(Z.formData))if(m0(H)){let K=`@${H.file}`;if(H.filename)K+=`;filename=${H.filename}`;if(H.contentType)K+=`;type=${H.contentType}`;Q.push("-F",`${z}=${K}`)}else{let K=String(H);Q.push("--form-string",`${z}=${K}`)}else if(Z.body){let z=typeof Z.body==="string"?Z.body:JSON.stringify(Z.body);if(Q.push("-d",z),!Z.headers?.["Content-Type"])Q.push("-H","Content-Type: application/json")}if(Z.timeout)Q.push("--max-time",Z.timeout.toString());if(Z.followRedirects!==!1){if(Q.push("-L"),Z.maxRedirects)Q.push("--max-redirs",Z.maxRedirects.toString())}if(Z.proxy)Q.push("-x",Z.proxy);if(Z.insecure||Z.ssl?.verify===!1)Q.push("-k");if(Z.ssl){if(Z.ssl.ca)Q.push("--cacert",Z.ssl.ca);if(Z.ssl.cert)Q.push("--cert",Z.ssl.cert);if(Z.ssl.key)Q.push("--key",Z.ssl.key)}if(G&&Z.output)Q.push("-o",Z.output);if($&&Z.http2)Q.push("--http2");if(W)Q.push("-s","-S");let Y=Z.url;if(Z.params&&Object.keys(Z.params).length>0){let z=new URLSearchParams(Z.params).toString();Y+=(Y.includes("?")?"&":"?")+z}return{args:Q,url:Y}}function T1(Z){return["curl",...Z].map((X)=>X.includes(" ")||X.includes('"')||X.includes("'")?`'${X.replace(/'/g,"'\\''")}'`:X).join(" ")}function h0(Z){return`
143
+ __CURL_BATCH_${Z}_START__%{json}__CURL_BATCH_${Z}_END__
144
+ `}var m1="__CURL_METRICS_START__",h1="__CURL_METRICS_END__";function $1(Z,X){if(!Z)return Z;try{let J=X?.includes("application/json"),W=Z.trim().startsWith("{")||Z.trim().startsWith("[");if(J||W)return JSON.parse(Z)}catch{}return Z}function I1(Z){return{duration:(Z.time_total||0)*1000,size:Z.size_download,dnsLookup:(Z.time_namelookup||0)*1000,tcpConnection:(Z.time_connect||0)*1000,tlsHandshake:(Z.time_appconnect||0)*1000,firstByte:(Z.time_starttransfer||0)*1000,download:(Z.time_total||0)*1000}}function g0(Z){let X=Z.match(new RegExp(`${m1}(.+?)${h1}`));if(!X)return{body:Z,metrics:{}};let J=Z.replace(new RegExp(`${m1}.+?${h1}`),"").trim(),W={};try{W=JSON.parse(X[1])}catch{}return{body:J,metrics:W}}function d0(Z,X){let J=`__CURL_BATCH_${X}_START__`,W=`__CURL_BATCH_${X}_END__`,$=Z.indexOf(J),G=Z.indexOf(W);if($===-1||G===-1)return{found:!1,metricsJson:"",startIdx:-1,endIdx:-1};return{found:!0,metricsJson:Z.substring($+J.length,G),startIdx:$,endIdx:G}}function f0(Z){let X={},J=Z.split(`
145
+ `).filter((W)=>W.includes(":"));for(let W of J){let[$,...G]=W.split(":");if($&&G.length>0)X[$.trim()]=G.join(":").trim()}return X}function N1(Z){return Z.response_code||Z.http_code}function p0(Z){if(Z===void 0)return!1;return Z>=200&&Z<400}class Z1{static buildCommand(Z){let{args:X,url:J}=F1(Z,{includeSilentFlags:!0,includeHttp2Flag:!0,includeOutputFlag:!0});return X.push(J),X}static formatCommandForDisplay(Z){return T1(Z)}static async executeCurl(Z){try{let X=Bun.spawn(["curl",...Z],{stdout:"pipe",stderr:"pipe"}),J=await new Response(X.stdout).text(),W=await new Response(X.stderr).text();if(await X.exited,X.exitCode!==0&&!J)return{success:!1,error:W||`Command failed with exit code ${X.exitCode}`};let{body:$,metrics:G}=g0(J),Q=N1(G),Y=Q?f0(W):{},z=I1(G);return{success:!0,status:Q,headers:Y,body:$,metrics:z}}catch(X){return{success:!1,error:X instanceof Error?X.message:String(X)}}}}class c0{color(Z,X){return i(Z,X)}formatResult(Z,X){let J=[];if(X.isNew&&X.updated)return J.push(` ${this.color("NEW","cyan")} Snapshot created for "${this.color(Z,"bright")}"`),J.join(`
146
+ `);if(X.updated)return J.push(` ${this.color("UPDATED","yellow")} Snapshot updated for "${this.color(Z,"bright")}"`),J.join(`
147
+ `);if(X.match)return J.push(` ${this.color("PASS","green")} Snapshot matches for "${this.color(Z,"bright")}"`),J.join(`
148
+ `);return J.push(` ${this.color("FAIL","red")} Snapshot mismatch for "${this.color(Z,"bright")}"`),J.push(""),J.push(this.formatDiff(X.differences)),J.push(""),J.push(this.color(" Run with --update-snapshots (-u) to update","dim")),J.join(`
149
+ `)}formatDiff(Z){let X=[];X.push(` ${this.color("- Expected","red")}`),X.push(` ${this.color("+ Received","green")}`),X.push("");for(let J of Z)X.push(this.formatDifference(J));return X.join(`
150
+ `)}formatDifference(Z){let X=[],J=Z.path||"(root)";switch(Z.type){case"added":X.push(` ${this.color(J,"cyan")}:`),X.push(` ${this.color(`+ ${this.stringify(Z.received)}`,"green")}`);break;case"removed":X.push(` ${this.color(J,"cyan")}:`),X.push(` ${this.color(`- ${this.stringify(Z.expected)}`,"red")}`);break;case"changed":X.push(` ${this.color(J,"cyan")}:`),X.push(` ${this.color(`- ${this.stringify(Z.expected)}`,"red")}`),X.push(` ${this.color(`+ ${this.stringify(Z.received)}`,"green")}`);break;case"type_mismatch":X.push(` ${this.color(J,"cyan")} (type mismatch):`),X.push(` ${this.color(`- ${this.stringify(Z.expected)} (${typeof Z.expected})`,"red")}`),X.push(` ${this.color(`+ ${this.stringify(Z.received)} (${typeof Z.received})`,"green")}`);break}return X.join(`
151
+ `)}stringify(Z){if(Z===void 0)return"undefined";if(Z===null)return"null";if(typeof Z==="string")return`"${Z}"`;if(typeof Z==="object"){let X=JSON.stringify(Z);if(X.length>80)return`${X.slice(0,77)}...`;return X}return String(Z)}formatSummary(Z){let X=[];if(Z.passed>0)X.push(this.color(`${Z.passed} passed`,"green"));if(Z.failed>0)X.push(this.color(`${Z.failed} failed`,"red"));if(Z.updated>0)X.push(this.color(`${Z.updated} updated`,"yellow"));if(Z.created>0)X.push(this.color(`${Z.created} created`,"cyan"));if(X.length===0)return"";return`Snapshots: ${X.join(", ")}`}}function g1(Z,X){if(Z.length===0)return 0;if(Z.length===1)return Z[0];let J=X/100*(Z.length-1),W=Math.floor(J),$=Math.ceil(J),G=J-W;if(W===$)return Z[W];return Z[W]*(1-G)+Z[$]*G}function W2(Z){if(Z.length===0)return 0;return Z.reduce((X,J)=>X+J,0)/Z.length}function $2(Z,X){if(Z.length<=1)return 0;let W=Z.map(($)=>($-X)**2).reduce(($,G)=>$+G,0)/Z.length;return Math.sqrt(W)}function t9(Z,X,J){let W=Z.slice(X),$=[...W].sort((z,H)=>z-H),G=W2($),Q=Z.length;return{iterations:W.length,warmup:X,min:$.length>0?$[0]:0,max:$.length>0?$[$.length-1]:0,mean:Math.round(G*100)/100,median:Math.round(g1($,50)*100)/100,p50:Math.round(g1($,50)*100)/100,p95:Math.round(g1($,95)*100)/100,p99:Math.round(g1($,99)*100)/100,stdDev:Math.round($2($,G)*100)/100,failures:J,failureRate:Q>0?Math.round(J/Q*1e4)/100:0,timings:W}}function e9(Z,X=10,J=40){if(Z.length===0)return["No data"];let W=Math.min(...Z),Q=(Math.max(...Z)-W||1)/X,Y=Array(X).fill(0);for(let K of Z){let U=Math.min(Math.floor((K-W)/Q),X-1);Y[U]++}let z=Math.max(...Y),H=[];for(let K=0;K<X;K++){let U=W+K*Q,M=W+(K+1)*Q,R=z>0?Math.round(Y[K]/z*J):0,_="\u2588".repeat(R),O=`${U.toFixed(0).padStart(6)}ms - ${M.toFixed(0).padStart(6)}ms`;H.push(`${O} \u2502${_} ${Y[K]}`)}return H}function Z4(Z,X){let J=["iteration","latency_ms"],W=Z.timings.map(($,G)=>`${G+1},${$}`);return[J.join(","),...W].join(`
152
+ `)}function X4(Z,X){return JSON.stringify({request:X,summary:{iterations:Z.iterations,warmup:Z.warmup,failures:Z.failures,failureRate:Z.failureRate,min:Z.min,max:Z.max,mean:Z.mean,median:Z.median,p50:Z.p50,p95:Z.p95,p99:Z.p99,stdDev:Z.stdDev},timings:Z.timings},null,2)}class a{config;redactor=q1();constructor(Z={}){this.config={verbose:!1,showHeaders:!1,showBody:!0,showMetrics:!1,format:"pretty",prettyLevel:"minimal",...Z}}redact(Z){return this.redactor.redact(Z)}color(Z,X){return i(Z,X)}shouldShowOutput(){if(this.config.format==="raw")return!1;if(this.config.format==="pretty")return!0;return this.config.verbose!==!1}shouldShowHeaders(){if(this.config.format!=="pretty")return this.config.showHeaders||!1;switch(this.config.prettyLevel||"standard"){case"minimal":return!1;case"standard":return this.config.showHeaders||!1;case"detailed":return!0;default:return this.config.showHeaders||!1}}shouldShowBody(){if(this.config.format!=="pretty")return this.config.showBody!==!1;switch(this.config.prettyLevel||"standard"){case"minimal":return!1;case"standard":return this.config.showBody!==!1;case"detailed":return!0;default:return this.config.showBody!==!1}}shouldShowMetrics(){if(this.config.format!=="pretty")return this.config.showMetrics||!1;switch(this.config.prettyLevel||"standard"){case"minimal":return!1;case"standard":return this.config.showMetrics||!1;case"detailed":return!0;default:return this.config.showMetrics||!1}}shouldShowRequestDetails(){if(this.config.format!=="pretty")return this.config.verbose||!1;switch(this.config.prettyLevel||"standard"){case"minimal":return!1;case"standard":return this.config.verbose||!1;case"detailed":return!0;default:return this.config.verbose||!1}}shouldShowSeparators(){if(this.config.format!=="pretty")return!0;switch(this.config.prettyLevel||"standard"){case"minimal":return!1;case"standard":return!0;case"detailed":return!0;default:return!0}}colorStatusCode(Z){return this.color(Z,"yellow")}logValidationErrors(Z){let X=Z.split("; ");if(X.length===1){let J=X[0].trim(),W=J.match(/^Expected status (.+?), got (.+)$/);if(W){let[,$,G]=W,Q=this.colorStatusCode($.replace(" or ","|")),Y=this.color(G,"red");console.log(` ${this.color("\u2717","red")} ${this.color("Error:","red")} Expected ${this.color("status","yellow")} ${Q}, got ${Y}`)}else console.log(` ${this.color("\u2717","red")} ${this.color("Error:","red")} ${J}`)}else{console.log(` ${this.color("\u2717","red")} ${this.color("Validation Errors:","red")}`);for(let J of X){let W=J.trim();if(W)if(W.startsWith("Expected ")){let $=W.match(/^Expected status (.+?), got (.+)$/);if($){let[,G,Q]=$,Y=this.colorStatusCode(G.replace(" or ","|")),z=this.color(Q,"red");console.log(` ${this.color("\u2022","red")} ${this.color("status","yellow")}: expected ${Y}, got ${z}`)}else{let G=W.match(/^Expected (.+?) to be (.+?), got (.+)$/);if(G){let[,Q,Y,z]=G;console.log(` ${this.color("\u2022","red")} ${this.color(Q,"yellow")}: expected ${this.color(Y,"green")}, got ${this.color(z,"red")}`)}else console.log(` ${this.color("\u2022","red")} ${W}`)}}else console.log(` ${this.color("\u2022","red")} ${W}`)}}}logExecutionStart(Z,X){if(!this.shouldShowOutput())return;if(this.shouldShowSeparators())console.log(),console.log(this.color(`Executing ${Z} request(s) in ${X} mode`,"dim")),console.log();else console.log()}logRequestStart(Z,X){return}logCommand(Z){if(this.config.dryRun||this.shouldShowRequestDetails())console.log(this.color(" Command:","dim")),console.log(this.color(` ${this.redact(Z)}`,"dim"))}logRetry(Z,X){console.log(this.color(` \u21BB Retry ${Z}/${X}...`,"yellow"))}logRequestComplete(Z){if(this.config.format==="raw"){if(Z.success&&this.config.showBody&&Z.body){let Y=y1(Z.body,this.config.format);console.log(Y)}return}if(this.config.format==="json"){let Y={request:{name:Z.request.name,url:this.redact(Z.request.url),method:Z.request.method||"GET"},success:Z.success,...Z.dryRun?{dryRun:!0}:{status:Z.status},...this.shouldShowHeaders()&&Z.headers?{headers:Z.headers}:{},...this.shouldShowBody()&&Z.body?{body:Z.body}:{},...Z.error?{error:Z.error}:{},...this.shouldShowMetrics()&&Z.metrics?{metrics:Z.metrics}:{}};console.log(JSON.stringify(Y,null,2));return}if(!this.shouldShowOutput())return;let X=this.config.prettyLevel||"minimal",J=Z.success?"green":"red",W=Z.success?"\u2713":"x",$=Z.request.name||"Request";if(X==="minimal"){let Y=Z.request.sourceFile?v0(Z.request.sourceFile):"inline";console.log(`${this.color(W,J)} ${this.color($,"bright")} [${Y}]`);let z=[],H=new H1;z.push({label:Z.request.method||"GET",value:this.redact(Z.request.url),color:"blue"});let K=Z.dryRun?"DRY-RUN":Z.status?`${Z.status}`:"ERROR";if(z.push({label:`${W} Status`,value:K,color:Z.dryRun?"cyan":J}),Z.metrics){let U=`${u(Z.metrics.duration)} | ${b1(Z.metrics.size)}`;z.push({label:"Duration",value:U,color:"cyan"})}if(H.render(z),Z.error)console.log(),this.logValidationErrors(Z.error);if(Z.snapshotResult)console.log(),this.logSnapshotResult(Z.request.name||"Request",Z.snapshotResult);console.log();return}console.log(`${this.color(W,J)} ${this.color($,"bright")}`);let G=[],Q=new H1;if(G.push({label:"URL",value:this.redact(Z.request.url),color:"blue"}),G.push({label:"Method",value:Z.request.method||"GET",color:"yellow"}),G.push({label:"Status",value:Z.dryRun?"DRY-RUN":String(Z.status||"ERROR"),color:Z.dryRun?"cyan":J}),Z.metrics)G.push({label:"Duration",value:u(Z.metrics.duration),color:"cyan"});if(this.shouldShowHeaders()&&Z.headers&&Object.keys(Z.headers).length>0){let Y=Object.entries(Z.headers).map(([z,H])=>({label:this.color(z,"dim"),value:String(H)}));G.push({label:"Headers",children:Y})}if(this.shouldShowBody()&&Z.body){let z=y1(Z.body,this.config.format).split(`
153
+ `),H=this.shouldShowRequestDetails()?1/0:10,K=z.slice(0,H);if(z.length>H)K.push(this.color(`... (${z.length-H} more lines)`,"dim"));G.push({label:"Response Body",value:K.join(`
154
+ `)})}if(this.shouldShowMetrics()&&Z.metrics&&X==="detailed"){let Y=Z.metrics,z=[];if(z.push({label:"Request Duration",value:u(Y.duration),color:"cyan"}),Y.size!==void 0)z.push({label:"Response Size",value:b1(Y.size),color:"cyan"});if(Y.dnsLookup)z.push({label:"DNS Lookup",value:u(Y.dnsLookup),color:"cyan"});if(Y.tcpConnection)z.push({label:"TCP Connection",value:u(Y.tcpConnection),color:"cyan"});if(Y.tlsHandshake)z.push({label:"TLS Handshake",value:u(Y.tlsHandshake),color:"cyan"});if(Y.firstByte)z.push({label:"Time to First Byte",value:u(Y.firstByte),color:"cyan"});G.push({label:"Metrics",children:z})}if(Q.render(G),Z.error)console.log(),this.logValidationErrors(Z.error);if(Z.snapshotResult)console.log(),this.logSnapshotResult(Z.request.name||"Request",Z.snapshotResult);console.log()}logSnapshotResult(Z,X){if(!X)return;let J=new c0;console.log(J.formatResult(Z,X))}logSummary(Z,X=!1){if(this.config.format==="raw")return;if(this.config.format==="json"){let z={summary:{total:Z.total,successful:Z.successful,failed:Z.failed,skipped:Z.skipped,duration:Z.duration},results:Z.results.map((H)=>({request:{name:H.request.name,url:this.redact(H.request.url),method:H.request.method||"GET"},success:H.success,...H.dryRun?{dryRun:!0}:{status:H.status},...this.shouldShowHeaders()&&H.headers?{headers:H.headers}:{},...this.shouldShowBody()&&H.body?{body:H.body}:{},...H.error?{error:H.error}:{},...this.shouldShowMetrics()&&H.metrics?{metrics:H.metrics}:{}}))};console.log(JSON.stringify(z,null,2));return}if(!this.shouldShowOutput())return;let J=this.config.prettyLevel||"minimal";if(X)console.log();if(J==="minimal"){let z=Z.failed===0?"green":"red",H=Z.skipped>0?`, ${Z.skipped} skipped`:"",K=Z.failed===0?`${Z.total} request${Z.total===1?"":"s"} completed successfully${H}`:`${Z.successful}/${Z.total} request${Z.total===1?"":"s"} completed, ${Z.failed} failed${H}`;console.log(`${X?"\u25C6 Global Summary":"Summary"}: ${this.color(K,z)}`);return}let W=(Z.successful/Z.total*100).toFixed(1),$=Z.failed===0?"green":"red",G=Z.skipped>0?`, ${Z.skipped} skipped`:"",Q=Z.failed===0?`${Z.total} request${Z.total===1?"":"s"} completed successfully${G}`:`${Z.successful}/${Z.total} request${Z.total===1?"":"s"} completed, ${Z.failed} failed${G}`,Y=X?"\u25C6 Global Summary":"Summary";if(console.log(),console.log(`${Y}: ${this.color(Q,$)} (${this.color(u(Z.duration),"cyan")})`),Z.failed>0&&this.shouldShowRequestDetails())Z.results.filter((z)=>!z.success).forEach((z)=>{let H=z.request.name||this.redact(z.request.url);console.log(` ${this.color("\u2022","red")} ${H}: ${z.error||""}`)})}logError(Z){console.error(this.color(`\u2717 ${Z}`,"red"))}logWarning(Z){console.warn(this.color(`\u26A0 ${Z}`,"yellow"))}logInfo(Z){console.log(this.color(`\u2139 ${Z}`,"blue"))}logSuccess(Z){console.log(this.color(`\u2713 ${Z}`,"green"))}logSkipped(Z,X,J){if(!this.shouldShowOutput())return;let W=Z.name||`Request ${X}`;if(this.config.format==="json"){let $={request:{name:Z.name,url:this.redact(Z.url),method:Z.method||"GET"},skipped:!0,reason:J||"condition not met"};console.log(JSON.stringify($,null,2));return}if(console.log(`${this.color("\u2298","yellow")} ${this.color(W,"bright")} ${this.color("[SKIP]","yellow")}`),J){let $=[{label:"Reason",value:J,color:"yellow"}];new H1().render($)}console.log()}logFileHeader(Z,X){if(!this.shouldShowOutput()||this.config.format!=="pretty")return;let J=Z.replace(/.*\//,"").replace(".yaml","");console.log(),console.log(this.color(`\u25B6 ${J}.yaml`,"bright")+this.color(` (${X} request${X===1?"":"s"})`,"dim"))}logWatch(Z){console.log(),console.log(`${this.color("Watching for changes...","cyan")} ${this.color("(press Ctrl+C to stop)","dim")}`);let X=Z.length<=3?Z.join(", "):`${Z.length} files`;console.log(this.color(` Files: ${X}`,"dim")),console.log()}logWatchReady(){console.log(),console.log(this.color("Watching for changes...","cyan"))}logFileChanged(Z){let X=new Date().toLocaleTimeString("en-US",{hour12:!1});console.log(this.color("-".repeat(50),"dim")),console.log(`${this.color(`[${X}]`,"dim")} File changed: ${this.color(Z,"yellow")}`),console.log()}logProfileStart(Z,X,J,W){if(!this.shouldShowOutput())return;console.log(),console.log(`${this.color("\u26A1 PROFILING","magenta")} ${this.color(Z,"bright")}`),console.log(this.color(` ${X} iterations, ${J} warmup, concurrency: ${W}`,"dim"))}logProfileResult(Z,X){let{stats:J,request:W}=Z,$=W.name||W.url;if(this.config.format==="json"){console.log(JSON.stringify({request:{name:$,url:W.url,method:W.method||"GET"},stats:{iterations:J.iterations,warmup:J.warmup,failures:J.failures,failureRate:J.failureRate,min:J.min,max:J.max,mean:J.mean,median:J.median,p50:J.p50,p95:J.p95,p99:J.p99,stdDev:J.stdDev}}));return}if(this.config.format==="raw"){console.log(`${J.p50} ${J.p95} ${J.p99} ${J.mean}`);return}console.log();let G=J.failures===0?this.color("\u2713","green"):this.color("\u26A0","yellow");if(console.log(`${G} ${this.color($,"bright")}`),console.log(this.color(" \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510","dim")),console.log(` \u2502 ${this.color("p50","cyan")} ${e(J.p50).padStart(10)} \u2502 ${this.color("min","dim")} ${e(J.min).padStart(10)} \u2502`),console.log(` \u2502 ${this.color("p95","yellow")} ${e(J.p95).padStart(10)} \u2502 ${this.color("max","dim")} ${e(J.max).padStart(10)} \u2502`),console.log(` \u2502 ${this.color("p99","red")} ${e(J.p99).padStart(10)} \u2502 ${this.color("mean","dim")} ${e(J.mean).padStart(10)} \u2502`),console.log(this.color(" \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518","dim")),console.log(this.color(` \u03C3 ${J.stdDev.toFixed(2)}ms | ${J.iterations} samples | ${J.failures} failures (${J.failureRate}%)`,"dim")),X&&J.timings.length>0){console.log(),console.log(this.color(" Distribution:","dim"));let Q=e9(J.timings,8,30);for(let Y of Q)console.log(` ${this.color(Y,"dim")}`)}}logProfileSummary(Z){if(!this.shouldShowOutput())return;let X=Z.reduce((W,$)=>W+$.stats.iterations,0),J=Z.reduce((W,$)=>W+$.stats.failures,0);if(console.log(),console.log(this.color("\u2500".repeat(50),"dim")),console.log(`${this.color("\u26A1 Profile Summary:","magenta")} ${Z.length} request${Z.length===1?"":"s"}, ${X} total iterations`),J>0)console.log(this.color(` ${J} total failures`,"yellow"))}}class u0{logger;profileConfig;constructor(Z,X){this.profileConfig=X,this.logger=new a(Z.output)}async executeSingleIteration(Z){let X=performance.now(),J=Z1.buildCommand(Z),W=await Z1.executeCurl(J);if(W.success)return{request:Z,success:!0,status:W.status,headers:W.headers,body:$1(W.body,W.headers?.["content-type"]),metrics:{...W.metrics,duration:performance.now()-X}};return{request:Z,success:!1,error:W.error,metrics:{duration:performance.now()-X}}}async executeWithConcurrency(Z,X,J){let W=[];for(let $=0;$<X;$+=J){let G=Math.min(J,X-$),Q=await Promise.all(Array.from({length:G},()=>this.executeSingleIteration(Z)));W.push(...Q)}return W}async profileRequest(Z,X=0){let J=this.profileConfig.iterations,W=this.profileConfig.warmup??1,$=this.profileConfig.concurrency??1,G=Z.name||`Request ${X+1}`;this.logger.logProfileStart(G,J,W,$);let Q=$===1?await this.executeSequentially(Z,J):await this.executeWithConcurrency(Z,J,$),Y=[],z=0;for(let U of Q)if(U.success&&U.metrics?.duration!==void 0)Y.push(U.metrics.duration);else z++,Y.push(0);let H=Y.map((U,M)=>Q[M].success?U:-1).filter((U)=>U>=0),K=t9(H,Math.min(W,H.length),z);return{request:Z,stats:K,iterations:Q}}async executeSequentially(Z,X){let J=[];for(let W=0;W<X;W++){let $=await this.executeSingleIteration(Z);J.push($)}return J}async profileRequests(Z){let X=[];for(let J=0;J<Z.length;J++){let W=await this.profileRequest(Z[J],J);X.push(W),this.logger.logProfileResult(W,this.profileConfig.histogram??!1)}return X}}function i0(Z,X){if(!X)return{success:!0};let J=[];if(X.status!==void 0){let $=J4(Z.status,X.status);J.push(...$)}if(X.headers){let $=W4(Z.headers,X.headers);J.push(...$)}if(X.body!==void 0){let $=a0(Z.body,X.body,"");J.push(...$)}if(X.responseTime!==void 0&&Z.metrics){let $=Z.metrics.duration;if(!f1($,X.responseTime))J.push(`Expected response time to match ${X.responseTime}ms, got ${$.toFixed(2)}ms`)}let W=J.length>0;if(X.failure===!0){if(W)return{success:!1,error:J.join("; ")};let $=Z.status||0;if($>=400)return{success:!0};return{success:!1,error:`Expected request to fail (4xx/5xx) but got status ${$}`}}if(W)return{success:!1,error:J.join("; ")};return{success:!0}}function J4(Z,X){let J=Array.isArray(X)?X:[X];if(!J.includes(Z||0))return[`Expected status ${J.join(" or ")}, got ${Z}`];return[]}function W4(Z,X){let J=[];for(let[W,$]of Object.entries(X)){let G=Z?.[W]||Z?.[W.toLowerCase()];if(G!==$)J.push(`Expected header ${W}="${$}", got "${G}"`)}return J}function a0(Z,X,J){let W=[];if(typeof X!=="object"||X===null){let $=d1(Z,X,J||"body");if(!$.isValid)W.push($.error);return W}if(Array.isArray(X)){let $=d1(Z,X,J||"body");if(!$.isValid)W.push($.error);return W}for(let[$,G]of Object.entries(X)){let Q=J?`${J}.${$}`:$,Y;if(Array.isArray(Z)&&$4($))Y=G4(Z,$);else Y=Z?.[$];if(typeof G==="object"&&G!==null&&!Array.isArray(G)){let z=a0(Y,G,Q);W.push(...z)}else{let z=d1(Y,G,Q);if(!z.isValid)W.push(z.error)}}return W}function d1(Z,X,J){if(X==="*")return{isValid:!0};if(Array.isArray(X)){if(!X.some(($)=>{if($==="*")return!0;if(typeof $==="string"&&l0($))return n0(Z,$);if(typeof $==="string"&&o0($))return f1(Z,$);return Z===$}))return{isValid:!1,error:`Expected ${J} to match one of ${JSON.stringify(X)}, got ${JSON.stringify(Z)}`};return{isValid:!0}}if(typeof X==="string"&&l0(X)){if(!n0(Z,X))return{isValid:!1,error:`Expected ${J} to match pattern ${X}, got ${JSON.stringify(Z)}`};return{isValid:!0}}if(typeof X==="string"&&o0(X)){if(!f1(Z,X))return{isValid:!1,error:`Expected ${J} to match range ${X}, got ${JSON.stringify(Z)}`};return{isValid:!0}}if(X==="null"||X===null){if(Z!==null)return{isValid:!1,error:`Expected ${J} to be null, got ${JSON.stringify(Z)}`};return{isValid:!0}}if(Z!==X)return{isValid:!1,error:`Expected ${J} to be ${JSON.stringify(X)}, got ${JSON.stringify(Z)}`};return{isValid:!0}}function l0(Z){return Z.startsWith("^")||Z.endsWith("$")||Z.includes("\\d")||Z.includes("\\w")||Z.includes("\\s")||Z.includes("[")||Z.includes("*")||Z.includes("+")||Z.includes("?")}function n0(Z,X){let J=String(Z);try{return new RegExp(X).test(J)}catch{return!1}}function o0(Z){return/^(>=?|<=?|>|<)\s*[\d.-]+(\s*,\s*(>=?|<=?|>|<)\s*[\d.-]+)*$/.test(Z)}function f1(Z,X){let J=Number(Z);if(Number.isNaN(J))return!1;let W=X.match(/^([\d.-]+)\s*-\s*([\d.-]+)$/);if(W){let G=Number(W[1]),Q=Number(W[2]);return J>=G&&J<=Q}return X.split(",").map((G)=>G.trim()).every((G)=>{let Q=G.match(/^(>=?|<=?|>|<)\s*([\d.-]+)$/);if(!Q)return!1;let Y=Q[1],z=Number(Q[2]);switch(Y){case">":return J>z;case">=":return J>=z;case"<":return J<z;case"<=":return J<=z;default:return!1}})}function $4(Z){return/^\[.*\]$/.test(Z)||Z==="*"||Z.startsWith("slice(")}function G4(Z,X){if(X==="*")return Z;if(X.startsWith("[")&&X.endsWith("]")){let J=X.slice(1,-1);if(J==="*")return Z;let W=Number(J);if(!Number.isNaN(W))return W>=0?Z[W]:Z[Z.length+W]}if(X.startsWith("slice(")){let J=X.match(/slice\((\d+)(?:,(\d+))?\)/);if(J){let W=Number(J[1]),$=J[2]?Number(J[2]):void 0;return Z.slice(W,$)}}return}async function p1(Z,X,J={}){if(Z.success&&X.expect){let G=i0(Z,X.expect);if(!G.success)Z.success=!1,Z.error=G.error}let{snapshotManager:W,snapshotConfig:$}=J;if(W&&$&&X.sourceFile&&Z.success){let G=await W.compareAndUpdate(X.sourceFile,X.name||"Request",Z,$);if(Z.snapshotResult=G,!G.match&&!G.updated){if(Z.success=!1,!Z.error)Z.error="Snapshot mismatch"}}return Z}function Q4(Z,X,J){return X*J**(Z-1)}async function r0(Z,X={}){let{config:J,shouldRetry:W,onRetry:$}=X,G=(J?.count??0)+1,Q=J?.delay??0,Y=J?.backoff??1,z=0,H;while(z<G){if(z>0&&$)$(z,J?.count??0);if(z>0&&Q>0){let K=Q4(z,Q,Y);await Bun.sleep(K)}z++;try{let K=await Z();if(W?.(K)){H="Operation returned retriable result";continue}return{value:K,success:!0,attempts:z}}catch(K){H=K instanceof Error?K.message:String(K)}}return{success:!1,attempts:z,error:H}}import*as r from"path";class s0{excludePaths;matchRules;constructor(Z){this.excludePaths=new Set(Z.exclude||[]),this.matchRules=new Map(Object.entries(Z.match||{}))}compare(Z,X){let J=[];if(Z.status!==void 0||X.status!==void 0){if(Z.status!==X.status&&!this.isExcluded("status"))J.push({path:"status",expected:Z.status,received:X.status,type:"changed"})}if(Z.headers||X.headers){let W=this.compareObjects(Z.headers||{},X.headers||{},"headers");J.push(...W)}if(Z.body!==void 0||X.body!==void 0){let W=this.deepCompare(Z.body,X.body,"body");J.push(...W)}return{match:J.length===0,differences:J}}deepCompare(Z,X,J){if(this.isExcluded(J))return[];if(this.matchesRule(J,X))return[];if(Z===null&&X===null)return[];if(Z===void 0&&X===void 0)return[];let W=this.getType(Z),$=this.getType(X);if(W!==$)return[{path:J,expected:Z,received:X,type:"type_mismatch"}];if(W!=="object"&&W!=="array"){if(Z!==X)return[{path:J,expected:Z,received:X,type:"changed"}];return[]}if(W==="array")return this.compareArrays(Z,X,J);return this.compareObjects(Z,X,J)}compareArrays(Z,X,J){let W=[],$=Math.max(Z.length,X.length);for(let G=0;G<$;G++){let Q=`${J}[${G}]`;if(G>=Z.length){if(!this.isExcluded(Q))W.push({path:Q,expected:void 0,received:X[G],type:"added"})}else if(G>=X.length){if(!this.isExcluded(Q))W.push({path:Q,expected:Z[G],received:void 0,type:"removed"})}else{let Y=this.deepCompare(Z[G],X[G],Q);W.push(...Y)}}return W}compareObjects(Z,X,J){let W=[],$=new Set([...Object.keys(Z),...Object.keys(X)]);for(let G of $){let Q=J?`${J}.${G}`:G,Y=G in Z,z=G in X;if(!Y&&z){if(!this.isExcluded(Q))W.push({path:Q,expected:void 0,received:X[G],type:"added"})}else if(Y&&!z){if(!this.isExcluded(Q))W.push({path:Q,expected:Z[G],received:void 0,type:"removed"})}else{let H=this.deepCompare(Z[G],X[G],Q);W.push(...H)}}return W}isExcluded(Z){if(this.excludePaths.has(Z))return!0;for(let X of this.excludePaths){if(X.startsWith("*.")){let J=X.slice(2);if(Z.endsWith(`.${J}`))return!0;if(Z.split(".").pop()===J)return!0}if(X.includes("[*]")){if(new RegExp(`^${X.replace(/\[\*\]/g,"\\[\\d+\\]").replace(/\./g,"\\.")}$`).test(Z))return!0}}return!1}matchesRule(Z,X){let J=this.matchRules.get(Z);if(!J)return!1;if(J==="*")return!0;if(J.startsWith("regex:")){let W=J.slice(6);try{return new RegExp(W).test(String(X))}catch{return!1}}return!1}getType(Z){if(Z===null)return"null";if(Z===void 0)return"undefined";if(Array.isArray(Z))return"array";return typeof Z}}var G2=1,Q2="__snapshots__";class c1{snapshotDir;globalConfig;writeLocks=new Map;constructor(Z={}){this.globalConfig=Z,this.snapshotDir=Z.dir||Q2}getSnapshotPath(Z){let X=r.dirname(Z),J=r.basename(Z,r.extname(Z));return r.join(X,this.snapshotDir,`${J}.snap.json`)}async load(Z){let X=this.getSnapshotPath(Z);try{let J=Bun.file(X);if(!await J.exists())return null;let W=await J.text();return JSON.parse(W)}catch{return null}}async save(Z,X){let J=this.getSnapshotPath(Z),W=this.writeLocks.get(J),$=(async()=>{if(W)await W;let G=r.dirname(J);await(await import("fs/promises")).mkdir(G,{recursive:!0});let Y=JSON.stringify(X,null,2);await Bun.write(J,Y)})();this.writeLocks.set(J,$),await $,this.writeLocks.delete(J)}async get(Z,X){return(await this.load(Z))?.snapshots[X]||null}createSnapshot(Z,X){let J=X.include||["body"],W={hash:"",updatedAt:new Date().toISOString()};if(J.includes("status")&&Z.status!==void 0)W.status=Z.status;if(J.includes("headers")&&Z.headers)W.headers=this.normalizeHeaders(Z.headers);if(J.includes("body")&&Z.body!==void 0)W.body=Z.body;return W.hash=this.hash(W),W}normalizeHeaders(Z){let X={},J=Object.keys(Z).sort();for(let W of J)X[W.toLowerCase()]=Z[W];return X}hash(Z){let X=JSON.stringify(Z),J=new Bun.CryptoHasher("md5");return J.update(X),J.digest("hex").slice(0,8)}async compareAndUpdate(Z,X,J,W){let $=W.name||X,G=await this.get(Z,$),Q=this.createSnapshot(J,W);if(!G){if(this.globalConfig.ci)return{match:!1,isNew:!0,updated:!1,differences:[{path:"",expected:"snapshot",received:"none",type:"removed"}]};return await this.updateSnapshot(Z,$,Q),{match:!0,isNew:!0,updated:!0,differences:[]}}let z=new s0(W).compare(G,Q);if(z.match)return{match:!0,isNew:!1,updated:!1,differences:[]};let H=this.globalConfig.updateMode||"none";if(H==="all"||H==="failing")return await this.updateSnapshot(Z,$,Q),{match:!0,isNew:!1,updated:!0,differences:z.differences};return{match:!1,isNew:!1,updated:!1,differences:z.differences}}async updateSnapshot(Z,X,J){let W=await this.load(Z);if(!W)W={version:G2,snapshots:{}};W.snapshots[X]=J,await this.save(Z,W)}static mergeConfig(Z,X){if(!X&&!Z?.enabled)return null;if(X===!0)return{enabled:!0,include:Z?.include||["body"],exclude:Z?.exclude||[],match:Z?.match||{}};if(typeof X==="object"&&X.enabled!==!1)return{enabled:!0,name:X.name,include:X.include||Z?.include||["body"],exclude:[...Z?.exclude||[],...X.exclude||[]],match:{...Z?.match||{},...X.match||{}}};if(Z?.enabled&&X===void 0)return{enabled:!0,include:Z.include||["body"],exclude:Z.exclude||[],match:Z.match||{}};return null}}function t0(Z,X){let J=X.split("."),W=Z;for(let $ of J){if(W===null||W===void 0)return;if(typeof W!=="object")return;let G=$.match(/^(\w+)\[(\d+)\]$/);if(G){let[,Q,Y]=G,z=Number.parseInt(Y,10);if(W=W[Q],Array.isArray(W))W=W[z];else return}else if(/^\d+$/.test($)&&Array.isArray(W))W=W[Number.parseInt($,10)];else W=W[$]}return W}function u1(Z){if(Z===void 0||Z===null)return"";if(typeof Z==="string")return Z;if(typeof Z==="number"||typeof Z==="boolean")return String(Z);return JSON.stringify(Z)}function Y4(Z,X){let J={},W={status:Z.status,headers:Z.headers||{},body:Z.body,metrics:Z.metrics};for(let[$,G]of Object.entries(X)){let Q=t0(W,G);J[$]=u1(Q)}return J}function z4(){return{}}function Y2(Z){let X=Z.trim(),J=X.match(/^(.+?)\s+(exists|not-exists)$/i);if(J)return{left:J[1].trim(),operator:J[2].toLowerCase()};let W=/^(.+?)\s*(==|!=|>=|<=|>|<|contains|matches)\s*(.+)$/i,$=X.match(W);if(!$)return null;let[,G,Q,Y]=$,z=z2(Y.trim());return{left:G.trim(),operator:Q.toLowerCase(),right:z}}function z2(Z){if(Z==="true")return!0;if(Z==="false")return!1;let X=Number(Z);if(!Number.isNaN(X)&&Z!=="")return X;if(Z.startsWith('"')&&Z.endsWith('"')||Z.startsWith("'")&&Z.endsWith("'"))return Z.slice(1,-1);return Z}function H2(Z,X){let J=Z.startsWith("store.")?Z.slice(6):Z;if(J in X){let G=X[J];if(G.startsWith("{")||G.startsWith("["))try{return JSON.parse(G)}catch{return G}let Q=Number(G);if(!Number.isNaN(Q)&&G!=="")return Q;if(G==="true")return!0;if(G==="false")return!1;return G}let W=J.split("."),$=W[0];if($ in X){let G=X[$];try{let Q=JSON.parse(G);return t0(Q,W.slice(1).join("."))}catch{return}}return}function H4(Z,X,J){if(J)return Z===X;return Z.toLowerCase()===X.toLowerCase()}function l1(Z,X){let J=H2(Z.left,X),W=Z.caseSensitive??!1,$=(Q)=>{if(Q===void 0)return"undefined";if(Q===null)return"null";if(typeof Q==="string")return`"${Q}"`;return String(Q)},G=`${Z.left} ${Z.operator}${Z.right!==void 0?` ${$(Z.right)}`:""}`;switch(Z.operator){case"exists":return{passed:J!==void 0&&J!==null&&J!=="",description:G};case"not-exists":return{passed:J===void 0||J===null||J==="",description:G};case"==":{let Q;if(typeof J==="string"&&typeof Z.right==="string")Q=H4(J,Z.right,W);else Q=J==Z.right;return{passed:Q,description:G}}case"!=":{let Q;if(typeof J==="string"&&typeof Z.right==="string")Q=!H4(J,Z.right,W);else Q=J!=Z.right;return{passed:Q,description:G}}case">":return{passed:Number(J)>Number(Z.right),description:G};case"<":return{passed:Number(J)<Number(Z.right),description:G};case">=":return{passed:Number(J)>=Number(Z.right),description:G};case"<=":return{passed:Number(J)<=Number(Z.right),description:G};case"contains":{let Q=u1(J),Y=String(Z.right??"");return{passed:W?Q.includes(Y):Q.toLowerCase().includes(Y.toLowerCase()),description:G}}case"matches":{let Q=u1(J),Y=String(Z.right??"");try{return{passed:new RegExp(Y,W?"":"i").test(Q),description:G}}catch{return{passed:!1,description:`${G} (invalid regex)`}}}default:return{passed:!1,description:`unknown operator: ${Z.operator}`}}}function K4(Z,X){if(typeof Z==="string"){let J=Y2(Z);if(!J)return{shouldRun:!1,reason:`invalid condition syntax: "${Z}"`};let W=l1(J,X);return{shouldRun:W.passed,reason:W.passed?void 0:`condition not met: ${W.description}`}}if(Z.all&&Z.all.length>0){for(let J of Z.all){let W=l1(J,X);if(!W.passed)return{shouldRun:!1,reason:`condition not met: ${W.description}`}}return{shouldRun:!0}}if(Z.any&&Z.any.length>0){let J=[];for(let W of Z.any){let $=l1(W,X);if($.passed)return{shouldRun:!0};J.push($.description)}return{shouldRun:!1,reason:`no conditions met: ${J.join(", ")}`}}if(Z.left&&Z.operator){let J={left:Z.left,operator:Z.operator,right:Z.right,caseSensitive:Z.caseSensitive},W=l1(J,X);return{shouldRun:W.passed,reason:W.passed?void 0:`condition not met: ${W.description}`}}return{shouldRun:!0}}class e0{poolConfig;constructor(Z={}){this.poolConfig={enabled:!0,maxStreamsPerHost:10,keepaliveTime:60,connectTimeout:30,...Z}}getHostKey(Z){try{let X=new URL(Z);return`${X.protocol}//${X.host}`}catch{return Z}}groupRequestsByHost(Z){let X=new Map;return Z.forEach((J,W)=>{let $=this.getHostKey(J.url),G=X.get($)||[];G.push({index:W,config:J}),X.set($,G)}),Array.from(X.entries()).map(([J,W])=>({host:J,requests:W}))}buildRequestArgs(Z,X){let{args:J,url:W}=F1(Z,{writeOutMarker:h0(X),includeSilentFlags:!1,includeHttp2Flag:!1,includeOutputFlag:!1});return J.push(W),J}buildBatchedCommand(Z){let X=[];return X.push("-Z"),X.push("--parallel-max",this.poolConfig.maxStreamsPerHost.toString()),X.push("--http2"),X.push("--keepalive-time",this.poolConfig.keepaliveTime.toString()),X.push("--connect-timeout",this.poolConfig.connectTimeout.toString()),X.push("-s","-S"),Z.requests.forEach((J,W)=>{if(W>0)X.push("--next");let $=this.buildRequestArgs(J.config,J.index);X.push(...$)}),X}parseBatchedOutput(Z,X,J,W){let $=new Map;for(let G of J.requests){let{found:Q,metricsJson:Y,startIdx:z}=d0(Z,G.index);if(!Q){$.set(G.index,{request:G.config,success:!1,error:X||`Request failed (exit code: ${W})`,metrics:{duration:0}});continue}let H={};try{H=JSON.parse(Y)}catch{}let K=z,U=0;for(let O of J.requests){if(O.index===G.index)continue;let I=`__CURL_BATCH_${O.index}_END__`,N=Z.indexOf(I);if(N!==-1&&N<K&&N+I.length>U)U=N+I.length}let M=Z.substring(U,K).trim(),R=N1(H),_=I1(H);$.set(G.index,{request:G.config,success:p0(R),status:R,body:$1(M),metrics:_})}return $}async executeBatch(Z){let X=this.buildBatchedCommand(Z);try{let J=Bun.spawn(["curl",...X],{stdout:"pipe",stderr:"pipe"}),W=await new Response(J.stdout).text(),$=await new Response(J.stderr).text();return await J.exited,this.parseBatchedOutput(W,$,Z,J.exitCode||0)}catch(J){let W=new Map;for(let $ of Z.requests)W.set($.index,{request:$.config,success:!1,error:J instanceof Error?J.message:String(J),metrics:{duration:0}});return W}}async executeAll(Z){let X=this.groupRequestsByHost(Z),J=new Map,W=X.map((G)=>this.executeBatch(G)),$=await Promise.all(W);for(let G of $)for(let[Q,Y]of G)J.set(Q,Y);return Z.map((G,Q)=>{return J.get(Q)||{request:Z[Q],success:!1,error:"Request not executed",metrics:{duration:0}}})}formatBatchedCommandForDisplay(Z){let X=this.buildBatchedCommand(Z);return T1(X)}}class Z9{logger;globalConfig;snapshotManager;pooledExecutor=null;constructor(Z={}){if(this.globalConfig=Z,this.logger=new a(Z.output),this.snapshotManager=new c1(Z.snapshot),Z.connectionPool?.enabled)this.pooledExecutor=new e0(Z.connectionPool)}mergeOutputConfig(Z){return{...this.globalConfig.output,...Z.sourceOutputConfig}}getSnapshotConfig(Z){return c1.mergeConfig(this.globalConfig.snapshot,Z.snapshot)}isFileAttachment(Z){return typeof Z==="object"&&Z!==null&&"file"in Z}async validateFileAttachments(Z){if(!Z.formData)return;let X=[];for(let[J,W]of Object.entries(Z.formData))if(this.isFileAttachment(W)){let $=W.file;if(!await Bun.file($).exists())X.push(`${J}: ${$}`)}if(X.length>0)return`File(s) not found: ${X.join(", ")}`;return}async executeRequest(Z,X=0){let J=performance.now(),W=this.mergeOutputConfig(Z),$=new a(W);$.logRequestStart(Z,X);let G=await this.validateFileAttachments(Z);if(G){let K={request:Z,success:!1,error:G,metrics:{duration:performance.now()-J}};return $.logRequestComplete(K),K}let Q=Z1.buildCommand(Z);if($.logCommand(Z1.formatCommandForDisplay(Q)),this.globalConfig.dryRun){let K={request:Z,success:!0,dryRun:!0,metrics:{duration:0}};return $.logRequestComplete(K),K}let Y=await r0(()=>Z1.executeCurl(Q),{config:Z.retry,shouldRetry:(K)=>!K.success,onRetry:(K,U)=>$.logRetry(K,U)});if(!Y.success||!Y.value?.success){let K={request:Z,success:!1,error:Y.error||Y.value?.error,metrics:{duration:performance.now()-J}};return $.logRequestComplete(K),K}let z=Y.value,H=this.processCurlResult(Z,z,J);return await p1(H,Z,{snapshotManager:this.snapshotManager,snapshotConfig:this.getSnapshotConfig(Z)}),$.logRequestComplete(H),H}processCurlResult(Z,X,J){let W=$1(X.body,X.headers?.["content-type"]);return{request:Z,success:!0,status:X.status,headers:X.headers,body:W,metrics:{...X.metrics,duration:performance.now()-J}}}async executeSequential(Z){let X=performance.now(),J=[],W=z4();for(let $=0;$<Z.length;$++){let G=this.interpolateStoreVariables(Z[$],W);if(G.when){let Y=K4(G.when,W);if(!Y.shouldRun){let z={request:G,success:!0,skipped:!0,skipReason:Y.reason};J.push(z),this.logger.logSkipped(G,$+1,Y.reason);continue}}let Q=await this.executeRequest(G,$+1);if(J.push(Q),Q.success&&G.store){let Y=Y4(Q,G.store);Object.assign(W,Y),this.logStoredValues(Y)}if(!Q.success&&!this.globalConfig.continueOnError){this.logger.logError("Stopping execution due to error");break}}return this.createSummary(J,performance.now()-X)}interpolateStoreVariables(Z,X){if(Object.keys(X).length===0)return Z;return y.interpolateVariables(Z,{},X)}logStoredValues(Z){if(Object.keys(Z).length===0)return;let X=Object.entries(Z);for(let[J,W]of X){let $=W.length>50?`${W.substring(0,50)}...`:W;this.logger.logInfo(`Stored: ${J} = "${$}"`)}}async executeParallel(Z){let X=performance.now();if(this.pooledExecutor&&!this.globalConfig.dryRun)return this.executePooled(Z,X);let J=this.globalConfig.maxConcurrency;if(!J||J>=Z.length){let $=Z.map((Q,Y)=>this.executeRequest(Q,Y+1)),G=await Promise.all($);return this.createSummary(G,performance.now()-X)}let W=[];for(let $=0;$<Z.length;$+=J){let Q=Z.slice($,$+J).map((H,K)=>this.executeRequest(H,$+K+1)),Y=await Promise.all(Q);if(W.push(...Y),Y.some((H)=>!H.success)&&!this.globalConfig.continueOnError){this.logger.logError("Stopping execution due to error");break}}return this.createSummary(W,performance.now()-X)}async executePooled(Z,X){this.logger.logInfo(`Using connection pooling (HTTP/2 multiplexing) for ${Z.length} requests`);let J=this.pooledExecutor.groupRequestsByHost(Z);for(let G of J)this.logger.logInfo(` ${G.host}: ${G.requests.length} request(s) batched`);let W=await this.pooledExecutor.executeAll(Z),$=[];for(let G=0;G<W.length;G++){let Q=W[G],Y=Z[G],z=this.mergeOutputConfig(Y),H=new a(z);if(H.logRequestStart(Y,G+1),await p1(Q,Y,{snapshotManager:this.snapshotManager,snapshotConfig:this.getSnapshotConfig(Y)}),H.logRequestComplete(Q),$.push(Q),!Q.success&&!this.globalConfig.continueOnError){this.logger.logError("Stopping execution due to error");break}}return this.createSummary($,performance.now()-X)}async execute(Z){this.logger.logExecutionStart(Z.length,this.globalConfig.execution||"sequential");let X=this.globalConfig.execution==="parallel"?await this.executeParallel(Z):await this.executeSequential(Z);if(this.logger.logSummary(X),this.globalConfig.output?.saveToFile)await this.saveSummaryToFile(X);return X}createSummary(Z,X){let J=Z.filter((G)=>G.skipped).length,W=Z.filter((G)=>G.success&&!G.skipped).length,$=Z.filter((G)=>!G.success).length;return{total:Z.length,successful:W,failed:$,skipped:J,duration:X,results:Z}}async saveSummaryToFile(Z){let X=this.globalConfig.output?.saveToFile;if(!X)return;let J=JSON.stringify(Z,null,2);await Bun.write(X,J),this.logger.logInfo(`Results saved to ${X}`)}}var B4=`${process.env.HOME}/.curl-runner-version-cache.json`,K2=86400000,B2="https://registry.npmjs.org/@curl-runner/cli/latest";class X9{async checkForUpdates(Z=!1){try{if(process.env.CI)return;let X=n();if(X==="0.0.0")return;if(!Z){let W=await this.getCachedVersion();if(W&&Date.now()-W.lastCheck<K2){this.compareVersions(X,W.latestVersion);return}}let J=await this.fetchLatestVersion();if(J)await this.setCachedVersion(J),this.compareVersions(X,J)}catch{}}async fetchLatestVersion(){try{let Z=await fetch(B2,{signal:AbortSignal.timeout(3000)});if(!Z.ok)return null;return(await Z.json()).version}catch{return null}}compareVersions(Z,X){if(this.isNewerVersion(Z,X))console.log(),console.log(D("\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E","yellow")),console.log(D("\u2502","yellow")+" "+D("\u2502","yellow")),console.log(D("\u2502","yellow")+" "+D("Update available!","bright")+` ${D(Z,"red")} \u2192 ${D(X,"green")} `+D("\u2502","yellow")),console.log(D("\u2502","yellow")+" "+D("\u2502","yellow")),console.log(D("\u2502","yellow")+" Run "+D("curl-runner upgrade","cyan")+" to update "+D("\u2502","yellow")),console.log(D("\u2502","yellow")+" "+D("\u2502","yellow")),console.log(D("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F","yellow")),console.log()}isNewerVersion(Z,X){try{let J=Z.replace(/^v/,""),W=X.replace(/^v/,""),$=J.split(".").map(Number),G=W.split(".").map(Number);for(let Q=0;Q<Math.max($.length,G.length);Q++){let Y=$[Q]||0,z=G[Q]||0;if(z>Y)return!0;if(z<Y)return!1}return!1}catch{return!1}}async getCachedVersion(){try{let Z=Bun.file(B4);if(await Z.exists())return JSON.parse(await Z.text())}catch{}return null}async setCachedVersion(Z){try{let X={lastCheck:Date.now(),latestVersion:Z};await Bun.write(B4,JSON.stringify(X))}catch{}}}import{watch as U2}from"fs";class J9{watchers=[];debounceTimer=null;isRunning=!1;pendingRun=!1;options;constructor(Z){this.options=Z}async start(){let{files:Z,logger:X}=this.options;await this.runRequests();for(let J of Z)try{let W=U2(J,($)=>{if($==="change")this.handleFileChange(J)});W.on("error",($)=>{X.logWarning(`Watch error on ${J}: ${$.message}`)}),this.watchers.push(W)}catch(W){X.logWarning(`Failed to watch ${J}: ${W instanceof Error?W.message:String(W)}`)}X.logWatch(Z),this.setupSignalHandlers(),await this.keepAlive()}handleFileChange(Z){let{config:X,logger:J}=this.options,W=X.debounce??300;if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(async()=>{if(this.isRunning){this.pendingRun=!0;return}if(X.clear!==!1)console.clear();J.logFileChanged(Z),await this.runRequests()},W)}async runRequests(){let{onRun:Z,logger:X}=this.options;this.isRunning=!0;try{await Z()}catch(J){X.logError(J instanceof Error?J.message:String(J))}if(this.isRunning=!1,this.pendingRun){this.pendingRun=!1;let{config:J}=this.options;if(J.clear!==!1)console.clear();X.logFileChanged("(queued change)"),await this.runRequests()}else X.logWatchReady()}setupSignalHandlers(){let Z=()=>{this.stop(),process.exit(0)};process.on("SIGINT",Z),process.on("SIGTERM",Z)}async keepAlive(){while(!0)await Bun.sleep(1000)}stop(){for(let Z of this.watchers)Z.close();if(this.watchers=[],this.debounceTimer)clearTimeout(this.debounceTimer),this.debounceTimer=null}}var X1=A1($9(),1);import{stdout as T4,stdin as T2}from"process";var h=A1(Q9(),1);import I2 from"readline";var N2=(Z)=>Z===161||Z===164||Z===167||Z===168||Z===170||Z===173||Z===174||Z>=176&&Z<=180||Z>=182&&Z<=186||Z>=188&&Z<=191||Z===198||Z===208||Z===215||Z===216||Z>=222&&Z<=225||Z===230||Z>=232&&Z<=234||Z===236||Z===237||Z===240||Z===242||Z===243||Z>=247&&Z<=250||Z===252||Z===254||Z===257||Z===273||Z===275||Z===283||Z===294||Z===295||Z===299||Z>=305&&Z<=307||Z===312||Z>=319&&Z<=322||Z===324||Z>=328&&Z<=331||Z===333||Z===338||Z===339||Z===358||Z===359||Z===363||Z===462||Z===464||Z===466||Z===468||Z===470||Z===472||Z===474||Z===476||Z===593||Z===609||Z===708||Z===711||Z>=713&&Z<=715||Z===717||Z===720||Z>=728&&Z<=731||Z===733||Z===735||Z>=768&&Z<=879||Z>=913&&Z<=929||Z>=931&&Z<=937||Z>=945&&Z<=961||Z>=963&&Z<=969||Z===1025||Z>=1040&&Z<=1103||Z===1105||Z===8208||Z>=8211&&Z<=8214||Z===8216||Z===8217||Z===8220||Z===8221||Z>=8224&&Z<=8226||Z>=8228&&Z<=8231||Z===8240||Z===8242||Z===8243||Z===8245||Z===8251||Z===8254||Z===8308||Z===8319||Z>=8321&&Z<=8324||Z===8364||Z===8451||Z===8453||Z===8457||Z===8467||Z===8470||Z===8481||Z===8482||Z===8486||Z===8491||Z===8531||Z===8532||Z>=8539&&Z<=8542||Z>=8544&&Z<=8555||Z>=8560&&Z<=8569||Z===8585||Z>=8592&&Z<=8601||Z===8632||Z===8633||Z===8658||Z===8660||Z===8679||Z===8704||Z===8706||Z===8707||Z===8711||Z===8712||Z===8715||Z===8719||Z===8721||Z===8725||Z===8730||Z>=8733&&Z<=8736||Z===8739||Z===8741||Z>=8743&&Z<=8748||Z===8750||Z>=8756&&Z<=8759||Z===8764||Z===8765||Z===8776||Z===8780||Z===8786||Z===8800||Z===8801||Z>=8804&&Z<=8807||Z===8810||Z===8811||Z===8814||Z===8815||Z===8834||Z===8835||Z===8838||Z===8839||Z===8853||Z===8857||Z===8869||Z===8895||Z===8978||Z>=9312&&Z<=9449||Z>=9451&&Z<=9547||Z>=9552&&Z<=9587||Z>=9600&&Z<=9615||Z>=9618&&Z<=9621||Z===9632||Z===9633||Z>=9635&&Z<=9641||Z===9650||Z===9651||Z===9654||Z===9655||Z===9660||Z===9661||Z===9664||Z===9665||Z>=9670&&Z<=9672||Z===9675||Z>=9678&&Z<=9681||Z>=9698&&Z<=9701||Z===9711||Z===9733||Z===9734||Z===9737||Z===9742||Z===9743||Z===9756||Z===9758||Z===9792||Z===9794||Z===9824||Z===9825||Z>=9827&&Z<=9829||Z>=9831&&Z<=9834||Z===9836||Z===9837||Z===9839||Z===9886||Z===9887||Z===9919||Z>=9926&&Z<=9933||Z>=9935&&Z<=9939||Z>=9941&&Z<=9953||Z===9955||Z===9960||Z===9961||Z>=9963&&Z<=9969||Z===9972||Z>=9974&&Z<=9977||Z===9979||Z===9980||Z===9982||Z===9983||Z===10045||Z>=10102&&Z<=10111||Z>=11094&&Z<=11097||Z>=12872&&Z<=12879||Z>=57344&&Z<=63743||Z>=65024&&Z<=65039||Z===65533||Z>=127232&&Z<=127242||Z>=127248&&Z<=127277||Z>=127280&&Z<=127337||Z>=127344&&Z<=127373||Z===127375||Z===127376||Z>=127387&&Z<=127404||Z>=917760&&Z<=917999||Z>=983040&&Z<=1048573||Z>=1048576&&Z<=1114109,L2=(Z)=>Z===12288||Z>=65281&&Z<=65376||Z>=65504&&Z<=65510,R2=(Z)=>Z>=4352&&Z<=4447||Z===8986||Z===8987||Z===9001||Z===9002||Z>=9193&&Z<=9196||Z===9200||Z===9203||Z===9725||Z===9726||Z===9748||Z===9749||Z>=9800&&Z<=9811||Z===9855||Z===9875||Z===9889||Z===9898||Z===9899||Z===9917||Z===9918||Z===9924||Z===9925||Z===9934||Z===9940||Z===9962||Z===9970||Z===9971||Z===9973||Z===9978||Z===9981||Z===9989||Z===9994||Z===9995||Z===10024||Z===10060||Z===10062||Z>=10067&&Z<=10069||Z===10071||Z>=10133&&Z<=10135||Z===10160||Z===10175||Z===11035||Z===11036||Z===11088||Z===11093||Z>=11904&&Z<=11929||Z>=11931&&Z<=12019||Z>=12032&&Z<=12245||Z>=12272&&Z<=12287||Z>=12289&&Z<=12350||Z>=12353&&Z<=12438||Z>=12441&&Z<=12543||Z>=12549&&Z<=12591||Z>=12593&&Z<=12686||Z>=12688&&Z<=12771||Z>=12783&&Z<=12830||Z>=12832&&Z<=12871||Z>=12880&&Z<=19903||Z>=19968&&Z<=42124||Z>=42128&&Z<=42182||Z>=43360&&Z<=43388||Z>=44032&&Z<=55203||Z>=63744&&Z<=64255||Z>=65040&&Z<=65049||Z>=65072&&Z<=65106||Z>=65108&&Z<=65126||Z>=65128&&Z<=65131||Z>=94176&&Z<=94180||Z===94192||Z===94193||Z>=94208&&Z<=100343||Z>=100352&&Z<=101589||Z>=101632&&Z<=101640||Z>=110576&&Z<=110579||Z>=110581&&Z<=110587||Z===110589||Z===110590||Z>=110592&&Z<=110882||Z===110898||Z>=110928&&Z<=110930||Z===110933||Z>=110948&&Z<=110951||Z>=110960&&Z<=111355||Z===126980||Z===127183||Z===127374||Z>=127377&&Z<=127386||Z>=127488&&Z<=127490||Z>=127504&&Z<=127547||Z>=127552&&Z<=127560||Z===127568||Z===127569||Z>=127584&&Z<=127589||Z>=127744&&Z<=127776||Z>=127789&&Z<=127797||Z>=127799&&Z<=127868||Z>=127870&&Z<=127891||Z>=127904&&Z<=127946||Z>=127951&&Z<=127955||Z>=127968&&Z<=127984||Z===127988||Z>=127992&&Z<=128062||Z===128064||Z>=128066&&Z<=128252||Z>=128255&&Z<=128317||Z>=128331&&Z<=128334||Z>=128336&&Z<=128359||Z===128378||Z===128405||Z===128406||Z===128420||Z>=128507&&Z<=128591||Z>=128640&&Z<=128709||Z===128716||Z>=128720&&Z<=128722||Z>=128725&&Z<=128727||Z>=128732&&Z<=128735||Z===128747||Z===128748||Z>=128756&&Z<=128764||Z>=128992&&Z<=129003||Z===129008||Z>=129292&&Z<=129338||Z>=129340&&Z<=129349||Z>=129351&&Z<=129535||Z>=129648&&Z<=129660||Z>=129664&&Z<=129672||Z>=129680&&Z<=129725||Z>=129727&&Z<=129733||Z>=129742&&Z<=129755||Z>=129760&&Z<=129768||Z>=129776&&Z<=129784||Z>=131072&&Z<=196605||Z>=196608&&Z<=262141,Y9=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,i1=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,a1=/\t{1,1000}/y,z9=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,r1=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,j2=/\p{M}+/gu,S2={limit:1/0,ellipsis:""},I4=(Z,X={},J={})=>{let W=X.limit??1/0,$=X.ellipsis??"",G=X?.ellipsisWidth??($?I4($,S2,J).width:0),Q=J.ansiWidth??0,Y=J.controlWidth??0,z=J.tabWidth??8,H=J.ambiguousWidth??1,K=J.emojiWidth??2,U=J.fullWidthWidth??2,M=J.regularWidth??1,R=J.wideWidth??2,_=0,O=0,I=Z.length,N=0,j=!1,A=I,k=Math.max(0,W-G),w=0,C=0,F=0,T=0;Z:for(;;){if(C>w||O>=I&&O>_){let f=Z.slice(w,C)||Z.slice(_,O);N=0;for(let c of f.replaceAll(j2,"")){let g=c.codePointAt(0)||0;if(L2(g)?T=U:R2(g)?T=R:H!==M&&N2(g)?T=H:T=M,F+T>k&&(A=Math.min(A,Math.max(w,_)+N)),F+T>W){j=!0;break Z}N+=c.length,F+=T}w=C=0}if(O>=I)break;if(r1.lastIndex=O,r1.test(Z)){if(N=r1.lastIndex-O,T=N*M,F+T>k&&(A=Math.min(A,O+Math.floor((k-F)/M))),F+T>W){j=!0;break}F+=T,w=_,C=O,O=_=r1.lastIndex;continue}if(Y9.lastIndex=O,Y9.test(Z)){if(F+Q>k&&(A=Math.min(A,O)),F+Q>W){j=!0;break}F+=Q,w=_,C=O,O=_=Y9.lastIndex;continue}if(i1.lastIndex=O,i1.test(Z)){if(N=i1.lastIndex-O,T=N*Y,F+T>k&&(A=Math.min(A,O+Math.floor((k-F)/Y))),F+T>W){j=!0;break}F+=T,w=_,C=O,O=_=i1.lastIndex;continue}if(a1.lastIndex=O,a1.test(Z)){if(N=a1.lastIndex-O,T=N*z,F+T>k&&(A=Math.min(A,O+Math.floor((k-F)/z))),F+T>W){j=!0;break}F+=T,w=_,C=O,O=_=a1.lastIndex;continue}if(z9.lastIndex=O,z9.test(Z)){if(F+K>k&&(A=Math.min(A,O)),F+K>W){j=!0;break}F+=K,w=_,C=O,O=_=z9.lastIndex;continue}O+=1}return{width:j?k:F,index:j?A:I,truncated:j,ellipsed:j&&W>=G}},E2={limit:1/0,ellipsis:"",ellipsisWidth:0},L1=(Z,X={})=>I4(Z,E2,X).width,t1="\x1B",N4="\x9B",A2=39,U9="\x07",L4="[",V2="]",R4="m",O9=`${V2}8;;`,M4=new RegExp(`(?:\\${L4}(?<code>\\d+)m|\\${O9}(?<uri>.*)${U9})`,"y"),k2=(Z)=>{if(Z>=30&&Z<=37||Z>=90&&Z<=97)return 39;if(Z>=40&&Z<=47||Z>=100&&Z<=107)return 49;if(Z===1||Z===2)return 22;if(Z===3)return 23;if(Z===4)return 24;if(Z===7)return 27;if(Z===8)return 28;if(Z===9)return 29;if(Z===0)return 0},D4=(Z)=>`${t1}${L4}${Z}${R4}`,F4=(Z)=>`${t1}${O9}${Z}${U9}`,P2=(Z)=>Z.map((X)=>L1(X)),H9=(Z,X,J)=>{let W=X[Symbol.iterator](),$=!1,G=!1,Q=Z.at(-1),Y=Q===void 0?0:L1(Q),z=W.next(),H=W.next(),K=0;for(;!z.done;){let U=z.value,M=L1(U);Y+M<=J?Z[Z.length-1]+=U:(Z.push(U),Y=0),(U===t1||U===N4)&&($=!0,G=X.startsWith(O9,K+1)),$?G?U===U9&&($=!1,G=!1):U===R4&&($=!1):(Y+=M,Y===J&&!H.done&&(Z.push(""),Y=0)),z=H,H=W.next(),K+=U.length}Q=Z.at(-1),!Y&&Q!==void 0&&Q.length>0&&Z.length>1&&(Z[Z.length-2]+=Z.pop())},C2=(Z)=>{let X=Z.split(" "),J=X.length;for(;J>0&&!(L1(X[J-1])>0);)J--;return J===X.length?Z:X.slice(0,J).join(" ")+X.slice(J).join("")},w2=(Z,X,J={})=>{if(J.trim!==!1&&Z.trim()==="")return"";let W="",$,G,Q=Z.split(" "),Y=P2(Q),z=[""];for(let[_,O]of Q.entries()){J.trim!==!1&&(z[z.length-1]=(z.at(-1)??"").trimStart());let I=L1(z.at(-1)??"");if(_!==0&&(I>=X&&(J.wordWrap===!1||J.trim===!1)&&(z.push(""),I=0),(I>0||J.trim===!1)&&(z[z.length-1]+=" ",I++)),J.hard&&Y[_]>X){let N=X-I,j=1+Math.floor((Y[_]-N-1)/X);Math.floor((Y[_]-1)/X)<j&&z.push(""),H9(z,O,X);continue}if(I+Y[_]>X&&I>0&&Y[_]>0){if(J.wordWrap===!1&&I<X){H9(z,O,X);continue}z.push("")}if(I+Y[_]>X&&J.wordWrap===!1){H9(z,O,X);continue}z[z.length-1]+=O}J.trim!==!1&&(z=z.map((_)=>C2(_)));let H=z.join(`
155
+ `),K=H[Symbol.iterator](),U=K.next(),M=K.next(),R=0;for(;!U.done;){let _=U.value,O=M.value;if(W+=_,_===t1||_===N4){M4.lastIndex=R+1;let N=M4.exec(H)?.groups;if(N?.code!==void 0){let j=Number.parseFloat(N.code);$=j===A2?void 0:j}else N?.uri!==void 0&&(G=N.uri.length===0?void 0:N.uri)}let I=$?k2($):void 0;O===`
156
+ `?(G&&(W+=F4("")),$&&I&&(W+=D4(I))):_===`
157
+ `&&($&&I&&(W+=D4($)),G&&(W+=F4(G))),R+=_.length,U=M,M=K.next()}return W};function K9(Z,X,J){return String(Z).normalize().replaceAll(`\r
158
+ `,`
159
+ `).split(`
160
+ `).map((W)=>w2(W,X,J)).join(`
161
+ `)}var q2=["up","down","left","right","space","enter","cancel"],J1={actions:new Set(q2),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0};function j4(Z,X){if(typeof Z=="string")return J1.aliases.get(Z)===X;for(let J of Z)if(J!==void 0&&j4(J,X))return!0;return!1}function x2(Z,X){if(Z===X)return;let J=Z.split(`
162
+ `),W=X.split(`
163
+ `),$=Math.max(J.length,W.length),G=[];for(let Q=0;Q<$;Q++)J[Q]!==W[Q]&&G.push(Q);return{lines:G,numLinesBefore:J.length,numLinesAfter:W.length,numLines:$}}var $8=globalThis.process.platform.startsWith("win"),B9=Symbol("clack:cancel");function L(Z){return Z===B9}function s1(Z,X){let J=Z;J.isTTY&&J.setRawMode(X)}var _9=(Z)=>("columns"in Z)&&typeof Z.columns=="number"?Z.columns:80,M9=(Z)=>("rows"in Z)&&typeof Z.rows=="number"?Z.rows:20;function Q1(Z,X,J,W=J){let $=_9(Z??T4);return K9(X,$-J.length,{hard:!0,trim:!1}).split(`
164
+ `).map((G,Q)=>`${Q===0?W:J}${G}`).join(`
165
+ `)}class W1{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(Z,X=!0){let{input:J=T2,output:W=T4,render:$,signal:G,...Q}=Z;this.opts=Q,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=$.bind(this),this._track=X,this._abortSignal=G,this.input=J,this.output=W}unsubscribe(){this._subscribers.clear()}setSubscriber(Z,X){let J=this._subscribers.get(Z)??[];J.push(X),this._subscribers.set(Z,J)}on(Z,X){this.setSubscriber(Z,{cb:X})}once(Z,X){this.setSubscriber(Z,{cb:X,once:!0})}emit(Z,...X){let J=this._subscribers.get(Z)??[],W=[];for(let $ of J)$.cb(...X),$.once&&W.push(()=>J.splice(J.indexOf($),1));for(let $ of W)$()}prompt(){return new Promise((Z)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),Z(B9);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=I2.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),s1(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(h.cursor.show),this.output.off("resize",this.render),s1(this.input,!1),Z(this.value)}),this.once("cancel",()=>{this.output.write(h.cursor.show),this.output.off("resize",this.render),s1(this.input,!1),Z(B9)})})}_isActionKey(Z,X){return Z==="\t"}_setValue(Z){this.value=Z,this.emit("value",this.value)}_setUserInput(Z,X){this.userInput=Z??"",this.emit("userInput",this.userInput),X&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(Z,X){if(this._track&&X.name!=="return"&&(X.name&&this._isActionKey(Z,X)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),X?.name&&(!this._track&&J1.aliases.has(X.name)&&this.emit("cursor",J1.aliases.get(X.name)),J1.actions.has(X.name)&&this.emit("cursor",X.name)),Z&&(Z.toLowerCase()==="y"||Z.toLowerCase()==="n")&&this.emit("confirm",Z.toLowerCase()==="y"),this.emit("key",Z?.toLowerCase(),X),X?.name==="return"){if(this.opts.validate){let J=this.opts.validate(this.value);J&&(this.error=J instanceof Error?J.message:J,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}j4([Z,X?.name,X?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
166
+ `),s1(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let Z=K9(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
167
+ `).length-1;this.output.write(h.cursor.move(-999,Z*-1))}render(){let Z=K9(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(Z!==this._prevFrame){if(this.state==="initial")this.output.write(h.cursor.hide);else{let X=x2(this._prevFrame,Z),J=M9(this.output);if(this.restoreCursor(),X){let W=Math.max(0,X.numLinesAfter-J),$=Math.max(0,X.numLinesBefore-J),G=X.lines.find((Q)=>Q>=W);if(G===void 0){this._prevFrame=Z;return}if(X.lines.length===1){this.output.write(h.cursor.move(0,G-$)),this.output.write(h.erase.lines(1));let Q=Z.split(`
168
+ `);this.output.write(Q[G]),this._prevFrame=Z,this.output.write(h.cursor.move(0,Q.length-G-1));return}else if(X.lines.length>1){if(W<$)G=W;else{let Y=G-$;Y>0&&this.output.write(h.cursor.move(0,Y))}this.output.write(h.erase.down());let Q=Z.split(`
169
+ `).slice(G);this.output.write(Q.join(`
170
+ `)),this._prevFrame=Z;return}}this.output.write(h.erase.down())}this.output.write(Z),this.state==="initial"&&(this.state="active"),this._prevFrame=Z}}}function b2(Z,X){if(Z===void 0||X.length===0)return 0;let J=X.findIndex((W)=>W.value===Z);return J!==-1?J:0}function y2(Z,X){return(X.label??String(X.value)).toLowerCase().includes(Z.toLowerCase())}function v2(Z,X){if(X)return Z?X:X[0]}class S4 extends W1{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#Z=0;#J="";#W;#X;get cursor(){return this.#Z}get userInputWithCursor(){if(!this.userInput)return X1.default.inverse(X1.default.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let Z=this.userInput.slice(0,this._cursor),[X,...J]=this.userInput.slice(this._cursor);return`${Z}${X1.default.inverse(X)}${J.join("")}`}get options(){return typeof this.#X=="function"?this.#X():this.#X}constructor(Z){super(Z),this.#X=Z.options;let X=this.options;this.filteredOptions=[...X],this.multiple=Z.multiple===!0,this.#W=Z.filter??y2;let J;if(Z.initialValue&&Array.isArray(Z.initialValue)?this.multiple?J=Z.initialValue:J=Z.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(J=[this.options[0].value]),J)for(let W of J){let $=X.findIndex((G)=>G.value===W);$!==-1&&(this.toggleSelected(W),this.#Z=$)}this.focusedValue=this.options[this.#Z]?.value,this.on("key",(W,$)=>this.#$(W,$)),this.on("userInput",(W)=>this.#G(W))}_isActionKey(Z,X){return Z==="\t"||this.multiple&&this.isNavigating&&X.name==="space"&&Z!==void 0&&Z!==""}#$(Z,X){let J=X.name==="up",W=X.name==="down",$=X.name==="return";J||W?(this.#Z=Math.max(0,Math.min(this.#Z+(J?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#Z]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):$?this.value=v2(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(X.name==="tab"||this.isNavigating&&X.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(Z){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(Z)?this.selectedValues=this.selectedValues.filter((X)=>X!==Z):this.selectedValues=[...this.selectedValues,Z]:this.selectedValues=[Z])}#G(Z){if(Z!==this.#J){this.#J=Z;let X=this.options;Z?this.filteredOptions=X.filter((J)=>this.#W(Z,J)):this.filteredOptions=[...X],this.#Z=b2(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#Z]?.value,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}}class D9 extends W1{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(Z){super(Z,!1),this.value=!!Z.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(X)=>{this.output.write(h.cursor.move(0,-1)),this.value=X,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}class E4 extends W1{options;cursor=0;#Z;getGroupItems(Z){return this.options.filter((X)=>X.group===Z)}isGroupSelected(Z){let X=this.getGroupItems(Z),J=this.value;return J===void 0?!1:X.every((W)=>J.includes(W.value))}toggleValue(){let Z=this.options[this.cursor];if(this.value===void 0&&(this.value=[]),Z.group===!0){let X=Z.value,J=this.getGroupItems(X);this.isGroupSelected(X)?this.value=this.value.filter((W)=>J.findIndex(($)=>$.value===W)===-1):this.value=[...this.value,...J.map((W)=>W.value)],this.value=Array.from(new Set(this.value))}else{let X=this.value.includes(Z.value);this.value=X?this.value.filter((J)=>J!==Z.value):[...this.value,Z.value]}}constructor(Z){super(Z,!1);let{options:X}=Z;this.#Z=Z.selectableGroups!==!1,this.options=Object.entries(X).flatMap(([J,W])=>[{value:J,group:!0,label:J},...W.map(($)=>({...$,group:J}))]),this.value=[...Z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:J})=>J===Z.cursorAt),this.#Z?0:1),this.on("cursor",(J)=>{switch(J){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let W=this.options[this.cursor]?.group===!0;!this.#Z&&W&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let W=this.options[this.cursor]?.group===!0;!this.#Z&&W&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}}function G1(Z,X,J){let W=Z+X,$=Math.max(J.length-1,0),G=W<0?$:W>$?0:W;return J[G].disabled?G1(G,X<0?-1:1,J):G}class F9 extends W1{options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter((Z)=>Z.disabled!==!0)}toggleAll(){let Z=this._enabledOptions,X=this.value!==void 0&&this.value.length===Z.length;this.value=X?[]:Z.map((J)=>J.value)}toggleInvert(){let Z=this.value;if(!Z)return;let X=this._enabledOptions.filter((J)=>!Z.includes(J.value));this.value=X.map((J)=>J.value)}toggleValue(){this.value===void 0&&(this.value=[]);let Z=this.value.includes(this._value);this.value=Z?this.value.filter((X)=>X!==this._value):[...this.value,this._value]}constructor(Z){super(Z,!1),this.options=Z.options,this.value=[...Z.initialValues??[]];let X=Math.max(this.options.findIndex(({value:J})=>J===Z.cursorAt),0);this.cursor=this.options[X].disabled?G1(X,1,this.options):X,this.on("key",(J)=>{J==="a"&&this.toggleAll(),J==="i"&&this.toggleInvert()}),this.on("cursor",(J)=>{switch(J){case"left":case"up":this.cursor=G1(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=G1(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var A4=class extends W1{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let Z=this.userInput;if(this.cursor>=Z.length)return`${this.masked}${X1.default.inverse(X1.default.hidden("_"))}`;let X=this.masked,J=X.slice(0,this.cursor),W=X.slice(this.cursor);return`${J}${X1.default.inverse(W[0])}${W.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:Z,...X}){super(X),this._mask=Z??"\u2022",this.on("userInput",(J)=>{this._setValue(J)})}};class T9 extends W1{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(Z){super(Z,!1),this.options=Z.options;let X=this.options.findIndex(({value:W})=>W===Z.initialValue),J=X===-1?0:X;this.cursor=this.options[J].disabled?G1(J,1,this.options):J,this.changeValue(),this.on("cursor",(W)=>{switch(W){case"left":case"up":this.cursor=G1(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=G1(this.cursor,1,this.options);break}this.changeValue()})}}class I9 extends W1{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let Z=this.userInput;if(this.cursor>=Z.length)return`${this.userInput}\u2588`;let X=Z.slice(0,this.cursor),[J,...W]=Z.slice(this.cursor);return`${X}${X1.default.inverse(J)}${W.join("")}`}get cursor(){return this._cursor}constructor(Z){super({...Z,initialUserInput:Z.initialUserInput??Z.initialValue}),this.on("userInput",(X)=>{this._setValue(X)}),this.on("finalize",()=>{this.value||(this.value=Z.defaultValue),this.value===void 0&&(this.value="")})}}var B=A1($9(),1);import p from"process";var q4=A1(Q9(),1);function m2(){return p.platform!=="win32"?p.env.TERM!=="linux":!!p.env.CI||!!p.env.WT_SESSION||!!p.env.TERMINUS_SUBLIME||p.env.ConEmuTask==="{cmd::Cmder}"||p.env.TERM_PROGRAM==="Terminus-Sublime"||p.env.TERM_PROGRAM==="vscode"||p.env.TERM==="xterm-256color"||p.env.TERM==="alacritty"||p.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var h2=m2();var V=(Z,X)=>h2?Z:X,g2=V("\u25C6","*"),d2=V("\u25A0","x"),f2=V("\u25B2","x"),x4=V("\u25C7","o"),p2=V("\u250C","T"),E=V("\u2502","|"),l=V("\u2514","\u2014"),U8=V("\u2510","T"),O8=V("\u2518","\u2014"),j9=V("\u25CF",">"),W0=V("\u25CB"," "),c2=V("\u25FB","[\u2022]"),V4=V("\u25FC","[+]"),k4=V("\u25FB","[ ]"),u2=V("\u25AA","\u2022"),_8=V("\u2500","-"),M8=V("\u256E","+"),D8=V("\u251C","+"),F8=V("\u256F","+"),T8=V("\u2570","+"),I8=V("\u256D","+"),l2=V("\u25CF","\u2022"),n2=V("\u25C6","*"),o2=V("\u25B2","!"),i2=V("\u25A0","x"),S1=(Z)=>{switch(Z){case"initial":case"active":return B.default.cyan(g2);case"cancel":return B.default.red(d2);case"error":return B.default.yellow(f2);case"submit":return B.default.green(x4)}},b4=(Z)=>{switch(Z){case"initial":case"active":return B.default.cyan(E);case"cancel":return B.default.red(E);case"error":return B.default.yellow(E);case"submit":return B.default.green(E)}},a2=(Z)=>Z===161||Z===164||Z===167||Z===168||Z===170||Z===173||Z===174||Z>=176&&Z<=180||Z>=182&&Z<=186||Z>=188&&Z<=191||Z===198||Z===208||Z===215||Z===216||Z>=222&&Z<=225||Z===230||Z>=232&&Z<=234||Z===236||Z===237||Z===240||Z===242||Z===243||Z>=247&&Z<=250||Z===252||Z===254||Z===257||Z===273||Z===275||Z===283||Z===294||Z===295||Z===299||Z>=305&&Z<=307||Z===312||Z>=319&&Z<=322||Z===324||Z>=328&&Z<=331||Z===333||Z===338||Z===339||Z===358||Z===359||Z===363||Z===462||Z===464||Z===466||Z===468||Z===470||Z===472||Z===474||Z===476||Z===593||Z===609||Z===708||Z===711||Z>=713&&Z<=715||Z===717||Z===720||Z>=728&&Z<=731||Z===733||Z===735||Z>=768&&Z<=879||Z>=913&&Z<=929||Z>=931&&Z<=937||Z>=945&&Z<=961||Z>=963&&Z<=969||Z===1025||Z>=1040&&Z<=1103||Z===1105||Z===8208||Z>=8211&&Z<=8214||Z===8216||Z===8217||Z===8220||Z===8221||Z>=8224&&Z<=8226||Z>=8228&&Z<=8231||Z===8240||Z===8242||Z===8243||Z===8245||Z===8251||Z===8254||Z===8308||Z===8319||Z>=8321&&Z<=8324||Z===8364||Z===8451||Z===8453||Z===8457||Z===8467||Z===8470||Z===8481||Z===8482||Z===8486||Z===8491||Z===8531||Z===8532||Z>=8539&&Z<=8542||Z>=8544&&Z<=8555||Z>=8560&&Z<=8569||Z===8585||Z>=8592&&Z<=8601||Z===8632||Z===8633||Z===8658||Z===8660||Z===8679||Z===8704||Z===8706||Z===8707||Z===8711||Z===8712||Z===8715||Z===8719||Z===8721||Z===8725||Z===8730||Z>=8733&&Z<=8736||Z===8739||Z===8741||Z>=8743&&Z<=8748||Z===8750||Z>=8756&&Z<=8759||Z===8764||Z===8765||Z===8776||Z===8780||Z===8786||Z===8800||Z===8801||Z>=8804&&Z<=8807||Z===8810||Z===8811||Z===8814||Z===8815||Z===8834||Z===8835||Z===8838||Z===8839||Z===8853||Z===8857||Z===8869||Z===8895||Z===8978||Z>=9312&&Z<=9449||Z>=9451&&Z<=9547||Z>=9552&&Z<=9587||Z>=9600&&Z<=9615||Z>=9618&&Z<=9621||Z===9632||Z===9633||Z>=9635&&Z<=9641||Z===9650||Z===9651||Z===9654||Z===9655||Z===9660||Z===9661||Z===9664||Z===9665||Z>=9670&&Z<=9672||Z===9675||Z>=9678&&Z<=9681||Z>=9698&&Z<=9701||Z===9711||Z===9733||Z===9734||Z===9737||Z===9742||Z===9743||Z===9756||Z===9758||Z===9792||Z===9794||Z===9824||Z===9825||Z>=9827&&Z<=9829||Z>=9831&&Z<=9834||Z===9836||Z===9837||Z===9839||Z===9886||Z===9887||Z===9919||Z>=9926&&Z<=9933||Z>=9935&&Z<=9939||Z>=9941&&Z<=9953||Z===9955||Z===9960||Z===9961||Z>=9963&&Z<=9969||Z===9972||Z>=9974&&Z<=9977||Z===9979||Z===9980||Z===9982||Z===9983||Z===10045||Z>=10102&&Z<=10111||Z>=11094&&Z<=11097||Z>=12872&&Z<=12879||Z>=57344&&Z<=63743||Z>=65024&&Z<=65039||Z===65533||Z>=127232&&Z<=127242||Z>=127248&&Z<=127277||Z>=127280&&Z<=127337||Z>=127344&&Z<=127373||Z===127375||Z===127376||Z>=127387&&Z<=127404||Z>=917760&&Z<=917999||Z>=983040&&Z<=1048573||Z>=1048576&&Z<=1114109,r2=(Z)=>Z===12288||Z>=65281&&Z<=65376||Z>=65504&&Z<=65510,s2=(Z)=>Z>=4352&&Z<=4447||Z===8986||Z===8987||Z===9001||Z===9002||Z>=9193&&Z<=9196||Z===9200||Z===9203||Z===9725||Z===9726||Z===9748||Z===9749||Z>=9800&&Z<=9811||Z===9855||Z===9875||Z===9889||Z===9898||Z===9899||Z===9917||Z===9918||Z===9924||Z===9925||Z===9934||Z===9940||Z===9962||Z===9970||Z===9971||Z===9973||Z===9978||Z===9981||Z===9989||Z===9994||Z===9995||Z===10024||Z===10060||Z===10062||Z>=10067&&Z<=10069||Z===10071||Z>=10133&&Z<=10135||Z===10160||Z===10175||Z===11035||Z===11036||Z===11088||Z===11093||Z>=11904&&Z<=11929||Z>=11931&&Z<=12019||Z>=12032&&Z<=12245||Z>=12272&&Z<=12287||Z>=12289&&Z<=12350||Z>=12353&&Z<=12438||Z>=12441&&Z<=12543||Z>=12549&&Z<=12591||Z>=12593&&Z<=12686||Z>=12688&&Z<=12771||Z>=12783&&Z<=12830||Z>=12832&&Z<=12871||Z>=12880&&Z<=19903||Z>=19968&&Z<=42124||Z>=42128&&Z<=42182||Z>=43360&&Z<=43388||Z>=44032&&Z<=55203||Z>=63744&&Z<=64255||Z>=65040&&Z<=65049||Z>=65072&&Z<=65106||Z>=65108&&Z<=65126||Z>=65128&&Z<=65131||Z>=94176&&Z<=94180||Z===94192||Z===94193||Z>=94208&&Z<=100343||Z>=100352&&Z<=101589||Z>=101632&&Z<=101640||Z>=110576&&Z<=110579||Z>=110581&&Z<=110587||Z===110589||Z===110590||Z>=110592&&Z<=110882||Z===110898||Z>=110928&&Z<=110930||Z===110933||Z>=110948&&Z<=110951||Z>=110960&&Z<=111355||Z===126980||Z===127183||Z===127374||Z>=127377&&Z<=127386||Z>=127488&&Z<=127490||Z>=127504&&Z<=127547||Z>=127552&&Z<=127560||Z===127568||Z===127569||Z>=127584&&Z<=127589||Z>=127744&&Z<=127776||Z>=127789&&Z<=127797||Z>=127799&&Z<=127868||Z>=127870&&Z<=127891||Z>=127904&&Z<=127946||Z>=127951&&Z<=127955||Z>=127968&&Z<=127984||Z===127988||Z>=127992&&Z<=128062||Z===128064||Z>=128066&&Z<=128252||Z>=128255&&Z<=128317||Z>=128331&&Z<=128334||Z>=128336&&Z<=128359||Z===128378||Z===128405||Z===128406||Z===128420||Z>=128507&&Z<=128591||Z>=128640&&Z<=128709||Z===128716||Z>=128720&&Z<=128722||Z>=128725&&Z<=128727||Z>=128732&&Z<=128735||Z===128747||Z===128748||Z>=128756&&Z<=128764||Z>=128992&&Z<=129003||Z===129008||Z>=129292&&Z<=129338||Z>=129340&&Z<=129349||Z>=129351&&Z<=129535||Z>=129648&&Z<=129660||Z>=129664&&Z<=129672||Z>=129680&&Z<=129725||Z>=129727&&Z<=129733||Z>=129742&&Z<=129755||Z>=129760&&Z<=129768||Z>=129776&&Z<=129784||Z>=131072&&Z<=196605||Z>=196608&&Z<=262141,N9=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,e1=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Z0=/\t{1,1000}/y,L9=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,X0=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,t2=/\p{M}+/gu,e2={limit:1/0,ellipsis:""},y4=(Z,X={},J={})=>{let W=X.limit??1/0,$=X.ellipsis??"",G=X?.ellipsisWidth??($?y4($,e2,J).width:0),Q=J.ansiWidth??0,Y=J.controlWidth??0,z=J.tabWidth??8,H=J.ambiguousWidth??1,K=J.emojiWidth??2,U=J.fullWidthWidth??2,M=J.regularWidth??1,R=J.wideWidth??2,_=0,O=0,I=Z.length,N=0,j=!1,A=I,k=Math.max(0,W-G),w=0,C=0,F=0,T=0;Z:for(;;){if(C>w||O>=I&&O>_){let f=Z.slice(w,C)||Z.slice(_,O);N=0;for(let c of f.replaceAll(t2,"")){let g=c.codePointAt(0)||0;if(r2(g)?T=U:s2(g)?T=R:H!==M&&a2(g)?T=H:T=M,F+T>k&&(A=Math.min(A,Math.max(w,_)+N)),F+T>W){j=!0;break Z}N+=c.length,F+=T}w=C=0}if(O>=I)break;if(X0.lastIndex=O,X0.test(Z)){if(N=X0.lastIndex-O,T=N*M,F+T>k&&(A=Math.min(A,O+Math.floor((k-F)/M))),F+T>W){j=!0;break}F+=T,w=_,C=O,O=_=X0.lastIndex;continue}if(N9.lastIndex=O,N9.test(Z)){if(F+Q>k&&(A=Math.min(A,O)),F+Q>W){j=!0;break}F+=Q,w=_,C=O,O=_=N9.lastIndex;continue}if(e1.lastIndex=O,e1.test(Z)){if(N=e1.lastIndex-O,T=N*Y,F+T>k&&(A=Math.min(A,O+Math.floor((k-F)/Y))),F+T>W){j=!0;break}F+=T,w=_,C=O,O=_=e1.lastIndex;continue}if(Z0.lastIndex=O,Z0.test(Z)){if(N=Z0.lastIndex-O,T=N*z,F+T>k&&(A=Math.min(A,O+Math.floor((k-F)/z))),F+T>W){j=!0;break}F+=T,w=_,C=O,O=_=Z0.lastIndex;continue}if(L9.lastIndex=O,L9.test(Z)){if(F+K>k&&(A=Math.min(A,O)),F+K>W){j=!0;break}F+=K,w=_,C=O,O=_=L9.lastIndex;continue}O+=1}return{width:j?k:F,index:j?A:I,truncated:j,ellipsed:j&&W>=G}},Z7={limit:1/0,ellipsis:"",ellipsisWidth:0},j1=(Z,X={})=>y4(Z,Z7,X).width,$0="\x1B",v4="\x9B",X7=39,E9="\x07",m4="[",J7="]",h4="m",A9=`${J7}8;;`,P4=new RegExp(`(?:\\${m4}(?<code>\\d+)m|\\${A9}(?<uri>.*)${E9})`,"y"),W7=(Z)=>{if(Z>=30&&Z<=37||Z>=90&&Z<=97)return 39;if(Z>=40&&Z<=47||Z>=100&&Z<=107)return 49;if(Z===1||Z===2)return 22;if(Z===3)return 23;if(Z===4)return 24;if(Z===7)return 27;if(Z===8)return 28;if(Z===9)return 29;if(Z===0)return 0},C4=(Z)=>`${$0}${m4}${Z}${h4}`,w4=(Z)=>`${$0}${A9}${Z}${E9}`,$7=(Z)=>Z.map((X)=>j1(X)),R9=(Z,X,J)=>{let W=X[Symbol.iterator](),$=!1,G=!1,Q=Z.at(-1),Y=Q===void 0?0:j1(Q),z=W.next(),H=W.next(),K=0;for(;!z.done;){let U=z.value,M=j1(U);Y+M<=J?Z[Z.length-1]+=U:(Z.push(U),Y=0),(U===$0||U===v4)&&($=!0,G=X.startsWith(A9,K+1)),$?G?U===E9&&($=!1,G=!1):U===h4&&($=!1):(Y+=M,Y===J&&!H.done&&(Z.push(""),Y=0)),z=H,H=W.next(),K+=U.length}Q=Z.at(-1),!Y&&Q!==void 0&&Q.length>0&&Z.length>1&&(Z[Z.length-2]+=Z.pop())},G7=(Z)=>{let X=Z.split(" "),J=X.length;for(;J>0&&!(j1(X[J-1])>0);)J--;return J===X.length?Z:X.slice(0,J).join(" ")+X.slice(J).join("")},Q7=(Z,X,J={})=>{if(J.trim!==!1&&Z.trim()==="")return"";let W="",$,G,Q=Z.split(" "),Y=$7(Q),z=[""];for(let[_,O]of Q.entries()){J.trim!==!1&&(z[z.length-1]=(z.at(-1)??"").trimStart());let I=j1(z.at(-1)??"");if(_!==0&&(I>=X&&(J.wordWrap===!1||J.trim===!1)&&(z.push(""),I=0),(I>0||J.trim===!1)&&(z[z.length-1]+=" ",I++)),J.hard&&Y[_]>X){let N=X-I,j=1+Math.floor((Y[_]-N-1)/X);Math.floor((Y[_]-1)/X)<j&&z.push(""),R9(z,O,X);continue}if(I+Y[_]>X&&I>0&&Y[_]>0){if(J.wordWrap===!1&&I<X){R9(z,O,X);continue}z.push("")}if(I+Y[_]>X&&J.wordWrap===!1){R9(z,O,X);continue}z[z.length-1]+=O}J.trim!==!1&&(z=z.map((_)=>G7(_)));let H=z.join(`
171
+ `),K=H[Symbol.iterator](),U=K.next(),M=K.next(),R=0;for(;!U.done;){let _=U.value,O=M.value;if(W+=_,_===$0||_===v4){P4.lastIndex=R+1;let N=P4.exec(H)?.groups;if(N?.code!==void 0){let j=Number.parseFloat(N.code);$=j===X7?void 0:j}else N?.uri!==void 0&&(G=N.uri.length===0?void 0:N.uri)}let I=$?W7($):void 0;O===`
172
+ `?(G&&(W+=w4("")),$&&I&&(W+=C4(I))):_===`
173
+ `&&($&&I&&(W+=C4($)),G&&(W+=w4(G))),R+=_.length,U=M,M=K.next()}return W};function Y7(Z,X,J){return String(Z).normalize().replaceAll(`\r
174
+ `,`
175
+ `).split(`
176
+ `).map((W)=>Q7(W,X,J)).join(`
177
+ `)}var z7=(Z,X,J,W,$)=>{let G=X,Q=0;for(let Y=J;Y<W;Y++){let z=Z[Y];if(G=G-z.length,Q++,G<=$)break}return{lineCount:G,removals:Q}},S9=(Z)=>{let{cursor:X,options:J,style:W}=Z,$=Z.output??process.stdout,G=_9($),Q=Z.columnPadding??0,Y=Z.rowPadding??4,z=G-Q,H=M9($),K=B.default.dim("..."),U=Z.maxItems??Number.POSITIVE_INFINITY,M=Math.max(H-Y,0),R=Math.max(Math.min(U,M),5),_=0;X>=R-3&&(_=Math.max(Math.min(X-R+3,J.length-R),0));let O=R<J.length&&_>0,I=R<J.length&&_+R<J.length,N=Math.min(_+R,J.length),j=[],A=0;O&&A++,I&&A++;let k=_+(O?1:0),w=N-(I?1:0);for(let F=k;F<w;F++){let T=Y7(W(J[F],F===X),z,{hard:!0,trim:!1}).split(`
178
+ `);j.push(T),A+=T.length}if(A>M){let F=0,T=0,f=A,c=X-k,g=(G3,Q3)=>z7(j,f,G3,Q3,M);O?({lineCount:f,removals:F}=g(0,c),f>M&&({lineCount:f,removals:T}=g(c+1,j.length))):({lineCount:f,removals:T}=g(c+1,j.length),f>M&&({lineCount:f,removals:F}=g(0,c))),F>0&&(O=!0,j.splice(0,F)),T>0&&(I=!0,j.splice(j.length-T,T))}let C=[];O&&C.push(K);for(let F of j)for(let T of F)C.push(T);return I&&C.push(K),C};var b=(Z)=>{let X=Z.active??"Yes",J=Z.inactive??"No";return new D9({active:X,inactive:J,signal:Z.signal,input:Z.input,output:Z.output,initialValue:Z.initialValue??!0,render(){let W=`${B.default.gray(E)}
179
+ ${S1(this.state)} ${Z.message}
180
+ `,$=this.value?X:J;switch(this.state){case"submit":return`${W}${B.default.gray(E)} ${B.default.dim($)}`;case"cancel":return`${W}${B.default.gray(E)} ${B.default.strikethrough(B.default.dim($))}
181
+ ${B.default.gray(E)}`;default:return`${W}${B.default.cyan(E)} ${this.value?`${B.default.green(j9)} ${X}`:`${B.default.dim(W0)} ${B.default.dim(X)}`} ${B.default.dim("/")} ${this.value?`${B.default.dim(W0)} ${B.default.dim(J)}`:`${B.default.green(j9)} ${J}`}
182
+ ${B.default.cyan(l)}
183
+ `}}}).prompt()},s=async(Z,X)=>{let J={},W=Object.keys(Z);for(let $ of W){let G=Z[$],Q=await G({results:J})?.catch((Y)=>{throw Y});if(typeof X?.onCancel=="function"&&L(Q)){J[$]="canceled",X.onCancel({results:J});continue}J[$]=Q}return J};var m={message:(Z=[],{symbol:X=B.default.gray(E),secondarySymbol:J=B.default.gray(E),output:W=process.stdout,spacing:$=1,withGuide:G}={})=>{let Q=[],Y=(G??J1.withGuide)!==!1,z=Y?J:"",H=Y?`${X} `:"",K=Y?`${J} `:"";for(let M=0;M<$;M++)Q.push(z);let U=Array.isArray(Z)?Z:Z.split(`
184
+ `);if(U.length>0){let[M,...R]=U;M.length>0?Q.push(`${H}${M}`):Q.push(Y?X:"");for(let _ of R)_.length>0?Q.push(`${K}${_}`):Q.push(Y?J:"")}W.write(`${Q.join(`
185
+ `)}
186
+ `)},info:(Z,X)=>{m.message(Z,{...X,symbol:B.default.blue(l2)})},success:(Z,X)=>{m.message(Z,{...X,symbol:B.default.green(n2)})},step:(Z,X)=>{m.message(Z,{...X,symbol:B.default.green(x4)})},warn:(Z,X)=>{m.message(Z,{...X,symbol:B.default.yellow(o2)})},warning:(Z,X)=>{m.warn(Z,X)},error:(Z,X)=>{m.message(Z,{...X,symbol:B.default.red(i2)})}},q=(Z="",X)=>{(X?.output??process.stdout).write(`${B.default.gray(l)} ${B.default.red(Z)}
187
+
188
+ `)},V9=(Z="",X)=>{(X?.output??process.stdout).write(`${B.default.gray(p2)} ${Z}
189
+ `)},G0=(Z="",X)=>{(X?.output??process.stdout).write(`${B.default.gray(E)}
190
+ ${B.default.gray(l)} ${Z}
191
+
192
+ `)},R1=(Z,X)=>Z.split(`
193
+ `).map((J)=>X(J)).join(`
194
+ `),g4=(Z)=>{let X=(W,$)=>{let G=W.label??String(W.value);return $==="disabled"?`${B.default.gray(k4)} ${R1(G,(Q)=>B.default.strikethrough(B.default.gray(Q)))}${W.hint?` ${B.default.dim(`(${W.hint??"disabled"})`)}`:""}`:$==="active"?`${B.default.cyan(c2)} ${G}${W.hint?` ${B.default.dim(`(${W.hint})`)}`:""}`:$==="selected"?`${B.default.green(V4)} ${R1(G,B.default.dim)}${W.hint?` ${B.default.dim(`(${W.hint})`)}`:""}`:$==="cancelled"?`${R1(G,(Q)=>B.default.strikethrough(B.default.dim(Q)))}`:$==="active-selected"?`${B.default.green(V4)} ${G}${W.hint?` ${B.default.dim(`(${W.hint})`)}`:""}`:$==="submitted"?`${R1(G,B.default.dim)}`:`${B.default.dim(k4)} ${R1(G,B.default.dim)}`},J=Z.required??!0;return new F9({options:Z.options,signal:Z.signal,input:Z.input,output:Z.output,initialValues:Z.initialValues,required:J,cursorAt:Z.cursorAt,validate(W){if(J&&(W===void 0||W.length===0))return`Please select at least one option.
195
+ ${B.default.reset(B.default.dim(`Press ${B.default.gray(B.default.bgWhite(B.default.inverse(" space ")))} to select, ${B.default.gray(B.default.bgWhite(B.default.inverse(" enter ")))} to submit`))}`},render(){let W=Q1(Z.output,Z.message,`${b4(this.state)} `,`${S1(this.state)} `),$=`${B.default.gray(E)}
196
+ ${W}
197
+ `,G=this.value??[],Q=(Y,z)=>{if(Y.disabled)return X(Y,"disabled");let H=G.includes(Y.value);return z&&H?X(Y,"active-selected"):H?X(Y,"selected"):X(Y,z?"active":"inactive")};switch(this.state){case"submit":{let Y=this.options.filter(({value:H})=>G.includes(H)).map((H)=>X(H,"submitted")).join(B.default.dim(", "))||B.default.dim("none"),z=Q1(Z.output,Y,`${B.default.gray(E)} `);return`${$}${z}`}case"cancel":{let Y=this.options.filter(({value:H})=>G.includes(H)).map((H)=>X(H,"cancelled")).join(B.default.dim(", "));if(Y.trim()==="")return`${$}${B.default.gray(E)}`;let z=Q1(Z.output,Y,`${B.default.gray(E)} `);return`${$}${z}
198
+ ${B.default.gray(E)}`}case"error":{let Y=`${B.default.yellow(E)} `,z=this.error.split(`
199
+ `).map((U,M)=>M===0?`${B.default.yellow(l)} ${B.default.yellow(U)}`:` ${U}`).join(`
200
+ `),H=$.split(`
201
+ `).length,K=z.split(`
202
+ `).length+1;return`${$}${Y}${S9({output:Z.output,options:this.options,cursor:this.cursor,maxItems:Z.maxItems,columnPadding:Y.length,rowPadding:H+K,style:Q}).join(`
203
+ ${Y}`)}
204
+ ${z}
205
+ `}default:{let Y=`${B.default.cyan(E)} `,z=$.split(`
206
+ `).length;return`${$}${Y}${S9({output:Z.output,options:this.options,cursor:this.cursor,maxItems:Z.maxItems,columnPadding:Y.length,rowPadding:z+2,style:Q}).join(`
207
+ ${Y}`)}
208
+ ${B.default.cyan(l)}
209
+ `}}}}).prompt()};var d4=(Z)=>new A4({validate:Z.validate,mask:Z.mask??u2,signal:Z.signal,input:Z.input,output:Z.output,render(){let X=`${B.default.gray(E)}
210
+ ${S1(this.state)} ${Z.message}
211
+ `,J=this.userInputWithCursor,W=this.masked;switch(this.state){case"error":{let $=W?` ${W}`:"";return Z.clearOnError&&this.clear(),`${X.trim()}
212
+ ${B.default.yellow(E)}${$}
213
+ ${B.default.yellow(l)} ${B.default.yellow(this.error)}
214
+ `}case"submit":{let $=W?` ${B.default.dim(W)}`:"";return`${X}${B.default.gray(E)}${$}`}case"cancel":{let $=W?` ${B.default.strikethrough(B.default.dim(W))}`:"";return`${X}${B.default.gray(E)}${$}${W?`
215
+ ${B.default.gray(E)}`:""}`}default:return`${X}${B.default.cyan(E)} ${J}
216
+ ${B.default.cyan(l)}
217
+ `}}}).prompt();var N8=B.default.magenta;var L8={light:V("\u2500","-"),heavy:V("\u2501","="),block:V("\u2588","#")};var J0=(Z,X)=>Z.includes(`
218
+ `)?Z.split(`
219
+ `).map((J)=>X(J)).join(`
220
+ `):X(Z),t=(Z)=>{let X=(J,W)=>{let $=J.label??String(J.value);switch(W){case"disabled":return`${B.default.gray(W0)} ${J0($,B.default.gray)}${J.hint?` ${B.default.dim(`(${J.hint??"disabled"})`)}`:""}`;case"selected":return`${J0($,B.default.dim)}`;case"active":return`${B.default.green(j9)} ${$}${J.hint?` ${B.default.dim(`(${J.hint})`)}`:""}`;case"cancelled":return`${J0($,(G)=>B.default.strikethrough(B.default.dim(G)))}`;default:return`${B.default.dim(W0)} ${J0($,B.default.dim)}`}};return new T9({options:Z.options,signal:Z.signal,input:Z.input,output:Z.output,initialValue:Z.initialValue,render(){let J=`${S1(this.state)} `,W=`${b4(this.state)} `,$=Q1(Z.output,Z.message,W,J),G=`${B.default.gray(E)}
221
+ ${$}
222
+ `;switch(this.state){case"submit":{let Q=`${B.default.gray(E)} `,Y=Q1(Z.output,X(this.options[this.cursor],"selected"),Q);return`${G}${Y}`}case"cancel":{let Q=`${B.default.gray(E)} `,Y=Q1(Z.output,X(this.options[this.cursor],"cancelled"),Q);return`${G}${Y}
223
+ ${B.default.gray(E)}`}default:{let Q=`${B.default.cyan(E)} `,Y=G.split(`
224
+ `).length;return`${G}${Q}${S9({output:Z.output,cursor:this.cursor,options:this.options,maxItems:Z.maxItems,columnPadding:Q.length,rowPadding:Y+2,style:(z,H)=>X(z,z.disabled?"disabled":H?"active":"inactive")}).join(`
225
+ ${Q}`)}
226
+ ${B.default.cyan(l)}
227
+ `}}}}).prompt()};var R8=`${B.default.gray(E)} `;var P=(Z)=>new I9({validate:Z.validate,placeholder:Z.placeholder,defaultValue:Z.defaultValue,initialValue:Z.initialValue,output:Z.output,signal:Z.signal,input:Z.input,render(){let X=(Z?.withGuide??J1.withGuide)!==!1,J=`${`${X?`${B.default.gray(E)}
228
+ `:""}${S1(this.state)} `}${Z.message}
229
+ `,W=Z.placeholder?B.default.inverse(Z.placeholder[0])+B.default.dim(Z.placeholder.slice(1)):B.default.inverse(B.default.hidden("_")),$=this.userInput?this.userInputWithCursor:W,G=this.value??"";switch(this.state){case"error":{let Q=this.error?` ${B.default.yellow(this.error)}`:"",Y=X?`${B.default.yellow(E)} `:"",z=X?B.default.yellow(l):"";return`${J.trim()}
230
+ ${Y}${$}
231
+ ${z}${Q}
232
+ `}case"submit":{let Q=G?` ${B.default.dim(G)}`:"",Y=X?B.default.gray(E):"";return`${J}${Y}${Q}`}case"cancel":{let Q=G?` ${B.default.strikethrough(B.default.dim(G))}`:"",Y=X?B.default.gray(E):"";return`${J}${Y}${Q}${G.trim()?`
233
+ ${Y}`:""}`}default:{let Q=X?`${B.default.cyan(E)} `:"",Y=X?B.default.cyan(l):"";return`${J}${Q}${$}
234
+ ${Y}
235
+ `}}}}).prompt();async function p4(Z){let X=await y.parseFile(Z),J;if(X.request)J=X.request;else if(X.requests&&X.requests.length>0)J=X.requests[0];else if(X.collection?.requests&&X.collection.requests.length>0)J=X.collection.requests[0];if(!J)throw Error("No request found in YAML file");return H7(J)}function H7(Z){let X={url:Z.url,method:Z.method||"GET"};if(Z.name)X.name=Z.name;if(Z.headers&&Object.keys(Z.headers).length>0)X.headers=Z.headers;if(Z.params&&Object.keys(Z.params).length>0)X.params=Z.params;if(Z.body!==void 0)if(typeof Z.body==="object"&&Z.body!==null)X.bodyType="json",X.body=Z.body;else X.bodyType="raw",X.body=Z.body;else if(Z.formData)X.bodyType="form",X.formData=Z.formData;else X.bodyType="none";if(Z.auth){if(Z.auth.type==="bearer")X.authType="bearer",X.token=Z.auth.token;else if(Z.auth.type==="basic")X.authType="basic",X.username=Z.auth.username,X.password=Z.auth.password}else X.authType="none";if(Z.timeout)X.timeout=Z.timeout;if(Z.followRedirects!==void 0)X.followRedirects=Z.followRedirects;if(Z.maxRedirects)X.maxRedirects=Z.maxRedirects;if(Z.insecure)X.insecure=Z.insecure;if(Z.http2)X.http2=Z.http2;if(Z.retry)X.retryEnabled=!0,X.retryCount=Z.retry.count,X.retryDelay=Z.retry.delay,X.retryBackoff=Z.retry.backoff;if(Z.expect){if(Z.expect.status)X.expectStatus=Z.expect.status;if(Z.expect.responseTime)X.expectResponseTime=Z.expect.responseTime}if(Z.output)X.outputFile=Z.output;return X}async function c4(Z){try{return await Bun.file(Z).exists()}catch{return!1}}var u4={"basic-get":{name:"Basic GET Request",description:"Simple GET request to fetch data",defaults:{method:"GET",followRedirects:!0}},"basic-post":{name:"Basic POST Request",description:"POST request with JSON body",defaults:{method:"POST",bodyType:"json",headers:{"Content-Type":"application/json"}}},"api-test":{name:"API Test",description:"Request with validation and response time check",defaults:{method:"GET",expectStatus:200,expectResponseTime:"< 2000",verbose:!0,showHeaders:!0}},"file-upload":{name:"File Upload",description:"Multipart form upload request",defaults:{method:"POST",bodyType:"form"}},"auth-flow":{name:"Auth Flow",description:"Request with authentication",defaults:{method:"POST",authType:"bearer",headers:{"Content-Type":"application/json"}}}};function l4(Z){return u4[Z]}function n4(){return Object.entries(u4).map(([Z,X])=>({value:Z,label:X.name,hint:X.description}))}var K7=["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"];async function o4(){let Z=[{value:"blank",label:"Blank",hint:"Start from scratch"},...n4()];return t({message:"Start from a template?",options:Z})}async function i4(Z){return await s({url:()=>P({message:"Request URL",placeholder:"https://api.example.com/endpoint",initialValue:Z?.url||"",validate:(J)=>{if(!J)return"URL is required";try{new URL(J)}catch{return"Invalid URL format"}}}),method:()=>t({message:"HTTP method",initialValue:Z?.method||"GET",options:K7.map((J)=>({value:J,label:J}))}),name:()=>P({message:"Request name (optional)",placeholder:"My API Request",initialValue:Z?.name||""})},{onCancel:()=>{q("Wizard cancelled"),process.exit(0)}})}async function a4(Z){let X=await b({message:"Add headers?",initialValue:Z?Object.keys(Z).length>0:!1});if(L(X)||!X)return L(X)?X:Z;let J={...Z},W=!0,$=await g4({message:"Add common headers (space to select)",options:[{value:"content-type-json",label:"Content-Type: application/json"},{value:"accept-json",label:"Accept: application/json"},{value:"user-agent",label:"User-Agent: curl-runner"}],required:!1});if(L($))return $;if(Array.isArray($))for(let G of $){if(G==="content-type-json")J["Content-Type"]="application/json";if(G==="accept-json")J.Accept="application/json";if(G==="user-agent")J["User-Agent"]="curl-runner"}while(W){let G=await b({message:"Add custom header?",initialValue:!1});if(L(G))return G;if(!G)break;let Q=await s({key:()=>P({message:"Header name",placeholder:"X-Custom-Header",validate:(Y)=>!Y?"Header name required":void 0}),value:()=>P({message:"Header value",placeholder:"value",validate:(Y)=>!Y?"Header value required":void 0})});if(Q.key&&Q.value)J[Q.key]=Q.value;W=!0}return Object.keys(J).length>0?J:void 0}async function r4(Z){let X=await t({message:"Request body type",initialValue:Z?.bodyType||"none",options:[{value:"none",label:"None",hint:"No request body"},{value:"json",label:"JSON",hint:"JSON object"},{value:"form",label:"Form Data",hint:"Multipart form / file upload"},{value:"raw",label:"Raw",hint:"Plain text or other"}]});if(L(X))return X;if(X==="none")return{bodyType:"none"};if(X==="json"){let W=await P({message:"JSON body (or press enter for interactive)",placeholder:'{"key": "value"}',initialValue:Z?.body?JSON.stringify(Z.body):""});if(L(W))return W;if(W)try{return{bodyType:"json",body:JSON.parse(W)}}catch{return m.warn("Invalid JSON, storing as raw string"),{bodyType:"raw",body:W}}let $={},G=!0;while(G){let Q=await s({key:()=>P({message:"Field name",placeholder:"key"}),value:()=>P({message:"Field value",placeholder:"value"}),type:()=>t({message:"Value type",options:[{value:"string",label:"String"},{value:"number",label:"Number"},{value:"boolean",label:"Boolean"}]})});if(Q.key)if(Q.type==="number")$[Q.key]=Number(Q.value);else if(Q.type==="boolean")$[Q.key]=Q.value==="true";else $[Q.key]=Q.value;let Y=await b({message:"Add another field?",initialValue:!1});if(L(Y))return Y;G=Y}return{bodyType:"json",body:$}}if(X==="form"){let W={},$=!0;while($){let G=await t({message:"Field type",options:[{value:"text",label:"Text field"},{value:"file",label:"File upload"}]});if(L(G))return G;let Q=await P({message:"Field name",placeholder:G==="file"?"file":"field",validate:(z)=>!z?"Field name required":void 0});if(L(Q))return Q;if(G==="file"){let z=await P({message:"File path",placeholder:"./upload.txt",validate:(H)=>!H?"File path required":void 0});if(L(z))return z;W[Q]={file:z}}else{let z=await P({message:"Field value",placeholder:"value"});if(L(z))return z;W[Q]=z}let Y=await b({message:"Add another field?",initialValue:!1});if(L(Y))return Y;$=Y}return{bodyType:"form",formData:W}}let J=await P({message:"Raw body content",placeholder:"Your content here",initialValue:Z?.body||""});if(L(J))return J;return{bodyType:"raw",body:J}}async function s4(Z){let X=await t({message:"Authentication",initialValue:Z?.authType||"none",options:[{value:"none",label:"None"},{value:"bearer",label:"Bearer Token",hint:"Authorization: Bearer <token>"},{value:"basic",label:"Basic Auth",hint:"Username/password"}]});if(L(X))return X;if(X==="none")return{authType:"none"};if(X==="bearer"){let W=await P({message:"Bearer token",placeholder:"your-token-here",initialValue:Z?.token||"",validate:($)=>!$?"Token required":void 0});if(L(W))return W;return{authType:"bearer",token:W}}let J=await s({username:()=>P({message:"Username",initialValue:Z?.username||"",validate:(W)=>!W?"Username required":void 0}),password:()=>d4({message:"Password",validate:(W)=>!W?"Password required":void 0})});if(L(J.username)||L(J.password))return Symbol("cancel");return{authType:"basic",username:J.username,password:J.password}}async function t4(Z){let X=await b({message:"Configure advanced options?",initialValue:!1});if(L(X)||!X)return L(X)?X:{};let J=await s({timeout:()=>P({message:"Timeout (ms)",placeholder:"30000",initialValue:Z?.timeout?.toString()||"",validate:($)=>{if(!$)return;let G=Number($);if(Number.isNaN(G)||G<0)return"Must be a positive number"}}),followRedirects:()=>b({message:"Follow redirects?",initialValue:Z?.followRedirects??!0}),insecure:()=>b({message:"Skip SSL verification? (insecure)",initialValue:Z?.insecure??!1}),http2:()=>b({message:"Use HTTP/2?",initialValue:Z?.http2??!1})}),W={};if(J.timeout)W.timeout=Number(J.timeout);if(J.followRedirects===!1)W.followRedirects=!1;if(J.insecure)W.insecure=!0;if(J.http2)W.http2=!0;return W}async function e4(Z){let X=await b({message:"Configure retry strategy?",initialValue:Z?.retryEnabled??!1});if(L(X)||!X)return L(X)?X:{};let J=await s({count:()=>P({message:"Max retry attempts",placeholder:"3",initialValue:Z?.retryCount?.toString()||"3",validate:(W)=>{let $=Number(W);if(Number.isNaN($)||$<1)return"Must be at least 1"}}),delay:()=>P({message:"Retry delay (ms)",placeholder:"1000",initialValue:Z?.retryDelay?.toString()||"1000",validate:(W)=>{if(!W)return;let $=Number(W);if(Number.isNaN($)||$<0)return"Must be a positive number"}}),backoff:()=>P({message:"Backoff multiplier",placeholder:"2 (exponential)",initialValue:Z?.retryBackoff?.toString()||"",validate:(W)=>{if(!W)return;let $=Number(W);if(Number.isNaN($)||$<1)return"Must be at least 1"}})});return{retryEnabled:!0,retryCount:Number(J.count),retryDelay:J.delay?Number(J.delay):void 0,retryBackoff:J.backoff?Number(J.backoff):void 0}}async function Z3(Z){let X=await b({message:"Add response validation?",initialValue:!!(Z?.expectStatus||Z?.expectResponseTime)});if(L(X)||!X)return L(X)?X:{};let J=await s({status:()=>P({message:"Expected status code(s)",placeholder:"200 or 200,201",initialValue:Z?.expectStatus?Array.isArray(Z.expectStatus)?Z.expectStatus.join(","):String(Z.expectStatus):""}),responseTime:()=>P({message:"Response time constraint",placeholder:"< 2000 (ms)",initialValue:Z?.expectResponseTime||""})}),W={};if(J.status){let $=J.status.split(",").map((G)=>Number(G.trim()));W.expectStatus=$.length===1?$[0]:$}if(J.responseTime)W.expectResponseTime=J.responseTime;return W}async function X3(Z){return await s({outputPath:()=>P({message:"Save to file",placeholder:"api-request.yaml",initialValue:Z?.outputFile||"request.yaml",validate:(J)=>{if(!J)return"File path required";if(!J.endsWith(".yaml")&&!J.endsWith(".yml"))return"File must end with .yaml or .yml"}}),runAfter:()=>b({message:"Run request after creating?",initialValue:!0})})}function B7(Z){let X={url:Z.url};if(Z.name)X.name=Z.name;if(Z.method&&Z.method!=="GET")X.method=Z.method;if(Z.headers&&Object.keys(Z.headers).length>0)X.headers=Z.headers;if(Z.params&&Object.keys(Z.params).length>0)X.params=Z.params;if(Z.bodyType==="json"&&Z.body)X.body=Z.body;else if(Z.bodyType==="form"&&Z.formData)X.formData=Z.formData;else if(Z.bodyType==="raw"&&Z.body)X.body=Z.body;if(Z.authType==="basic"&&Z.username)X.auth={type:"basic",username:Z.username,password:Z.password||""};else if(Z.authType==="bearer"&&Z.token)X.auth={type:"bearer",token:Z.token};if(Z.timeout)X.timeout=Z.timeout;if(Z.followRedirects===!1)X.followRedirects=!1;if(Z.maxRedirects)X.maxRedirects=Z.maxRedirects;if(Z.insecure)X.insecure=!0;if(Z.http2)X.http2=!0;if(Z.retryEnabled&&Z.retryCount){if(X.retry={count:Z.retryCount},Z.retryDelay)X.retry.delay=Z.retryDelay;if(Z.retryBackoff)X.retry.backoff=Z.retryBackoff}if(Z.expectStatus||Z.expectResponseTime){if(X.expect={},Z.expectStatus)X.expect.status=Z.expectStatus;if(Z.expectResponseTime)X.expect.responseTime=Z.expectResponseTime}if(Z.outputFile)X.output=Z.outputFile;return X}function k9(Z){return{request:B7(Z)}}function P9(Z){return E1(Z)}function E1(Z,X=0){let J=" ".repeat(X);if(Z===null||Z===void 0)return"null";if(typeof Z==="string"){if(Z.includes(":")||Z.includes("#")||Z.includes(`
236
+ `)||Z.startsWith(" ")||Z.endsWith(" ")||/^[0-9]/.test(Z)||["true","false","null","yes","no"].includes(Z.toLowerCase()))return JSON.stringify(Z);return Z}if(typeof Z==="number"||typeof Z==="boolean")return String(Z);if(Array.isArray(Z)){if(Z.length===0)return"[]";if(Z.every((W)=>typeof W!=="object"||W===null))return`[${Z.map((W)=>E1(W,0)).join(", ")}]`;return Z.map((W)=>`${J}- ${E1(W,X+1).trimStart()}`).join(`
237
+ `)}if(typeof Z==="object"){let W=Object.entries(Z);if(W.length===0)return"{}";let $=[];for(let[G,Q]of W){if(Q===void 0)continue;if(typeof Q==="object"&&Q!==null&&!Array.isArray(Q)){$.push(`${J}${G}:`);let Y=E1(Q,X+1);$.push(Y)}else{let Y=E1(Q,X+1);if(Y.includes(`
238
+ `))$.push(`${J}${G}:`),$.push(Y);else $.push(`${J}${G}: ${Y}`)}}return $.join(`
239
+ `)}return String(Z)}async function C9(Z={}){V9(`curl-runner wizard v${n()}`);let X;if(Z.editFile){if(!await c4(Z.editFile))q(`File not found: ${Z.editFile}`),process.exit(1);m.info(`Editing: ${Z.editFile}`);let Q=await p4(Z.editFile);X=await J3(Q),Z.outputPath=Z.outputPath||Z.editFile}else{let Q=await o4();if(L(Q))q("Wizard cancelled"),process.exit(0);let Y=Q==="blank"?void 0:l4(Q).defaults;X=await J3(Y)}let J=await X3({outputFile:Z.outputPath});if(L(J))q("Wizard cancelled"),process.exit(0);let W=k9(X),$=P9(W);m.step("Preview:"),console.log(),console.log($),console.log();let G=await b({message:`Save to ${J.outputPath}?`,initialValue:!0});if(L(G)||!G)q("Wizard cancelled"),process.exit(0);if(await Bun.write(J.outputPath,$),m.success(`Saved to ${J.outputPath}`),J.runAfter)m.step("Running request..."),console.log(),await Bun.spawn(["bun","run",process.argv[1],J.outputPath],{stdout:"inherit",stderr:"inherit"}).exited;G0("Done!")}async function J3(Z){let X=await i4(Z);if(L(X))q("Wizard cancelled"),process.exit(0);let J={...Z,...X},W=await a4(Z?.headers);if(L(W))q("Wizard cancelled"),process.exit(0);if(W)J.headers=W;if(!["GET","HEAD","OPTIONS"].includes(J.method)){let z=await r4(Z);if(L(z))q("Wizard cancelled"),process.exit(0);J={...J,...z}}let $=await s4(Z);if(L($))q("Wizard cancelled"),process.exit(0);J={...J,...$};let G=await t4(Z);if(L(G))q("Wizard cancelled"),process.exit(0);J={...J,...G};let Q=await e4(Z);if(L(Q))q("Wizard cancelled"),process.exit(0);J={...J,...Q};let Y=await Z3(Z);if(L(Y))q("Wizard cancelled"),process.exit(0);return J={...J,...Y},J}async function W3(Z){V9("curl-runner quick init");let X=Z||await P({message:"Request URL",placeholder:"https://api.example.com/endpoint",validate:(Y)=>{if(!Y)return"URL is required";try{new URL(Y)}catch{return"Invalid URL format"}}});if(L(X))q("Cancelled"),process.exit(0);let J=await t({message:"HTTP method",initialValue:"GET",options:[{value:"GET",label:"GET"},{value:"POST",label:"POST"},{value:"PUT",label:"PUT"},{value:"DELETE",label:"DELETE"}]});if(L(J))q("Cancelled"),process.exit(0);let W=await P({message:"Save to",placeholder:"request.yaml",initialValue:"request.yaml",validate:(Y)=>{if(!Y)return"Filename required";if(!Y.endsWith(".yaml")&&!Y.endsWith(".yml"))return"Must end with .yaml or .yml"}});if(L(W))q("Cancelled"),process.exit(0);let $=k9({url:X,method:J}),G=P9($);await Bun.write(W,G),m.success(`Created ${W}`);let Q=await b({message:"Run now?",initialValue:!0});if(L(Q)){G0("Done!");return}if(Q)console.log(),await Bun.spawn(["bun","run",process.argv[1],W],{stdout:"inherit",stderr:"inherit"}).exited;G0("Done!")}class $3{logger=new a;async run(Z){try{let X=await x0(Z,{onInfo:(Q)=>this.logger.logInfo(Q),onWarning:(Q)=>this.logger.logWarning(Q)}),{config:J,cliOptions:W,mode:$,rawArgs:G}=X;if($!=="version"&&$!=="help")new X9().checkForUpdates().catch(()=>{});switch($){case"help":this.showHelp();return;case"version":console.log(`curl-runner v${n()}`);return;case"upgrade":if(G.includes("--help")||G.includes("-h")){m9();return}await new Y0().run(G.slice(1));return;case"validate":if(G.includes("--help")||G.includes("-h")){n9();return}await new _0().run(G.slice(1));return;case"diff-subcommand":await this.executeDiffSubcommand(G.slice(1),W);return;case"convert":await this.executeConvert(G);return;case"init":await this.executeInit(G);return;case"edit":await this.executeEdit(G);return;case"profile":case"watch":case"normal":await this.executeMain(W,J,$);return}}catch(X){this.logger.logError(X instanceof Error?X.message:String(X)),process.exit(1)}}async executeMain(Z,X,J){let W=await this.findYamlFiles(Z.files,Z.all);if(W.length===0)this.logger.logError("No YAML files found"),process.exit(1);this.logger.logInfo(`Found ${W.length} YAML file(s)`);let $=[],G=X;for(let Q of W){this.logger.logInfo(`Processing: ${Q}`);let{requests:Y,config:z}=await this.processYamlFile(Q),H=z?.output||{},K=Y.map((U)=>({...U,sourceOutputConfig:H,sourceFile:Q}));if(z)G=x1(G,z);$.push(...K)}if($.length===0)this.logger.logError("No requests found in YAML files"),process.exit(1);if(J==="profile"){let Q=b0(Z,G);await this.executeProfileMode($,G,Q)}else if(J==="watch"){let Q=y0(Z,G);await new J9({files:W,config:Q,logger:this.logger,onRun:async()=>{await this.executeRequests(W,G)}}).start()}else{let Q=await this.executeRequests(W,G),Y=this.determineExitCode(Q,G);process.exit(Y)}}async executeProfileMode(Z,X,J){let $=await new u0(X,J).profileRequests(Z);if(this.logger.logProfileSummary($),J.exportFile){let Y=[],z=J.exportFile.endsWith(".csv");for(let K of $){let U=K.request.name||K.request.url;Y.push(z?Z4(K.stats,U):X4(K.stats,U))}let H=z?Y.join(`
240
+
241
+ `):`[${Y.join(`,
242
+ `)}]`;await Bun.write(J.exportFile,H),this.logger.logInfo(`Profile results exported to ${J.exportFile}`)}let G=$.reduce((Y,z)=>Y+z.stats.failures,0),Q=$.reduce((Y,z)=>Y+z.stats.iterations+z.stats.warmup,0);process.exit(G>0&&G/Q>0.5?1:0)}async executeRequests(Z,X){let J=[],W=[];for(let Q of Z){let{requests:Y,config:z}=await this.processYamlFile(Q),H=z?.output||{},K=Y.map((U)=>({...U,sourceOutputConfig:H,sourceFile:Q}));J.push({file:Q,requests:K,config:z}),W.push(...K)}let $=new Z9(X),G;if(J.length>1){let Q=[],Y=0;for(let U=0;U<J.length;U++){let M=J[U];this.logger.logFileHeader(M.file,M.requests.length);let R=await $.execute(M.requests);if(Q.push(...R.results),Y+=R.duration,U<J.length-1)console.log()}let z=Q.filter((U)=>U.success&&!U.skipped).length,H=Q.filter((U)=>!U.success&&!U.skipped).length,K=Q.filter((U)=>U.skipped).length;G={total:Q.length,successful:z,failed:H,skipped:K,duration:Y,results:Q},this.logger.logSummary(G,!0)}else G=await $.execute(W);if(X.diff?.enabled||X.diff?.save||X.diff?.compareWith)await this.handleDiffMode(Z[0],G.results,X.diff);return G}async handleDiffMode(Z,X,J){let W=new D1(J),$=new M1(J.outputFormat||"terminal"),G=z1.mergeConfig(J,!0)||{},Q=J.label||"current",Y=J.compareWith;if(J.save)await W.saveBaseline(Z,Q,X,G),this.logger.logInfo(`Baseline saved as '${Q}'`);if(Y){let z=await W.compareWithBaseline(Z,X,Q,Y,G);if(z.newBaselines===z.totalRequests){this.logger.logWarning(`No baseline '${Y}' found. Saving current run as baseline.`),await W.saveBaseline(Z,Y,X,G);return}if(console.log($.formatSummary(z,Y,Q)),J.save)await W.saveBaseline(Z,Q,X,G)}else if(J.enabled&&!J.save){let z=await W.listLabels(Z);if(z.length===0)await W.saveBaseline(Z,"baseline",X,G),this.logger.logInfo("No baselines found. Saved current run as 'baseline'.");else if(z.length===1){let H=await W.compareWithBaseline(Z,X,Q,z[0],G);console.log($.formatSummary(H,z[0],Q))}else this.logger.logInfo(`Available baselines: ${z.join(", ")}`),this.logger.logInfo("Use --diff-compare <label> to compare against a specific baseline.")}}async executeConvert(Z){if(Z.includes("--help")||Z.includes("-h")){this.showConvertHelp();return}let X=j0(Z);if(!X)this.showConvertHelp(),process.exit(1);let J;switch(X.subcommand){case"curl":J=N0(X.input,X.options);break;case"file":J=await L0(X.input,X.options);break;case"yaml":J=await R0(X.input,X.options);break}if(X.options.debug&&J.debug)console.log(this.logger.color("DEBUG:","yellow")),console.log(JSON.stringify(J.debug,null,2)),console.log();if(J.warnings.length>0&&!X.options.output)for(let W of J.warnings)this.logger.logWarning(W);if(X.options.output)await Bun.write(X.options.output,J.output),this.logger.logInfo(`Written to ${X.options.output}`);else console.log(J.output)}async executeInit(Z){let X=A0(Z);if(Z.includes("--help")||Z.includes("-h")){this.showInitHelp();return}if(X.wizard)await C9({outputPath:X.outputPath});else await W3(X.url)}async executeEdit(Z){let X=V0(Z);if(Z.includes("--help")||Z.includes("-h")){this.showEditHelp();return}if(!X.file)this.logger.logError("Usage: curl-runner edit <file.yaml>"),process.exit(1);await C9({editFile:X.file,outputPath:X.outputPath})}async executeDiffSubcommand(Z,X){let J=Z[0],W=Z[1],$=Z[2];if(!$){let H=await this.findYamlFiles([],X.all);if(H.length===0)this.logger.logError("No YAML files found. Specify a file: curl-runner diff <label1> <label2> <file.yaml>"),process.exit(1);if(H.length>1)this.logger.logError("Multiple YAML files found. Specify which file to use."),process.exit(1);$=H[0]}let G={dir:X.diffDir||"__baselines__",outputFormat:X.diffOutput||"terminal"},Q=new D1(G),Y=new M1(G.outputFormat||"terminal"),z={exclude:[],match:{}};try{let H=await Q.compareTwoBaselines($,J,W,z);console.log(Y.formatSummary(H,J,W)),process.exit(H.changed>0?1:0)}catch(H){this.logger.logError(H instanceof Error?H.message:String(H)),process.exit(1)}}async findYamlFiles(Z,X){let J=new Set,W=[];if(Z.length===0)W=X?["**/*.yaml","**/*.yml"]:["*.yaml","*.yml"];else for(let $ of Z)try{let Q=await(await import("fs/promises")).stat($);if(Q.isDirectory()){if(W.push(`${$}/*.yaml`,`${$}/*.yml`),X)W.push(`${$}/**/*.yaml`,`${$}/**/*.yml`)}else if(Q.isFile())W.push($)}catch{W.push($)}for(let $ of W){let G=new U7($);for await(let Q of G.scan("."))if(Q.endsWith(".yaml")||Q.endsWith(".yml"))J.add(Q)}return Array.from(J).sort()}async processYamlFile(Z){let X=await y.parseFile(Z),J=[],W;if(X.global)W=X.global;let $={...X.global?.variables,...X.collection?.variables},G={...X.global?.defaults,...X.collection?.defaults};if(X.request)J.push(this.prepareRequest(X.request,$,G));if(X.requests)for(let Q of X.requests)J.push(this.prepareRequest(Q,$,G));if(X.collection?.requests)for(let Q of X.collection.requests)J.push(this.prepareRequest(Q,$,G));return{requests:J,config:W}}prepareRequest(Z,X,J){let W=y.interpolateVariables(Z,X);return y.mergeConfigs(J,W)}determineExitCode(Z,X){let{failed:J,total:W}=Z,$=X.ci;if(J===0)return 0;if($){if($.strictExit)return 1;if($.failOn!==void 0&&J>$.failOn)return 1;if($.failOnPercentage!==void 0&&W>0){if(J/W*100>$.failOnPercentage)return 1}if($.failOn!==void 0||$.failOnPercentage!==void 0)return 0}return!X.continueOnError?1:0}showInitHelp(){console.log(`
243
+ ${this.logger.color("\uD83D\uDE80 CURL RUNNER - INIT","bright")}
244
+
245
+ ${this.logger.color("USAGE:","yellow")}
246
+ curl-runner init [url] [options]
247
+
248
+ ${this.logger.color("OPTIONS:","yellow")}
249
+ -w, --wizard Launch full interactive wizard
250
+ -o, --output <file> Output file path (default: request.yaml)
251
+ -h, --help Show this help
252
+
253
+ ${this.logger.color("EXAMPLES:","yellow")}
254
+ # Quick init with prompts
255
+ curl-runner init
256
+
257
+ # Quick init with URL
258
+ curl-runner init https://api.example.com/users
259
+
260
+ # Full wizard mode
261
+ curl-runner init --wizard
262
+
263
+ # Wizard with custom output
264
+ curl-runner init -w -o api-test.yaml
265
+ `)}showEditHelp(){console.log(`
266
+ ${this.logger.color("\uD83D\uDE80 CURL RUNNER - EDIT","bright")}
267
+
268
+ ${this.logger.color("USAGE:","yellow")}
269
+ curl-runner edit <file.yaml> [options]
270
+
271
+ ${this.logger.color("OPTIONS:","yellow")}
272
+ -o, --output <file> Save to different file (default: overwrite original)
273
+ -h, --help Show this help
274
+
275
+ ${this.logger.color("EXAMPLES:","yellow")}
276
+ # Edit existing file
277
+ curl-runner edit api-test.yaml
278
+
279
+ # Edit and save to new file
280
+ curl-runner edit api-test.yaml -o api-test-v2.yaml
281
+ `)}showConvertHelp(){console.log(`
282
+ ${this.logger.color("CURL RUNNER - CONVERT","bright")}
283
+
284
+ ${this.logger.color("USAGE:","yellow")}
285
+ curl-runner convert curl "<curl command>" Convert curl \u2192 YAML
286
+ curl-runner convert file <script.sh> Convert shell script \u2192 YAML
287
+ curl-runner convert yaml <test.yaml> Convert YAML \u2192 curl
288
+
289
+ ${this.logger.color("OPTIONS:","yellow")}
290
+ -o, --output <file> Write output to file
291
+ --pretty Pretty-print output (default for YAML)
292
+ --loss-report Show warnings for unsupported features (default)
293
+ --debug Show token stream, AST, and IR
294
+ -h, --help Show this help
295
+
296
+ ${this.logger.color("EXAMPLES:","yellow")}
297
+ # Convert inline curl to YAML
298
+ curl-runner convert curl "curl -X POST https://api.example.com -d '{"name":"Alex"}'"
299
+
300
+ # Convert and save to file
301
+ curl-runner convert curl "curl https://api.example.com" -o test.yaml
302
+
303
+ # Convert shell script (batch)
304
+ curl-runner convert file scripts/api-tests.sh
305
+
306
+ # Convert YAML back to curl
307
+ curl-runner convert yaml test.yaml
308
+
309
+ # Debug mode
310
+ curl-runner convert curl "curl https://example.com" --debug
311
+ `)}showHelp(){console.log(`
312
+ ${this.logger.color("\uD83D\uDE80 CURL RUNNER","bright")}
313
+
314
+ ${this.logger.color("USAGE:","yellow")}
315
+ curl-runner [files...] [options]
316
+
317
+ ${this.logger.color("OPTIONS:","yellow")}
318
+ -h, --help Show this help message
319
+ -n, --dry-run Show curl commands without executing
320
+ --http2 Use HTTP/2 protocol with multiplexing
321
+ --connection-pool Enable TCP connection pooling with HTTP/2 multiplexing
322
+ --max-streams <n> Max concurrent streams per host (default: 10)
323
+ --keepalive-time <sec> TCP keepalive time in seconds (default: 60)
324
+ --connect-timeout <sec> Connection timeout in seconds (default: 30)
325
+ -v, --verbose Enable verbose output
326
+ -q, --quiet Suppress non-error output
327
+ -p, --execution parallel Execute requests in parallel
328
+ --max-concurrent <n> Limit concurrent requests in parallel mode
329
+ -c, --continue-on-error Continue execution on errors
330
+ -o, --output <file> Save results to file
331
+ --all Find all YAML files recursively
332
+ --timeout <ms> Set request timeout in milliseconds
333
+ --retries <count> Set maximum retry attempts
334
+ --retry-delay <ms> Set delay between retries in milliseconds
335
+ --no-retry Disable retry mechanism
336
+ --output-format <format> Set output format (json|pretty|raw)
337
+ --pretty-level <level> Set pretty format level (minimal|standard|detailed)
338
+ --show-headers Include response headers in output
339
+ --show-body Include response body in output
340
+ --show-metrics Include performance metrics in output
341
+ --version Show version
342
+
343
+ ${this.logger.color("WATCH MODE:","yellow")}
344
+ -w, --watch Watch files and re-run on changes
345
+ --watch-debounce <ms> Debounce delay for watch mode (default: 300)
346
+ --no-watch-clear Don't clear screen between watch runs
347
+
348
+ ${this.logger.color("PROFILE MODE:","yellow")}
349
+ -P, --profile <n> Run each request N times for latency stats
350
+ --profile-warmup <n> Warmup iterations to exclude from stats (default: 1)
351
+ --profile-concurrency <n> Concurrent iterations (default: 1 = sequential)
352
+ --profile-histogram Show ASCII histogram of latency distribution
353
+ --profile-export <file> Export raw timings to file (.json or .csv)
354
+
355
+ ${this.logger.color("CI/CD OPTIONS:","yellow")}
356
+ --strict-exit Exit with code 1 if any validation fails (for CI/CD)
357
+ --fail-on <count> Exit with code 1 if failures exceed this count
358
+ --fail-on-percentage <pct> Exit with code 1 if failure percentage exceeds this value
359
+
360
+ ${this.logger.color("SNAPSHOT OPTIONS:","yellow")}
361
+ -s, --snapshot Enable snapshot testing
362
+ -u, --update-snapshots Update all snapshots
363
+ --update-failing Update only failing snapshots
364
+ --snapshot-dir <dir> Custom snapshot directory (default: __snapshots__)
365
+ --ci-snapshot Fail if snapshot is missing (CI mode)
366
+
367
+ ${this.logger.color("DIFF OPTIONS:","yellow")}
368
+ -d, --diff Enable response diffing (compare with baseline)
369
+ --diff-save Save current run as baseline
370
+ --diff-label <name> Label for current run (e.g., 'staging', 'v1.0')
371
+ --diff-compare <label> Compare against this baseline label
372
+ --diff-dir <dir> Baseline storage directory (default: __baselines__)
373
+ --diff-output <format> Output format (terminal|json|markdown)
374
+
375
+ ${this.logger.color("DIFF SUBCOMMAND:","yellow")}
376
+ curl-runner diff <label1> <label2> [file.yaml]
377
+ Compare two stored baselines without making requests
378
+
379
+ ${this.logger.color("UPGRADE:","yellow")}
380
+ curl-runner upgrade Upgrade to latest version (auto-detects install method)
381
+ curl-runner upgrade --dry-run Preview upgrade command without executing
382
+ curl-runner upgrade --force Force reinstall even if up to date
383
+
384
+ ${this.logger.color("VALIDATE:","yellow")}
385
+ curl-runner validate Validate YAML files against curl-runner schema
386
+ curl-runner validate --fix Validate and auto-fix issues where possible
387
+ curl-runner validate -q Only show files with issues
388
+
389
+ ${this.logger.color("CONVERT:","yellow")}
390
+ curl-runner convert curl "<cmd>" Convert curl command to YAML
391
+ curl-runner convert file <sh> Convert shell script to YAML (batch)
392
+ curl-runner convert yaml <yaml> Convert YAML to curl command(s)
393
+
394
+ ${this.logger.color("WIZARD:","yellow")}
395
+ curl-runner init Quick create a new YAML file
396
+ curl-runner init --wizard Full interactive wizard
397
+ curl-runner init <url> Quick create with URL
398
+ curl-runner edit <file.yaml> Edit existing YAML file
399
+
400
+ ${this.logger.color("EXAMPLES:","yellow")}
401
+ # Run all YAML files in current directory
402
+ curl-runner
403
+
404
+ # Run specific file
405
+ curl-runner api-tests.yaml
406
+
407
+ # Run all files in a directory
408
+ curl-runner examples/
409
+
410
+ # Run all files in multiple directories
411
+ curl-runner tests/ examples/
412
+
413
+ # Run all files recursively in parallel
414
+ curl-runner --all -p
415
+
416
+ # Run in parallel with max 5 concurrent requests
417
+ curl-runner -p --max-concurrent 5 tests.yaml
418
+
419
+ # Run directory recursively
420
+ curl-runner --all examples/
421
+
422
+ # Run with verbose output and continue on errors
423
+ curl-runner tests/*.yaml -vc
424
+
425
+ # Dry run - show curl commands without executing
426
+ curl-runner api.yaml --dry-run
427
+
428
+ # Use HTTP/2 for all requests
429
+ curl-runner api.yaml --http2
430
+
431
+ # Enable connection pooling with HTTP/2 multiplexing
432
+ curl-runner api.yaml -p --connection-pool
433
+
434
+ # Connection pooling with custom settings
435
+ curl-runner api.yaml -p --connection-pool --max-streams 20
436
+
437
+ # Run with minimal pretty output (only status and errors)
438
+ curl-runner --output-format pretty --pretty-level minimal test.yaml
439
+
440
+ # Run with detailed pretty output (show all information)
441
+ curl-runner --output-format pretty --pretty-level detailed test.yaml
442
+
443
+ # CI/CD: Fail if any validation fails (strict mode)
444
+ curl-runner tests/ --strict-exit
445
+
446
+ # CI/CD: Run all tests but fail if any validation fails
447
+ curl-runner tests/ --continue-on-error --strict-exit
448
+
449
+ # CI/CD: Allow up to 2 failures
450
+ curl-runner tests/ --fail-on 2
451
+
452
+ # CI/CD: Allow up to 10% failures
453
+ curl-runner tests/ --fail-on-percentage 10
454
+
455
+ # Watch mode - re-run on file changes
456
+ curl-runner api.yaml --watch
457
+
458
+ # Watch with custom debounce
459
+ curl-runner tests/ -w --watch-debounce 500
460
+
461
+ # Profile mode - run request 100 times for latency stats
462
+ curl-runner api.yaml -P 100
463
+
464
+ # Profile with 5 warmup iterations and histogram
465
+ curl-runner api.yaml --profile 50 --profile-warmup 5 --profile-histogram
466
+
467
+ # Profile with concurrent iterations and export
468
+ curl-runner api.yaml -P 100 --profile-concurrency 10 --profile-export results.json
469
+
470
+ # Snapshot testing - save and compare responses
471
+ curl-runner api.yaml --snapshot
472
+
473
+ # Update all snapshots
474
+ curl-runner api.yaml -su
475
+
476
+ # CI mode - fail if snapshot missing
477
+ curl-runner api.yaml --snapshot --ci-snapshot
478
+
479
+ # Response diffing - save baseline for staging
480
+ curl-runner api.yaml --diff-save --diff-label staging
481
+
482
+ # Compare current run against staging baseline
483
+ curl-runner api.yaml --diff --diff-compare staging
484
+
485
+ # Compare staging vs production baselines (offline)
486
+ curl-runner diff staging production api.yaml
487
+
488
+ # Auto-diff: creates baseline on first run, compares on subsequent runs
489
+ curl-runner api.yaml --diff
490
+
491
+ # Diff with JSON output for CI
492
+ curl-runner api.yaml --diff --diff-compare staging --diff-output json
493
+
494
+ # Create new YAML file with wizard
495
+ curl-runner init --wizard
496
+
497
+ # Quick create with URL
498
+ curl-runner init https://api.example.com/users
499
+
500
+ # Edit existing YAML file
501
+ curl-runner edit api-test.yaml
502
+
503
+ ${this.logger.color("YAML STRUCTURE:","yellow")}
504
+ Single request:
505
+ request:
506
+ url: https://api.example.com
507
+ method: GET
508
+
509
+ Multiple requests:
510
+ requests:
511
+ - url: https://api.example.com/users
512
+ method: GET
513
+ - url: https://api.example.com/posts
514
+ method: POST
515
+ body: { title: "Test" }
516
+
517
+ With global config:
518
+ global:
519
+ execution: parallel
520
+ variables:
521
+ BASE_URL: https://api.example.com
522
+ requests:
523
+ - url: \${BASE_URL}/users
524
+ method: GET
525
+ `)}}var O7=new $3;O7.run(process.argv.slice(2));
526
+
527
+ //# debugId=FAB3C76B90A11F4F64756E2164756E21
528
+ //# sourceMappingURL=cli.js.map