@curl-runner/cli 1.25.0 → 2.0.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 DELETED
@@ -1,537 +0,0 @@
1
- #!/usr/bin/env bun
2
- // @bun
3
- var F3=Object.create;var{getPrototypeOf:D3,defineProperty:h9,getOwnPropertyNames:N3}=Object;var T3=Object.prototype.hasOwnProperty;function I3(Z){return this[Z]}var j3,L3,P1=(Z,J,X)=>{var $=Z!=null&&typeof Z==="object";if($){var W=J?j3??=new WeakMap:L3??=new WeakMap,Q=W.get(Z);if(Q)return Q}X=Z!=null?F3(D3(Z)):{};let G=J||!Z||!Z.__esModule?h9(X,"default",{value:Z,enumerable:!0}):X;for(let Y of N3(Z))if(!T3.call(G,Y))h9(G,Y,{get:I3.bind(Z,Y),enumerable:!0});if($)W.set(Z,G);return G};var g9=(Z,J)=>()=>(J||Z((J={exports:{}}).exports,J),J.exports);var B1=import.meta.require;var U9=g9((C8,K9)=>{var s1=process||{},j4=s1.argv||[],r1=s1.env||{},w7=!(!!r1.NO_COLOR||j4.includes("--no-color"))&&(!!r1.FORCE_COLOR||j4.includes("--color")||s1.platform==="win32"||(s1.stdout||{}).isTTY&&r1.TERM!=="dumb"||!!r1.CI),q7=(Z,J,X=Z)=>($)=>{let W=""+$,Q=W.indexOf(J,Z.length);return~Q?Z+x7(W,J,X,Q)+J:Z+W+J},x7=(Z,J,X,$)=>{let W="",Q=0;do W+=Z.substring(Q,$)+X,Q=$+J.length,$=Z.indexOf(J,Q);while(~$);return W+Z.substring(Q)},L4=(Z=w7)=>{let J=Z?q7:()=>String;return{isColorSupported:Z,reset:J("\x1B[0m","\x1B[0m"),bold:J("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:J("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:J("\x1B[3m","\x1B[23m"),underline:J("\x1B[4m","\x1B[24m"),inverse:J("\x1B[7m","\x1B[27m"),hidden:J("\x1B[8m","\x1B[28m"),strikethrough:J("\x1B[9m","\x1B[29m"),black:J("\x1B[30m","\x1B[39m"),red:J("\x1B[31m","\x1B[39m"),green:J("\x1B[32m","\x1B[39m"),yellow:J("\x1B[33m","\x1B[39m"),blue:J("\x1B[34m","\x1B[39m"),magenta:J("\x1B[35m","\x1B[39m"),cyan:J("\x1B[36m","\x1B[39m"),white:J("\x1B[37m","\x1B[39m"),gray:J("\x1B[90m","\x1B[39m"),bgBlack:J("\x1B[40m","\x1B[49m"),bgRed:J("\x1B[41m","\x1B[49m"),bgGreen:J("\x1B[42m","\x1B[49m"),bgYellow:J("\x1B[43m","\x1B[49m"),bgBlue:J("\x1B[44m","\x1B[49m"),bgMagenta:J("\x1B[45m","\x1B[49m"),bgCyan:J("\x1B[46m","\x1B[49m"),bgWhite:J("\x1B[47m","\x1B[49m"),blackBright:J("\x1B[90m","\x1B[39m"),redBright:J("\x1B[91m","\x1B[39m"),greenBright:J("\x1B[92m","\x1B[39m"),yellowBright:J("\x1B[93m","\x1B[39m"),blueBright:J("\x1B[94m","\x1B[39m"),magentaBright:J("\x1B[95m","\x1B[39m"),cyanBright:J("\x1B[96m","\x1B[39m"),whiteBright:J("\x1B[97m","\x1B[39m"),bgBlackBright:J("\x1B[100m","\x1B[49m"),bgRedBright:J("\x1B[101m","\x1B[49m"),bgGreenBright:J("\x1B[102m","\x1B[49m"),bgYellowBright:J("\x1B[103m","\x1B[49m"),bgBlueBright:J("\x1B[104m","\x1B[49m"),bgMagentaBright:J("\x1B[105m","\x1B[49m"),bgCyanBright:J("\x1B[106m","\x1B[49m"),bgWhiteBright:J("\x1B[107m","\x1B[49m")}};K9.exports=L4();K9.exports.createColors=L4});var M9=g9((w8,R4)=>{var B9={to(Z,J){if(!J)return`\x1B[${Z+1}G`;return`\x1B[${J+1};${Z+1}H`},move(Z,J){let X="";if(Z<0)X+=`\x1B[${-Z}D`;else if(Z>0)X+=`\x1B[${Z}C`;if(J<0)X+=`\x1B[${-J}A`;else if(J>0)X+=`\x1B[${J}B`;return X},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"},b7={up:(Z=1)=>"\x1B[S".repeat(Z),down:(Z=1)=>"\x1B[T".repeat(Z)},y7={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 J="";for(let X=0;X<Z;X++)J+=this.line+(X<Z-1?B9.up():"");if(Z)J+=B9.left;return J}};R4.exports={cursor:B9,scroll:b7,erase:y7,beep:"\x07"}});var{Glob:C2}=globalThis.Bun;var d9={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 N(Z,J){return`${d9[J]}${Z}${d9.reset}`}var R3=[`${process.env.HOME}/.local/bin/curl-runner`,`${process.env.USERPROFILE}\\.local\\bin\\curl-runner.exe`];function f9(){let Z=process.execPath,J=process.argv[0];if(S3(Z))return{source:"bun",path:Z,canAutoUpgrade:!0};if(E3(Z,J))return{source:"npm",path:Z,canAutoUpgrade:!0};if(A3(Z))return{source:"curl",path:Z,canAutoUpgrade:!0};return{source:"standalone",path:Z,canAutoUpgrade:!0}}function S3(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((X)=>Z.includes(X))}function E3(Z,J){if(Z.includes("node_modules"))return!0;if(J.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(($)=>Z.includes($)||J.includes($))}function A3(Z){return R3.some((J)=>Z===J||Z.startsWith(J))}function p9(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 c9(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 K0(){return process.platform==="win32"}function i(){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 J of Z)try{let X=B1(J);if(X.name==="@curl-runner/cli"&&X.version)return X.version}catch{}return"0.0.0"}catch{return"0.0.0"}}var V3="https://registry.npmjs.org/@curl-runner/cli/latest",k3="https://api.github.com/repos/alexvcasillas/curl-runner/releases/latest";class U0{async run(Z){let J=this.parseArgs(Z);console.log(),console.log(N("curl-runner upgrade","bright")),console.log();let X=f9();console.log(`${N("Installation:","cyan")} ${this.formatSource(X.source)}`),console.log(`${N("Current version:","cyan")} ${i()}`);let $=await this.fetchLatestVersion(X.source);if(!$)console.log(N("Failed to fetch latest version","red")),process.exit(1);console.log(`${N("Latest version:","cyan")} ${$}`),console.log();let W=i();if(!J.force&&!this.isNewerVersion(W,$)){console.log(N("Already up to date!","green"));return}let Q=K0()?c9(X.source):p9(X.source);if(J.dryRun){console.log(N("Dry run - would execute:","yellow")),console.log(` ${N(Q,"cyan")}`);return}console.log(`${N("Upgrading...","yellow")}`),console.log(),await this.executeUpgrade(X,Q)}parseArgs(Z){let J={};for(let X of Z)if(X==="--dry-run"||X==="-n")J.dryRun=!0;else if(X==="--force"||X==="-f")J.force=!0;return J}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 Q=await fetch(V3,{signal:AbortSignal.timeout(5000)});if(!Q.ok)return null;return(await Q.json()).version}let J=await fetch(k3,{signal:AbortSignal.timeout(5000),headers:{Accept:"application/vnd.github.v3+json"}});if(!J.ok)return null;let $=(await J.json()).tag_name,W=$.match(/(\d+\.\d+\.\d+)/);return W?W[1]:$.replace(/^v/,"")}catch{return null}}isNewerVersion(Z,J){let X=Z.replace(/^v/,""),$=J.replace(/^v/,""),W=X.split(".").map(Number),Q=$.split(".").map(Number);for(let G=0;G<Math.max(W.length,Q.length);G++){let Y=W[G]||0,z=Q[G]||0;if(z>Y)return!0;if(z<Y)return!1}return!1}async executeUpgrade(Z,J){let{source:X}=Z;try{if(X==="bun")await this.runBunUpgrade();else if(X==="npm")await this.runNpmUpgrade();else await this.runShellUpgrade(J)}catch($){let W=$ instanceof Error?$.message:String($);if(W.includes("EACCES")||W.includes("permission"))console.log(),console.log(N("Permission denied. Try running with sudo:","yellow")),console.log(` ${N(`sudo ${J}`,"cyan")}`),process.exit(1);console.log(N(`Upgrade failed: ${W}`,"red")),console.log(),console.log(N("Manual upgrade:","yellow")),console.log(` ${N(J,"cyan")}`),process.exit(1)}}async runBunUpgrade(){let J=await Bun.spawn(["bun","install","-g","@curl-runner/cli@latest"],{stdout:"inherit",stderr:"inherit"}).exited;if(J!==0)throw Error(`bun install failed with exit code ${J}`);this.showSuccess()}async runNpmUpgrade(){let J=await Bun.spawn(["npm","install","-g","@curl-runner/cli@latest"],{stdout:"inherit",stderr:"inherit"}).exited;if(J!==0)throw Error(`npm install failed with exit code ${J}`);this.showSuccess()}async runShellUpgrade(Z){let J;if(K0())J=Bun.spawn(["powershell","-Command",Z],{stdout:"inherit",stderr:"inherit"});else J=Bun.spawn(["bash","-c",Z],{stdout:"inherit",stderr:"inherit"});let X=await J.exited;if(X!==0)throw Error(`Upgrade script failed with exit code ${X}`);this.showSuccess()}showSuccess(){console.log(),console.log(N("Upgrade complete!","green")),console.log(),console.log("Run `curl-runner --version` to verify.")}}function u9(){console.log(`
4
- ${N("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
- ${N("USAGE:","yellow")}
10
- curl-runner upgrade [options]
11
-
12
- ${N("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
- ${N("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:a9}=globalThis.Bun;var P3=["DATE","TIME","UUID","RANDOM"],C3=new Set(["__proto__","prototype","constructor"]);function M1(Z,J={}){let{variables:X={},storeContext:$,resolveEnv:W=!0}=J;if(typeof Z==="string")return w3(Z,X,$,W);if(Array.isArray(Z))return Z.map((Q)=>M1(Q,J));if(Z&&typeof Z==="object"){let Q={};for(let[G,Y]of Object.entries(Z)){if(C3.has(G))continue;Q[G]=M1(Y,J)}return Q}return Z}function w3(Z,J,X,$=!0){let W=i9(Z);if(W.length===0)return Z;if(W.length===1&&W[0].start===0&&W[0].end===Z.length){let Y=O1(W[0].name,J,X,$);return Y!==null?Y:Z}let Q="",G=0;for(let Y of W){Q+=Z.slice(G,Y.start);let z=O1(Y.name,J,X,$);Q+=z!==null?z:Z.slice(Y.start,Y.end),G=Y.end}return Q+=Z.slice(G),Q}function O1(Z,J,X,$=!0){if(Z.startsWith("store.")&&X){let Y=Z.slice(6);if(Y in X)return X[Y];return null}let W=Z.match(/^([^:]+):(upper|lower)$/);if(W){let[,Y,z]=W,H=J[Y]??($?process.env[Y]:void 0);if(H)return z==="upper"?H.toUpperCase():H.toLowerCase();return null}let Q=Z.indexOf(":");if(Q!==-1){let Y=Z.slice(0,Q),z=Z.slice(Q+1);if(!P3.includes(Y)){let H=O1(Y,J,X,$);if(H!==null)return H;if(z.startsWith("${")){let K=z.endsWith("}")?z.slice(2,-1):z.slice(2),B=O1(K,J,X,$);return B!==null?B:z}return z}}let G=l9(Z);if(G!==null)return G;if(Z in J)return J[Z];if($&&Z in process.env)return process.env[Z];return null}function l9(Z){if(Z==="UUID")return crypto.randomUUID();if(Z==="UUID:short")return crypto.randomUUID().split("-")[0];let J=Z.match(/^RANDOM:(\d+)-(\d+)$/);if(J){let $=Number(J[1]),W=Number(J[2]);return String(Math.floor(Math.random()*(W-$+1))+$)}let X=Z.match(/^RANDOM:string:(\d+)$/);if(X){let $=Number(X[1]),W="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";return Array.from({length:$},()=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(Math.random()*62))).join("")}if(Z==="CURRENT_TIME"||Z==="TIMESTAMP")return Date.now().toString();if(Z.startsWith("DATE:"))return n9(new Date,Z.slice(5));if(Z.startsWith("TIME:"))return o9(new Date,Z.slice(5));return null}function n9(Z,J){let X=Z.getFullYear(),$=String(Z.getMonth()+1).padStart(2,"0"),W=String(Z.getDate()).padStart(2,"0");return J.replace("YYYY",X.toString()).replace("MM",$).replace("DD",W)}function o9(Z,J){let X=String(Z.getHours()).padStart(2,"0"),$=String(Z.getMinutes()).padStart(2,"0"),W=String(Z.getSeconds()).padStart(2,"0");return J.replace("HH",X).replace("mm",$).replace("ss",W)}function i9(Z){let J=[],X=0;while(X<Z.length)if(Z[X]==="$"&&Z[X+1]==="{"){let $=X;X+=2;let W=1,Q=X;while(X<Z.length&&W>0){if(Z[X]==="{")W++;else if(Z[X]==="}")W--;X++}if(W===0)J.push({start:$,end:X,name:Z.slice(Q,X-1)})}else X++;return J}class y{static async parseFile(Z){let X=await Bun.file(Z).text();return Bun.YAML.parse(X)}static parse(Z){return Bun.YAML.parse(Z)}static interpolateVariables(Z,J,X){return M1(Z,{variables:J,storeContext:X})}static mergeConfigs(Z,J){return{...Z,...J,headers:{...Z.headers,...J.headers},params:{...Z.params,...J.params},variables:{...Z.variables,...J.variables},retry:Z.retry||J.retry?{...Z.retry,...J.retry}:void 0}}}var B0=["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],M0=["basic","bearer","digest","ntlm","oauth2"],O0=["sequential","parallel"],_0=["json","pretty","raw"],F0=["minimal","standard","detailed"],D0=["==","!=",">","<",">=","<=","contains","matches","exists","not-exists"],r9=["none","all","failing"],s9=["terminal","json","markdown"],q3={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"},x3={"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"},b3=["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"],y3=["execution","maxConcurrency","continueOnError","dryRun","http2","connectionPool","ci","ssl","watch","profile","snapshot","diff","variables","output","defaults"],v3=["name","description","variables","defaults","requests"],t9=[/^(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 N0{issues=[];currentFile="";definedVariables=new Set;storedVariables=new Set;requestNames=new Set;async run(Z){let J=this.parseArgs(Z),X=Z.filter((Y)=>!Y.startsWith("-"));if(X.length===0)X.push("*.yaml","*.yml");console.log(),console.log(N("curl-runner validate","bright")),console.log();let $=await this.findYamlFiles(X);if($.length===0){console.log(N("No YAML files found","yellow"));return}console.log(`${N("Files:","cyan")} ${$.length} found`),console.log();let W=0,Q=0,G=0;for(let Y of $){let z=await this.validateFile(Y,J),H=z.issues.filter((U)=>U.severity==="error"),K=z.issues.filter((U)=>U.severity==="warning"),B=z.issues.filter((U)=>U.severity==="info");if(!z.valid||J.strict&&K.length>0){G++,W+=z.issues.length,console.log(`${N("\u2717","red")} ${Y}`);for(let D of z.issues){let O=D.severity==="error"?N("\u25CF","red"):D.severity==="warning"?N("\u25CF","yellow"):N("\u25CF","blue");if(console.log(` ${O} ${D.path}: ${D.message}`),D.fix&&!J.fix)console.log(` ${N("fix:","cyan")} ${D.fix.description}`)}if(J.fix&&z.fixedContent){await Bun.write(Y,z.fixedContent);let D=z.issues.filter((O)=>O.fix).length;Q+=D,console.log(` ${N("\u2713","green")} Fixed ${D} issue(s)`)}let U=[];if(H.length>0)U.push(`${H.length} error(s)`);if(K.length>0)U.push(`${K.length} warning(s)`);if(B.length>0)U.push(`${B.length} info`);if(U.length>0)console.log(` ${N("\u2192","dim")} ${U.join(", ")}`);console.log()}else if(K.length>0||B.length>0){W+=z.issues.length,console.log(`${N("\u2713","green")} ${Y}`);for(let D of z.issues){let O=D.severity==="warning"?N("\u25CF","yellow"):N("\u25CF","blue");if(console.log(` ${O} ${D.path}: ${D.message}`),D.fix&&!J.fix)console.log(` ${N("fix:","cyan")} ${D.fix.description}`)}if(J.fix&&z.fixedContent){await Bun.write(Y,z.fixedContent);let D=z.issues.filter((O)=>O.fix).length;Q+=D,console.log(` ${N("\u2713","green")} Fixed ${D} issue(s)`)}let U=[];if(K.length>0)U.push(`${K.length} warning(s)`);if(B.length>0)U.push(`${B.length} info`);if(U.length>0)console.log(` ${N("\u2192","dim")} ${U.join(", ")}`);console.log()}else if(!J.quiet)console.log(`${N("\u2713","green")} ${Y}`)}if(console.log(),G===0)console.log(N("All files valid!","green"));else{if(console.log(`${N("Summary:","cyan")} ${G} file(s) with ${W} issue(s)`),J.fix)console.log(`${N("Fixed:","green")} ${Q} issue(s)`);process.exit(1)}}parseArgs(Z){let J={};for(let X of Z)if(X==="--fix"||X==="-f")J.fix=!0;else if(X==="--quiet"||X==="-q")J.quiet=!0;else if(X==="--strict"||X==="-s")J.strict=!0;return J}async findYamlFiles(Z){let J=new Set,X=await import("fs/promises");for(let $ of Z)try{let W=await X.stat($);if(W.isDirectory()){let Q=new a9(`${$}/**/*.{yaml,yml}`);for await(let G of Q.scan("."))J.add(G)}else if(W.isFile()&&($.endsWith(".yaml")||$.endsWith(".yml")))J.add($)}catch{let W=$.startsWith("/"),Q=new a9(W?$.slice(1):$),G=W?"/":".";for await(let Y of Q.scan(G)){let z=W?`/${Y}`:Y;if(z.endsWith(".yaml")||z.endsWith(".yml"))J.add(z)}}return Array.from(J).sort()}async validateFile(Z,J){this.issues=[],this.currentFile=Z,this.definedVariables=new Set,this.storedVariables=new Set,this.requestNames=new Set;let X;try{X=await y.parseFile(Z)}catch(Q){let G=Q instanceof Error?Q.message:String(Q);return this.addIssue("","error",`Failed to parse YAML: ${G}`),{file:Z,valid:!1,issues:this.issues}}if(this.collectDefinedVariables(X),this.validateYamlStructure(X),X.global)this.validateGlobalConfig(X.global,"global");if(X.collection)this.validateCollection(X.collection,"collection");if(X.request)this.validateRequest(X.request,"request");if(X.requests)if(!Array.isArray(X.requests))this.addIssue("requests","error","Must be an array");else X.requests.forEach((Q,G)=>{this.validateRequest(Q,`requests[${G}]`)});this.checkDuplicateRequestNames();let $;if(J.fix&&this.issues.some((Q)=>Q.fix)){let Q=JSON.parse(JSON.stringify(X));for(let G of this.issues)if(G.fix){let Y=G.fix.apply();this.applyFix(Q,G.path,Y)}$=this.toYaml(Q)}let W=this.issues.filter((Q)=>Q.severity==="error");return{file:Z,valid:W.length===0,issues:this.issues,fixedContent:$}}collectDefinedVariables(Z){if(Z.global?.variables)for(let X of Object.keys(Z.global.variables))this.definedVariables.add(X);if(Z.collection?.variables)for(let X of Object.keys(Z.collection.variables))this.definedVariables.add(X);this.definedVariables.add("env");let J=[...Z.requests||[],...Z.collection?.requests||[],Z.request].filter(Boolean);for(let X of J){if(X.variables)for(let $ of Object.keys(X.variables))this.definedVariables.add($);if(X.store)for(let $ of Object.keys(X.store))this.storedVariables.add($)}}validateYamlStructure(Z){let J="request"in Z,X="requests"in Z,$="collection"in Z;if(!J&&!X&&!$)this.addIssue("","error",'Missing request(s). Must have "request", "requests", or "collection"');if(J&&X)this.addIssue("","warning",'Both "request" and "requests" defined; both will be executed');if($&&(J||X))this.addIssue("","warning","Collection mixed with request/requests; may cause confusion");let W=["version","global","collection","requests","request"];for(let Q of Object.keys(Z))if(!W.includes(Q))this.addIssue(Q,"warning",`Unknown top-level key "${Q}"`,{description:`Remove unknown key "${Q}"`,apply:()=>{return}});if(Z.version!==void 0){if(typeof Z.version!=="string")this.addIssue("version","warning","Version should be a string")}}validateGlobalConfig(Z,J){if(this.checkUnknownKeys(Z,y3,J),Z.execution&&!O0.includes(Z.execution)){let $=this.findClosestMatch(Z.execution,[...O0]);this.addIssue(`${J}.execution`,"error",`Invalid execution mode "${Z.execution}". Must be: ${O0.join(", ")}`,$?{description:`Change to "${$}"`,apply:()=>$}:void 0)}if(Z.maxConcurrency!==void 0){if(typeof Z.maxConcurrency!=="number"||Z.maxConcurrency<1)this.addIssue(`${J}.maxConcurrency`,"error","Must be a positive number");if(Z.execution==="sequential")this.addIssue(`${J}.maxConcurrency`,"warning","maxConcurrency has no effect with sequential execution")}let X=Z;if(this.validateBooleanField(X,"continueOnError",J),this.validateBooleanField(X,"dryRun",J),this.validateBooleanField(X,"http2",J),Z.output)this.validateOutputConfig(Z.output,`${J}.output`);if(Z.connectionPool)this.validateConnectionPool(Z.connectionPool,`${J}.connectionPool`);if(Z.ci)this.validateCIConfig(Z.ci,`${J}.ci`);if(Z.ssl)this.validateSSLConfig(Z.ssl,`${J}.ssl`);if(Z.watch)this.validateWatchConfig(Z.watch,`${J}.watch`);if(Z.profile)this.validateProfileConfig(Z.profile,`${J}.profile`);if(Z.snapshot)this.validateSnapshotConfig(Z.snapshot,`${J}.snapshot`);if(Z.diff)this.validateDiffConfig(Z.diff,`${J}.diff`);if(Z.variables)this.validateVariables(Z.variables,`${J}.variables`);if(Z.defaults)this.validateRequestConfig(Z.defaults,`${J}.defaults`,!0)}validateBooleanField(Z,J,X){if(Z[J]!==void 0&&typeof Z[J]!=="boolean"){let $=String(Z[J]).toLowerCase();if($==="true"||$==="false")this.addIssue(`${X}.${J}`,"warning",`Should be boolean, not string "${Z[J]}"`,{description:`Convert to ${$}`,apply:()=>$==="true"});else this.addIssue(`${X}.${J}`,"error","Must be a boolean")}}validateVariables(Z,J){if(typeof Z!=="object"||Array.isArray(Z)){this.addIssue(J,"error","Must be an object");return}for(let[X,$]of Object.entries(Z)){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(X))this.addIssue(`${J}.${X}`,"warning","Variable names should use alphanumeric characters and underscores");if(typeof $==="string"&&this.isSensitiveValue(X,$))this.addIssue(`${J}.${X}`,"warning",'Potentially sensitive value hardcoded. Consider using environment variables like "${env.VAR}"')}}validateOutputConfig(Z,J){let X=["verbose","showHeaders","showBody","showMetrics","format","prettyLevel","saveToFile","dryRun"];if(this.checkUnknownKeys(Z,X,J),Z.format&&!_0.includes(Z.format)){let $=this.findClosestMatch(Z.format,[..._0]);this.addIssue(`${J}.format`,"error",`Invalid format "${Z.format}". Must be: ${_0.join(", ")}`,$?{description:`Change to "${$}"`,apply:()=>$}:void 0)}if(Z.prettyLevel&&!F0.includes(Z.prettyLevel)){let $=this.findClosestMatch(Z.prettyLevel,[...F0]);this.addIssue(`${J}.prettyLevel`,"error",`Invalid prettyLevel "${Z.prettyLevel}". Must be: ${F0.join(", ")}`,$?{description:`Change to "${$}"`,apply:()=>$}:void 0)}this.validateBooleanField(Z,"verbose",J),this.validateBooleanField(Z,"showHeaders",J),this.validateBooleanField(Z,"showBody",J),this.validateBooleanField(Z,"showMetrics",J)}validateConnectionPool(Z,J){let X=["enabled","maxStreamsPerHost","keepaliveTime","connectTimeout"];if(this.checkUnknownKeys(Z,X,J),this.validateBooleanField(Z,"enabled",J),Z.maxStreamsPerHost!==void 0){if(typeof Z.maxStreamsPerHost!=="number"||Z.maxStreamsPerHost<1)this.addIssue(`${J}.maxStreamsPerHost`,"error","Must be a positive number");else if(Z.maxStreamsPerHost>100)this.addIssue(`${J}.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(`${J}.keepaliveTime`,"error","Must be a non-negative number")}if(Z.connectTimeout!==void 0){if(typeof Z.connectTimeout!=="number"||Z.connectTimeout<0)this.addIssue(`${J}.connectTimeout`,"error","Must be a non-negative number")}}validateCIConfig(Z,J){let X=["strictExit","failOn","failOnPercentage"];if(this.checkUnknownKeys(Z,X,J),this.validateBooleanField(Z,"strictExit",J),Z.failOn!==void 0&&(typeof Z.failOn!=="number"||Z.failOn<0))this.addIssue(`${J}.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(`${J}.failOnPercentage`,"error","Must be a number between 0 and 100")}if(Z.failOn!==void 0&&Z.failOnPercentage!==void 0)this.addIssue(J,"info","Both failOn and failOnPercentage are set; failOn takes precedence")}validateSSLConfig(Z,J){let X=["verify","ca","cert","key"];if(this.checkUnknownKeys(Z,X,J),this.validateBooleanField(Z,"verify",J),Z.ca&&typeof Z.ca!=="string")this.addIssue(`${J}.ca`,"error","Must be a string path");if(Z.cert&&typeof Z.cert!=="string")this.addIssue(`${J}.cert`,"error","Must be a string path");if(Z.key&&typeof Z.key!=="string")this.addIssue(`${J}.key`,"error","Must be a string path");if(Z.cert&&!Z.key)this.addIssue(`${J}`,"warning","cert provided without key; mTLS may fail");if(Z.key&&!Z.cert)this.addIssue(`${J}`,"warning","key provided without cert; mTLS may fail");if(Z.ca&&typeof Z.ca==="string")this.validateFilePath(Z.ca,`${J}.ca`);if(Z.cert&&typeof Z.cert==="string")this.validateFilePath(Z.cert,`${J}.cert`);if(Z.key&&typeof Z.key==="string")this.validateFilePath(Z.key,`${J}.key`)}validateFilePath(Z,J){if(Z.includes("${"))return;if(Z.includes(".."))this.addIssue(J,"info",'Path contains ".."; ensure this is intentional')}validateWatchConfig(Z,J){let X=["enabled","debounce","clear"];if(this.checkUnknownKeys(Z,X,J),Z.debounce!==void 0){if(typeof Z.debounce!=="number"||Z.debounce<0)this.addIssue(`${J}.debounce`,"error","Must be a non-negative number")}this.validateBooleanField(Z,"enabled",J),this.validateBooleanField(Z,"clear",J)}validateProfileConfig(Z,J){let X=["iterations","warmup","concurrency","percentiles"];if(this.checkUnknownKeys(Z,X,J),Z.iterations!==void 0){if(typeof Z.iterations!=="number"||Z.iterations<1)this.addIssue(`${J}.iterations`,"error","Must be a positive number");else if(Z.iterations>1e4)this.addIssue(`${J}.iterations`,"warning","Very high iteration count may take long")}if(Z.warmup!==void 0){if(typeof Z.warmup!=="number"||Z.warmup<0)this.addIssue(`${J}.warmup`,"error","Must be a non-negative number")}if(Z.concurrency!==void 0){if(typeof Z.concurrency!=="number"||Z.concurrency<1)this.addIssue(`${J}.concurrency`,"error","Must be a positive number")}}validateSnapshotConfig(Z,J){let X=["updateMode","dir","ignoreFields","ignoreHeaders"];if(this.checkUnknownKeys(Z,X,J),Z.updateMode&&!r9.includes(Z.updateMode))this.addIssue(`${J}.updateMode`,"error",`Invalid updateMode "${Z.updateMode}". Must be: ${r9.join(", ")}`);if(Z.dir&&typeof Z.dir!=="string")this.addIssue(`${J}.dir`,"error","Must be a string")}validateDiffConfig(Z,J){let X=["outputFormat","dir","ignoreFields","ignoreHeaders","baselineUrl"];if(this.checkUnknownKeys(Z,X,J),Z.outputFormat&&!s9.includes(Z.outputFormat))this.addIssue(`${J}.outputFormat`,"error",`Invalid outputFormat "${Z.outputFormat}". Must be: ${s9.join(", ")}`);if(Z.dir&&typeof Z.dir!=="string")this.addIssue(`${J}.dir`,"error","Must be a string")}validateCollection(Z,J){if(this.checkUnknownKeys(Z,v3,J),!Z.name)this.addIssue(`${J}.name`,"warning","Collection name is recommended");if(!Z.requests||!Array.isArray(Z.requests))this.addIssue(`${J}.requests`,"error","Collection must have a requests array");else{if(Z.requests.length===0)this.addIssue(`${J}.requests`,"warning","Collection has no requests");Z.requests.forEach((X,$)=>{this.validateRequest(X,`${J}.requests[${$}]`)})}if(Z.variables)this.validateVariables(Z.variables,`${J}.variables`);if(Z.defaults)this.validateRequestConfig(Z.defaults,`${J}.defaults`,!0)}validateRequest(Z,J){this.validateRequestConfig(Z,J,!1)}validateRequestConfig(Z,J,X){if(this.checkUnknownKeys(Z,b3,J),Z.name)this.requestNames.add(`${J}:${Z.name}`);if(!X&&!Z.url)this.addIssue(`${J}.url`,"error","URL is required");if(Z.url)this.validateURL(Z.url,`${J}.url`);if(Z.method)this.validateMethod(Z.method,`${J}.method`);if(Z.headers)this.validateHeaders(Z.headers,`${J}.headers`,Z);else if(Z.body!==void 0)this.addIssue(`${J}.headers`,"info","Body present but no Content-Type header; consider adding one");if(Z.params){if(typeof Z.params!=="object"||Array.isArray(Z.params))this.addIssue(`${J}.params`,"error","Params must be an object")}if(Z.body!==void 0&&Z.formData!==void 0)this.addIssue(`${J}`,"error",'Cannot use both "body" and "formData"');if(Z.body!==void 0)this.validateBody(Z.body,`${J}.body`,Z);if(Z.formData)this.validateFormData(Z.formData,`${J}.formData`);if(Z.timeout!==void 0)this.validateTimeout(Z.timeout,`${J}.timeout`);if(Z.auth)this.validateAuth(Z.auth,`${J}.auth`);if(Z.ssl)this.validateSSLConfig(Z.ssl,`${J}.ssl`);if(Z.insecure!==void 0){if(this.validateBooleanField(Z,"insecure",J),Z.insecure===!0)this.addIssue(`${J}.insecure`,"warning","Insecure mode disables SSL verification")}if(Z.proxy)this.validateProxyURL(Z.proxy,`${J}.proxy`);if(Z.retry)this.validateRetry(Z.retry,`${J}.retry`,Z.method);if(Z.when)this.validateWhenCondition(Z.when,`${J}.when`);if(Z.expect)this.validateExpect(Z.expect,`${J}.expect`);if(Z.store)this.validateStore(Z.store,`${J}.store`);if(Z.maxRedirects!==void 0){if(typeof Z.maxRedirects!=="number"||Z.maxRedirects<0)this.addIssue(`${J}.maxRedirects`,"error","Must be a non-negative number");else if(Z.maxRedirects>50)this.addIssue(`${J}.maxRedirects`,"warning","Very high redirect limit")}if(this.validateBooleanField(Z,"followRedirects",J),this.validateBooleanField(Z,"http2",J),Z.snapshot!==void 0&&typeof Z.snapshot==="object")this.validateSnapshotConfig(Z.snapshot,`${J}.snapshot`);if(Z.diff!==void 0&&typeof Z.diff==="object")this.validateDiffConfig(Z.diff,`${J}.diff`)}validateURL(Z,J){if(typeof Z!=="string"){this.addIssue(J,"error","URL must be a string");return}let X=Z.includes("${"),$=Z,W=!1;for(let[Q,G]of Object.entries(q3))if(Q==="http:/"||Q==="https:/"?new RegExp(Q.replace("/","\\/")+"(?!\\/)","i").test(Z):Z.toLowerCase().includes(Q)){$=Z.replace(new RegExp(Q,"gi"),G),W=!0,this.addIssue(J,"error",`URL contains typo "${Q}"`,{description:`Fix to "${G}"`,apply:()=>$});break}if(!W&&!Z.startsWith("http")&&!X)this.addIssue(J,"warning","URL should start with http:// or https://",{description:"Prepend https://",apply:()=>`https://${Z}`});if(!X&&Z.match(/https?:\/\/[^/]+\/\/+/)){let Q=Z.replace(/(https?:\/\/[^/]+)(\/+)/g,"$1/");this.addIssue(J,"warning","URL contains double slashes in path",{description:"Remove extra slashes",apply:()=>Q})}if(Z.includes(" ")){let Q=Z.replace(/ /g,"%20");this.addIssue(J,"error","URL contains spaces",{description:"Encode spaces as %20",apply:()=>Q})}if(Z.startsWith("http://")&&!Z.includes("localhost")&&!Z.includes("127.0.0.1"))this.addIssue(J,"info","Using HTTP instead of HTTPS; consider using HTTPS for security");if(!X){let Q=Z.match(/:(\d+)/);if(Q){let G=parseInt(Q[1],10);if(G<1||G>65535)this.addIssue(J,"error",`Invalid port number ${G}. Must be 1-65535`)}}}validateProxyURL(Z,J){if(typeof Z!=="string"){this.addIssue(J,"error","Proxy must be a string URL");return}if(!Z.includes("${")&&!Z.match(/^(https?|socks[45]?):\/\//i))this.addIssue(J,"error","Proxy URL should start with http://, https://, socks4://, or socks5://")}validateMethod(Z,J){let X=Z.toUpperCase();if(!B0.includes(X)){let $=this.findClosestMatch(X,[...B0]);this.addIssue(J,"error",`Invalid method "${Z}". Must be: ${B0.join(", ")}`,$?{description:`Change to "${$}"`,apply:()=>$}:void 0)}else if(Z!==X)this.addIssue(J,"warning",`Method should be uppercase: "${X}"`,{description:`Change to "${X}"`,apply:()=>X})}validateHeaders(Z,J,X){if(typeof Z!=="object"||Array.isArray(Z)){this.addIssue(J,"error","Headers must be an object");return}let $=new Map;for(let[G,Y]of Object.entries(Z)){let z=G.toLowerCase(),H=x3[z];if(H&&G!==H)this.addIssue(`${J}.${G}`,"info",`Header "${G}" should be "${H}" for consistency`,{description:`Rename to "${H}"`,apply:()=>({rename:H,value:Y})});if($.has(z))this.addIssue(`${J}.${G}`,"warning",`Duplicate header "${G}" (case-insensitive match with "${$.get(z)}")`);if($.set(z,G),typeof Y!=="string"&&typeof Y!=="number")this.addIssue(`${J}.${G}`,"error","Header value must be a string or number");if(typeof Y==="string"&&this.isSensitiveValue(G,Y))this.addIssue(`${J}.${G}`,"warning",'Potentially sensitive header value. Consider using variables like "${env.TOKEN}"')}let W=this.getHeaderValue(Z,"content-type");if(X.body!==void 0&&!W)this.addIssue(J,"info","Body present but no Content-Type header; consider adding one");let Q=this.getHeaderValue(Z,"authorization");if(X.auth&&Q)this.addIssue(J,"warning","Both auth block and Authorization header present; auth block may be ignored")}getHeaderValue(Z,J){let X=J.toLowerCase();for(let[$,W]of Object.entries(Z))if($.toLowerCase()===X)return W;return}validateBody(Z,J,X){let $=(X.method||"GET").toUpperCase();if(["GET","HEAD","OPTIONS"].includes($))this.addIssue(J,"warning",`Body with ${$} method may be ignored by some servers`);if(typeof Z==="string"){let W=Z.trim(),G=(X.headers?this.getHeaderValue(X.headers,"content-type"):null)?.toLowerCase().includes("json");if(W.startsWith("{")&&W.endsWith("}")||W.startsWith("[")&&W.endsWith("]")||G)try{JSON.parse(W)}catch{this.addIssue(J,"warning","Body looks like JSON but is invalid; check syntax")}}}validateFormData(Z,J){if(typeof Z!=="object"||Array.isArray(Z)){this.addIssue(J,"error","FormData must be an object");return}for(let[X,$]of Object.entries(Z))if(typeof $==="object"&&$!==null&&"file"in $){if(typeof $.file!=="string")this.addIssue(`${J}.${X}.file`,"error","File path must be a string");else this.validateFilePath($.file,`${J}.${X}.file`);if($.contentType&&typeof $.contentType!=="string")this.addIssue(`${J}.${X}.contentType`,"error","contentType must be a string");if($.filename&&typeof $.filename!=="string")this.addIssue(`${J}.${X}.filename`,"error","filename must be a string")}}validateTimeout(Z,J){if(typeof Z!=="number"){if(typeof Z==="string"){let X=parseInt(Z,10);if(!Number.isNaN(X)&&X>0){this.addIssue(J,"warning","Timeout should be a number, not string",{description:`Convert to ${X}`,apply:()=>X});return}}this.addIssue(J,"error","Timeout must be a positive number");return}if(Z<=0)this.addIssue(J,"error","Timeout must be a positive number");else if(Z<100)this.addIssue(J,"warning","Very short timeout (<100ms) may cause failures");else if(Z>300000)this.addIssue(J,"warning","Very long timeout (>5min) - is this intentional?")}validateAuth(Z,J){let X=["type","username","password","token"];if(this.checkUnknownKeys(Z,X,J),!Z.type){this.addIssue(`${J}.type`,"error","Auth type is required");return}if(!M0.includes(Z.type)){let $=this.findClosestMatch(Z.type,[...M0]);this.addIssue(`${J}.type`,"error",`Invalid auth type "${Z.type}". Must be: ${M0.join(", ")}`,$?{description:`Change to "${$}"`,apply:()=>$}:void 0);return}if(Z.type==="basic"){if(!Z.username)this.addIssue(`${J}.username`,"error","Username required for basic auth");if(!Z.password)this.addIssue(`${J}.password`,"warning","Password missing for basic auth");if(Z.password&&typeof Z.password==="string"&&!Z.password.includes("${"))this.addIssue(`${J}.password`,"warning",'Hardcoded password. Consider using "${env.PASSWORD}"')}if(Z.type==="bearer"){if(!Z.token)this.addIssue(`${J}.token`,"error","Token required for bearer auth");if(Z.token&&typeof Z.token==="string"&&!Z.token.includes("${"))this.addIssue(`${J}.token`,"warning",'Hardcoded token. Consider using "${env.TOKEN}"')}}validateRetry(Z,J,X){let $=["count","delay","backoff"];if(this.checkUnknownKeys(Z,$,J),Z.count===void 0)this.addIssue(`${J}.count`,"error","Retry count is required");else if(typeof Z.count!=="number"||Z.count<0)this.addIssue(`${J}.count`,"error","Retry count must be a non-negative number");else if(Z.count>10)this.addIssue(`${J}.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(`${J}.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(`${J}.backoff`,"error","Retry backoff must be >= 1");else if(Z.backoff>5)this.addIssue(`${J}.backoff`,"warning","High backoff multiplier may cause very long delays")}if(X&&["POST","PATCH"].includes(X.toUpperCase())&&Z.count&&Z.count>0)this.addIssue(J,"info",`Retrying ${X} requests may cause duplicate operations`)}validateWhenCondition(Z,J){if(typeof Z==="string"){this.validateWhenString(Z,J);return}let X="all"in Z&&Z.all,$="any"in Z&&Z.any,W="left"in Z||"operator"in Z||"right"in Z;if(!X&&!$&&!W){this.addIssue(J,"error",'When condition must have "all", "any", or "left"');return}if(X&&$||X&&W||$&&W)this.addIssue(J,"warning","When condition has multiple forms; behavior may be unexpected");if(X)if(!Array.isArray(Z.all))this.addIssue(`${J}.all`,"error","Must be an array");else{if(Z.all.length===0)this.addIssue(`${J}.all`,"warning",'Empty "all" array - condition always true');Z.all.forEach((Q,G)=>{this.validateConditionExpression(Q,`${J}.all[${G}]`)})}if($)if(!Array.isArray(Z.any))this.addIssue(`${J}.any`,"error","Must be an array");else{if(Z.any.length===0)this.addIssue(`${J}.any`,"warning",'Empty "any" array - condition always false');Z.any.forEach((Q,G)=>{this.validateConditionExpression(Q,`${J}.any[${G}]`)})}if(W)this.validateConditionExpression(Z,J)}validateWhenString(Z,J){if(!Z.includes("store.")&&!Z.includes("env."))this.addIssue(J,"warning","When string should reference store.* or env.* values");if(!/\s*(==|!=|>=|<=|>|<|contains|matches|exists|not-exists)\s*/.test(Z))this.addIssue(J,"warning","When string should contain a valid operator (==, !=, >, <, >=, <=, contains, matches, exists)")}validateConditionExpression(Z,J){if(!Z.left)this.addIssue(`${J}.left`,"error","Left operand is required");else if(!Z.left.startsWith("store.")&&!Z.left.startsWith("env."))this.addIssue(`${J}.left`,"warning",'Left operand should start with "store." or "env."');if(!Z.operator)this.addIssue(`${J}.operator`,"error","Operator is required");else if(!D0.includes(Z.operator)){let X=this.findClosestMatch(Z.operator,[...D0]);this.addIssue(`${J}.operator`,"error",`Invalid operator "${Z.operator}". Must be: ${D0.join(", ")}`,X?{description:`Change to "${X}"`,apply:()=>X}:void 0)}if(Z.operator!=="exists"&&Z.operator!=="not-exists"){if(Z.right===void 0)this.addIssue(`${J}.right`,"error","Right operand is required")}}validateExpect(Z,J){let X=["failure","status","headers","body","responseTime"];if(this.checkUnknownKeys(Z,X,J),this.validateBooleanField(Z,"failure",J),Z.status!==void 0)this.validateExpectStatus(Z.status,`${J}.status`);if(Z.headers){if(typeof Z.headers!=="object"||Array.isArray(Z.headers))this.addIssue(`${J}.headers`,"error","Expected headers must be an object")}if(Z.responseTime!==void 0)this.validateResponseTime(Z.responseTime,`${J}.responseTime`)}validateExpectStatus(Z,J){if(Array.isArray(Z)){if(Z.length===0)this.addIssue(J,"warning","Empty status array - no status will match");for(let X of Z)if(typeof X!=="number"||X<100||X>599){this.addIssue(J,"error","Status codes must be numbers between 100-599");break}}else if(typeof Z==="string"){let X=parseInt(Z,10);if(!Number.isNaN(X)&&X>=100&&X<=599)this.addIssue(J,"warning","Status should be a number, not string",{description:`Convert to ${X}`,apply:()=>X});else this.addIssue(J,"error","Status code must be a number between 100-599")}else if(typeof Z!=="number"||Z<100||Z>599)this.addIssue(J,"error","Status code must be a number between 100-599")}validateResponseTime(Z,J){if(typeof Z!=="string"){this.addIssue(J,"error",'Response time must be a string (e.g., "< 1000")');return}let X=/^[<>]=?\s*(\d+|\$\{[^}]+\})(\s*,\s*[<>]=?\s*(\d+|\$\{[^}]+\}))?$/;if(!Z.match(X))this.addIssue(J,"warning",'Response time should be like "< 1000", "> 500, < 2000"')}validateStore(Z,J){if(typeof Z!=="object"||Array.isArray(Z)){this.addIssue(J,"error","Store must be an object");return}for(let[X,$]of Object.entries(Z)){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(X))this.addIssue(`${J}.${X}`,"warning","Store variable names should use alphanumeric characters and underscores");if(typeof $!=="string")this.addIssue(`${J}.${X}`,"error","Store path must be a string");else{let W=["body","status","headers","responseTime"],Q=$.split(".")[0];if(!W.includes(Q))this.addIssue(`${J}.${X}`,"warning",`Store path should start with: ${W.join(", ")}`)}}}checkDuplicateRequestNames(){let Z=new Map;for(let J of this.requestNames){let[X,$]=J.split(":");if(!Z.has($))Z.set($,[]);Z.get($).push(X)}for(let[J,X]of Z)if(X.length>1)this.addIssue(X[1],"warning",`Duplicate request name "${J}" (also at ${X[0]})`)}checkUnknownKeys(Z,J,X){for(let $ of Object.keys(Z))if(!J.includes($)){let W=this.findClosestMatch($,J);this.addIssue(`${X}.${$}`,"warning",W?`Unknown key "${$}" (did you mean "${W}"?)`:`Unknown key "${$}"`,W?{description:`Rename to "${W}"`,apply:()=>({rename:W})}:void 0)}}findClosestMatch(Z,J){let X=Z.toLowerCase(),$=null,W=3;for(let Q of J){let G=Q.toLowerCase();if(X===G)return Q;if(G.startsWith(X)||X.startsWith(G))return Q;let Y=this.editDistance(X,G);if(Y<W)W=Y,$=Q}return $}editDistance(Z,J){if(Z.length===0)return J.length;if(J.length===0)return Z.length;let X=[];for(let $=0;$<=J.length;$++)X[$]=[$];for(let $=0;$<=Z.length;$++)X[0][$]=$;for(let $=1;$<=J.length;$++)for(let W=1;W<=Z.length;W++)if(J.charAt($-1)===Z.charAt(W-1))X[$][W]=X[$-1][W-1];else X[$][W]=Math.min(X[$-1][W-1]+1,X[$][W-1]+1,X[$-1][W]+1);return X[J.length][Z.length]}isSensitiveValue(Z,J){if(J.includes("${"))return!1;for(let X of t9)if(X.test(Z))return!0;for(let X of t9)if(X.test(J))return!0;return!1}addIssue(Z,J,X,$){this.issues.push({file:this.currentFile,path:Z||"(root)",severity:J,message:X,fix:$})}applyFix(Z,J,X){if(!J||J==="(root)")return;let $=J.split(".").flatMap((Q)=>{let G=Q.match(/^(\w+)\[(\d+)\]$/);return G?[G[1],Number(G[2])]:Q}),W=Z;for(let Q=0;Q<$.length-1;Q++){let G=$[Q];if(typeof W==="object"&&W!==null)W=W[G]}if(typeof W==="object"&&W!==null){let Q=$[$.length-1];if(typeof X==="object"&&X!==null&&"rename"in X){let G=X,Y=G.value??W[Q];delete W[Q],W[G.rename]=Y}else if(X===void 0)delete W[Q];else W[Q]=X}}toYaml(Z){return this.serializeYaml(Z)}serializeYaml(Z,J=0){let X=" ".repeat(J);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(($)=>{if(typeof $==="object"&&$!==null){let Q=this.serializeYaml($,J+1).split(`
23
- `);return`${X}- ${Q[0]}
24
- ${Q.slice(1).map((G)=>`${X} ${G}`).join(`
25
- `)}`.trimEnd()}return`${X}- ${this.serializeYaml($,J)}`}).join(`
26
- `)}if(typeof Z==="object"){let $=Object.entries(Z).filter(([,W])=>W!==void 0);if($.length===0)return"{}";return $.map(([W,Q])=>{if(typeof Q==="object"&&Q!==null&&!Array.isArray(Q)){let G=this.serializeYaml(Q,J+1);return`${X}${W}:
27
- ${G.split(`
28
- `).map((Y)=>` ${Y}`).join(`
29
- `)}`}if(Array.isArray(Q))return`${X}${W}:
30
- ${this.serializeYaml(Q,J+1)}`;return`${X}${W}: ${this.serializeYaml(Q,J)}`}).join(`
31
- `)}return String(Z)}}function e9(){console.log(`
32
- ${N("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
- ${N("USAGE:","yellow")}
38
- curl-runner validate [files...] [options]
39
-
40
- ${N("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
- ${N("ARGUMENTS:","yellow")}
47
- files File paths or glob patterns (default: *.yaml, *.yml)
48
-
49
- ${N("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
- ${N("VALIDATION CATEGORIES:","yellow")}
58
-
59
- ${N("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
- ${N("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
- ${N("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
- ${N("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
- ${N("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
- ${N("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
- ${N("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
- ${N("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 T0(Z){let J=[],X=Z.split(`
119
- `),$=0;while($<X.length){let W=X[$].trim();if(!W||W.startsWith("#")||W.startsWith("//")){$++;continue}let Q=m3(W);if(Q>=0){let G=W.slice(Q);while(G.endsWith("\\")&&$+1<X.length)G=G.slice(0,-1),$++,G+=` ${X[$].trim()}`;let Y=h3(G);if(Y>0)G=G.slice(0,Y).trim();if(G=G.replace(/;\s*$/,"").trim(),G.length>4)J.push(G)}$++}return J}function m3(Z){if(Z.startsWith("curl ")||Z==="curl")return 0;let J=[/(?:^|&&\s*|;\s*|\|\|\s*|\$\(\s*|`\s*)curl\s/];for(let X of J){let $=X.exec(Z);if($){let W=Z.indexOf("curl",$.index);if(W>=0)return W}}return-1}function h3(Z){let J=!1,X=!1;for(let $=0;$<Z.length;$++){let W=Z[$];if(W==="\\"&&!J){$++;continue}if(W==="'"&&!X){J=!J;continue}if(W==='"'&&!J){X=!X;continue}if(W==="|"&&!J&&!X)return $}return-1}function I0(Z){let J=["curl"];if(Z.method!=="GET"||Z.body||Z.formData)J.push(`-X ${Z.method}`);for(let[$,W]of Object.entries(Z.headers))J.push(`-H ${x(`${$}: ${W}`)}`);if(Z.auth){if(Z.auth.type==="basic")J.push(`-u ${x(`${Z.auth.username||""}:${Z.auth.password||""}`)}`);else if(Z.auth.type==="bearer")J.push(`-H ${x(`Authorization: Bearer ${Z.auth.token||""}`)}`)}if(Z.formData)for(let[$,W]of Object.entries(Z.formData))if(typeof W==="string")J.push(`--form-string ${x(`${$}=${W}`)}`);else{let Q=`@${W.file}`;if(W.filename)Q+=`;filename=${W.filename}`;if(W.contentType)Q+=`;type=${W.contentType}`;J.push(`-F ${x(`${$}=${Q}`)}`)}else if(Z.body)if(Z.body.type==="json"){if(J.push(`-d ${x(JSON.stringify(Z.body.content))}`),!Z.headers["Content-Type"])J.push(`-H ${x("Content-Type: application/json")}`)}else if(Z.body.type==="urlencoded")J.push(`--data-urlencode ${x(String(Z.body.content))}`);else if(Z.body.type==="binary")J.push(`--data-binary ${x(String(Z.body.content))}`);else J.push(`-d ${x(String(Z.body.content))}`);if(Z.timeout!==void 0)J.push(`--max-time ${Math.ceil(Z.timeout/1000)}`);if(Z.followRedirects)J.push("-L");if(Z.maxRedirects!==void 0)J.push(`--max-redirs ${Z.maxRedirects}`);if(Z.proxy)J.push(`-x ${x(Z.proxy)}`);if(Z.insecure)J.push("-k");if(Z.http2)J.push("--http2");if(Z.output)J.push(`-o ${x(Z.output)}`);if(Z.ssl){if(Z.ssl.ca)J.push(`--cacert ${x(Z.ssl.ca)}`);if(Z.ssl.cert)J.push(`--cert ${x(Z.ssl.cert)}`);if(Z.ssl.key)J.push(`--key ${x(Z.ssl.key)}`)}let X=Z.url;if(Z.params&&Object.keys(Z.params).length>0){let $=new URLSearchParams(Z.params).toString();X+=(X.includes("?")?"&":"?")+$}return J.push(x(X)),J.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 _1(Z){let J=[],X="",$=0,W=Z.length;while($<W){let Q=Z[$];if(Q==="\\"&&$+1<W&&(Z[$+1]===`
120
- `||Z[$+1]==="\r")){if($+=2,$<W&&Z[$]===`
121
- `)$++;while($<W&&(Z[$]===" "||Z[$]==="\t"))$++;continue}if(Q===" "||Q==="\t"||Q===`
122
- `||Q==="\r"){if(X.length>0)J.push(X),X="";$++;continue}if(Q==="'"){$++;while($<W&&Z[$]!=="'")X+=Z[$],$++;if($<W)$++;continue}if(Q==='"'){$++;while($<W&&Z[$]!=='"'){if(Z[$]==="\\"&&$+1<W){let G=Z[$+1];if(G==='"'||G==="\\"||G==="$"||G==="`"||G===`
123
- `){if(G===`
124
- `){$+=2;continue}X+=G,$+=2;continue}}X+=Z[$],$++}if($<W)$++;continue}if(Q==="\\"&&$+1<W){X+=Z[$+1],$+=2;continue}X+=Q,$++}if(X.length>0)J.push(X);return J}var j0=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"]),Z4=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 w1(Z){let J=_1(Z.trim());return J4(J)}function J4(Z){let J={url:"",headers:[],unsupportedFlags:[]},X=[],$=[],W=[],Q=[],G=[],Y=[],z=0;if(Z.length>0&&Z[0]==="curl")z=1;while(z<Z.length){let H=Z[z];if(!H.startsWith("-")){if(!J.url)J.url=H;z++;continue}if(H.startsWith("-")&&!H.startsWith("--")&&H.length>2){let K=`-${H[1]}`;if(j0.has(K)){let U=H.slice(2);z=C1(K,U,Z,z,J,X,$,W,Q,G,Y);continue}let B=!0;for(let U=1;U<H.length;U++){let D=`-${H[U]}`;if(!Z4.has(D)){B=!1;break}}if(B){for(let U=1;U<H.length;U++)z=C1(`-${H[U]}`,void 0,Z,z,J,X,$,W,Q,G,Y);z++;continue}}if(j0.has(H)){let K=Z[z+1];z=C1(H,K,Z,z,J,X,$,W,Q,G,Y);continue}if(Z4.has(H)){z=C1(H,void 0,Z,z,J,X,$,W,Q,G,Y);continue}if(H.startsWith("-")){let K=Z[z+1];if(K&&!K.startsWith("-"))J.unsupportedFlags.push({flag:H,value:K}),z+=2;else J.unsupportedFlags.push({flag:H}),z++;continue}z++}if(X.length>0)J.data=X;if($.length>0)J.dataRaw=$;if(W.length>0)J.dataBinary=W;if(Q.length>0)J.dataUrlencode=Q;if(G.length>0)J.form=G;if(Y.length>0)J.formString=Y;return J}function C1(Z,J,X,$,W,Q,G,Y,z,H,K){switch(Z){case"-X":case"--request":return W.method=J?.toUpperCase(),$+2;case"-H":case"--header":{if(J){let B=J.indexOf(":");if(B>0)W.headers.push({key:J.slice(0,B).trim(),value:J.slice(B+1).trim()})}return $+2}case"-d":case"--data":case"--data-ascii":if(J!==void 0)Q.push(J);return $+2;case"--data-raw":if(J!==void 0)G.push(J);return $+2;case"--data-binary":if(J!==void 0)Y.push(J);return $+2;case"--data-urlencode":if(J!==void 0)z.push(J);return $+2;case"-F":case"--form":if(J!==void 0)H.push(J);return $+2;case"--form-string":if(J!==void 0)K.push(J);return $+2;case"-u":case"--user":return W.user=J,$+2;case"-o":case"--output":return W.output=J,$+2;case"-x":case"--proxy":return W.proxy=J,$+2;case"--max-time":case"-m":if(J)W.maxTime=Number(J);return $+2;case"--max-redirs":if(J)W.maxRedirs=Number(J);return $+2;case"--cacert":return W.cacert=J,$+2;case"--cert":return W.cert=J,$+2;case"--key":return W.key=J,$+2;case"-b":case"--cookie":return W.cookie=J,$+2;case"-c":case"--cookie-jar":return W.cookieJar=J,$+2;case"-A":case"--user-agent":return W.userAgent=J,$+2;case"-e":case"--referer":return W.referer=J,$+2;case"-G":case"--get":return W.get=!0,$+1;case"-I":case"--head":return W.head=!0,$+1;case"-L":case"--location":return W.location=!0,$+1;case"-k":case"--insecure":return W.insecure=!0,$+1;case"--compressed":return W.compressed=!0,$+1;case"--http2":return W.http2=!0,$+1;case"-s":case"--silent":return W.silent=!0,$+1;case"-v":case"--verbose":return W.verbose=!0,$+1;default:if(j0.has(Z))return $+2;return $+1}}function q1(Z){let J=[],{url:X,params:$}=g3(Z.url),W=d3(Z),Q=p3(Z,W),{body:G,formData:Y}=c3(Z,J),z=n3(Z,G,Y),H=o3(Z);for(let B of Z.unsupportedFlags)J.push(`Unsupported curl flag: ${B.flag}${B.value?` ${B.value}`:""}`);if(Z.compressed)J.push("Flag --compressed has no YAML equivalent; curl handles decompression natively");if(Z.cookie)J.push(`Cookie flag (-b ${Z.cookie}) stored as header; manual review recommended`),W.Cookie=Z.cookie;if(Z.cookieJar)J.push(`Cookie jar flag (-c ${Z.cookieJar}) has no YAML equivalent`);if(Z.userAgent&&!W["User-Agent"])W["User-Agent"]=Z.userAgent;if(Z.referer&&!W.Referer)W.Referer=Z.referer;let K={method:z,url:X,headers:W,metadata:{source:"curl",warnings:J,unsupportedFlags:Z.unsupportedFlags.length>0?Z.unsupportedFlags:void 0}};if(Object.keys($).length>0)K.params=$;if(G)K.body=G;if(Y)K.formData=Y;if(Q)K.auth=Q;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 g3(Z){let J={};if(!Z)return{url:"",params:J};let X=Z.indexOf("?");if(X===-1)return{url:Z,params:J};let $=Z.slice(0,X),W=Z.slice(X+1);for(let Q of W.split("&")){let G=Q.indexOf("=");if(G>0){let Y=decodeURIComponent(Q.slice(0,G)),z=decodeURIComponent(Q.slice(G+1));J[Y]=z}else if(Q.length>0)J[decodeURIComponent(Q)]=""}return{url:$,params:J}}function d3(Z){let J={};for(let X of Z.headers){if(X.key.toLowerCase()==="authorization")continue;J[f3(X.key)]=X.value}return J}function f3(Z){return Z.split("-").map((J)=>J.charAt(0).toUpperCase()+J.slice(1).toLowerCase()).join("-")}function p3(Z,J){if(Z.user){let X=Z.user.indexOf(":");if(X>0)return{type:"basic",username:Z.user.slice(0,X),password:Z.user.slice(X+1)};return{type:"basic",username:Z.user,password:""}}for(let X of Z.headers)if(X.key.toLowerCase()==="authorization"){let $=X.value.trim();if($.toLowerCase().startsWith("bearer "))return{type:"bearer",token:$.slice(7).trim()};if($.toLowerCase().startsWith("basic "))try{let W=atob($.slice(6).trim()),Q=W.indexOf(":");if(Q>0)return{type:"basic",username:W.slice(0,Q),password:W.slice(Q+1)}}catch{J.Authorization=$}else J.Authorization=$}return}function c3(Z,J){if(Z.form&&Z.form.length>0){let $={};for(let W of Z.form)u3(W,$);if(Z.formString)for(let W of Z.formString){let Q=W.indexOf("=");if(Q>0)$[W.slice(0,Q)]=W.slice(Q+1)}return{formData:$}}if(Z.dataUrlencode&&Z.dataUrlencode.length>0)return{body:{type:"urlencoded",content:Z.dataUrlencode.map((W)=>encodeURIComponent(W)).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 X=[...Z.data||[],...Z.dataRaw||[]];if(X.length>0){let $=X.join("&");try{return{body:{type:"json",content:JSON.parse($)}}}catch{if(l3($))return{body:{type:"urlencoded",content:$}};return{body:{type:"raw",content:$}}}}return{}}function u3(Z,J){let X=Z.indexOf("=");if(X<=0)return;let $=Z.slice(0,X),W=Z.slice(X+1);if(W.startsWith("@")){let Q=W.slice(1).split(";"),G={file:Q[0]};for(let Y=1;Y<Q.length;Y++){let[z,H]=Q[Y].split("=");if(z==="filename")G.filename=H;else if(z==="type")G.contentType=H}J[$]=G}else J[$]=W}function l3(Z){return/^[^=&]+=[^&]*(&[^=&]+=[^&]*)*$/.test(Z)}function n3(Z,J,X){if(Z.method)return Z.method;if(Z.head)return"HEAD";if(Z.get)return"GET";if(J||X)return"POST";return"GET"}function o3(Z){if(!Z.cacert&&!Z.cert&&!Z.key)return;let J={};if(Z.cacert)J.ca=Z.cacert;if(Z.cert)J.cert=Z.cert;if(Z.key)J.key=Z.key;return J}function x1(Z,J){let X=[],$=J?.pretty??!0;if((J?.lossReport??!0)&&Z.metadata.warnings.length>0){for(let Q of Z.metadata.warnings)X.push(`# Warning: ${Q}`);X.push("")}if(X.push("request:"),Z.name)X.push(` name: ${E(Z.name)}`);if(X.push(` method: ${Z.method}`),X.push(` url: ${E(Z.url)}`),Z.params&&Object.keys(Z.params).length>0){X.push(" params:");for(let[Q,G]of H1(Z.params))X.push(` ${d(Q)}: ${E(G)}`)}if(Object.keys(Z.headers).length>0){X.push(" headers:");for(let[Q,G]of H1(Z.headers))X.push(` ${d(Q)}: ${E(G)}`)}if(Z.auth){if(X.push(" auth:"),X.push(` type: ${Z.auth.type}`),Z.auth.type==="basic")X.push(` username: ${E(Z.auth.username||"")}`),X.push(` password: ${E(Z.auth.password||"")}`);else if(Z.auth.type==="bearer")X.push(` token: ${E(Z.auth.token||"")}`)}if(Z.body)if(X.push(" body:"),Z.body.type==="json")if($){let Q=X4(Z.body.content,4);X.push(...Q)}else X.push(` json: ${JSON.stringify(Z.body.content)}`);else if(Z.body.type==="urlencoded")X.push(` form: ${E(String(Z.body.content))}`);else if(Z.body.type==="binary")X.push(` binary: ${E(String(Z.body.content))}`);else X.push(` raw: ${E(String(Z.body.content))}`);if(Z.formData&&Object.keys(Z.formData).length>0){X.push(" formData:");for(let[Q,G]of H1(Z.formData))if(typeof G==="string")X.push(` ${d(Q)}: ${E(G)}`);else{if(X.push(` ${d(Q)}:`),X.push(` file: ${E(G.file)}`),G.filename)X.push(` filename: ${E(G.filename)}`);if(G.contentType)X.push(` contentType: ${E(G.contentType)}`)}}if(Z.timeout!==void 0)X.push(` timeout: ${Z.timeout}`);if(Z.followRedirects)X.push(" followRedirects: true");if(Z.maxRedirects!==void 0)X.push(` maxRedirects: ${Z.maxRedirects}`);if(Z.proxy)X.push(` proxy: ${E(Z.proxy)}`);if(Z.insecure)X.push(" insecure: true");if(Z.http2)X.push(" http2: true");if(Z.output)X.push(` output: ${E(Z.output)}`);if(Z.ssl){if(X.push(" ssl:"),Z.ssl.ca)X.push(` ca: ${E(Z.ssl.ca)}`);if(Z.ssl.cert)X.push(` cert: ${E(Z.ssl.cert)}`);if(Z.ssl.key)X.push(` key: ${E(Z.ssl.key)}`)}return`${X.join(`
125
- `)}
126
- `}function L0(Z,J){let X=[],$=J?.pretty??!0;if(J?.lossReport??!0){let Q=Z.flatMap((G)=>G.metadata.warnings);if(Q.length>0){for(let G of Q)X.push(`# Warning: ${G}`);X.push("")}}X.push("requests:");for(let Q=0;Q<Z.length;Q++){let G=Z[Q];if(Q>0)X.push("");if(G.name)X.push(` - name: ${E(G.name)}`);else X.push(` - name: request_${Q+1}`);if(X.push(` method: ${G.method}`),X.push(` url: ${E(G.url)}`),G.params&&Object.keys(G.params).length>0){X.push(" params:");for(let[Y,z]of H1(G.params))X.push(` ${d(Y)}: ${E(z)}`)}if(Object.keys(G.headers).length>0){X.push(" headers:");for(let[Y,z]of H1(G.headers))X.push(` ${d(Y)}: ${E(z)}`)}if(G.auth){if(X.push(" auth:"),X.push(` type: ${G.auth.type}`),G.auth.type==="basic")X.push(` username: ${E(G.auth.username||"")}`),X.push(` password: ${E(G.auth.password||"")}`);else if(G.auth.type==="bearer")X.push(` token: ${E(G.auth.token||"")}`)}if(G.body)if(X.push(" body:"),G.body.type==="json")if($){let Y=X4(G.body.content,6);X.push(...Y)}else X.push(` json: ${JSON.stringify(G.body.content)}`);else if(G.body.type==="urlencoded")X.push(` form: ${E(String(G.body.content))}`);else if(G.body.type==="binary")X.push(` binary: ${E(String(G.body.content))}`);else X.push(` raw: ${E(String(G.body.content))}`);if(G.formData&&Object.keys(G.formData).length>0){X.push(" formData:");for(let[Y,z]of H1(G.formData))if(typeof z==="string")X.push(` ${d(Y)}: ${E(z)}`);else{if(X.push(` ${d(Y)}:`),X.push(` file: ${E(z.file)}`),z.filename)X.push(` filename: ${E(z.filename)}`);if(z.contentType)X.push(` contentType: ${E(z.contentType)}`)}}if(G.timeout!==void 0)X.push(` timeout: ${G.timeout}`);if(G.followRedirects)X.push(" followRedirects: true");if(G.maxRedirects!==void 0)X.push(` maxRedirects: ${G.maxRedirects}`);if(G.proxy)X.push(` proxy: ${E(G.proxy)}`);if(G.insecure)X.push(" insecure: true");if(G.http2)X.push(" http2: true");if(G.output)X.push(` output: ${E(G.output)}`);if(G.ssl){if(X.push(" ssl:"),G.ssl.ca)X.push(` ca: ${E(G.ssl.ca)}`);if(G.ssl.cert)X.push(` cert: ${E(G.ssl.cert)}`);if(G.ssl.key)X.push(` key: ${E(G.ssl.key)}`)}}return`${X.join(`
127
- `)}
128
- `}function X4(Z,J){let X=" ".repeat(J);if(Z===null||Z===void 0)return[`${X}json: null`];if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")return[`${X}json: ${JSON.stringify(Z)}`];if(Array.isArray(Z)){if(Z.length===0)return[`${X}json: []`];if(Z.every(($)=>typeof $!=="object"||$===null))return[`${X}json: [${Z.map(($)=>JSON.stringify($)).join(", ")}]`];return[`${X}json: ${JSON.stringify(Z)}`]}if(typeof Z==="object"){let $=Z,W=Object.keys($);if(W.length===0)return[`${X}json: {}`];let Q=[];Q.push(`${X}json:`);for(let G of W){let Y=$[G];if(Y===null)Q.push(`${X} ${d(G)}: null`);else if(typeof Y==="object"&&!Array.isArray(Y))Q.push(`${X} ${d(G)}: ${JSON.stringify(Y)}`);else if(Array.isArray(Y))Q.push(`${X} ${d(G)}: ${JSON.stringify(Y)}`);else Q.push(`${X} ${d(G)}: ${i3(Y)}`)}return Q}return[`${X}json: ${JSON.stringify(Z)}`]}function E(Z){if(Z==="")return'""';if(a3(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 i3(Z){if(typeof Z==="string")return E(Z);if(typeof Z==="number"||typeof Z==="boolean")return String(Z);return JSON.stringify(Z)}function a3(Z){if(/[{}[\],&*?|>!%#@`]/.test(Z))return!0;if(/: /.test(Z)||Z.endsWith(":"))return!0;if(Z.startsWith("'")||Z.startsWith('"'))return!0;let J=Z.toLowerCase();if(["true","false","null","yes","no","on","off"].includes(J))return!0;if(/^-?\d+(\.\d+)?$/.test(Z))return!0;if(Z.startsWith(" ")||Z.endsWith(" "))return!0;return!1}function H1(Z){return Object.entries(Z).sort(([J],[X])=>J.localeCompare(X))}function R0(Z){let J=[],X={};if(Z.headers)for(let[W,Q]of Object.entries(Z.headers))X[W]=Q;let $={method:Z.method||"GET",url:Z.url,headers:X,metadata:{source:"yaml",warnings:J}};if(Z.name)$.name=Z.name;if(Z.params)$.params={...Z.params};if(Z.auth)$.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 W=Z.body;if("json"in W)$.body={type:"json",content:W.json};else if("form"in W)$.body={type:"urlencoded",content:String(W.form)};else if("raw"in W)$.body={type:"raw",content:String(W.raw)};else if("binary"in W)$.body={type:"binary",content:String(W.binary)};else $.body={type:"json",content:Z.body}}else $.body={type:"json",content:Z.body};if(Z.formData){let W={};for(let[Q,G]of Object.entries(Z.formData))if(typeof G==="object"&&G!==null&&"file"in G)W[Q]={file:G.file,filename:G.filename,contentType:G.contentType};else W[Q]=String(G);$.formData=W}if(Z.timeout)$.timeout=Z.timeout;if(Z.followRedirects!==void 0)$.followRedirects=Z.followRedirects;if(Z.maxRedirects)$.maxRedirects=Z.maxRedirects;if(Z.proxy)$.proxy=Z.proxy;if(Z.insecure)$.insecure=!0;if(Z.http2)$.http2=!0;if(Z.output)$.output=Z.output;if(Z.ssl){if($.ssl={},Z.ssl.ca)$.ssl.ca=Z.ssl.ca;if(Z.ssl.cert)$.ssl.cert=Z.ssl.cert;if(Z.ssl.key)$.ssl.key=Z.ssl.key}if(Z.expect)J.push("expect block has no curl equivalent");if(Z.store)J.push("store block has no curl equivalent");if(Z.when)J.push("when condition has no curl equivalent");if(Z.retry)J.push("retry config simplified in curl output");if(Z.snapshot)J.push("snapshot config has no curl equivalent");if(Z.diff)J.push("diff config has no curl equivalent");return $}function S0(Z,J){let X=w1(Z),$=q1(X),Q={output:x1($,{pretty:J?.pretty??!0,lossReport:J?.lossReport??!0}),warnings:$.metadata.warnings};if(J?.debug)Q.debug={tokens:_1(Z.trim()),ast:X,ir:$};return Q}async function E0(Z,J){let X=await Bun.file(Z).text(),$=T0(X);if($.length===0)return{output:"",warnings:["No curl commands found in file"]};let W=[],Q=[];for(let z=0;z<$.length;z++){let H=w1($[z]),K=q1(H);K.name=`request_${z+1}`,W.push(K),Q.push(...K.metadata.warnings)}if(W.length===1){let H={output:x1(W[0],{pretty:J?.pretty??!0,lossReport:J?.lossReport??!0}),warnings:Q};if(J?.debug)H.debug={ir:W[0]};return H}let Y={output:L0(W,{pretty:J?.pretty??!0,lossReport:J?.lossReport??!0}),warnings:Q};if(J?.debug)Y.debug={ir:W};return Y}async function A0(Z,J){let X=await Bun.file(Z).text(),$=Bun.YAML.parse(X),W=[];if($.request)W.push($.request);if($.requests)W.push(...$.requests);if($.collection?.requests)W.push(...$.collection.requests);if(W.length===0)return{output:"",warnings:["No requests found in YAML file"]};let Q=[],G=[];for(let z of W){let H=R0(z);Q.push(...H.metadata.warnings),G.push(I0(H))}return{output:G.join(`
129
-
130
- `),warnings:Q}}function V0(Z){if(Z.length<3)return null;let J=Z[1];if(J!=="curl"&&J!=="file"&&J!=="yaml")return null;let X=Z[2],$={};for(let W=3;W<Z.length;W++)switch(Z[W]){case"--output":case"-o":$.output=Z[++W];break;case"--pretty":$.pretty=!0;break;case"--normalize":$.normalize=!0;break;case"--loss-report":$.lossReport=!0;break;case"--batch":$.batch=!0;break;case"--env-detect":$.envDetect=!0;break;case"--debug":$.debug=!0;break}return{subcommand:J,input:X,options:$}}function k0(Z){let J={files:[]};for(let X=0;X<Z.length;X++){let $=Z[X],W=Z[X+1],Q=W!==void 0&&!W.startsWith("-");if($.startsWith("--"))X+=r3($.slice(2),W,Q,J);else if($.startsWith("-"))X+=s3($.slice(1),W,Q,J);else J.files.push($)}return J}function r3(Z,J,X,$){switch(Z){case"help":return $.help=!0,0;case"version":return $.version=!0,0;case"all":return $.all=!0,0;case"dry-run":return $.dryRun=!0,0;case"http2":return $.http2=!0,0;case"connection-pool":return $.connectionPool=!0,0;case"quiet":return $.quiet=!0,0;case"show-headers":return $.showHeaders=!0,0;case"show-body":return $.showBody=!0,0;case"show-metrics":return $.showMetrics=!0,0;case"no-retry":return $.noRetry=!0,0;case"watch":return $.watch=!0,0;case"watch-clear":return $.watchClear=!0,0;case"no-watch-clear":return $.watchClear=!1,0;case"profile-histogram":return $.profileHistogram=!0,0;case"snapshot":return $.snapshot=!0,0;case"update-snapshots":return $.snapshotUpdate="all",0;case"update-failing":return $.snapshotUpdate="failing",0;case"ci-snapshot":return $.snapshotCi=!0,0;case"diff":return $.diff=!0,0;case"diff-save":return $.diffSave=!0,0;case"strict-exit":return $.strictExit=!0,0;case"no-redact":return $.noRedact=!0,0;case"allow-path":return $.allowPath=!0,0}if(!X){if(Z==="verbose")return $.verbose=!0,0;if(Z==="continue-on-error")return $.continueOnError=!0,0;return 0}switch(Z){case"env":return $.env=J,1;case"execution":if(J==="sequential"||J==="parallel")$.execution=J;return 1;case"max-concurrent":{let W=Number.parseInt(J,10);if(W>0)$.maxConcurrency=W;return 1}case"max-streams":{let W=Number.parseInt(J,10);if(W>0)$.maxStreams=W;return 1}case"keepalive-time":return $.keepaliveTime=Number.parseInt(J,10),1;case"connect-timeout":return $.connectTimeout=Number.parseInt(J,10),1;case"verbose":return $.verbose=J==="true",1;case"output":return $.output=J,1;case"output-format":if(["json","pretty","raw"].includes(J))$.outputFormat=J;return 1;case"pretty-level":if(["minimal","standard","detailed"].includes(J))$.prettyLevel=J;return 1;case"timeout":return $.timeout=Number.parseInt(J,10),1;case"retries":return $.retries=Number.parseInt(J,10),1;case"retry-delay":return $.retryDelay=Number.parseInt(J,10),1;case"continue-on-error":return $.continueOnError=J==="true",1;case"watch-debounce":return $.watchDebounce=Number.parseInt(J,10),1;case"profile":return $.profile=Number.parseInt(J,10),1;case"profile-warmup":return $.profileWarmup=Number.parseInt(J,10),1;case"profile-concurrency":return $.profileConcurrency=Number.parseInt(J,10),1;case"profile-export":return $.profileExport=J,1;case"snapshot-dir":return $.snapshotDir=J,1;case"diff-label":return $.diffLabel=J,1;case"diff-compare":return $.diffCompare=J,1;case"diff-dir":return $.diffDir=J,1;case"diff-output":if(["terminal","json","markdown"].includes(J))$.diffOutput=J;return 1;case"fail-on":return $.failOn=Number.parseInt(J,10),1;case"fail-on-percentage":{let W=Number.parseFloat(J);if(W>=0&&W<=100)$.failOnPercentage=W;return 1}case"allow-protocol":{let W=J.toLowerCase();return $.allowProtocols=$.allowProtocols?[...$.allowProtocols,W]:[W],1}default:return 1}}function s3(Z,J,X,$){let W=0;for(let Q of Z)switch(Q){case"h":$.help=!0;break;case"v":$.verbose=!0;break;case"p":$.execution="parallel";break;case"c":break;case"q":$.quiet=!0;break;case"w":$.watch=!0;break;case"s":$.snapshot=!0;break;case"u":$.snapshotUpdate="all";break;case"d":$.diff=!0;break;case"n":$.dryRun=!0;break;case"o":if(X)$.output=J,W=1;break;case"P":if(X)$.profile=Number.parseInt(J,10),W=1;break;case"e":if(X)$.env=J,W=1;break}return W}function P0(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 C0(Z){let J={};for(let X=1;X<Z.length;X++){let $=Z[X],W=Z[X+1];if($==="--wizard"||$==="-w")J.wizard=!0;else if($==="-o"||$==="--output"){if(W&&!W.startsWith("-"))J.outputPath=W,X++}else if(!$.startsWith("-")&&!J.url)J.url=$}return J}function w0(Z){let J={file:""};for(let X=1;X<Z.length;X++){let $=Z[X],W=Z[X+1];if($==="-o"||$==="--output"){if(W&&!W.startsWith("-"))J.outputPath=W,X++}else if(!$.startsWith("-")&&!J.file)J.file=$}return J}function q0(Z){if(Z.help)return"help";if(Z.version)return"version";return null}import{join as b1}from"path";function t3(Z){let J={},X=Z.split(`
131
- `);for(let $ of X){let W=$.trim();if(!W||W.startsWith("#"))continue;let Q=W.indexOf("=");if(Q===-1)continue;let G=W.slice(0,Q).trim(),Y=W.slice(Q+1).trim();if(Y.startsWith('"')&&Y.endsWith('"')||Y.startsWith("'")&&Y.endsWith("'"))Y=Y.slice(1,-1);if(W.slice(Q+1).trim().startsWith('"'))Y=Y.replace(/\\n/g,`
132
- `).replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\\\/g,"\\");if(G)J[G]=Y}return J}async function e3(Z){let J=Bun.file(Z);if(!await J.exists())return{};try{let X=await J.text();return t3(X)}catch{return{}}}function Z7(Z){return Object.keys(Z).filter((J)=>J.startsWith("SECRET_"))}async function x0(Z=process.cwd(),J){let X=[b1(Z,".env"),b1(Z,".env.local")];if(J)X.push(b1(Z,`.env.${J}`),b1(Z,`.env.${J}.local`));let $={};for(let W of X){let Q=await e3(W);$={...$,...Q}}return{variables:$,secretKeys:Z7($)}}function b0(){let Z={};return J7(Z),X7(Z),$7(Z),W7(Z),Q7(Z),G7(Z),Y7(Z),z7(Z),H7(Z),K7(Z),Z}function J7(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 J=Number.parseInt(process.env.CURL_RUNNER_MAX_CONCURRENCY,10);if(J>0)Z.maxConcurrency=J}}function X7(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 $7(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 J=process.env.CURL_RUNNER_OUTPUT_FORMAT;if(["json","pretty","raw"].includes(J))Z.output={...Z.output,format:J}}if(process.env.CURL_RUNNER_PRETTY_LEVEL){let J=process.env.CURL_RUNNER_PRETTY_LEVEL;if(["minimal","standard","detailed"].includes(J))Z.output={...Z.output,prettyLevel:J}}if(process.env.CURL_RUNNER_OUTPUT_FILE)Z.output={...Z.output,saveToFile:process.env.CURL_RUNNER_OUTPUT_FILE}}function W7(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 J=Number.parseFloat(process.env.CURL_RUNNER_FAIL_ON_PERCENTAGE);if(J>=0&&J<=100)Z.ci={...Z.ci,failOnPercentage:J}}}function Q7(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 G7(Z){if(process.env.CURL_RUNNER_PROFILE){let J=Number.parseInt(process.env.CURL_RUNNER_PROFILE,10);if(J>0)Z.profile={...Z.profile,iterations:J}}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 Y7(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 J=process.env.CURL_RUNNER_SNAPSHOT_UPDATE.toLowerCase();if(["none","all","failing"].includes(J))Z.snapshot={...Z.snapshot,updateMode:J}}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 z7(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 J=process.env.CURL_RUNNER_DIFF_OUTPUT.toLowerCase();if(["terminal","json","markdown"].includes(J))Z.diff={...Z.diff,outputFormat:J}}}function H7(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)}}}function K7(Z){if(process.env.CURL_RUNNER_ALLOWED_PROTOCOLS){let J=process.env.CURL_RUNNER_ALLOWED_PROTOCOLS.split(",").map((X)=>X.trim().toLowerCase()).filter(Boolean);if(J.length>0)Z.security={...Z.security,allowedProtocols:J}}if(process.env.CURL_RUNNER_ALLOW_PATHS)Z.security={...Z.security,allowPaths:process.env.CURL_RUNNER_ALLOW_PATHS.toLowerCase()==="true"}}var $4=["curl-runner.yaml","curl-runner.yml",".curl-runner.yaml",".curl-runner.yml"];async function y0(Z,J){for(let X of $4)try{if(await Bun.file(X).exists()){let Q=(await y.parseFile(X)).global||{};return Z?.(`Loaded configuration from ${X}`),{config:Q,path:X}}}catch($){J?.(`Failed to load configuration from ${X}: ${$}`)}return{config:{},path:null}}var U7=/authorization|api[-_]?key|token|secret|cookie/i,B7=[/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,/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,/AIza[0-9A-Za-z_-]{35}/g,/(?:api[_-]?key|token|secret)=([^&\s"']+)/g];class W4{secrets=new Map;sortedSecrets=[];patternRedaction=!0;addSecrets(Z){for(let[J,X]of Object.entries(Z))if(X&&X.length>0)this.secrets.set(J,X);this.updateSortedSecrets()}addSecret(Z,J){if(J&&J.length>0)this.secrets.set(Z,J),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,J)=>J.length-Z.length)}redact(Z){let J=Z;for(let X of this.sortedSecrets)J=J.split(X).join("[REDACTED]");if(this.patternRedaction)for(let X of B7)if(X.lastIndex=0,X.source.includes("("))J=J.replace(X,($,W)=>W?$.replace(W,"[REDACTED]"):"[REDACTED]");else J=J.replace(X,"[REDACTED]");return J}hasSecrets(){return this.secrets.size>0}get secretCount(){return this.secrets.size}}var v0=null;function Q1(){if(!v0)v0=new W4;return v0}function m0(Z){let J=Q1();for(let X of Z){let $=X.auth;if($){if($.type==="bearer"&&$.token)J.addSecret(`__req_bearer_${$.token.slice(0,8)}`,$.token);else if($.type==="basic"){if($.password)J.addSecret(`__req_basic_pass_${$.password.slice(0,8)}`,$.password);if($.username&&$.password){let W=`${$.username}:${$.password}`;J.addSecret(`__req_basic_combined_${W.slice(0,8)}`,W)}}}if(X.headers){for(let[W,Q]of Object.entries(X.headers))if(U7.test(W)&&Q){J.addSecret(`__req_header_${W.toLowerCase()}_${Q.slice(0,8)}`,Q);let G=/^Bearer\s+(\S+)$/i.exec(Q);if(G){let Y=G[1];J.addSecret(`__req_header_bearer_bare_${Y.slice(0,8)}`,Y)}}}}}var f=["http","https"];function h0(Z,J){let X;try{X=new URL(Z)}catch{return{valid:!1,error:`Invalid URL: "${Z}"`}}let $=X.protocol.slice(0,-1).toLowerCase();if(!J.includes($)){let W=J.join(", ");return{valid:!1,error:`Blocked protocol "${$}" (allowed: ${W}). Use --allow-protocol to permit it.`}}return{valid:!0}}async function g0(Z,J){let X=P0(Z);if(X==="upgrade")return{config:{},cliOptions:{files:[]},files:[],mode:"upgrade",rawArgs:Z,secretKeys:[]};if(X==="init")return{config:{},cliOptions:{files:[]},files:[],mode:"init",rawArgs:Z,secretKeys:[]};if(X==="edit")return{config:{},cliOptions:{files:[]},files:[],mode:"edit",rawArgs:Z,secretKeys:[]};if(X==="validate")return{config:{},cliOptions:{files:[]},files:[],mode:"validate",rawArgs:Z,secretKeys:[]};if(X==="convert")return{config:{},cliOptions:{files:[]},files:[],mode:"convert",rawArgs:Z,secretKeys:[]};let $=k0(Z),W=q0($);if(W)return{config:{},cliOptions:$,files:$.files,mode:W,rawArgs:Z,secretKeys:[]};if(X==="diff-subcommand")return{config:{},cliOptions:$,files:Z.slice(1),mode:"diff-subcommand",rawArgs:Z,secretKeys:[]};let Q=b0(),{config:G}=await y0(J?.onInfo,J?.onWarning),Y=y1(G,Q);Y=M7(Y,$);let z=$.env??Y.env?.environment,{variables:H,secretKeys:K}=await x0(process.cwd(),z);if(Y.variables={...H,...Y.variables},!$.noRedact&&Y.env?.redactSecrets!==!1&&K.length>0){let D=Q1(),O={};for(let _ of K)if(Y.variables?.[_])O[_]=Y.variables[_];D.addSecrets(O)}let U=O7($,Y);return{config:Y,cliOptions:$,files:$.files,mode:U,rawArgs:Z,secretKeys:K}}function y1(Z,J){return{...Z,...J,env:{...Z.env,...J.env},variables:{...Z.variables,...J.variables},output:{...Z.output,...J.output},defaults:{...Z.defaults,...J.defaults,retry:Z.defaults?.retry||J.defaults?.retry?{...Z.defaults?.retry,...J.defaults?.retry}:void 0},ci:{...Z.ci,...J.ci},watch:{...Z.watch,...J.watch},snapshot:{...Z.snapshot,...J.snapshot},diff:{...Z.diff,...J.diff},connectionPool:{...Z.connectionPool,...J.connectionPool},security:{...Z.security,...J.security}}}function M7(Z,J){let X={...Z};if(J.env)X.env={...X.env,environment:J.env};if(J.noRedact)X.env={...X.env,redactSecrets:!1};if(J.execution)X.execution=J.execution;if(J.maxConcurrency!==void 0)X.maxConcurrency=J.maxConcurrency;if(J.continueOnError!==void 0)X.continueOnError=J.continueOnError;if(J.dryRun!==void 0)X.dryRun=J.dryRun,X.output={...X.output,dryRun:J.dryRun};if(J.http2!==void 0)X.http2=J.http2,X.defaults={...X.defaults,http2:J.http2};if(J.connectionPool!==void 0)X.connectionPool={...X.connectionPool,enabled:J.connectionPool};if(J.maxStreams!==void 0)X.connectionPool={...X.connectionPool,enabled:!0,maxStreamsPerHost:J.maxStreams};if(J.keepaliveTime!==void 0)X.connectionPool={...X.connectionPool,enabled:!0,keepaliveTime:J.keepaliveTime};if(J.connectTimeout!==void 0)X.connectionPool={...X.connectionPool,enabled:!0,connectTimeout:J.connectTimeout};if(J.verbose!==void 0)X.output={...X.output,verbose:J.verbose};if(J.quiet)X.output={...X.output,verbose:!1,quiet:!0};if(J.output)X.output={...X.output,saveToFile:J.output};if(J.outputFormat)X.output={...X.output,format:J.outputFormat};if(J.prettyLevel)X.output={...X.output,prettyLevel:J.prettyLevel};if(J.showHeaders!==void 0)X.output={...X.output,showHeaders:J.showHeaders};if(J.showBody!==void 0)X.output={...X.output,showBody:J.showBody};if(J.showMetrics!==void 0)X.output={...X.output,showMetrics:J.showMetrics};if(J.timeout)X.defaults={...X.defaults,timeout:J.timeout};if(J.retries||J.noRetry){let $=J.noRetry?0:J.retries||0;X.defaults={...X.defaults,retry:{...X.defaults?.retry,count:$}}}if(J.retryDelay)X.defaults={...X.defaults,retry:{...X.defaults?.retry,delay:J.retryDelay}};if(J.strictExit!==void 0)X.ci={...X.ci,strictExit:J.strictExit};if(J.failOn!==void 0)X.ci={...X.ci,failOn:J.failOn};if(J.failOnPercentage!==void 0)X.ci={...X.ci,failOnPercentage:J.failOnPercentage};if(J.snapshot!==void 0)X.snapshot={...X.snapshot,enabled:J.snapshot};if(J.snapshotUpdate!==void 0)X.snapshot={...X.snapshot,enabled:!0,updateMode:J.snapshotUpdate};if(J.snapshotDir!==void 0)X.snapshot={...X.snapshot,dir:J.snapshotDir};if(J.snapshotCi!==void 0)X.snapshot={...X.snapshot,ci:J.snapshotCi};if(J.diff!==void 0)X.diff={...X.diff,enabled:J.diff};if(J.diffSave!==void 0)X.diff={...X.diff,enabled:!0,save:J.diffSave};if(J.diffLabel!==void 0)X.diff={...X.diff,label:J.diffLabel};if(J.diffCompare!==void 0)X.diff={...X.diff,enabled:!0,compareWith:J.diffCompare};if(J.diffDir!==void 0)X.diff={...X.diff,dir:J.diffDir};if(J.diffOutput!==void 0)X.diff={...X.diff,outputFormat:J.diffOutput};if(J.allowProtocols&&J.allowProtocols.length>0)X.security={...X.security,allowedProtocols:J.allowProtocols};if(J.allowPath)X.security={...X.security,allowPaths:!0};if(!X.security?.allowedProtocols||X.security.allowedProtocols.length===0)X.security={...X.security,allowedProtocols:f};return X}function O7(Z,J){let X=Z.watch||J.watch?.enabled,$=Z.profile??J.profile?.iterations;if($&&$>0)return"profile";if(X)return"watch";return"normal"}function d0(Z,J){return{iterations:Z.profile??J.profile?.iterations??10,warmup:Z.profileWarmup??J.profile?.warmup??1,concurrency:Z.profileConcurrency??J.profile?.concurrency??1,histogram:Z.profileHistogram??J.profile?.histogram??!1,exportFile:Z.profileExport??J.profile?.exportFile}}function f0(Z,J){return{enabled:!0,debounce:Z.watchDebounce??J.watch?.debounce??300,clear:Z.watchClear??J.watch?.clear??!0}}import*as a from"fs/promises";import*as v from"path";var _7=1,F7="__baselines__";class K1{baselineDir;writeLocks=new Map;constructor(Z={}){this.baselineDir=Z.dir||F7}getBaselinePath(Z,J){let X=v.dirname(Z),$=v.basename(Z,v.extname(Z));return v.join(X,this.baselineDir,`${$}.${J}.baseline.json`)}getBaselineDir(Z){return v.join(v.dirname(Z),this.baselineDir)}async load(Z,J){let X=this.getBaselinePath(Z,J);try{let $=Bun.file(X);if(!await $.exists())return null;let W=await $.text();return JSON.parse(W)}catch{return null}}async save(Z,J,X){let $=this.getBaselinePath(Z,J),W=this.writeLocks.get($),Q=(async()=>{if(W)await W;let G=v.dirname($);await a.mkdir(G,{recursive:!0});let Y=JSON.stringify(X,null,2);await Bun.write($,Y)})();this.writeLocks.set($,Q),await Q,this.writeLocks.delete($)}async get(Z,J,X){return(await this.load(Z,J))?.baselines[X]||null}async listLabels(Z){let J=this.getBaselineDir(Z),X=v.basename(Z,v.extname(Z));try{let $=await a.readdir(J),W=[];for(let Q of $){let G=Q.match(new RegExp(`^${X}\\.(.+)\\.baseline\\.json$`));if(G)W.push(G[1])}return W.sort()}catch{return[]}}createBaseline(Z,J){let X={hash:"",capturedAt:new Date().toISOString()};if(Z.status!==void 0)X.status=Z.status;if(Z.headers)X.headers=this.normalizeHeaders(Z.headers);if(Z.body!==void 0)X.body=Z.body;if(J.includeTimings&&Z.metrics?.duration!==void 0)X.timing=Z.metrics.duration;return X.hash=this.hash(X),X}normalizeHeaders(Z){let J={},X=Object.keys(Z).sort();for(let $ of X){let W=Z[$];J[$.toLowerCase()]=Array.isArray(W)?W.join(", "):W}return J}hash(Z){let J=JSON.stringify(Z),X=new Bun.CryptoHasher("md5");return X.update(J),X.digest("hex").slice(0,8)}async saveBaseline(Z,J,X,$){let W={};for(let G of X){if(G.skipped||!G.success)continue;let Y=G.request.name||G.request.url;W[Y]=this.createBaseline(G,$)}let Q={version:_7,label:J,capturedAt:new Date().toISOString(),baselines:W};await this.save(Z,J,Q)}async cleanOldBaselines(Z,J){let X=this.getBaselineDir(Z),$=Date.now()-J*24*60*60*1000,W=0;try{let Q=await a.readdir(X);for(let G of Q){if(!G.endsWith(".baseline.json"))continue;let Y=v.join(X,G);if((await a.stat(Y)).mtimeMs<$)await a.unlink(Y),W++}}catch{}return W}static mergeConfig(Z,J){if(!J&&!Z?.enabled)return null;if(J===!0)return{enabled:!0,exclude:Z?.exclude||[],match:Z?.match||{},includeTimings:Z?.includeTimings||!1};if(typeof J==="object"&&J.enabled!==!1)return{enabled:!0,exclude:[...Z?.exclude||[],...J.exclude||[]],match:{...Z?.match||{},...J.match||{}},includeTimings:J.includeTimings??Z?.includeTimings??!1};if(Z?.enabled&&J===void 0)return{enabled:!0,exclude:Z.exclude||[],match:Z.match||{},includeTimings:Z.includeTimings||!1};return null}}var F1={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 r(Z,J){return`${F1[J]}${Z}${F1.reset}`}function l(Z){if(Z<1000)return`${Z.toFixed(0)}ms`;return`${(Z/1000).toFixed(2)}s`}function Z1(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 v1(Z){if(!Z)return"0 B";let J=["B","KB","MB","GB"],X=Math.floor(Math.log(Z)/Math.log(1024));return`${(Z/1024**X).toFixed(2)} ${J[X]}`}function m1(Z,J="pretty"){if(J==="raw")return typeof Z==="string"?Z:JSON.stringify(Z);if(J==="json")return JSON.stringify(Z);return JSON.stringify(Z,null,2)}function p0(Z){return Z.replace(/.*\//,"").replace(".yaml","")}class U1{color(Z,J){if(!J||!(J in F1))return Z;return r(Z,J)}render(Z,J=" "){Z.forEach((X,$)=>{let W=$===Z.length-1,Q=W?`${J}\u2514\u2500`:`${J}\u251C\u2500`;if(X.label&&X.value){let G=X.color?this.color(X.value,X.color):X.value,Y=G.split(`
133
- `);if(Y.length===1)console.log(`${Q} ${X.label}: ${G}`);else{console.log(`${Q} ${X.label}:`);let z=W?`${J} `:`${J}\u2502 `;for(let H of Y)console.log(`${z}${H}`)}}else if(X.label&&!X.value)console.log(`${Q} ${X.label}:`);else if(!X.label&&X.value){let G=W?`${J} `:`${J}\u2502 `;console.log(`${G}${X.value}`)}if(X.children&&X.children.length>0){let G=W?`${J} `:`${J}\u2502 `;this.render(X.children,G)}})}}class D1{outputFormat;constructor(Z="terminal"){this.outputFormat=Z}color(Z,J){if(this.outputFormat!=="terminal")return Z;return r(Z,J)}formatSummary(Z,J,X){switch(this.outputFormat){case"json":return this.formatSummaryJson(Z);case"markdown":return this.formatSummaryMarkdown(Z,J,X);default:return this.formatSummaryTerminal(Z,J,X)}}formatSummaryTerminal(Z,J,X){let $=[];$.push(""),$.push(`${this.color("Response Diff:","bright")} ${this.color(J,"cyan")} \u2192 ${this.color(X,"cyan")}`),$.push("");for(let W of Z.results)$.push(this.formatResultTerminal(W)),$.push("");return $.push(this.formatStatsSummary(Z)),$.join(`
134
- `)}formatSummaryJson(Z){return JSON.stringify({summary:{total:Z.totalRequests,unchanged:Z.unchanged,changed:Z.changed,newBaselines:Z.newBaselines},results:Z.results.map((J)=>({request:J.requestName,status:J.hasDifferences?"changed":J.isNewBaseline?"new":"unchanged",differences:J.differences,timingDiff:J.timingDiff}))},null,2)}formatSummaryMarkdown(Z,J,X){let $=[];if($.push(`# Response Diff: ${J} \u2192 ${X}`),$.push(""),$.push("| Metric | Count |"),$.push("|--------|-------|"),$.push(`| Total Requests | ${Z.totalRequests} |`),$.push(`| Unchanged | ${Z.unchanged} |`),$.push(`| Changed | ${Z.changed} |`),$.push(`| New Baselines | ${Z.newBaselines} |`),$.push(""),Z.changed>0){$.push("## Changes"),$.push("");for(let W of Z.results)if(W.hasDifferences)$.push(this.formatResultMarkdown(W))}if(Z.newBaselines>0){$.push("## New Requests"),$.push("");for(let W of Z.results)if(W.isNewBaseline)$.push(`- \`${W.requestName}\``);$.push("")}return $.join(`
135
- `)}formatResultTerminal(Z){let J=[];if(Z.isNewBaseline)return J.push(` ${this.color("NEW","cyan")} ${this.color(Z.requestName,"bright")}`),J.join(`
136
- `);if(!Z.hasDifferences)return J.push(` ${this.color("\u2713","green")} ${this.color(Z.requestName,"bright")} ${this.color("(no changes)","dim")}`),J.join(`
137
- `);J.push(` ${this.color("\u2717","red")} ${this.color(Z.requestName,"bright")}`);for(let X of Z.differences)J.push(this.formatDifferenceTerminal(X));if(Z.timingDiff){let{baseline:X,current:$,changePercent:W}=Z.timingDiff,Q=W>=0?"+":"",G=W>20?"red":W<-20?"green":"yellow";J.push(` ${this.color("timing:","cyan")} ${X}ms \u2192 ${$}ms ${this.color(`(${Q}${W.toFixed(0)}%)`,G)}`)}return J.join(`
138
- `)}formatDifferenceTerminal(Z){let J=[],X=Z.path||"(root)";switch(Z.type){case"added":J.push(` ${this.color(X,"cyan")}:`),J.push(` ${this.color(`+ ${this.stringify(Z.current)}`,"green")}`);break;case"removed":J.push(` ${this.color(X,"cyan")}:`),J.push(` ${this.color(`- ${this.stringify(Z.baseline)}`,"red")}`);break;case"changed":J.push(` ${this.color(X,"cyan")}:`),J.push(` ${this.color(`- ${this.stringify(Z.baseline)}`,"red")}`),J.push(` ${this.color(`+ ${this.stringify(Z.current)}`,"green")}`);break;case"type_mismatch":J.push(` ${this.color(X,"cyan")} (type mismatch):`),J.push(` ${this.color(`- ${this.stringify(Z.baseline)} (${typeof Z.baseline})`,"red")}`),J.push(` ${this.color(`+ ${this.stringify(Z.current)} (${typeof Z.current})`,"green")}`);break}return J.join(`
139
- `)}formatResultMarkdown(Z){let J=[];J.push(`### \`${Z.requestName}\``),J.push(""),J.push("```diff");for(let X of Z.differences)J.push(this.formatDifferenceMarkdown(X));if(J.push("```"),Z.timingDiff){let{baseline:X,current:$,changePercent:W}=Z.timingDiff,Q=W>=0?"+":"";J.push(""),J.push(`**Timing:** ${X}ms \u2192 ${$}ms (${Q}${W.toFixed(0)}%)`)}return J.push(""),J.join(`
140
- `)}formatDifferenceMarkdown(Z){let J=[],X=Z.path||"(root)";switch(Z.type){case"added":J.push(`# ${X}:`),J.push(`+ ${this.stringify(Z.current)}`);break;case"removed":J.push(`# ${X}:`),J.push(`- ${this.stringify(Z.baseline)}`);break;case"changed":J.push(`# ${X}:`),J.push(`- ${this.stringify(Z.baseline)}`),J.push(`+ ${this.stringify(Z.current)}`);break;case"type_mismatch":J.push(`# ${X} (type mismatch):`),J.push(`- ${this.stringify(Z.baseline)} (${typeof Z.baseline})`),J.push(`+ ${this.stringify(Z.current)} (${typeof Z.current})`);break}return J.join(`
141
- `)}formatStatsSummary(Z){let J=[];if(Z.unchanged>0)J.push(this.color(`${Z.unchanged} unchanged`,"green"));if(Z.changed>0)J.push(this.color(`${Z.changed} changed`,"red"));if(Z.newBaselines>0)J.push(this.color(`${Z.newBaselines} new`,"cyan"));return`Summary: ${J.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 J=JSON.stringify(Z);if(J.length>80)return`${J.slice(0,77)}...`;return J}return String(Z)}}class h1{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,J,X,$,W){let Q=[];if(Z.status!==void 0||J.status!==void 0){if(Z.status!==J.status&&!this.isExcluded("status"))Q.push({path:"status",baseline:Z.status,current:J.status,type:"changed"})}if(Z.headers||J.headers){let Y=this.compareObjects(Z.headers||{},J.headers||{},"headers");Q.push(...Y)}if(Z.body!==void 0||J.body!==void 0){let Y=this.deepCompare(Z.body,J.body,"body");Q.push(...Y)}let G={requestName:W,hasDifferences:Q.length>0,isNewBaseline:!1,baselineLabel:X,currentLabel:$,differences:Q};if(this.includeTimings&&Z.timing!==void 0&&J.timing!==void 0){let Y=(J.timing-Z.timing)/Z.timing*100;G.timingDiff={baseline:Z.timing,current:J.timing,changePercent:Y}}return G}deepCompare(Z,J,X){if(this.isExcluded(X))return[];if(this.matchesRule(X,J))return[];if(Z===null&&J===null)return[];if(Z===void 0&&J===void 0)return[];let $=this.getType(Z),W=this.getType(J);if($!==W)return[{path:X,baseline:Z,current:J,type:"type_mismatch"}];if($!=="object"&&$!=="array"){if(Z!==J)return[{path:X,baseline:Z,current:J,type:"changed"}];return[]}if($==="array")return this.compareArrays(Z,J,X);return this.compareObjects(Z,J,X)}compareArrays(Z,J,X){let $=[],W=Math.max(Z.length,J.length);for(let Q=0;Q<W;Q++){let G=`${X}[${Q}]`;if(Q>=Z.length){if(!this.isExcluded(G))$.push({path:G,baseline:void 0,current:J[Q],type:"added"})}else if(Q>=J.length){if(!this.isExcluded(G))$.push({path:G,baseline:Z[Q],current:void 0,type:"removed"})}else{let Y=this.deepCompare(Z[Q],J[Q],G);$.push(...Y)}}return $}compareObjects(Z,J,X){let $=[],W=new Set([...Object.keys(Z),...Object.keys(J)]);for(let Q of W){let G=X?`${X}.${Q}`:Q,Y=Q in Z,z=Q in J;if(!Y&&z){if(!this.isExcluded(G))$.push({path:G,baseline:void 0,current:J[Q],type:"added"})}else if(Y&&!z){if(!this.isExcluded(G))$.push({path:G,baseline:Z[Q],current:void 0,type:"removed"})}else{let H=this.deepCompare(Z[Q],J[Q],G);$.push(...H)}}return $}isExcluded(Z){if(this.excludePaths.has(Z))return!0;for(let J of this.excludePaths){if(J.startsWith("*.")){let X=J.slice(2);if(Z.endsWith(`.${X}`))return!0;if(Z.split(".").pop()===X)return!0}if(J.includes("[*]")){if(new RegExp(`^${J.replace(/\[\*\]/g,"\\[\\d+\\]").replace(/\./g,"\\.")}$`).test(Z))return!0}}return!1}matchesRule(Z,J){let X=this.matchRules.get(Z);if(!X)return!1;if(X==="*")return!0;if(X.startsWith("regex:")){let $=X.slice(6);try{return new RegExp($).test(String(J))}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 N1{manager;constructor(Z={}){this.manager=new K1(Z)}async compareWithBaseline(Z,J,X,$,W){let Q=await this.manager.load(Z,$),G=[];for(let Y of J){if(Y.skipped||!Y.success)continue;let z=Y.request.name||Y.request.url,H=this.manager.createBaseline(Y,W);if(!Q){G.push({requestName:z,hasDifferences:!1,isNewBaseline:!0,baselineLabel:$,currentLabel:X,differences:[]});continue}let K=Q.baselines[z];if(!K){G.push({requestName:z,hasDifferences:!1,isNewBaseline:!0,baselineLabel:$,currentLabel:X,differences:[]});continue}let U=new h1(W).compare(K,H,$,X,z);G.push(U)}return{totalRequests:G.length,unchanged:G.filter((Y)=>!Y.hasDifferences&&!Y.isNewBaseline).length,changed:G.filter((Y)=>Y.hasDifferences).length,newBaselines:G.filter((Y)=>Y.isNewBaseline).length,results:G}}async compareTwoBaselines(Z,J,X,$){let W=await this.manager.load(Z,J),Q=await this.manager.load(Z,X);if(!W)throw Error(`Baseline '${J}' not found`);if(!Q)throw Error(`Baseline '${X}' not found`);let G=new Set([...Object.keys(W.baselines),...Object.keys(Q.baselines)]),Y=[],z=new h1($);for(let H of G){let K=W.baselines[H],B=Q.baselines[H];if(!K){Y.push({requestName:H,hasDifferences:!0,isNewBaseline:!1,baselineLabel:J,currentLabel:X,differences:[{path:"",baseline:void 0,current:"exists",type:"added"}]});continue}if(!B){Y.push({requestName:H,hasDifferences:!0,isNewBaseline:!1,baselineLabel:J,currentLabel:X,differences:[{path:"",baseline:"exists",current:void 0,type:"removed"}]});continue}let U=z.compare(K,B,J,X,H);Y.push(U)}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,J,X,$){await this.manager.saveBaseline(Z,J,X,$)}async listLabels(Z){return this.manager.listLabels(Z)}getManager(){return this.manager}}function c0(Z){return typeof Z==="object"&&Z!==null&&"file"in Z}var D7=`
142
- __CURL_METRICS_START__%{json}__CURL_METRICS_END__`;function T1(Z,J={}){let{writeOutMarker:X=D7,includeSilentFlags:$=!0,includeHttp2Flag:W=!0,includeOutputFlag:Q=!0,allowedProtocols:G=f}=J,Y=[];if(Y.push("-X",Z.method||"GET"),Y.push("-w",X),Y.push("-D","-"),Z.headers)for(let[K,B]of Object.entries(Z.headers))Y.push("-H",`${K}: ${B}`);if(Z.auth){if(Z.auth.type==="basic"&&Z.auth.username&&Z.auth.password)Y.push("-u",`${Z.auth.username}:${Z.auth.password}`);else if(Z.auth.type==="bearer"&&Z.auth.token)Y.push("-H",`Authorization: Bearer ${Z.auth.token}`)}if(Z.formData)for(let[K,B]of Object.entries(Z.formData))if(c0(B)){let U=`@${B.file}`;if(B.filename)U+=`;filename=${B.filename}`;if(B.contentType)U+=`;type=${B.contentType}`;Y.push("-F",`${K}=${U}`)}else{let U=String(B);Y.push("--form-string",`${K}=${U}`)}else if(Z.body){let K=typeof Z.body==="string"?Z.body:JSON.stringify(Z.body);if(Y.push("--data-raw",K),!Z.headers?.["Content-Type"])Y.push("-H","Content-Type: application/json")}if(Z.timeout)Y.push("--max-time",Z.timeout.toString());if(Z.followRedirects!==!1){if(Y.push("-L"),Z.maxRedirects)Y.push("--max-redirs",Z.maxRedirects.toString())}if(Z.proxy)Y.push("-x",Z.proxy);if(Z.insecure||Z.ssl?.verify===!1)Y.push("-k");if(Z.ssl){if(Z.ssl.ca)Y.push("--cacert",Z.ssl.ca);if(Z.ssl.cert)Y.push("--cert",Z.ssl.cert);if(Z.ssl.key)Y.push("--key",Z.ssl.key)}if(Q&&Z.output)Y.push("-o",Z.output);if(W&&Z.http2)Y.push("--http2");let z=`-all,${G.join(",")}`;if(Y.push("--proto",z),Y.push("--proto-redir",z),$)Y.push("-s","-S");let H=Z.url;if(Z.params&&Object.keys(Z.params).length>0){let K=new URLSearchParams(Z.params).toString();H+=(H.includes("?")?"&":"?")+K}return{args:Y,url:H}}function I1(Z){return["curl",...Z].map((J)=>J.includes(" ")||J.includes('"')||J.includes("'")?`'${J.replace(/'/g,"'\\''")}'`:J).join(" ")}function u0(Z){return`
143
- __CURL_BATCH_${Z}_START__%{json}__CURL_BATCH_${Z}_END__
144
- `}var g1="__CURL_METRICS_START__",d1="__CURL_METRICS_END__";function G1(Z,J){if(!Z)return Z;try{let X=J?.includes("application/json"),$=Z.trim().startsWith("{")||Z.trim().startsWith("[");if(X||$)return JSON.parse(Z)}catch{}return Z}function j1(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 Q4(Z){let J=Z.match(new RegExp(`${g1}(.+?)${d1}`));if(!J)return{body:Z,metrics:{}};let X=Z.replace(new RegExp(`${g1}.+?${d1}`),"").trim(),$={};try{$=JSON.parse(J[1])}catch{}return{body:X,metrics:$}}function l0(Z,J){let X=`__CURL_BATCH_${J}_START__`,$=`__CURL_BATCH_${J}_END__`,W=Z.indexOf(X),Q=Z.indexOf($);if(W===-1||Q===-1)return{found:!1,metricsJson:"",startIdx:-1,endIdx:-1};return{found:!0,metricsJson:Z.substring(W+X.length,Q),startIdx:W,endIdx:Q}}var N7=/^HTTP\/[\d.]+\s+(\d{3})/;function f1(Z){let J=[],X=0;while(X<Z.length){while(X<Z.length){let U=Z.charCodeAt(X);if(U===13||U===10||U===32||U===9)X++;else break}if(X>=Z.length)break;let $=Z.slice(X).match(N7);if(!$)break;let W=Number($[1]),Q=Z.indexOf(`\r
145
- \r
146
- `,X),G=Z.indexOf(`
147
-
148
- `,X),Y,z;if(Q!==-1&&(G===-1||Q<=G))Y=Q,z=4;else if(G!==-1)Y=G,z=2;else break;let K=Z.indexOf(`
149
- `,X)+1,B={};if(K>0&&K<Y)for(let U of Z.slice(K,Y).split(/\r?\n/)){if(!U)continue;let D=U.indexOf(":");if(D===-1)continue;let O=U.slice(0,D).trim().toLowerCase();if(!O)continue;let _=U.slice(D+1).trim(),F=B[O];if(F===void 0)B[O]=_;else if(Array.isArray(F))F.push(_);else B[O]=[F,_]}J.push({status:W,headers:B}),X=Y+z}return{blocks:J,bodyOffset:X}}function n0(Z){let{blocks:J,bodyOffset:X}=f1(Z),$;for(let G=J.length-1;G>=0;G--)if(J[G].status>=200){$=J[G];break}let{body:W,metrics:Q}=Q4(Z.slice(X));return{headers:$?.headers??{},status:$?.status,headerHistory:J,body:W,metrics:Q}}function L1(Z){return Z.response_code||Z.http_code}function o0(Z){if(Z===void 0)return!1;return Z>=200&&Z<400}class J1{static buildCommand(Z,J=f){let{args:X,url:$}=T1(Z,{includeSilentFlags:!0,includeHttp2Flag:!0,includeOutputFlag:!0,allowedProtocols:J});return X.push("--",$),X}static formatCommandForDisplay(Z){return I1(Z)}static async executeCurl(Z){try{let J=Bun.spawn(["curl",...Z],{stdout:"pipe",stderr:"pipe"}),X=await new Response(J.stdout).text(),$=await new Response(J.stderr).text();if(await J.exited,J.exitCode!==0&&!X)return{success:!1,error:$||`Command failed with exit code ${J.exitCode}`};let{headers:W,status:Q,headerHistory:G,body:Y,metrics:z}=n0(X),H=L1(z)??Q,K=j1(z);return{success:!0,status:H,headers:W,headerHistory:G,body:Y,metrics:K}}catch(J){return{success:!1,error:J instanceof Error?J.message:String(J)}}}}class i0{color(Z,J){return r(Z,J)}formatResult(Z,J){let X=[];if(J.isNew&&J.updated)return X.push(` ${this.color("NEW","cyan")} Snapshot created for "${this.color(Z,"bright")}"`),X.join(`
150
- `);if(J.updated)return X.push(` ${this.color("UPDATED","yellow")} Snapshot updated for "${this.color(Z,"bright")}"`),X.join(`
151
- `);if(J.match)return X.push(` ${this.color("PASS","green")} Snapshot matches for "${this.color(Z,"bright")}"`),X.join(`
152
- `);return X.push(` ${this.color("FAIL","red")} Snapshot mismatch for "${this.color(Z,"bright")}"`),X.push(""),X.push(this.formatDiff(J.differences)),X.push(""),X.push(this.color(" Run with --update-snapshots (-u) to update","dim")),X.join(`
153
- `)}formatDiff(Z){let J=[];J.push(` ${this.color("- Expected","red")}`),J.push(` ${this.color("+ Received","green")}`),J.push("");for(let X of Z)J.push(this.formatDifference(X));return J.join(`
154
- `)}formatDifference(Z){let J=[],X=Z.path||"(root)";switch(Z.type){case"added":J.push(` ${this.color(X,"cyan")}:`),J.push(` ${this.color(`+ ${this.stringify(Z.received)}`,"green")}`);break;case"removed":J.push(` ${this.color(X,"cyan")}:`),J.push(` ${this.color(`- ${this.stringify(Z.expected)}`,"red")}`);break;case"changed":J.push(` ${this.color(X,"cyan")}:`),J.push(` ${this.color(`- ${this.stringify(Z.expected)}`,"red")}`),J.push(` ${this.color(`+ ${this.stringify(Z.received)}`,"green")}`);break;case"type_mismatch":J.push(` ${this.color(X,"cyan")} (type mismatch):`),J.push(` ${this.color(`- ${this.stringify(Z.expected)} (${typeof Z.expected})`,"red")}`),J.push(` ${this.color(`+ ${this.stringify(Z.received)} (${typeof Z.received})`,"green")}`);break}return J.join(`
155
- `)}stringify(Z){if(Z===void 0)return"undefined";if(Z===null)return"null";if(typeof Z==="string")return`"${Z}"`;if(typeof Z==="object"){let J=JSON.stringify(Z);if(J.length>80)return`${J.slice(0,77)}...`;return J}return String(Z)}formatSummary(Z){let J=[];if(Z.passed>0)J.push(this.color(`${Z.passed} passed`,"green"));if(Z.failed>0)J.push(this.color(`${Z.failed} failed`,"red"));if(Z.updated>0)J.push(this.color(`${Z.updated} updated`,"yellow"));if(Z.created>0)J.push(this.color(`${Z.created} created`,"cyan"));if(J.length===0)return"";return`Snapshots: ${J.join(", ")}`}}function p1(Z,J){if(Z.length===0)return 0;if(Z.length===1)return Z[0];let X=J/100*(Z.length-1),$=Math.floor(X),W=Math.ceil(X),Q=X-$;if($===W)return Z[$];return Z[$]*(1-Q)+Z[W]*Q}function T7(Z){if(Z.length===0)return 0;return Z.reduce((J,X)=>J+X,0)/Z.length}function I7(Z,J){if(Z.length<=1)return 0;let $=Z.map((W)=>(W-J)**2).reduce((W,Q)=>W+Q,0)/Z.length;return Math.sqrt($)}function G4(Z,J,X){let $=Z.slice(J),W=[...$].sort((z,H)=>z-H),Q=T7(W),G=Z.length;return{iterations:$.length,warmup:J,min:W.length>0?W[0]:0,max:W.length>0?W[W.length-1]:0,mean:Math.round(Q*100)/100,median:Math.round(p1(W,50)*100)/100,p50:Math.round(p1(W,50)*100)/100,p95:Math.round(p1(W,95)*100)/100,p99:Math.round(p1(W,99)*100)/100,stdDev:Math.round(I7(W,Q)*100)/100,failures:X,failureRate:G>0?Math.round(X/G*1e4)/100:0,timings:$}}function Y4(Z,J=10,X=40){if(Z.length===0)return["No data"];let $=Math.min(...Z),G=(Math.max(...Z)-$||1)/J,Y=Array(J).fill(0);for(let K of Z){let B=Math.min(Math.floor((K-$)/G),J-1);Y[B]++}let z=Math.max(...Y),H=[];for(let K=0;K<J;K++){let B=$+K*G,U=$+(K+1)*G,D=z>0?Math.round(Y[K]/z*X):0,O="\u2588".repeat(D),_=`${B.toFixed(0).padStart(6)}ms - ${U.toFixed(0).padStart(6)}ms`;H.push(`${_} \u2502${O} ${Y[K]}`)}return H}function z4(Z,J){let X=["iteration","latency_ms"],$=Z.timings.map((W,Q)=>`${Q+1},${W}`);return[X.join(","),...$].join(`
156
- `)}function H4(Z,J){return JSON.stringify({request:J,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 n{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,J){return r(Z,J)}shouldShowOutput(){if(this.config.quiet)return!1;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 J=Z.split("; ");if(J.length===1){let X=J[0].trim(),$=X.match(/^Expected status (.+?), got (.+)$/);if($){let[,W,Q]=$,G=this.colorStatusCode(W.replace(" or ","|")),Y=this.color(Q,"red");console.log(` ${this.color("\u2717","red")} ${this.color("Error:","red")} Expected ${this.color("status","yellow")} ${G}, got ${Y}`)}else console.log(` ${this.color("\u2717","red")} ${this.color("Error:","red")} ${X}`)}else{console.log(` ${this.color("\u2717","red")} ${this.color("Validation Errors:","red")}`);for(let X of J){let $=X.trim();if($)if($.startsWith("Expected ")){let W=$.match(/^Expected status (.+?), got (.+)$/);if(W){let[,Q,G]=W,Y=this.colorStatusCode(Q.replace(" or ","|")),z=this.color(G,"red");console.log(` ${this.color("\u2022","red")} ${this.color("status","yellow")}: expected ${Y}, got ${z}`)}else{let Q=$.match(/^Expected (.+?) to be (.+?), got (.+)$/);if(Q){let[,G,Y,z]=Q;console.log(` ${this.color("\u2022","red")} ${this.color(G,"yellow")}: expected ${this.color(Y,"green")}, got ${this.color(z,"red")}`)}else console.log(` ${this.color("\u2022","red")} ${$}`)}}else console.log(` ${this.color("\u2022","red")} ${$}`)}}}logExecutionStart(Z,J){if(!this.shouldShowOutput())return;if(this.shouldShowSeparators())console.log(),console.log(this.color(`Executing ${Z} request(s) in ${J} mode`,"dim")),console.log();else console.log()}logRequestStart(Z,J){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,J){if(!this.shouldShowOutput())return;console.log(this.color(` \u21BB Retry ${Z}/${J}...`,"yellow"))}logRequestComplete(Z){if(this.config.quiet)return;if(this.config.format==="raw"){if(Z.success&&this.config.showBody&&Z.body){let Y=m1(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 J=this.config.prettyLevel||"minimal",X=Z.success?"green":"red",$=Z.success?"\u2713":"x",W=Z.request.name||"Request";if(J==="minimal"){let Y=Z.request.sourceFile?p0(Z.request.sourceFile):"inline";console.log(`${this.color($,X)} ${this.color(W,"bright")} [${Y}]`);let z=[],H=new U1;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:`${$} Status`,value:K,color:Z.dryRun?"cyan":X}),Z.metrics){let B=`${l(Z.metrics.duration)} | ${v1(Z.metrics.size)}`;z.push({label:"Duration",value:B,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($,X)} ${this.color(W,"bright")}`);let Q=[],G=new U1;if(Q.push({label:"URL",value:this.redact(Z.request.url),color:"blue"}),Q.push({label:"Method",value:Z.request.method||"GET",color:"yellow"}),Q.push({label:"Status",value:Z.dryRun?"DRY-RUN":String(Z.status||"ERROR"),color:Z.dryRun?"cyan":X}),Z.metrics)Q.push({label:"Duration",value:l(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)}));Q.push({label:"Headers",children:Y})}if(this.shouldShowBody()&&Z.body){let z=m1(Z.body,this.config.format).split(`
157
- `),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"));Q.push({label:"Response Body",value:K.join(`
158
- `)})}if(this.shouldShowMetrics()&&Z.metrics&&J==="detailed"){let Y=Z.metrics,z=[];if(z.push({label:"Request Duration",value:l(Y.duration),color:"cyan"}),Y.size!==void 0)z.push({label:"Response Size",value:v1(Y.size),color:"cyan"});if(Y.dnsLookup)z.push({label:"DNS Lookup",value:l(Y.dnsLookup),color:"cyan"});if(Y.tcpConnection)z.push({label:"TCP Connection",value:l(Y.tcpConnection),color:"cyan"});if(Y.tlsHandshake)z.push({label:"TLS Handshake",value:l(Y.tlsHandshake),color:"cyan"});if(Y.firstByte)z.push({label:"Time to First Byte",value:l(Y.firstByte),color:"cyan"});Q.push({label:"Metrics",children:z})}if(G.render(Q),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,J){if(!J)return;let X=new i0;console.log(X.formatResult(Z,J))}logSummary(Z,J=!1){if(this.config.quiet)return;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 X=this.config.prettyLevel||"minimal";if(J)console.log();if(X==="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(`${J?"\u25C6 Global Summary":"Summary"}: ${this.color(K,z)}`);return}let $=(Z.successful/Z.total*100).toFixed(1),W=Z.failed===0?"green":"red",Q=Z.skipped>0?`, ${Z.skipped} skipped`:"",G=Z.failed===0?`${Z.total} request${Z.total===1?"":"s"} completed successfully${Q}`:`${Z.successful}/${Z.total} request${Z.total===1?"":"s"} completed, ${Z.failed} failed${Q}`,Y=J?"\u25C6 Global Summary":"Summary";if(console.log(),console.log(`${Y}: ${this.color(G,W)} (${this.color(l(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){if(!this.shouldShowOutput())return;console.warn(this.color(`\u26A0 ${Z}`,"yellow"))}logInfo(Z){if(!this.shouldShowOutput())return;console.log(this.color(`\u2139 ${Z}`,"blue"))}logSuccess(Z){if(!this.shouldShowOutput())return;console.log(this.color(`\u2713 ${Z}`,"green"))}logSkipped(Z,J,X){if(!this.shouldShowOutput())return;let $=Z.name||`Request ${J}`;if(this.config.format==="json"){let W={request:{name:Z.name,url:this.redact(Z.url),method:Z.method||"GET"},skipped:!0,reason:X||"condition not met"};console.log(JSON.stringify(W,null,2));return}if(console.log(`${this.color("\u2298","yellow")} ${this.color($,"bright")} ${this.color("[SKIP]","yellow")}`),X){let W=[{label:"Reason",value:X,color:"yellow"}];new U1().render(W)}console.log()}logFileHeader(Z,J){if(!this.shouldShowOutput()||this.config.format!=="pretty")return;let X=Z.replace(/.*\//,"").replace(".yaml","");console.log(),console.log(this.color(`\u25B6 ${X}.yaml`,"bright")+this.color(` (${J} request${J===1?"":"s"})`,"dim"))}logWatch(Z){if(!this.shouldShowOutput())return;console.log(),console.log(`${this.color("Watching for changes...","cyan")} ${this.color("(press Ctrl+C to stop)","dim")}`);let J=Z.length<=3?Z.join(", "):`${Z.length} files`;console.log(this.color(` Files: ${J}`,"dim")),console.log()}logWatchReady(){if(!this.shouldShowOutput())return;console.log(),console.log(this.color("Watching for changes...","cyan"))}logFileChanged(Z){if(!this.shouldShowOutput())return;let J=new Date().toLocaleTimeString("en-US",{hour12:!1});console.log(this.color("-".repeat(50),"dim")),console.log(`${this.color(`[${J}]`,"dim")} File changed: ${this.color(Z,"yellow")}`),console.log()}logProfileStart(Z,J,X,$){if(!this.shouldShowOutput())return;console.log(),console.log(`${this.color("\u26A1 PROFILING","magenta")} ${this.color(Z,"bright")}`),console.log(this.color(` ${J} iterations, ${X} warmup, concurrency: ${$}`,"dim"))}logProfileResult(Z,J){let{stats:X,request:$}=Z,W=$.name||$.url;if(this.config.format==="json"){console.log(JSON.stringify({request:{name:W,url:$.url,method:$.method||"GET"},stats:{iterations:X.iterations,warmup:X.warmup,failures:X.failures,failureRate:X.failureRate,min:X.min,max:X.max,mean:X.mean,median:X.median,p50:X.p50,p95:X.p95,p99:X.p99,stdDev:X.stdDev}}));return}if(this.config.format==="raw"){console.log(`${X.p50} ${X.p95} ${X.p99} ${X.mean}`);return}console.log();let Q=X.failures===0?this.color("\u2713","green"):this.color("\u26A0","yellow");if(console.log(`${Q} ${this.color(W,"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")} ${Z1(X.p50).padStart(10)} \u2502 ${this.color("min","dim")} ${Z1(X.min).padStart(10)} \u2502`),console.log(` \u2502 ${this.color("p95","yellow")} ${Z1(X.p95).padStart(10)} \u2502 ${this.color("max","dim")} ${Z1(X.max).padStart(10)} \u2502`),console.log(` \u2502 ${this.color("p99","red")} ${Z1(X.p99).padStart(10)} \u2502 ${this.color("mean","dim")} ${Z1(X.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 ${X.stdDev.toFixed(2)}ms | ${X.iterations} samples | ${X.failures} failures (${X.failureRate}%)`,"dim")),J&&X.timings.length>0){console.log(),console.log(this.color(" Distribution:","dim"));let G=Y4(X.timings,8,30);for(let Y of G)console.log(` ${this.color(Y,"dim")}`)}}logProfileSummary(Z){if(!this.shouldShowOutput())return;let J=Z.reduce(($,W)=>$+W.stats.iterations,0),X=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"}, ${J} total iterations`),X>0)console.log(this.color(` ${X} total failures`,"yellow"))}}class a0{logger;profileConfig;constructor(Z,J){this.profileConfig=J,this.logger=new n(Z.output)}async executeSingleIteration(Z){let J=performance.now(),X=J1.buildCommand(Z),$=await J1.executeCurl(X);if($.success){let W=$.headers?.["content-type"],Q=Array.isArray(W)?W[0]:W;return{request:Z,success:!0,status:$.status,headers:$.headers,body:G1($.body,Q),metrics:{...$.metrics,duration:performance.now()-J}}}return{request:Z,success:!1,error:$.error,metrics:{duration:performance.now()-J}}}async executeWithConcurrency(Z,J,X){let $=[];for(let W=0;W<J;W+=X){let Q=Math.min(X,J-W),G=await Promise.all(Array.from({length:Q},()=>this.executeSingleIteration(Z)));$.push(...G)}return $}async profileRequest(Z,J=0){let X=this.profileConfig.iterations,$=this.profileConfig.warmup??1,W=this.profileConfig.concurrency??1,Q=Z.name||`Request ${J+1}`;this.logger.logProfileStart(Q,X,$,W);let G=W===1?await this.executeSequentially(Z,X):await this.executeWithConcurrency(Z,X,W),Y=[],z=0;for(let B of G)if(B.success&&B.metrics?.duration!==void 0)Y.push(B.metrics.duration);else z++,Y.push(0);let H=Y.map((B,U)=>G[U].success?B:-1).filter((B)=>B>=0),K=G4(H,Math.min($,H.length),z);return{request:Z,stats:K,iterations:G}}async executeSequentially(Z,J){let X=[];for(let $=0;$<J;$++){let W=await this.executeSingleIteration(Z);X.push(W)}return X}async profileRequests(Z){let J=[];for(let X=0;X<Z.length;X++){let $=await this.profileRequest(Z[X],X);J.push($),this.logger.logProfileResult($,this.profileConfig.histogram??!1)}return J}}function e0(Z,J){if(!J)return{success:!0};let X=[];if(J.status!==void 0){let W=K4(Z.status,J.status);X.push(...W)}if(J.headers){let W=U4(Z.headers,J.headers);X.push(...W)}if(J.body!==void 0){let W=c1(Z.body,J.body,"");X.push(...W)}if(J.responseTime!==void 0&&Z.metrics){let W=Z.metrics.duration;if(!u1(W,J.responseTime))X.push(`Expected response time to match ${J.responseTime}ms, got ${W.toFixed(2)}ms`)}let $=X.length>0;if(J.failure===!0){if($)return{success:!1,error:X.join("; ")};let W=Z.status||0;if(W>=400)return{success:!0};return{success:!1,error:`Expected request to fail (4xx/5xx) but got status ${W}`}}if($)return{success:!1,error:X.join("; ")};return{success:!0}}function K4(Z,J){let X=Array.isArray(J)?J:[J];if(!X.includes(Z||0))return[`Expected status ${X.join(" or ")}, got ${Z}`];return[]}function U4(Z,J){let X=[];for(let[$,W]of Object.entries(J)){let Q=Z?.[$.toLowerCase()];if(!(Array.isArray(Q)?Q.includes(W)||Q.join(", ")===W:Q===W)){let Y=Array.isArray(Q)?`[${Q.map((z)=>`"${z}"`).join(", ")}]`:`"${Q}"`;X.push(`Expected header ${$}="${W}", got ${Y}`)}}return X}function c1(Z,J,X){let $=[];if(typeof J!=="object"||J===null){let W=R1(Z,J,X||"body");if(!W.isValid)$.push(W.error);return $}if(Array.isArray(J)){if(Array.isArray(Z)){for(let Q=0;Q<J.length;Q++){let G=J[Q],Y=`${X||"body"}[${Q}]`;if(typeof G==="object"&&G!==null){if(!Z.some((H)=>{return c1(H,G,Y).length===0}))$.push(`Expected ${X||"body"} to contain item matching ${JSON.stringify(G)}, but no match found`)}else if(!Z.some((H)=>{return R1(H,G,Y).isValid}))$.push(`Expected ${X||"body"} to contain item matching ${JSON.stringify(G)}, but no match found`)}return $}let W=R1(Z,J,X||"body");if(!W.isValid)$.push(W.error);return $}for(let[W,Q]of Object.entries(J)){let G=X?`${X}.${W}`:W,Y;if(Array.isArray(Z)&&B4(W))Y=M4(Z,W);else Y=Z?.[W];if(typeof Q==="object"&&Q!==null){let z=c1(Y,Q,G);$.push(...z)}else{let z=R1(Y,Q,G);if(!z.isValid)$.push(z.error)}}return $}function R1(Z,J,X){if(J==="$absent"){if(Z!==void 0)return{isValid:!1,error:`Expected ${X} to be absent, got ${JSON.stringify(Z)}`};return{isValid:!0}}if(J==="$exists"){if(Z===void 0)return{isValid:!1,error:`Expected ${X} to exist, but it was absent`};return{isValid:!0}}if(J==="*")return{isValid:!0};if(Array.isArray(J)){if(!J.some((W)=>{if(W==="*")return!0;if(typeof W==="string"&&r0(W))return s0(Z,W);if(typeof W==="string"&&t0(W))return u1(Z,W);return Z===W}))return{isValid:!1,error:`Expected ${X} to match one of ${JSON.stringify(J)}, got ${JSON.stringify(Z)}`};return{isValid:!0}}if(typeof J==="string"&&r0(J)){if(!s0(Z,J))return{isValid:!1,error:`Expected ${X} to match pattern ${J}, got ${JSON.stringify(Z)}`};return{isValid:!0}}if(typeof J==="string"&&t0(J)){if(!u1(Z,J))return{isValid:!1,error:`Expected ${X} to match range ${J}, got ${JSON.stringify(Z)}`};return{isValid:!0}}if(J==="null"||J===null){if(Z!==null)return{isValid:!1,error:`Expected ${X} to be null, got ${JSON.stringify(Z)}`};return{isValid:!0}}if(Z!==J)return{isValid:!1,error:`Expected ${X} to be ${JSON.stringify(J)}, got ${JSON.stringify(Z)}`};return{isValid:!0}}function r0(Z){return Z.startsWith("^")||Z.endsWith("$")||Z.includes("\\d")||Z.includes("\\w")||Z.includes("\\s")}function s0(Z,J){let X=String(Z);try{let $=new RegExp(J),W=X.length>1e5?X.slice(0,1e5):X;return $.test(W)}catch{return!1}}function t0(Z){return/^(>=?|<=?|>|<)\s*[\d.-]+(\s*,\s*(>=?|<=?|>|<)\s*[\d.-]+)*$/.test(Z)}function u1(Z,J){let X=Number(Z);if(Number.isNaN(X))return!1;let $=J.match(/^([\d.-]+)\s*-\s*([\d.-]+)$/);if($){let Q=Number($[1]),G=Number($[2]);return X>=Q&&X<=G}return J.split(",").map((Q)=>Q.trim()).every((Q)=>{let G=Q.match(/^(>=?|<=?|>|<)\s*([\d.-]+)$/);if(!G)return!1;let Y=G[1],z=Number(G[2]);switch(Y){case">":return X>z;case">=":return X>=z;case"<":return X<z;case"<=":return X<=z;default:return!1}})}function B4(Z){return/^\[.*\]$/.test(Z)||Z==="*"||Z.startsWith("slice(")}function M4(Z,J){if(J==="*")return Z;if(J.startsWith("[")&&J.endsWith("]")){let X=J.slice(1,-1);if(X==="*")return Z;let $=Number(X);if(!Number.isNaN($))return $>=0?Z[$]:Z[Z.length+$]}if(J.startsWith("slice(")){let X=J.match(/slice\((\d+)(?:,(\d+))?\)/);if(X){let $=Number(X[1]),W=X[2]?Number(X[2]):void 0;return Z.slice($,W)}}return}async function l1(Z,J,X={}){if(Z.success&&J.expect){let Q=e0(Z,J.expect);if(!Q.success)Z.success=!1,Z.error=Q.error}let{snapshotManager:$,snapshotConfig:W}=X;if($&&W&&J.sourceFile&&Z.success){let Q=await $.compareAndUpdate(J.sourceFile,J.name||"Request",Z,W);if(Z.snapshotResult=Q,!Q.match&&!Q.updated){if(Z.success=!1,!Z.error)Z.error="Snapshot mismatch"}}return Z}function O4(Z,J,X){return J*X**(Z-1)}async function Z9(Z,J={}){let{config:X,shouldRetry:$,onRetry:W,getDelay:Q}=J,G=(X?.count??0)+1,Y=X?.delay??0,z=X?.backoff??1,H=0,K,B;while(H<G){if(H>0&&W)W(H,X?.count??0);if(H>0){let D=Q?.(H,B)??(Y>0?O4(H,Y,z):0);if(D>0)await Bun.sleep(D)}H++;try{let U=await Z();if(B=U,$?.(U)){K="Operation returned retriable result";continue}return{value:U,success:!0,attempts:H}}catch(U){K=U instanceof Error?U.message:String(U)}}return{value:B,success:!1,attempts:H,error:K}}var J9=[429,500,502,503,504];import{isAbsolute as j7,resolve as X9,sep as L7}from"path";function n1(Z,J){if(J?.allow)return{valid:!0,resolved:Z};let X=J?.baseDir??process.cwd(),$=X9(X),W;if(j7(Z))W=X9(Z);else W=X9($,Z);if(!(W===$||W.startsWith($+L7)))return{valid:!1,error:`Path "${Z}" escapes the working directory. Use --allow-path to permit it.`};return{valid:!0,resolved:W}}import*as s from"path";class $9{excludePaths;matchRules;constructor(Z){this.excludePaths=new Set(Z.exclude||[]),this.matchRules=new Map(Object.entries(Z.match||{}))}compare(Z,J){let X=[];if(Z.status!==void 0||J.status!==void 0){if(Z.status!==J.status&&!this.isExcluded("status"))X.push({path:"status",expected:Z.status,received:J.status,type:"changed"})}if(Z.headers||J.headers){let $=this.compareObjects(Z.headers||{},J.headers||{},"headers");X.push(...$)}if(Z.body!==void 0||J.body!==void 0){let $=this.deepCompare(Z.body,J.body,"body");X.push(...$)}return{match:X.length===0,differences:X}}deepCompare(Z,J,X){if(this.isExcluded(X))return[];if(this.matchesRule(X,J))return[];if(Z===null&&J===null)return[];if(Z===void 0&&J===void 0)return[];let $=this.getType(Z),W=this.getType(J);if($!==W)return[{path:X,expected:Z,received:J,type:"type_mismatch"}];if($!=="object"&&$!=="array"){if(Z!==J)return[{path:X,expected:Z,received:J,type:"changed"}];return[]}if($==="array")return this.compareArrays(Z,J,X);return this.compareObjects(Z,J,X)}compareArrays(Z,J,X){let $=[],W=Math.max(Z.length,J.length);for(let Q=0;Q<W;Q++){let G=`${X}[${Q}]`;if(Q>=Z.length){if(!this.isExcluded(G))$.push({path:G,expected:void 0,received:J[Q],type:"added"})}else if(Q>=J.length){if(!this.isExcluded(G))$.push({path:G,expected:Z[Q],received:void 0,type:"removed"})}else{let Y=this.deepCompare(Z[Q],J[Q],G);$.push(...Y)}}return $}compareObjects(Z,J,X){let $=[],W=new Set([...Object.keys(Z),...Object.keys(J)]);for(let Q of W){let G=X?`${X}.${Q}`:Q,Y=Q in Z,z=Q in J;if(!Y&&z){if(!this.isExcluded(G))$.push({path:G,expected:void 0,received:J[Q],type:"added"})}else if(Y&&!z){if(!this.isExcluded(G))$.push({path:G,expected:Z[Q],received:void 0,type:"removed"})}else{let H=this.deepCompare(Z[Q],J[Q],G);$.push(...H)}}return $}isExcluded(Z){if(this.excludePaths.has(Z))return!0;for(let J of this.excludePaths){if(J.startsWith("*.")){let X=J.slice(2);if(Z.endsWith(`.${X}`))return!0;if(Z.split(".").pop()===X)return!0}if(J.includes("[*]")){if(new RegExp(`^${J.replace(/\[\*\]/g,"\\[\\d+\\]").replace(/\./g,"\\.")}$`).test(Z))return!0}}return!1}matchesRule(Z,J){let X=this.matchRules.get(Z);if(!X)return!1;if(X==="*")return!0;if(X.startsWith("regex:")){let $=X.slice(6);try{return new RegExp($).test(String(J))}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 R7=1,S7="__snapshots__";class o1{snapshotDir;globalConfig;writeLocks=new Map;constructor(Z={}){this.globalConfig=Z,this.snapshotDir=Z.dir||S7}getSnapshotPath(Z){let J=s.dirname(Z),X=s.basename(Z,s.extname(Z));return s.join(J,this.snapshotDir,`${X}.snap.json`)}async load(Z){let J=this.getSnapshotPath(Z);try{let X=Bun.file(J);if(!await X.exists())return null;let $=await X.text();return JSON.parse($)}catch{return null}}async save(Z,J){let X=this.getSnapshotPath(Z),$=this.writeLocks.get(X),W=(async()=>{if($)await $;let Q=s.dirname(X);await(await import("fs/promises")).mkdir(Q,{recursive:!0});let Y=JSON.stringify(J,null,2);await Bun.write(X,Y)})();this.writeLocks.set(X,W),await W,this.writeLocks.delete(X)}async get(Z,J){return(await this.load(Z))?.snapshots[J]||null}createSnapshot(Z,J){let X=J.include||["body"],$={hash:"",updatedAt:new Date().toISOString()};if(X.includes("status")&&Z.status!==void 0)$.status=Z.status;if(X.includes("headers")&&Z.headers)$.headers=this.normalizeHeaders(Z.headers);if(X.includes("body")&&Z.body!==void 0)$.body=Z.body;return $.hash=this.hash($),$}normalizeHeaders(Z){let J={},X=Object.keys(Z).sort();for(let $ of X){let W=Z[$];J[$.toLowerCase()]=Array.isArray(W)?W.join(", "):W}return J}hash(Z){let J=JSON.stringify(Z),X=new Bun.CryptoHasher("md5");return X.update(J),X.digest("hex").slice(0,8)}async compareAndUpdate(Z,J,X,$){let W=$.name||J,Q=await this.get(Z,W),G=this.createSnapshot(X,$);if(!Q){if(this.globalConfig.ci)return{match:!1,isNew:!0,updated:!1,differences:[{path:"",expected:"snapshot",received:"none",type:"removed"}]};return await this.updateSnapshot(Z,W,G),{match:!0,isNew:!0,updated:!0,differences:[]}}let z=new $9($).compare(Q,G);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,W,G),{match:!0,isNew:!1,updated:!0,differences:z.differences};return{match:!1,isNew:!1,updated:!1,differences:z.differences}}async updateSnapshot(Z,J,X){let $=await this.load(Z);if(!$)$={version:R7,snapshots:{}};$.snapshots[J]=X,await this.save(Z,$)}static mergeConfig(Z,J){if(!J&&!Z?.enabled)return null;if(J===!0)return{enabled:!0,include:Z?.include||["body"],exclude:Z?.exclude||[],match:Z?.match||{}};if(typeof J==="object"&&J.enabled!==!1)return{enabled:!0,name:J.name,include:J.include||Z?.include||["body"],exclude:[...Z?.exclude||[],...J.exclude||[]],match:{...Z?.match||{},...J.match||{}}};if(Z?.enabled&&J===void 0)return{enabled:!0,include:Z.include||["body"],exclude:Z.exclude||[],match:Z.match||{}};return null}}var W9=new Set(["__proto__","prototype","constructor"]);function Q9(Z,J){let X=J.split("."),$=Z;for(let W of X){if($===null||$===void 0)return;if(typeof $!=="object")return;let Q=W.match(/^(\w+)\[(\d+)\]$/);if(Q){let[,G,Y]=Q;if(W9.has(G))return;let z=Number.parseInt(Y,10);if($=$[G],Array.isArray($))$=$[z];else return}else if(/^\d+$/.test(W)&&Array.isArray($))$=$[Number.parseInt(W,10)];else{if(W9.has(W))return;$=$[W]}}return $}function i1(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 _4(Z,J){let X={},$={status:Z.status,headers:Z.headers||{},body:Z.body,metrics:Z.metrics};for(let[W,Q]of Object.entries(J)){if(W9.has(W))continue;let G=Q9($,Q);X[W]=i1(G)}return X}function F4(){return{}}var D4=1e5;function E7(Z){let J=Z.trim(),X=J.match(/^(.+?)\s+(exists|not-exists)$/i);if(X)return{left:X[1].trim(),operator:X[2].toLowerCase()};let $=/^(.+?)\s*(==|!=|>=|<=|>|<|contains|matches)\s*(.+)$/i,W=J.match($);if(!W)return null;let[,Q,G,Y]=W,z=A7(Y.trim());return{left:Q.trim(),operator:G.toLowerCase(),right:z}}function A7(Z){if(Z==="true")return!0;if(Z==="false")return!1;let J=Number(Z);if(!Number.isNaN(J)&&Z!=="")return J;if(Z.startsWith('"')&&Z.endsWith('"')||Z.startsWith("'")&&Z.endsWith("'"))return Z.slice(1,-1);return Z}function V7(Z,J){let X=Z.startsWith("store.")?Z.slice(6):Z;if(X in J){let Q=J[X];if(Q.startsWith("{")||Q.startsWith("["))try{return JSON.parse(Q)}catch{return Q}let G=Number(Q);if(!Number.isNaN(G)&&Q!=="")return G;if(Q==="true")return!0;if(Q==="false")return!1;return Q}let $=X.split("."),W=$[0];if(W in J){let Q=J[W];try{let G=JSON.parse(Q);return Q9(G,$.slice(1).join("."))}catch{return}}return}function N4(Z,J,X){if(X)return Z===J;return Z.toLowerCase()===J.toLowerCase()}function a1(Z,J){let X=V7(Z.left,J),$=Z.caseSensitive??!1,W=(G)=>{if(G===void 0)return"undefined";if(G===null)return"null";if(typeof G==="string")return`"${G}"`;return String(G)},Q=`${Z.left} ${Z.operator}${Z.right!==void 0?` ${W(Z.right)}`:""}`;switch(Z.operator){case"exists":return{passed:X!==void 0&&X!==null&&X!=="",description:Q};case"not-exists":return{passed:X===void 0||X===null||X==="",description:Q};case"==":{let G;if(typeof X==="string"&&typeof Z.right==="string")G=N4(X,Z.right,$);else G=X==Z.right;return{passed:G,description:Q}}case"!=":{let G;if(typeof X==="string"&&typeof Z.right==="string")G=!N4(X,Z.right,$);else G=X!=Z.right;return{passed:G,description:Q}}case">":return{passed:Number(X)>Number(Z.right),description:Q};case"<":return{passed:Number(X)<Number(Z.right),description:Q};case">=":return{passed:Number(X)>=Number(Z.right),description:Q};case"<=":return{passed:Number(X)<=Number(Z.right),description:Q};case"contains":{let G=i1(X),Y=String(Z.right??"");return{passed:$?G.includes(Y):G.toLowerCase().includes(Y.toLowerCase()),description:Q}}case"matches":{let G=i1(X),Y=String(Z.right??"");try{let H=new RegExp(Y,$?"":"i"),K=G.length>D4?G.slice(0,D4):G;return{passed:H.test(K),description:Q}}catch{return{passed:!1,description:`${Q} (invalid regex)`}}}default:return{passed:!1,description:`unknown operator: ${Z.operator}`}}}function T4(Z,J){if(typeof Z==="string"){let X=E7(Z);if(!X)return{shouldRun:!1,reason:`invalid condition syntax: "${Z}"`};let $=a1(X,J);return{shouldRun:$.passed,reason:$.passed?void 0:`condition not met: ${$.description}`}}if(Z.all&&Z.all.length>0){for(let X of Z.all){let $=a1(X,J);if(!$.passed)return{shouldRun:!1,reason:`condition not met: ${$.description}`}}return{shouldRun:!0}}if(Z.any&&Z.any.length>0){let X=[];for(let $ of Z.any){let W=a1($,J);if(W.passed)return{shouldRun:!0};X.push(W.description)}return{shouldRun:!1,reason:`no conditions met: ${X.join(", ")}`}}if(Z.left&&Z.operator){let X={left:Z.left,operator:Z.operator,right:Z.right,caseSensitive:Z.caseSensitive},$=a1(X,J);return{shouldRun:$.passed,reason:$.passed?void 0:`condition not met: ${$.description}`}}return{shouldRun:!0}}class G9{poolConfig;allowedProtocols;constructor(Z={},J=f){this.poolConfig={enabled:!0,maxStreamsPerHost:10,keepaliveTime:60,connectTimeout:30,...Z},this.allowedProtocols=J}getHostKey(Z){try{let J=new URL(Z);return`${J.protocol}//${J.host}`}catch{return Z}}groupRequestsByHost(Z){let J=new Map;return Z.forEach((X,$)=>{let W=this.getHostKey(X.url),Q=J.get(W)||[];Q.push({index:$,config:X}),J.set(W,Q)}),Array.from(J.entries()).map(([X,$])=>({host:X,requests:$}))}buildRequestArgs(Z,J){let{args:X,url:$}=T1(Z,{writeOutMarker:u0(J),includeSilentFlags:!1,includeHttp2Flag:!1,includeOutputFlag:!1,allowedProtocols:this.allowedProtocols});return X.push("--",$),X}buildBatchedCommand(Z){let J=[];return J.push("-Z"),J.push("--parallel-max",this.poolConfig.maxStreamsPerHost.toString()),J.push("--http2"),J.push("--keepalive-time",this.poolConfig.keepaliveTime.toString()),J.push("--connect-timeout",this.poolConfig.connectTimeout.toString()),J.push("-s","-S"),Z.requests.forEach((X,$)=>{if($>0)J.push("--next");let W=this.buildRequestArgs(X.config,X.index);J.push(...W)}),J}parseBatchedOutput(Z,J,X,$){let W=new Map;for(let Q of X.requests){let{found:G,metricsJson:Y,startIdx:z}=l0(Z,Q.index);if(!G){W.set(Q.index,{request:Q.config,success:!1,error:J||`Request failed (exit code: ${$})`,metrics:{duration:0}});continue}let H={};try{H=JSON.parse(Y)}catch{}let K=z,B=0;for(let R of X.requests){if(R.index===Q.index)continue;let V=`__CURL_BATCH_${R.index}_END__`,P=Z.indexOf(V);if(P!==-1&&P<K&&P+V.length>B)B=P+V.length}let U=Z.substring(B,K),{blocks:D,bodyOffset:O}=f1(U),_;for(let R=D.length-1;R>=0;R--)if(D[R].status>=200){_=D[R];break}let F=U.slice(O).trim(),j=L1(H)??_?.status,L=j1(H);W.set(Q.index,{request:Q.config,success:o0(j),status:j,headers:_?.headers??{},headerHistory:D,body:G1(F),metrics:L})}return W}async executeBatch(Z){let J=this.buildBatchedCommand(Z);try{let X=Bun.spawn(["curl",...J],{stdout:"pipe",stderr:"pipe"}),$=await new Response(X.stdout).text(),W=await new Response(X.stderr).text();return await X.exited,this.parseBatchedOutput($,W,Z,X.exitCode||0)}catch(X){let $=new Map;for(let W of Z.requests)$.set(W.index,{request:W.config,success:!1,error:X instanceof Error?X.message:String(X),metrics:{duration:0}});return $}}async executeAll(Z){let J=this.groupRequestsByHost(Z),X=new Map,$=J.map((Q)=>this.executeBatch(Q)),W=await Promise.all($);for(let Q of W)for(let[G,Y]of Q)X.set(G,Y);return Z.map((Q,G)=>{return X.get(G)||{request:Z[G],success:!1,error:"Request not executed",metrics:{duration:0}}})}formatBatchedCommandForDisplay(Z){let J=this.buildBatchedCommand(Z);return I1(J)}}class Y9{logger;globalConfig;snapshotManager;pooledExecutor=null;constructor(Z={}){if(this.globalConfig=Z,this.logger=new n(Z.output),this.snapshotManager=new o1(Z.snapshot),Z.connectionPool?.enabled)this.pooledExecutor=new G9(Z.connectionPool,Z.security?.allowedProtocols??f)}mergeOutputConfig(Z){return{...this.globalConfig.output,...Z.sourceOutputConfig}}getSnapshotConfig(Z){return o1.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 J=[];for(let[X,$]of Object.entries(Z.formData))if(this.isFileAttachment($)){let W=$.file;if(!await Bun.file(W).exists())J.push(`${X}: ${W}`)}if(J.length>0)return`File(s) not found: ${J.join(", ")}`;return}validateRequestPaths(Z){let J=this.globalConfig.security?.allowPaths??!1;if(Z.output){let X=n1(Z.output,{allow:J});if(!X.valid)return X.error}if(Z.formData){for(let[X,$]of Object.entries(Z.formData))if(this.isFileAttachment($)){let W=n1($.file,{allow:J});if(!W.valid)return`formData field "${X}": ${W.error}`}}return}async executeRequest(Z,J=0){let X=performance.now(),$=this.mergeOutputConfig(Z),W=new n($);W.logRequestStart(Z,J);let Q=this.validateRequestPaths(Z);if(Q){let F={request:Z,success:!1,error:Q,metrics:{duration:performance.now()-X}};return W.logRequestComplete(F),F}let G=await this.validateFileAttachments(Z);if(G){let F={request:Z,success:!1,error:G,metrics:{duration:performance.now()-X}};return W.logRequestComplete(F),F}let Y=this.globalConfig.security?.allowedProtocols??f,z=h0(Z.url,Y);if(!z.valid){let F={request:Z,success:!1,error:z.error,metrics:{duration:performance.now()-X}};return W.logRequestComplete(F),F}let H=J1.buildCommand(Z,Y);if(W.logCommand(J1.formatCommandForDisplay(H)),this.globalConfig.dryRun){let F={request:Z,success:!0,dryRun:!0,metrics:{duration:0}};return W.logRequestComplete(F),F}let K=Z.retry?.retryableStatuses??[...J9],B=(Z.retry?.count??0)>0,U=await Z9(()=>J1.executeCurl(H),{config:Z.retry,shouldRetry:(F)=>{if(!F.success)return!0;if(B&&F.status!==void 0)return K.includes(F.status);return!1},onRetry:(F,j)=>W.logRetry(F,j),getDelay:(F,j)=>{if(j?.status===429&&j.headers){let L=j.headers["retry-after"],R=Array.isArray(L)?L[0]:L;if(R){let V=Number(R);if(!Number.isNaN(V))return V*1000}}return}}),D=B&&U.value?.status!==void 0&&K.includes(U.value.status);if(!U.success||!U.value?.success||D){let F={request:Z,success:!1,status:U.value?.status,error:U.error||U.value?.error||`Request failed with status ${U.value?.status}`,metrics:{duration:performance.now()-X}};return W.logRequestComplete(F),F}let O=U.value,_=this.processCurlResult(Z,O,X);return await l1(_,Z,{snapshotManager:this.snapshotManager,snapshotConfig:this.getSnapshotConfig(Z)}),W.logRequestComplete(_),_}processCurlResult(Z,J,X){let $=J.headers?.["content-type"],W=Array.isArray($)?$[0]:$,Q=G1(J.body,W);return{request:Z,success:!0,status:J.status,headers:J.headers,headerHistory:J.headerHistory,body:Q,metrics:{...J.metrics,duration:performance.now()-X}}}async executeSequential(Z){let J=performance.now(),X=[],$=F4();for(let W=0;W<Z.length;W++){let Q=this.interpolateStoreVariables(Z[W],$);if(Q.when){let Y=T4(Q.when,$);if(!Y.shouldRun){let z={request:Q,success:!0,skipped:!0,skipReason:Y.reason};X.push(z),this.logger.logSkipped(Q,W+1,Y.reason);continue}}let G=await this.executeRequest(Q,W+1);if(X.push(G),G.success&&Q.store){let Y=_4(G,Q.store);Object.assign($,Y),this.logStoredValues(Y)}if(!G.success&&!this.globalConfig.continueOnError){this.logger.logError("Stopping execution due to error");break}}return this.createSummary(X,performance.now()-J)}interpolateStoreVariables(Z,J){if(Object.keys(J).length===0)return Z;return y.interpolateVariables(Z,{},J)}logStoredValues(Z){if(Object.keys(Z).length===0)return;let J=Object.entries(Z);for(let[X,$]of J){let W=$.length>50?`${$.substring(0,50)}...`:$;this.logger.logInfo(`Stored: ${X} = "${W}"`)}}async executeParallel(Z){let J=performance.now();if(this.pooledExecutor&&!this.globalConfig.dryRun)return this.executePooled(Z,J);let X=this.globalConfig.maxConcurrency;if(!X||X>=Z.length){let W=Z.map((G,Y)=>this.executeRequest(G,Y+1)),Q=await Promise.all(W);return this.createSummary(Q,performance.now()-J)}let $=[];for(let W=0;W<Z.length;W+=X){let G=Z.slice(W,W+X).map((H,K)=>this.executeRequest(H,W+K+1)),Y=await Promise.all(G);if($.push(...Y),Y.some((H)=>!H.success)&&!this.globalConfig.continueOnError){this.logger.logError("Stopping execution due to error");break}}return this.createSummary($,performance.now()-J)}async executePooled(Z,J){this.logger.logInfo(`Using connection pooling (HTTP/2 multiplexing) for ${Z.length} requests`);let X=this.globalConfig.security?.allowedProtocols??f,$=[],W=[];for(let U of Z){let D=h0(U.url,X);if(!D.valid){$.push({request:U,success:!1,error:D.error,metrics:{duration:0}});continue}let O=this.validateRequestPaths(U);if(O)$.push({request:U,success:!1,error:O,metrics:{duration:0}});else W.push(U)}let Q=this.pooledExecutor.groupRequestsByHost(W);for(let U of Q)this.logger.logInfo(` ${U.host}: ${U.requests.length} request(s) batched`);let G=W.length>0?await this.pooledExecutor.executeAll(W):[],Y=new Set(W.map((U)=>Z.indexOf(U))),z=0,H=0,K=Z.map((U,D)=>{if(!Y.has(D))return $[H++];return G[z++]}),B=[];for(let U=0;U<K.length;U++){let D=K[U],O=Z[U],_=this.mergeOutputConfig(O),F=new n(_);if(F.logRequestStart(O,U+1),D.success)await l1(D,O,{snapshotManager:this.snapshotManager,snapshotConfig:this.getSnapshotConfig(O)});if(F.logRequestComplete(D),B.push(D),!D.success&&!this.globalConfig.continueOnError){this.logger.logError("Stopping execution due to error");break}}return this.createSummary(B,performance.now()-J)}async execute(Z){this.logger.logExecutionStart(Z.length,this.globalConfig.execution||"sequential");let J=this.globalConfig.execution==="parallel"?await this.executeParallel(Z):await this.executeSequential(Z);if(this.logger.logSummary(J),this.globalConfig.output?.saveToFile)await this.saveSummaryToFile(J);return J}createSummary(Z,J){let X=Z.filter((Q)=>Q.skipped).length,$=Z.filter((Q)=>Q.success&&!Q.skipped).length,W=Z.filter((Q)=>!Q.success).length;return{total:Z.length,successful:$,failed:W,skipped:X,duration:J,results:Z}}async saveSummaryToFile(Z){let J=this.globalConfig.output?.saveToFile;if(!J)return;let X=this.globalConfig.security?.allowPaths??!1,$=n1(J,{allow:X});if(!$.valid){this.logger.logError(`Cannot save results: ${$.error}`);return}let W=JSON.stringify(Z,null,2),Q=Q1().redact(W);await Bun.write(J,Q),this.logger.logInfo(`Results saved to ${J}`)}}var I4=`${process.env.HOME}/.curl-runner-version-cache.json`,k7=86400000,P7="https://registry.npmjs.org/@curl-runner/cli/latest";class z9{async checkForUpdates(Z=!1){try{if(process.env.CI)return;let J=i();if(J==="0.0.0")return;if(!Z){let $=await this.getCachedVersion();if($&&Date.now()-$.lastCheck<k7){this.compareVersions(J,$.latestVersion);return}}let X=await this.fetchLatestVersion();if(X)await this.setCachedVersion(X),this.compareVersions(J,X)}catch{}}async fetchLatestVersion(){try{let Z=await fetch(P7,{signal:AbortSignal.timeout(3000)});if(!Z.ok)return null;return(await Z.json()).version}catch{return null}}compareVersions(Z,J){if(this.isNewerVersion(Z,J))console.log(),console.log(N("\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(N("\u2502","yellow")+" "+N("\u2502","yellow")),console.log(N("\u2502","yellow")+" "+N("Update available!","bright")+` ${N(Z,"red")} \u2192 ${N(J,"green")} `+N("\u2502","yellow")),console.log(N("\u2502","yellow")+" "+N("\u2502","yellow")),console.log(N("\u2502","yellow")+" Run "+N("curl-runner upgrade","cyan")+" to update "+N("\u2502","yellow")),console.log(N("\u2502","yellow")+" "+N("\u2502","yellow")),console.log(N("\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,J){try{let X=Z.replace(/^v/,""),$=J.replace(/^v/,""),W=X.split(".").map(Number),Q=$.split(".").map(Number);for(let G=0;G<Math.max(W.length,Q.length);G++){let Y=W[G]||0,z=Q[G]||0;if(z>Y)return!0;if(z<Y)return!1}return!1}catch{return!1}}async getCachedVersion(){try{let Z=Bun.file(I4);if(await Z.exists())return JSON.parse(await Z.text())}catch{}return null}async setCachedVersion(Z){try{let J={lastCheck:Date.now(),latestVersion:Z};await Bun.write(I4,JSON.stringify(J))}catch{}}}import{watch as C7}from"fs";class H9{watchers=[];debounceTimer=null;isRunning=!1;pendingRun=!1;options;constructor(Z){this.options=Z}async start(){let{files:Z,logger:J}=this.options;await this.runRequests();for(let X of Z)try{let $=C7(X,(W)=>{if(W==="change")this.handleFileChange(X)});$.on("error",(W)=>{J.logWarning(`Watch error on ${X}: ${W.message}`)}),this.watchers.push($)}catch($){J.logWarning(`Failed to watch ${X}: ${$ instanceof Error?$.message:String($)}`)}J.logWatch(Z),this.setupSignalHandlers(),await this.keepAlive()}handleFileChange(Z){let{config:J,logger:X}=this.options,$=J.debounce??300;if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(async()=>{if(this.isRunning){this.pendingRun=!0;return}if(J.clear!==!1)console.clear();X.logFileChanged(Z),await this.runRequests()},$)}async runRequests(){let{onRun:Z,logger:J}=this.options;this.isRunning=!0;try{await Z()}catch(X){J.logError(X instanceof Error?X.message:String(X))}if(this.isRunning=!1,this.pendingRun){this.pendingRun=!1;let{config:X}=this.options;if(X.clear!==!1)console.clear();J.logFileChanged("(queued change)"),await this.runRequests()}else J.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=P1(U9(),1);import{stdout as V4,stdin as v7}from"process";var h=P1(M9(),1);import m7 from"readline";var h7=(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,g7=(Z)=>Z===12288||Z>=65281&&Z<=65376||Z>=65504&&Z<=65510,d7=(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,O9=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,t1=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,e1=/\t{1,1000}/y,_9=/[\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,Z0=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,f7=/\p{M}+/gu,p7={limit:1/0,ellipsis:""},k4=(Z,J={},X={})=>{let $=J.limit??1/0,W=J.ellipsis??"",Q=J?.ellipsisWidth??(W?k4(W,p7,X).width:0),G=X.ansiWidth??0,Y=X.controlWidth??0,z=X.tabWidth??8,H=X.ambiguousWidth??1,K=X.emojiWidth??2,B=X.fullWidthWidth??2,U=X.regularWidth??1,D=X.wideWidth??2,O=0,_=0,F=Z.length,j=0,L=!1,R=F,V=Math.max(0,$-Q),P=0,w=0,T=0,I=0;Z:for(;;){if(w>P||_>=F&&_>O){let p=Z.slice(P,w)||Z.slice(O,_);j=0;for(let u of p.replaceAll(f7,"")){let g=u.codePointAt(0)||0;if(g7(g)?I=B:d7(g)?I=D:H!==U&&h7(g)?I=H:I=U,T+I>V&&(R=Math.min(R,Math.max(P,O)+j)),T+I>$){L=!0;break Z}j+=u.length,T+=I}P=w=0}if(_>=F)break;if(Z0.lastIndex=_,Z0.test(Z)){if(j=Z0.lastIndex-_,I=j*U,T+I>V&&(R=Math.min(R,_+Math.floor((V-T)/U))),T+I>$){L=!0;break}T+=I,P=O,w=_,_=O=Z0.lastIndex;continue}if(O9.lastIndex=_,O9.test(Z)){if(T+G>V&&(R=Math.min(R,_)),T+G>$){L=!0;break}T+=G,P=O,w=_,_=O=O9.lastIndex;continue}if(t1.lastIndex=_,t1.test(Z)){if(j=t1.lastIndex-_,I=j*Y,T+I>V&&(R=Math.min(R,_+Math.floor((V-T)/Y))),T+I>$){L=!0;break}T+=I,P=O,w=_,_=O=t1.lastIndex;continue}if(e1.lastIndex=_,e1.test(Z)){if(j=e1.lastIndex-_,I=j*z,T+I>V&&(R=Math.min(R,_+Math.floor((V-T)/z))),T+I>$){L=!0;break}T+=I,P=O,w=_,_=O=e1.lastIndex;continue}if(_9.lastIndex=_,_9.test(Z)){if(T+K>V&&(R=Math.min(R,_)),T+K>$){L=!0;break}T+=K,P=O,w=_,_=O=_9.lastIndex;continue}_+=1}return{width:L?V:T,index:L?R:F,truncated:L,ellipsed:L&&$>=Q}},c7={limit:1/0,ellipsis:"",ellipsisWidth:0},S1=(Z,J={})=>k4(Z,c7,J).width,X0="\x1B",P4="\x9B",u7=39,T9="\x07",C4="[",l7="]",w4="m",I9=`${l7}8;;`,S4=new RegExp(`(?:\\${C4}(?<code>\\d+)m|\\${I9}(?<uri>.*)${T9})`,"y"),n7=(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},E4=(Z)=>`${X0}${C4}${Z}${w4}`,A4=(Z)=>`${X0}${I9}${Z}${T9}`,o7=(Z)=>Z.map((J)=>S1(J)),F9=(Z,J,X)=>{let $=J[Symbol.iterator](),W=!1,Q=!1,G=Z.at(-1),Y=G===void 0?0:S1(G),z=$.next(),H=$.next(),K=0;for(;!z.done;){let B=z.value,U=S1(B);Y+U<=X?Z[Z.length-1]+=B:(Z.push(B),Y=0),(B===X0||B===P4)&&(W=!0,Q=J.startsWith(I9,K+1)),W?Q?B===T9&&(W=!1,Q=!1):B===w4&&(W=!1):(Y+=U,Y===X&&!H.done&&(Z.push(""),Y=0)),z=H,H=$.next(),K+=B.length}G=Z.at(-1),!Y&&G!==void 0&&G.length>0&&Z.length>1&&(Z[Z.length-2]+=Z.pop())},i7=(Z)=>{let J=Z.split(" "),X=J.length;for(;X>0&&!(S1(J[X-1])>0);)X--;return X===J.length?Z:J.slice(0,X).join(" ")+J.slice(X).join("")},a7=(Z,J,X={})=>{if(X.trim!==!1&&Z.trim()==="")return"";let $="",W,Q,G=Z.split(" "),Y=o7(G),z=[""];for(let[O,_]of G.entries()){X.trim!==!1&&(z[z.length-1]=(z.at(-1)??"").trimStart());let F=S1(z.at(-1)??"");if(O!==0&&(F>=J&&(X.wordWrap===!1||X.trim===!1)&&(z.push(""),F=0),(F>0||X.trim===!1)&&(z[z.length-1]+=" ",F++)),X.hard&&Y[O]>J){let j=J-F,L=1+Math.floor((Y[O]-j-1)/J);Math.floor((Y[O]-1)/J)<L&&z.push(""),F9(z,_,J);continue}if(F+Y[O]>J&&F>0&&Y[O]>0){if(X.wordWrap===!1&&F<J){F9(z,_,J);continue}z.push("")}if(F+Y[O]>J&&X.wordWrap===!1){F9(z,_,J);continue}z[z.length-1]+=_}X.trim!==!1&&(z=z.map((O)=>i7(O)));let H=z.join(`
159
- `),K=H[Symbol.iterator](),B=K.next(),U=K.next(),D=0;for(;!B.done;){let O=B.value,_=U.value;if($+=O,O===X0||O===P4){S4.lastIndex=D+1;let j=S4.exec(H)?.groups;if(j?.code!==void 0){let L=Number.parseFloat(j.code);W=L===u7?void 0:L}else j?.uri!==void 0&&(Q=j.uri.length===0?void 0:j.uri)}let F=W?n7(W):void 0;_===`
160
- `?(Q&&($+=A4("")),W&&F&&($+=E4(F))):O===`
161
- `&&(W&&F&&($+=E4(W)),Q&&($+=A4(Q))),D+=O.length,B=U,U=K.next()}return $};function D9(Z,J,X){return String(Z).normalize().replaceAll(`\r
162
- `,`
163
- `).split(`
164
- `).map(($)=>a7($,J,X)).join(`
165
- `)}var r7=["up","down","left","right","space","enter","cancel"],$1={actions:new Set(r7),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 q4(Z,J){if(typeof Z=="string")return $1.aliases.get(Z)===J;for(let X of Z)if(X!==void 0&&q4(X,J))return!0;return!1}function s7(Z,J){if(Z===J)return;let X=Z.split(`
166
- `),$=J.split(`
167
- `),W=Math.max(X.length,$.length),Q=[];for(let G=0;G<W;G++)X[G]!==$[G]&&Q.push(G);return{lines:Q,numLinesBefore:X.length,numLinesAfter:$.length,numLines:W}}var b8=globalThis.process.platform.startsWith("win"),N9=Symbol("clack:cancel");function S(Z){return Z===N9}function J0(Z,J){let X=Z;X.isTTY&&X.setRawMode(J)}var j9=(Z)=>("columns"in Z)&&typeof Z.columns=="number"?Z.columns:80,L9=(Z)=>("rows"in Z)&&typeof Z.rows=="number"?Z.rows:20;function z1(Z,J,X,$=X){let W=j9(Z??V4);return D9(J,W-X.length,{hard:!0,trim:!1}).split(`
168
- `).map((Q,G)=>`${G===0?$:X}${Q}`).join(`
169
- `)}class W1{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(Z,J=!0){let{input:X=v7,output:$=V4,render:W,signal:Q,...G}=Z;this.opts=G,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=W.bind(this),this._track=J,this._abortSignal=Q,this.input=X,this.output=$}unsubscribe(){this._subscribers.clear()}setSubscriber(Z,J){let X=this._subscribers.get(Z)??[];X.push(J),this._subscribers.set(Z,X)}on(Z,J){this.setSubscriber(Z,{cb:J})}once(Z,J){this.setSubscriber(Z,{cb:J,once:!0})}emit(Z,...J){let X=this._subscribers.get(Z)??[],$=[];for(let W of X)W.cb(...J),W.once&&$.push(()=>X.splice(X.indexOf(W),1));for(let W of $)W()}prompt(){return new Promise((Z)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),Z(N9);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=m7.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),J0(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),J0(this.input,!1),Z(this.value)}),this.once("cancel",()=>{this.output.write(h.cursor.show),this.output.off("resize",this.render),J0(this.input,!1),Z(N9)})})}_isActionKey(Z,J){return Z==="\t"}_setValue(Z){this.value=Z,this.emit("value",this.value)}_setUserInput(Z,J){this.userInput=Z??"",this.emit("userInput",this.userInput),J&&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,J){if(this._track&&J.name!=="return"&&(J.name&&this._isActionKey(Z,J)&&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"),J?.name&&(!this._track&&$1.aliases.has(J.name)&&this.emit("cursor",$1.aliases.get(J.name)),$1.actions.has(J.name)&&this.emit("cursor",J.name)),Z&&(Z.toLowerCase()==="y"||Z.toLowerCase()==="n")&&this.emit("confirm",Z.toLowerCase()==="y"),this.emit("key",Z?.toLowerCase(),J),J?.name==="return"){if(this.opts.validate){let X=this.opts.validate(this.value);X&&(this.error=X instanceof Error?X.message:X,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}q4([Z,J?.name,J?.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(`
170
- `),J0(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let Z=D9(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
171
- `).length-1;this.output.write(h.cursor.move(-999,Z*-1))}render(){let Z=D9(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 J=s7(this._prevFrame,Z),X=L9(this.output);if(this.restoreCursor(),J){let $=Math.max(0,J.numLinesAfter-X),W=Math.max(0,J.numLinesBefore-X),Q=J.lines.find((G)=>G>=$);if(Q===void 0){this._prevFrame=Z;return}if(J.lines.length===1){this.output.write(h.cursor.move(0,Q-W)),this.output.write(h.erase.lines(1));let G=Z.split(`
172
- `);this.output.write(G[Q]),this._prevFrame=Z,this.output.write(h.cursor.move(0,G.length-Q-1));return}else if(J.lines.length>1){if($<W)Q=$;else{let Y=Q-W;Y>0&&this.output.write(h.cursor.move(0,Y))}this.output.write(h.erase.down());let G=Z.split(`
173
- `).slice(Q);this.output.write(G.join(`
174
- `)),this._prevFrame=Z;return}}this.output.write(h.erase.down())}this.output.write(Z),this.state==="initial"&&(this.state="active"),this._prevFrame=Z}}}function t7(Z,J){if(Z===void 0||J.length===0)return 0;let X=J.findIndex(($)=>$.value===Z);return X!==-1?X:0}function e7(Z,J){return(J.label??String(J.value)).toLowerCase().includes(Z.toLowerCase())}function Z2(Z,J){if(J)return Z?J:J[0]}class x4 extends W1{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#Z=0;#X="";#$;#J;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),[J,...X]=this.userInput.slice(this._cursor);return`${Z}${X1.default.inverse(J)}${X.join("")}`}get options(){return typeof this.#J=="function"?this.#J():this.#J}constructor(Z){super(Z),this.#J=Z.options;let J=this.options;this.filteredOptions=[...J],this.multiple=Z.multiple===!0,this.#$=Z.filter??e7;let X;if(Z.initialValue&&Array.isArray(Z.initialValue)?this.multiple?X=Z.initialValue:X=Z.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(X=[this.options[0].value]),X)for(let $ of X){let W=J.findIndex((Q)=>Q.value===$);W!==-1&&(this.toggleSelected($),this.#Z=W)}this.focusedValue=this.options[this.#Z]?.value,this.on("key",($,W)=>this.#W($,W)),this.on("userInput",($)=>this.#Q($))}_isActionKey(Z,J){return Z==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&Z!==void 0&&Z!==""}#W(Z,J){let X=J.name==="up",$=J.name==="down",W=J.name==="return";X||$?(this.#Z=Math.max(0,Math.min(this.#Z+(X?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#Z]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):W?this.value=Z2(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(J.name==="tab"||this.isNavigating&&J.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((J)=>J!==Z):this.selectedValues=[...this.selectedValues,Z]:this.selectedValues=[Z])}#Q(Z){if(Z!==this.#X){this.#X=Z;let J=this.options;Z?this.filteredOptions=J.filter((X)=>this.#$(Z,X)):this.filteredOptions=[...J],this.#Z=t7(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#Z]?.value,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}}class R9 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",(J)=>{this.output.write(h.cursor.move(0,-1)),this.value=J,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}class b4 extends W1{options;cursor=0;#Z;getGroupItems(Z){return this.options.filter((J)=>J.group===Z)}isGroupSelected(Z){let J=this.getGroupItems(Z),X=this.value;return X===void 0?!1:J.every(($)=>X.includes($.value))}toggleValue(){let Z=this.options[this.cursor];if(this.value===void 0&&(this.value=[]),Z.group===!0){let J=Z.value,X=this.getGroupItems(J);this.isGroupSelected(J)?this.value=this.value.filter(($)=>X.findIndex((W)=>W.value===$)===-1):this.value=[...this.value,...X.map(($)=>$.value)],this.value=Array.from(new Set(this.value))}else{let J=this.value.includes(Z.value);this.value=J?this.value.filter((X)=>X!==Z.value):[...this.value,Z.value]}}constructor(Z){super(Z,!1);let{options:J}=Z;this.#Z=Z.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([X,$])=>[{value:X,group:!0,label:X},...$.map((W)=>({...W,group:X}))]),this.value=[...Z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:X})=>X===Z.cursorAt),this.#Z?0:1),this.on("cursor",(X)=>{switch(X){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let $=this.options[this.cursor]?.group===!0;!this.#Z&&$&&(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 $=this.options[this.cursor]?.group===!0;!this.#Z&&$&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}}function Y1(Z,J,X){let $=Z+J,W=Math.max(X.length-1,0),Q=$<0?W:$>W?0:$;return X[Q].disabled?Y1(Q,J<0?-1:1,X):Q}class S9 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,J=this.value!==void 0&&this.value.length===Z.length;this.value=J?[]:Z.map((X)=>X.value)}toggleInvert(){let Z=this.value;if(!Z)return;let J=this._enabledOptions.filter((X)=>!Z.includes(X.value));this.value=J.map((X)=>X.value)}toggleValue(){this.value===void 0&&(this.value=[]);let Z=this.value.includes(this._value);this.value=Z?this.value.filter((J)=>J!==this._value):[...this.value,this._value]}constructor(Z){super(Z,!1),this.options=Z.options,this.value=[...Z.initialValues??[]];let J=Math.max(this.options.findIndex(({value:X})=>X===Z.cursorAt),0);this.cursor=this.options[J].disabled?Y1(J,1,this.options):J,this.on("key",(X)=>{X==="a"&&this.toggleAll(),X==="i"&&this.toggleInvert()}),this.on("cursor",(X)=>{switch(X){case"left":case"up":this.cursor=Y1(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Y1(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var y4=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 J=this.masked,X=J.slice(0,this.cursor),$=J.slice(this.cursor);return`${X}${X1.default.inverse($[0])}${$.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:Z,...J}){super(J),this._mask=Z??"\u2022",this.on("userInput",(X)=>{this._setValue(X)})}};class E9 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 J=this.options.findIndex(({value:$})=>$===Z.initialValue),X=J===-1?0:J;this.cursor=this.options[X].disabled?Y1(X,1,this.options):X,this.changeValue(),this.on("cursor",($)=>{switch($){case"left":case"up":this.cursor=Y1(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Y1(this.cursor,1,this.options);break}this.changeValue()})}}class A9 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 J=Z.slice(0,this.cursor),[X,...$]=Z.slice(this.cursor);return`${J}${X1.default.inverse(X)}${$.join("")}`}get cursor(){return this._cursor}constructor(Z){super({...Z,initialUserInput:Z.initialUserInput??Z.initialValue}),this.on("userInput",(J)=>{this._setValue(J)}),this.on("finalize",()=>{this.value||(this.value=Z.defaultValue),this.value===void 0&&(this.value="")})}}var M=P1(U9(),1);import c from"process";var f4=P1(M9(),1);function J2(){return c.platform!=="win32"?c.env.TERM!=="linux":!!c.env.CI||!!c.env.WT_SESSION||!!c.env.TERMINUS_SUBLIME||c.env.ConEmuTask==="{cmd::Cmder}"||c.env.TERM_PROGRAM==="Terminus-Sublime"||c.env.TERM_PROGRAM==="vscode"||c.env.TERM==="xterm-256color"||c.env.TERM==="alacritty"||c.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var X2=J2();var k=(Z,J)=>X2?Z:J,$2=k("\u25C6","*"),W2=k("\u25A0","x"),Q2=k("\u25B2","x"),p4=k("\u25C7","o"),G2=k("\u250C","T"),A=k("\u2502","|"),o=k("\u2514","\u2014"),p8=k("\u2510","T"),c8=k("\u2518","\u2014"),C9=k("\u25CF",">"),Y0=k("\u25CB"," "),Y2=k("\u25FB","[\u2022]"),v4=k("\u25FC","[+]"),m4=k("\u25FB","[ ]"),z2=k("\u25AA","\u2022"),u8=k("\u2500","-"),l8=k("\u256E","+"),n8=k("\u251C","+"),o8=k("\u256F","+"),i8=k("\u2570","+"),a8=k("\u256D","+"),H2=k("\u25CF","\u2022"),K2=k("\u25C6","*"),U2=k("\u25B2","!"),B2=k("\u25A0","x"),V1=(Z)=>{switch(Z){case"initial":case"active":return M.default.cyan($2);case"cancel":return M.default.red(W2);case"error":return M.default.yellow(Q2);case"submit":return M.default.green(p4)}},c4=(Z)=>{switch(Z){case"initial":case"active":return M.default.cyan(A);case"cancel":return M.default.red(A);case"error":return M.default.yellow(A);case"submit":return M.default.green(A)}},M2=(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,O2=(Z)=>Z===12288||Z>=65281&&Z<=65376||Z>=65504&&Z<=65510,_2=(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,V9=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,$0=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,W0=/\t{1,1000}/y,k9=/[\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,Q0=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,F2=/\p{M}+/gu,D2={limit:1/0,ellipsis:""},u4=(Z,J={},X={})=>{let $=J.limit??1/0,W=J.ellipsis??"",Q=J?.ellipsisWidth??(W?u4(W,D2,X).width:0),G=X.ansiWidth??0,Y=X.controlWidth??0,z=X.tabWidth??8,H=X.ambiguousWidth??1,K=X.emojiWidth??2,B=X.fullWidthWidth??2,U=X.regularWidth??1,D=X.wideWidth??2,O=0,_=0,F=Z.length,j=0,L=!1,R=F,V=Math.max(0,$-Q),P=0,w=0,T=0,I=0;Z:for(;;){if(w>P||_>=F&&_>O){let p=Z.slice(P,w)||Z.slice(O,_);j=0;for(let u of p.replaceAll(F2,"")){let g=u.codePointAt(0)||0;if(O2(g)?I=B:_2(g)?I=D:H!==U&&M2(g)?I=H:I=U,T+I>V&&(R=Math.min(R,Math.max(P,O)+j)),T+I>$){L=!0;break Z}j+=u.length,T+=I}P=w=0}if(_>=F)break;if(Q0.lastIndex=_,Q0.test(Z)){if(j=Q0.lastIndex-_,I=j*U,T+I>V&&(R=Math.min(R,_+Math.floor((V-T)/U))),T+I>$){L=!0;break}T+=I,P=O,w=_,_=O=Q0.lastIndex;continue}if(V9.lastIndex=_,V9.test(Z)){if(T+G>V&&(R=Math.min(R,_)),T+G>$){L=!0;break}T+=G,P=O,w=_,_=O=V9.lastIndex;continue}if($0.lastIndex=_,$0.test(Z)){if(j=$0.lastIndex-_,I=j*Y,T+I>V&&(R=Math.min(R,_+Math.floor((V-T)/Y))),T+I>$){L=!0;break}T+=I,P=O,w=_,_=O=$0.lastIndex;continue}if(W0.lastIndex=_,W0.test(Z)){if(j=W0.lastIndex-_,I=j*z,T+I>V&&(R=Math.min(R,_+Math.floor((V-T)/z))),T+I>$){L=!0;break}T+=I,P=O,w=_,_=O=W0.lastIndex;continue}if(k9.lastIndex=_,k9.test(Z)){if(T+K>V&&(R=Math.min(R,_)),T+K>$){L=!0;break}T+=K,P=O,w=_,_=O=k9.lastIndex;continue}_+=1}return{width:L?V:T,index:L?R:F,truncated:L,ellipsed:L&&$>=Q}},N2={limit:1/0,ellipsis:"",ellipsisWidth:0},A1=(Z,J={})=>u4(Z,N2,J).width,z0="\x1B",l4="\x9B",T2=39,q9="\x07",n4="[",I2="]",o4="m",x9=`${I2}8;;`,h4=new RegExp(`(?:\\${n4}(?<code>\\d+)m|\\${x9}(?<uri>.*)${q9})`,"y"),j2=(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},g4=(Z)=>`${z0}${n4}${Z}${o4}`,d4=(Z)=>`${z0}${x9}${Z}${q9}`,L2=(Z)=>Z.map((J)=>A1(J)),P9=(Z,J,X)=>{let $=J[Symbol.iterator](),W=!1,Q=!1,G=Z.at(-1),Y=G===void 0?0:A1(G),z=$.next(),H=$.next(),K=0;for(;!z.done;){let B=z.value,U=A1(B);Y+U<=X?Z[Z.length-1]+=B:(Z.push(B),Y=0),(B===z0||B===l4)&&(W=!0,Q=J.startsWith(x9,K+1)),W?Q?B===q9&&(W=!1,Q=!1):B===o4&&(W=!1):(Y+=U,Y===X&&!H.done&&(Z.push(""),Y=0)),z=H,H=$.next(),K+=B.length}G=Z.at(-1),!Y&&G!==void 0&&G.length>0&&Z.length>1&&(Z[Z.length-2]+=Z.pop())},R2=(Z)=>{let J=Z.split(" "),X=J.length;for(;X>0&&!(A1(J[X-1])>0);)X--;return X===J.length?Z:J.slice(0,X).join(" ")+J.slice(X).join("")},S2=(Z,J,X={})=>{if(X.trim!==!1&&Z.trim()==="")return"";let $="",W,Q,G=Z.split(" "),Y=L2(G),z=[""];for(let[O,_]of G.entries()){X.trim!==!1&&(z[z.length-1]=(z.at(-1)??"").trimStart());let F=A1(z.at(-1)??"");if(O!==0&&(F>=J&&(X.wordWrap===!1||X.trim===!1)&&(z.push(""),F=0),(F>0||X.trim===!1)&&(z[z.length-1]+=" ",F++)),X.hard&&Y[O]>J){let j=J-F,L=1+Math.floor((Y[O]-j-1)/J);Math.floor((Y[O]-1)/J)<L&&z.push(""),P9(z,_,J);continue}if(F+Y[O]>J&&F>0&&Y[O]>0){if(X.wordWrap===!1&&F<J){P9(z,_,J);continue}z.push("")}if(F+Y[O]>J&&X.wordWrap===!1){P9(z,_,J);continue}z[z.length-1]+=_}X.trim!==!1&&(z=z.map((O)=>R2(O)));let H=z.join(`
175
- `),K=H[Symbol.iterator](),B=K.next(),U=K.next(),D=0;for(;!B.done;){let O=B.value,_=U.value;if($+=O,O===z0||O===l4){h4.lastIndex=D+1;let j=h4.exec(H)?.groups;if(j?.code!==void 0){let L=Number.parseFloat(j.code);W=L===T2?void 0:L}else j?.uri!==void 0&&(Q=j.uri.length===0?void 0:j.uri)}let F=W?j2(W):void 0;_===`
176
- `?(Q&&($+=d4("")),W&&F&&($+=g4(F))):O===`
177
- `&&(W&&F&&($+=g4(W)),Q&&($+=d4(Q))),D+=O.length,B=U,U=K.next()}return $};function E2(Z,J,X){return String(Z).normalize().replaceAll(`\r
178
- `,`
179
- `).split(`
180
- `).map(($)=>S2($,J,X)).join(`
181
- `)}var A2=(Z,J,X,$,W)=>{let Q=J,G=0;for(let Y=X;Y<$;Y++){let z=Z[Y];if(Q=Q-z.length,G++,Q<=W)break}return{lineCount:Q,removals:G}},w9=(Z)=>{let{cursor:J,options:X,style:$}=Z,W=Z.output??process.stdout,Q=j9(W),G=Z.columnPadding??0,Y=Z.rowPadding??4,z=Q-G,H=L9(W),K=M.default.dim("..."),B=Z.maxItems??Number.POSITIVE_INFINITY,U=Math.max(H-Y,0),D=Math.max(Math.min(B,U),5),O=0;J>=D-3&&(O=Math.max(Math.min(J-D+3,X.length-D),0));let _=D<X.length&&O>0,F=D<X.length&&O+D<X.length,j=Math.min(O+D,X.length),L=[],R=0;_&&R++,F&&R++;let V=O+(_?1:0),P=j-(F?1:0);for(let T=V;T<P;T++){let I=E2($(X[T],T===J),z,{hard:!0,trim:!1}).split(`
182
- `);L.push(I),R+=I.length}if(R>U){let T=0,I=0,p=R,u=J-V,g=(O3,_3)=>A2(L,p,O3,_3,U);_?({lineCount:p,removals:T}=g(0,u),p>U&&({lineCount:p,removals:I}=g(u+1,L.length))):({lineCount:p,removals:I}=g(u+1,L.length),p>U&&({lineCount:p,removals:T}=g(0,u))),T>0&&(_=!0,L.splice(0,T)),I>0&&(F=!0,L.splice(L.length-I,I))}let w=[];_&&w.push(K);for(let T of L)for(let I of T)w.push(I);return F&&w.push(K),w};var b=(Z)=>{let J=Z.active??"Yes",X=Z.inactive??"No";return new R9({active:J,inactive:X,signal:Z.signal,input:Z.input,output:Z.output,initialValue:Z.initialValue??!0,render(){let $=`${M.default.gray(A)}
183
- ${V1(this.state)} ${Z.message}
184
- `,W=this.value?J:X;switch(this.state){case"submit":return`${$}${M.default.gray(A)} ${M.default.dim(W)}`;case"cancel":return`${$}${M.default.gray(A)} ${M.default.strikethrough(M.default.dim(W))}
185
- ${M.default.gray(A)}`;default:return`${$}${M.default.cyan(A)} ${this.value?`${M.default.green(C9)} ${J}`:`${M.default.dim(Y0)} ${M.default.dim(J)}`} ${M.default.dim("/")} ${this.value?`${M.default.dim(Y0)} ${M.default.dim(X)}`:`${M.default.green(C9)} ${X}`}
186
- ${M.default.cyan(o)}
187
- `}}}).prompt()},t=async(Z,J)=>{let X={},$=Object.keys(Z);for(let W of $){let Q=Z[W],G=await Q({results:X})?.catch((Y)=>{throw Y});if(typeof J?.onCancel=="function"&&S(G)){X[W]="canceled",J.onCancel({results:X});continue}X[W]=G}return X};var m={message:(Z=[],{symbol:J=M.default.gray(A),secondarySymbol:X=M.default.gray(A),output:$=process.stdout,spacing:W=1,withGuide:Q}={})=>{let G=[],Y=(Q??$1.withGuide)!==!1,z=Y?X:"",H=Y?`${J} `:"",K=Y?`${X} `:"";for(let U=0;U<W;U++)G.push(z);let B=Array.isArray(Z)?Z:Z.split(`
188
- `);if(B.length>0){let[U,...D]=B;U.length>0?G.push(`${H}${U}`):G.push(Y?J:"");for(let O of D)O.length>0?G.push(`${K}${O}`):G.push(Y?X:"")}$.write(`${G.join(`
189
- `)}
190
- `)},info:(Z,J)=>{m.message(Z,{...J,symbol:M.default.blue(H2)})},success:(Z,J)=>{m.message(Z,{...J,symbol:M.default.green(K2)})},step:(Z,J)=>{m.message(Z,{...J,symbol:M.default.green(p4)})},warn:(Z,J)=>{m.message(Z,{...J,symbol:M.default.yellow(U2)})},warning:(Z,J)=>{m.warn(Z,J)},error:(Z,J)=>{m.message(Z,{...J,symbol:M.default.red(B2)})}},q=(Z="",J)=>{(J?.output??process.stdout).write(`${M.default.gray(o)} ${M.default.red(Z)}
191
-
192
- `)},b9=(Z="",J)=>{(J?.output??process.stdout).write(`${M.default.gray(G2)} ${Z}
193
- `)},H0=(Z="",J)=>{(J?.output??process.stdout).write(`${M.default.gray(A)}
194
- ${M.default.gray(o)} ${Z}
195
-
196
- `)},E1=(Z,J)=>Z.split(`
197
- `).map((X)=>J(X)).join(`
198
- `),i4=(Z)=>{let J=($,W)=>{let Q=$.label??String($.value);return W==="disabled"?`${M.default.gray(m4)} ${E1(Q,(G)=>M.default.strikethrough(M.default.gray(G)))}${$.hint?` ${M.default.dim(`(${$.hint??"disabled"})`)}`:""}`:W==="active"?`${M.default.cyan(Y2)} ${Q}${$.hint?` ${M.default.dim(`(${$.hint})`)}`:""}`:W==="selected"?`${M.default.green(v4)} ${E1(Q,M.default.dim)}${$.hint?` ${M.default.dim(`(${$.hint})`)}`:""}`:W==="cancelled"?`${E1(Q,(G)=>M.default.strikethrough(M.default.dim(G)))}`:W==="active-selected"?`${M.default.green(v4)} ${Q}${$.hint?` ${M.default.dim(`(${$.hint})`)}`:""}`:W==="submitted"?`${E1(Q,M.default.dim)}`:`${M.default.dim(m4)} ${E1(Q,M.default.dim)}`},X=Z.required??!0;return new S9({options:Z.options,signal:Z.signal,input:Z.input,output:Z.output,initialValues:Z.initialValues,required:X,cursorAt:Z.cursorAt,validate($){if(X&&($===void 0||$.length===0))return`Please select at least one option.
199
- ${M.default.reset(M.default.dim(`Press ${M.default.gray(M.default.bgWhite(M.default.inverse(" space ")))} to select, ${M.default.gray(M.default.bgWhite(M.default.inverse(" enter ")))} to submit`))}`},render(){let $=z1(Z.output,Z.message,`${c4(this.state)} `,`${V1(this.state)} `),W=`${M.default.gray(A)}
200
- ${$}
201
- `,Q=this.value??[],G=(Y,z)=>{if(Y.disabled)return J(Y,"disabled");let H=Q.includes(Y.value);return z&&H?J(Y,"active-selected"):H?J(Y,"selected"):J(Y,z?"active":"inactive")};switch(this.state){case"submit":{let Y=this.options.filter(({value:H})=>Q.includes(H)).map((H)=>J(H,"submitted")).join(M.default.dim(", "))||M.default.dim("none"),z=z1(Z.output,Y,`${M.default.gray(A)} `);return`${W}${z}`}case"cancel":{let Y=this.options.filter(({value:H})=>Q.includes(H)).map((H)=>J(H,"cancelled")).join(M.default.dim(", "));if(Y.trim()==="")return`${W}${M.default.gray(A)}`;let z=z1(Z.output,Y,`${M.default.gray(A)} `);return`${W}${z}
202
- ${M.default.gray(A)}`}case"error":{let Y=`${M.default.yellow(A)} `,z=this.error.split(`
203
- `).map((B,U)=>U===0?`${M.default.yellow(o)} ${M.default.yellow(B)}`:` ${B}`).join(`
204
- `),H=W.split(`
205
- `).length,K=z.split(`
206
- `).length+1;return`${W}${Y}${w9({output:Z.output,options:this.options,cursor:this.cursor,maxItems:Z.maxItems,columnPadding:Y.length,rowPadding:H+K,style:G}).join(`
207
- ${Y}`)}
208
- ${z}
209
- `}default:{let Y=`${M.default.cyan(A)} `,z=W.split(`
210
- `).length;return`${W}${Y}${w9({output:Z.output,options:this.options,cursor:this.cursor,maxItems:Z.maxItems,columnPadding:Y.length,rowPadding:z+2,style:G}).join(`
211
- ${Y}`)}
212
- ${M.default.cyan(o)}
213
- `}}}}).prompt()};var a4=(Z)=>new y4({validate:Z.validate,mask:Z.mask??z2,signal:Z.signal,input:Z.input,output:Z.output,render(){let J=`${M.default.gray(A)}
214
- ${V1(this.state)} ${Z.message}
215
- `,X=this.userInputWithCursor,$=this.masked;switch(this.state){case"error":{let W=$?` ${$}`:"";return Z.clearOnError&&this.clear(),`${J.trim()}
216
- ${M.default.yellow(A)}${W}
217
- ${M.default.yellow(o)} ${M.default.yellow(this.error)}
218
- `}case"submit":{let W=$?` ${M.default.dim($)}`:"";return`${J}${M.default.gray(A)}${W}`}case"cancel":{let W=$?` ${M.default.strikethrough(M.default.dim($))}`:"";return`${J}${M.default.gray(A)}${W}${$?`
219
- ${M.default.gray(A)}`:""}`}default:return`${J}${M.default.cyan(A)} ${X}
220
- ${M.default.cyan(o)}
221
- `}}}).prompt();var r8=M.default.magenta;var s8={light:k("\u2500","-"),heavy:k("\u2501","="),block:k("\u2588","#")};var G0=(Z,J)=>Z.includes(`
222
- `)?Z.split(`
223
- `).map((X)=>J(X)).join(`
224
- `):J(Z),e=(Z)=>{let J=(X,$)=>{let W=X.label??String(X.value);switch($){case"disabled":return`${M.default.gray(Y0)} ${G0(W,M.default.gray)}${X.hint?` ${M.default.dim(`(${X.hint??"disabled"})`)}`:""}`;case"selected":return`${G0(W,M.default.dim)}`;case"active":return`${M.default.green(C9)} ${W}${X.hint?` ${M.default.dim(`(${X.hint})`)}`:""}`;case"cancelled":return`${G0(W,(Q)=>M.default.strikethrough(M.default.dim(Q)))}`;default:return`${M.default.dim(Y0)} ${G0(W,M.default.dim)}`}};return new E9({options:Z.options,signal:Z.signal,input:Z.input,output:Z.output,initialValue:Z.initialValue,render(){let X=`${V1(this.state)} `,$=`${c4(this.state)} `,W=z1(Z.output,Z.message,$,X),Q=`${M.default.gray(A)}
225
- ${W}
226
- `;switch(this.state){case"submit":{let G=`${M.default.gray(A)} `,Y=z1(Z.output,J(this.options[this.cursor],"selected"),G);return`${Q}${Y}`}case"cancel":{let G=`${M.default.gray(A)} `,Y=z1(Z.output,J(this.options[this.cursor],"cancelled"),G);return`${Q}${Y}
227
- ${M.default.gray(A)}`}default:{let G=`${M.default.cyan(A)} `,Y=Q.split(`
228
- `).length;return`${Q}${G}${w9({output:Z.output,cursor:this.cursor,options:this.options,maxItems:Z.maxItems,columnPadding:G.length,rowPadding:Y+2,style:(z,H)=>J(z,z.disabled?"disabled":H?"active":"inactive")}).join(`
229
- ${G}`)}
230
- ${M.default.cyan(o)}
231
- `}}}}).prompt()};var t8=`${M.default.gray(A)} `;var C=(Z)=>new A9({validate:Z.validate,placeholder:Z.placeholder,defaultValue:Z.defaultValue,initialValue:Z.initialValue,output:Z.output,signal:Z.signal,input:Z.input,render(){let J=(Z?.withGuide??$1.withGuide)!==!1,X=`${`${J?`${M.default.gray(A)}
232
- `:""}${V1(this.state)} `}${Z.message}
233
- `,$=Z.placeholder?M.default.inverse(Z.placeholder[0])+M.default.dim(Z.placeholder.slice(1)):M.default.inverse(M.default.hidden("_")),W=this.userInput?this.userInputWithCursor:$,Q=this.value??"";switch(this.state){case"error":{let G=this.error?` ${M.default.yellow(this.error)}`:"",Y=J?`${M.default.yellow(A)} `:"",z=J?M.default.yellow(o):"";return`${X.trim()}
234
- ${Y}${W}
235
- ${z}${G}
236
- `}case"submit":{let G=Q?` ${M.default.dim(Q)}`:"",Y=J?M.default.gray(A):"";return`${X}${Y}${G}`}case"cancel":{let G=Q?` ${M.default.strikethrough(M.default.dim(Q))}`:"",Y=J?M.default.gray(A):"";return`${X}${Y}${G}${Q.trim()?`
237
- ${Y}`:""}`}default:{let G=J?`${M.default.cyan(A)} `:"",Y=J?M.default.cyan(o):"";return`${X}${G}${W}
238
- ${Y}
239
- `}}}}).prompt();async function s4(Z){let J=await y.parseFile(Z),X;if(J.request)X=J.request;else if(J.requests&&J.requests.length>0)X=J.requests[0];else if(J.collection?.requests&&J.collection.requests.length>0)X=J.collection.requests[0];if(!X)throw Error("No request found in YAML file");return V2(X)}function V2(Z){let J={url:Z.url,method:Z.method||"GET"};if(Z.name)J.name=Z.name;if(Z.headers&&Object.keys(Z.headers).length>0)J.headers=Z.headers;if(Z.params&&Object.keys(Z.params).length>0)J.params=Z.params;if(Z.body!==void 0)if(typeof Z.body==="object"&&Z.body!==null)J.bodyType="json",J.body=Z.body;else J.bodyType="raw",J.body=Z.body;else if(Z.formData)J.bodyType="form",J.formData=Z.formData;else J.bodyType="none";if(Z.auth){if(Z.auth.type==="bearer")J.authType="bearer",J.token=Z.auth.token;else if(Z.auth.type==="basic")J.authType="basic",J.username=Z.auth.username,J.password=Z.auth.password}else J.authType="none";if(Z.timeout)J.timeout=Z.timeout;if(Z.followRedirects!==void 0)J.followRedirects=Z.followRedirects;if(Z.maxRedirects)J.maxRedirects=Z.maxRedirects;if(Z.insecure)J.insecure=Z.insecure;if(Z.http2)J.http2=Z.http2;if(Z.retry)J.retryEnabled=!0,J.retryCount=Z.retry.count,J.retryDelay=Z.retry.delay,J.retryBackoff=Z.retry.backoff;if(Z.expect){if(Z.expect.status)J.expectStatus=Z.expect.status;if(Z.expect.responseTime)J.expectResponseTime=Z.expect.responseTime}if(Z.output)J.outputFile=Z.output;return J}async function t4(Z){try{return await Bun.file(Z).exists()}catch{return!1}}var e4={"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 Z3(Z){return e4[Z]}function J3(){return Object.entries(e4).map(([Z,J])=>({value:Z,label:J.name,hint:J.description}))}var k2=["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"];async function X3(){let Z=[{value:"blank",label:"Blank",hint:"Start from scratch"},...J3()];return e({message:"Start from a template?",options:Z})}async function $3(Z){return await t({url:()=>C({message:"Request URL",placeholder:"https://api.example.com/endpoint",initialValue:Z?.url||"",validate:(X)=>{if(!X)return"URL is required";try{new URL(X)}catch{return"Invalid URL format"}}}),method:()=>e({message:"HTTP method",initialValue:Z?.method||"GET",options:k2.map((X)=>({value:X,label:X}))}),name:()=>C({message:"Request name (optional)",placeholder:"My API Request",initialValue:Z?.name||""})},{onCancel:()=>{q("Wizard cancelled"),process.exit(0)}})}async function W3(Z){let J=await b({message:"Add headers?",initialValue:Z?Object.keys(Z).length>0:!1});if(S(J)||!J)return S(J)?J:Z;let X={...Z},$=!0,W=await i4({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(S(W))return W;if(Array.isArray(W))for(let Q of W){if(Q==="content-type-json")X["Content-Type"]="application/json";if(Q==="accept-json")X.Accept="application/json";if(Q==="user-agent")X["User-Agent"]="curl-runner"}while($){let Q=await b({message:"Add custom header?",initialValue:!1});if(S(Q))return Q;if(!Q)break;let G=await t({key:()=>C({message:"Header name",placeholder:"X-Custom-Header",validate:(Y)=>!Y?"Header name required":void 0}),value:()=>C({message:"Header value",placeholder:"value",validate:(Y)=>!Y?"Header value required":void 0})});if(G.key&&G.value)X[G.key]=G.value;$=!0}return Object.keys(X).length>0?X:void 0}async function Q3(Z){let J=await e({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(S(J))return J;if(J==="none")return{bodyType:"none"};if(J==="json"){let $=await C({message:"JSON body (or press enter for interactive)",placeholder:'{"key": "value"}',initialValue:Z?.body?JSON.stringify(Z.body):""});if(S($))return $;if($)try{return{bodyType:"json",body:JSON.parse($)}}catch{return m.warn("Invalid JSON, storing as raw string"),{bodyType:"raw",body:$}}let W={},Q=!0;while(Q){let G=await t({key:()=>C({message:"Field name",placeholder:"key"}),value:()=>C({message:"Field value",placeholder:"value"}),type:()=>e({message:"Value type",options:[{value:"string",label:"String"},{value:"number",label:"Number"},{value:"boolean",label:"Boolean"}]})});if(G.key)if(G.type==="number")W[G.key]=Number(G.value);else if(G.type==="boolean")W[G.key]=G.value==="true";else W[G.key]=G.value;let Y=await b({message:"Add another field?",initialValue:!1});if(S(Y))return Y;Q=Y}return{bodyType:"json",body:W}}if(J==="form"){let $={},W=!0;while(W){let Q=await e({message:"Field type",options:[{value:"text",label:"Text field"},{value:"file",label:"File upload"}]});if(S(Q))return Q;let G=await C({message:"Field name",placeholder:Q==="file"?"file":"field",validate:(z)=>!z?"Field name required":void 0});if(S(G))return G;if(Q==="file"){let z=await C({message:"File path",placeholder:"./upload.txt",validate:(H)=>!H?"File path required":void 0});if(S(z))return z;$[G]={file:z}}else{let z=await C({message:"Field value",placeholder:"value"});if(S(z))return z;$[G]=z}let Y=await b({message:"Add another field?",initialValue:!1});if(S(Y))return Y;W=Y}return{bodyType:"form",formData:$}}let X=await C({message:"Raw body content",placeholder:"Your content here",initialValue:Z?.body||""});if(S(X))return X;return{bodyType:"raw",body:X}}async function G3(Z){let J=await e({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(S(J))return J;if(J==="none")return{authType:"none"};if(J==="bearer"){let $=await C({message:"Bearer token",placeholder:"your-token-here",initialValue:Z?.token||"",validate:(W)=>!W?"Token required":void 0});if(S($))return $;return{authType:"bearer",token:$}}let X=await t({username:()=>C({message:"Username",initialValue:Z?.username||"",validate:($)=>!$?"Username required":void 0}),password:()=>a4({message:"Password",validate:($)=>!$?"Password required":void 0})});if(S(X.username)||S(X.password))return Symbol("cancel");return{authType:"basic",username:X.username,password:X.password}}async function Y3(Z){let J=await b({message:"Configure advanced options?",initialValue:!1});if(S(J)||!J)return S(J)?J:{};let X=await t({timeout:()=>C({message:"Timeout (ms)",placeholder:"30000",initialValue:Z?.timeout?.toString()||"",validate:(W)=>{if(!W)return;let Q=Number(W);if(Number.isNaN(Q)||Q<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})}),$={};if(X.timeout)$.timeout=Number(X.timeout);if(X.followRedirects===!1)$.followRedirects=!1;if(X.insecure)$.insecure=!0;if(X.http2)$.http2=!0;return $}async function z3(Z){let J=await b({message:"Configure retry strategy?",initialValue:Z?.retryEnabled??!1});if(S(J)||!J)return S(J)?J:{};let X=await t({count:()=>C({message:"Max retry attempts",placeholder:"3",initialValue:Z?.retryCount?.toString()||"3",validate:($)=>{let W=Number($);if(Number.isNaN(W)||W<1)return"Must be at least 1"}}),delay:()=>C({message:"Retry delay (ms)",placeholder:"1000",initialValue:Z?.retryDelay?.toString()||"1000",validate:($)=>{if(!$)return;let W=Number($);if(Number.isNaN(W)||W<0)return"Must be a positive number"}}),backoff:()=>C({message:"Backoff multiplier",placeholder:"2 (exponential)",initialValue:Z?.retryBackoff?.toString()||"",validate:($)=>{if(!$)return;let W=Number($);if(Number.isNaN(W)||W<1)return"Must be at least 1"}})});return{retryEnabled:!0,retryCount:Number(X.count),retryDelay:X.delay?Number(X.delay):void 0,retryBackoff:X.backoff?Number(X.backoff):void 0}}async function H3(Z){let J=await b({message:"Add response validation?",initialValue:!!(Z?.expectStatus||Z?.expectResponseTime)});if(S(J)||!J)return S(J)?J:{};let X=await t({status:()=>C({message:"Expected status code(s)",placeholder:"200 or 200,201",initialValue:Z?.expectStatus?Array.isArray(Z.expectStatus)?Z.expectStatus.join(","):String(Z.expectStatus):""}),responseTime:()=>C({message:"Response time constraint",placeholder:"< 2000 (ms)",initialValue:Z?.expectResponseTime||""})}),$={};if(X.status){let W=X.status.split(",").map((Q)=>Number(Q.trim()));$.expectStatus=W.length===1?W[0]:W}if(X.responseTime)$.expectResponseTime=X.responseTime;return $}async function K3(Z){return await t({outputPath:()=>C({message:"Save to file",placeholder:"api-request.yaml",initialValue:Z?.outputFile||"request.yaml",validate:(X)=>{if(!X)return"File path required";if(!X.endsWith(".yaml")&&!X.endsWith(".yml"))return"File must end with .yaml or .yml"}}),runAfter:()=>b({message:"Run request after creating?",initialValue:!0})})}function P2(Z){let J={url:Z.url};if(Z.name)J.name=Z.name;if(Z.method&&Z.method!=="GET")J.method=Z.method;if(Z.headers&&Object.keys(Z.headers).length>0)J.headers=Z.headers;if(Z.params&&Object.keys(Z.params).length>0)J.params=Z.params;if(Z.bodyType==="json"&&Z.body)J.body=Z.body;else if(Z.bodyType==="form"&&Z.formData)J.formData=Z.formData;else if(Z.bodyType==="raw"&&Z.body)J.body=Z.body;if(Z.authType==="basic"&&Z.username)J.auth={type:"basic",username:Z.username,password:Z.password||""};else if(Z.authType==="bearer"&&Z.token)J.auth={type:"bearer",token:Z.token};if(Z.timeout)J.timeout=Z.timeout;if(Z.followRedirects===!1)J.followRedirects=!1;if(Z.maxRedirects)J.maxRedirects=Z.maxRedirects;if(Z.insecure)J.insecure=!0;if(Z.http2)J.http2=!0;if(Z.retryEnabled&&Z.retryCount){if(J.retry={count:Z.retryCount},Z.retryDelay)J.retry.delay=Z.retryDelay;if(Z.retryBackoff)J.retry.backoff=Z.retryBackoff}if(Z.expectStatus||Z.expectResponseTime){if(J.expect={},Z.expectStatus)J.expect.status=Z.expectStatus;if(Z.expectResponseTime)J.expect.responseTime=Z.expectResponseTime}if(Z.outputFile)J.output=Z.outputFile;return J}function y9(Z){return{request:P2(Z)}}function v9(Z){return k1(Z)}function k1(Z,J=0){let X=" ".repeat(J);if(Z===null||Z===void 0)return"null";if(typeof Z==="string"){if(Z.includes(":")||Z.includes("#")||Z.includes(`
240
- `)||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(($)=>typeof $!=="object"||$===null))return`[${Z.map(($)=>k1($,0)).join(", ")}]`;return Z.map(($)=>`${X}- ${k1($,J+1).trimStart()}`).join(`
241
- `)}if(typeof Z==="object"){let $=Object.entries(Z);if($.length===0)return"{}";let W=[];for(let[Q,G]of $){if(G===void 0)continue;if(typeof G==="object"&&G!==null&&!Array.isArray(G)){W.push(`${X}${Q}:`);let Y=k1(G,J+1);W.push(Y)}else{let Y=k1(G,J+1);if(Y.includes(`
242
- `))W.push(`${X}${Q}:`),W.push(Y);else W.push(`${X}${Q}: ${Y}`)}}return W.join(`
243
- `)}return String(Z)}async function m9(Z={}){b9(`curl-runner wizard v${i()}`);let J;if(Z.editFile){if(!await t4(Z.editFile))q(`File not found: ${Z.editFile}`),process.exit(1);m.info(`Editing: ${Z.editFile}`);let G=await s4(Z.editFile);J=await U3(G),Z.outputPath=Z.outputPath||Z.editFile}else{let G=await X3();if(S(G))q("Wizard cancelled"),process.exit(0);let Y=G==="blank"?void 0:Z3(G).defaults;J=await U3(Y)}let X=await K3({outputFile:Z.outputPath});if(S(X))q("Wizard cancelled"),process.exit(0);let $=y9(J),W=v9($);m.step("Preview:"),console.log(),console.log(W),console.log();let Q=await b({message:`Save to ${X.outputPath}?`,initialValue:!0});if(S(Q)||!Q)q("Wizard cancelled"),process.exit(0);if(await Bun.write(X.outputPath,W),m.success(`Saved to ${X.outputPath}`),X.runAfter)m.step("Running request..."),console.log(),await Bun.spawn(["bun","run",process.argv[1],X.outputPath],{stdout:"inherit",stderr:"inherit"}).exited;H0("Done!")}async function U3(Z){let J=await $3(Z);if(S(J))q("Wizard cancelled"),process.exit(0);let X={...Z,...J},$=await W3(Z?.headers);if(S($))q("Wizard cancelled"),process.exit(0);if($)X.headers=$;if(!["GET","HEAD","OPTIONS"].includes(X.method)){let z=await Q3(Z);if(S(z))q("Wizard cancelled"),process.exit(0);X={...X,...z}}let W=await G3(Z);if(S(W))q("Wizard cancelled"),process.exit(0);X={...X,...W};let Q=await Y3(Z);if(S(Q))q("Wizard cancelled"),process.exit(0);X={...X,...Q};let G=await z3(Z);if(S(G))q("Wizard cancelled"),process.exit(0);X={...X,...G};let Y=await H3(Z);if(S(Y))q("Wizard cancelled"),process.exit(0);return X={...X,...Y},X}async function B3(Z){b9("curl-runner quick init");let J=Z||await C({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(S(J))q("Cancelled"),process.exit(0);let X=await e({message:"HTTP method",initialValue:"GET",options:[{value:"GET",label:"GET"},{value:"POST",label:"POST"},{value:"PUT",label:"PUT"},{value:"DELETE",label:"DELETE"}]});if(S(X))q("Cancelled"),process.exit(0);let $=await C({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(S($))q("Cancelled"),process.exit(0);let W=y9({url:J,method:X}),Q=v9(W);await Bun.write($,Q),m.success(`Created ${$}`);let G=await b({message:"Run now?",initialValue:!0});if(S(G)){H0("Done!");return}if(G)console.log(),await Bun.spawn(["bun","run",process.argv[1],$],{stdout:"inherit",stderr:"inherit"}).exited;H0("Done!")}class M3{logger=new n;async run(Z){try{let J=Z.includes("--quiet")||Z.includes("-q"),X=await g0(Z,{onInfo:J?void 0:(Y)=>this.logger.logInfo(Y),onWarning:J?void 0:(Y)=>this.logger.logWarning(Y)}),{config:$,cliOptions:W,mode:Q,rawArgs:G}=X;if(this.logger=new n($.output),Q!=="version"&&Q!=="help")new z9().checkForUpdates().catch(()=>{});switch(Q){case"help":this.showHelp();return;case"version":console.log(`curl-runner v${i()}`);return;case"upgrade":if(G.includes("--help")||G.includes("-h")){u9();return}await new U0().run(G.slice(1));return;case"validate":if(G.includes("--help")||G.includes("-h")){e9();return}await new N0().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,$,Q);return}}catch(J){this.logger.logError(J instanceof Error?J.message:String(J)),process.exit(1)}}async executeMain(Z,J,X){let $=await this.findYamlFiles(Z.files,Z.all);if($.length===0)this.logger.logError("No YAML files found"),process.exit(1);this.logger.logInfo(`Found ${$.length} YAML file(s)`);let W=[],Q=J;for(let G of $){this.logger.logInfo(`Processing: ${G}`);let{requests:Y,config:z}=await this.processYamlFile(G,Q.defaults),H=z?.output||{},K=Y.map((B)=>({...B,sourceOutputConfig:H,sourceFile:G}));if(z)Q=y1(Q,z);W.push(...K)}if(W.length===0)this.logger.logError("No requests found in YAML files"),process.exit(1);if(m0(W),X==="profile"){let G=d0(Z,Q);await this.executeProfileMode(W,Q,G)}else if(X==="watch"){let G=f0(Z,Q);await new H9({files:$,config:G,logger:this.logger,onRun:async()=>{await this.executeRequests($,Q)}}).start()}else{let G=await this.executeRequests($,Q),Y=this.determineExitCode(G,Q);process.exit(Y)}}async executeProfileMode(Z,J,X){let W=await new a0(J,X).profileRequests(Z);if(this.logger.logProfileSummary(W),X.exportFile){let Y=[],z=X.exportFile.endsWith(".csv");for(let K of W){let B=K.request.name||K.request.url;Y.push(z?z4(K.stats,B):H4(K.stats,B))}let H=z?Y.join(`
244
-
245
- `):`[${Y.join(`,
246
- `)}]`;await Bun.write(X.exportFile,H),this.logger.logInfo(`Profile results exported to ${X.exportFile}`)}let Q=W.reduce((Y,z)=>Y+z.stats.failures,0),G=W.reduce((Y,z)=>Y+z.stats.iterations+z.stats.warmup,0);process.exit(Q>0&&Q/G>0.5?1:0)}async executeRequests(Z,J){let X=[],$=[];for(let G of Z){let{requests:Y,config:z}=await this.processYamlFile(G,J.defaults),H=z?.output||{},K=Y.map((B)=>({...B,sourceOutputConfig:H,sourceFile:G}));X.push({file:G,requests:K,config:z}),$.push(...K)}m0($);let W=new Y9(J),Q;if(X.length>1){let G=[],Y=0;for(let B=0;B<X.length;B++){let U=X[B];this.logger.logFileHeader(U.file,U.requests.length);let D=await W.execute(U.requests);if(G.push(...D.results),Y+=D.duration,B<X.length-1&&!J.output?.quiet)console.log()}let z=G.filter((B)=>B.success&&!B.skipped).length,H=G.filter((B)=>!B.success&&!B.skipped).length,K=G.filter((B)=>B.skipped).length;Q={total:G.length,successful:z,failed:H,skipped:K,duration:Y,results:G},this.logger.logSummary(Q,!0)}else Q=await W.execute($);if(J.diff?.enabled||J.diff?.save||J.diff?.compareWith)await this.handleDiffMode(Z[0],Q.results,J.diff);return Q}async handleDiffMode(Z,J,X){let $=new N1(X),W=new D1(X.outputFormat||"terminal"),Q=K1.mergeConfig(X,!0)||{},G=X.label||"current",Y=X.compareWith;if(X.save)await $.saveBaseline(Z,G,J,Q),this.logger.logInfo(`Baseline saved as '${G}'`);if(Y){let z=await $.compareWithBaseline(Z,J,G,Y,Q);if(z.newBaselines===z.totalRequests){this.logger.logWarning(`No baseline '${Y}' found. Saving current run as baseline.`),await $.saveBaseline(Z,Y,J,Q);return}if(console.log(W.formatSummary(z,Y,G)),X.save)await $.saveBaseline(Z,G,J,Q)}else if(X.enabled&&!X.save){let z=await $.listLabels(Z);if(z.length===0)await $.saveBaseline(Z,"baseline",J,Q),this.logger.logInfo("No baselines found. Saved current run as 'baseline'.");else if(z.length===1){let H=await $.compareWithBaseline(Z,J,G,z[0],Q);console.log(W.formatSummary(H,z[0],G))}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 J=V0(Z);if(!J)this.showConvertHelp(),process.exit(1);let X;switch(J.subcommand){case"curl":X=S0(J.input,J.options);break;case"file":X=await E0(J.input,J.options);break;case"yaml":X=await A0(J.input,J.options);break}if(J.options.debug&&X.debug)console.log(this.logger.color("DEBUG:","yellow")),console.log(JSON.stringify(X.debug,null,2)),console.log();if(X.warnings.length>0&&!J.options.output)for(let $ of X.warnings)this.logger.logWarning($);if(J.options.output)await Bun.write(J.options.output,X.output),this.logger.logInfo(`Written to ${J.options.output}`);else console.log(X.output)}async executeInit(Z){let J=C0(Z);if(Z.includes("--help")||Z.includes("-h")){this.showInitHelp();return}if(J.wizard)await m9({outputPath:J.outputPath});else await B3(J.url)}async executeEdit(Z){let J=w0(Z);if(Z.includes("--help")||Z.includes("-h")){this.showEditHelp();return}if(!J.file)this.logger.logError("Usage: curl-runner edit <file.yaml>"),process.exit(1);await m9({editFile:J.file,outputPath:J.outputPath})}async executeDiffSubcommand(Z,J){let X=Z[0],$=Z[1],W=Z[2];if(!W){let H=await this.findYamlFiles([],J.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);W=H[0]}let Q={dir:J.diffDir||"__baselines__",outputFormat:J.diffOutput||"terminal"},G=new N1(Q),Y=new D1(Q.outputFormat||"terminal"),z={exclude:[],match:{}};try{let H=await G.compareTwoBaselines(W,X,$,z);console.log(Y.formatSummary(H,X,$)),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,J){let X=new Set,$=[];if(Z.length===0)$=J?["**/*.yaml","**/*.yml"]:["*.yaml","*.yml"];else for(let W of Z)try{let G=await(await import("fs/promises")).stat(W);if(G.isDirectory()){if($.push(`${W}/*.yaml`,`${W}/*.yml`),J)$.push(`${W}/**/*.yaml`,`${W}/**/*.yml`)}else if(G.isFile())$.push(W)}catch{$.push(W)}for(let W of $){let Q=new C2(W);for await(let G of Q.scan("."))if(G.endsWith(".yaml")||G.endsWith(".yml"))X.add(G)}return Array.from(X).sort()}async processYamlFile(Z,J={}){let X=await y.parseFile(Z),$=[],W;if(X.global)W=X.global;let Q={...X.global?.variables,...X.collection?.variables},G={...J,...X.global?.defaults,...X.collection?.defaults};if(X.request)$.push(this.prepareRequest(X.request,Q,G));if(X.requests)for(let Y of X.requests)$.push(this.prepareRequest(Y,Q,G));if(X.collection?.requests)for(let Y of X.collection.requests)$.push(this.prepareRequest(Y,Q,G));return{requests:$,config:W}}prepareRequest(Z,J,X){let $=y.interpolateVariables(Z,J);return y.mergeConfigs(X,$)}determineExitCode(Z,J){let{failed:X,total:$}=Z,W=J.ci;if(X===0)return 0;if(W){if(W.strictExit)return 1;if(W.failOn!==void 0&&X>W.failOn)return 1;if(W.failOnPercentage!==void 0&&$>0){if(X/$*100>W.failOnPercentage)return 1}if(W.failOn!==void 0||W.failOnPercentage!==void 0)return 0}return!J.continueOnError?1:0}showInitHelp(){console.log(`
247
- ${this.logger.color("\uD83D\uDE80 CURL RUNNER - INIT","bright")}
248
-
249
- ${this.logger.color("USAGE:","yellow")}
250
- curl-runner init [url] [options]
251
-
252
- ${this.logger.color("OPTIONS:","yellow")}
253
- -w, --wizard Launch full interactive wizard
254
- -o, --output <file> Output file path (default: request.yaml)
255
- -h, --help Show this help
256
-
257
- ${this.logger.color("EXAMPLES:","yellow")}
258
- # Quick init with prompts
259
- curl-runner init
260
-
261
- # Quick init with URL
262
- curl-runner init https://api.example.com/users
263
-
264
- # Full wizard mode
265
- curl-runner init --wizard
266
-
267
- # Wizard with custom output
268
- curl-runner init -w -o api-test.yaml
269
- `)}showEditHelp(){console.log(`
270
- ${this.logger.color("\uD83D\uDE80 CURL RUNNER - EDIT","bright")}
271
-
272
- ${this.logger.color("USAGE:","yellow")}
273
- curl-runner edit <file.yaml> [options]
274
-
275
- ${this.logger.color("OPTIONS:","yellow")}
276
- -o, --output <file> Save to different file (default: overwrite original)
277
- -h, --help Show this help
278
-
279
- ${this.logger.color("EXAMPLES:","yellow")}
280
- # Edit existing file
281
- curl-runner edit api-test.yaml
282
-
283
- # Edit and save to new file
284
- curl-runner edit api-test.yaml -o api-test-v2.yaml
285
- `)}showConvertHelp(){console.log(`
286
- ${this.logger.color("CURL RUNNER - CONVERT","bright")}
287
-
288
- ${this.logger.color("USAGE:","yellow")}
289
- curl-runner convert curl "<curl command>" Convert curl \u2192 YAML
290
- curl-runner convert file <script.sh> Convert shell script \u2192 YAML
291
- curl-runner convert yaml <test.yaml> Convert YAML \u2192 curl
292
-
293
- ${this.logger.color("OPTIONS:","yellow")}
294
- -o, --output <file> Write output to file
295
- --pretty Pretty-print output (default for YAML)
296
- --loss-report Show warnings for unsupported features (default)
297
- --debug Show token stream, AST, and IR
298
- -h, --help Show this help
299
-
300
- ${this.logger.color("EXAMPLES:","yellow")}
301
- # Convert inline curl to YAML
302
- curl-runner convert curl "curl -X POST https://api.example.com -d '{"name":"Alex"}'"
303
-
304
- # Convert and save to file
305
- curl-runner convert curl "curl https://api.example.com" -o test.yaml
306
-
307
- # Convert shell script (batch)
308
- curl-runner convert file scripts/api-tests.sh
309
-
310
- # Convert YAML back to curl
311
- curl-runner convert yaml test.yaml
312
-
313
- # Debug mode
314
- curl-runner convert curl "curl https://example.com" --debug
315
- `)}showHelp(){console.log(`
316
- ${this.logger.color("\uD83D\uDE80 CURL RUNNER","bright")}
317
-
318
- ${this.logger.color("USAGE:","yellow")}
319
- curl-runner [files...] [options]
320
-
321
- ${this.logger.color("OPTIONS:","yellow")}
322
- -h, --help Show this help message
323
- -n, --dry-run Show curl commands without executing
324
- --http2 Use HTTP/2 protocol with multiplexing
325
- --connection-pool Enable TCP connection pooling with HTTP/2 multiplexing
326
- --max-streams <n> Max concurrent streams per host (default: 10)
327
- --keepalive-time <sec> TCP keepalive time in seconds (default: 60)
328
- --connect-timeout <sec> Connection timeout in seconds (default: 30)
329
- -v, --verbose Enable verbose output
330
- -q, --quiet Suppress non-error output
331
- -p, --execution parallel Execute requests in parallel
332
- --max-concurrent <n> Limit concurrent requests in parallel mode
333
- -c, --continue-on-error Continue execution on errors
334
- -o, --output <file> Save results to file
335
- --all Find all YAML files recursively
336
- --timeout <ms> Set request timeout in milliseconds
337
- --retries <count> Set maximum retry attempts
338
- --retry-delay <ms> Set delay between retries in milliseconds
339
- --no-retry Disable retry mechanism
340
- --output-format <format> Set output format (json|pretty|raw)
341
- --pretty-level <level> Set pretty format level (minimal|standard|detailed)
342
- --show-headers Include response headers in output
343
- --show-body Include response body in output
344
- --show-metrics Include performance metrics in output
345
- --version Show version
346
-
347
- ${this.logger.color("WATCH MODE:","yellow")}
348
- -w, --watch Watch files and re-run on changes
349
- --watch-debounce <ms> Debounce delay for watch mode (default: 300)
350
- --no-watch-clear Don't clear screen between watch runs
351
-
352
- ${this.logger.color("PROFILE MODE:","yellow")}
353
- -P, --profile <n> Run each request N times for latency stats
354
- --profile-warmup <n> Warmup iterations to exclude from stats (default: 1)
355
- --profile-concurrency <n> Concurrent iterations (default: 1 = sequential)
356
- --profile-histogram Show ASCII histogram of latency distribution
357
- --profile-export <file> Export raw timings to file (.json or .csv)
358
-
359
- ${this.logger.color("CI/CD OPTIONS:","yellow")}
360
- --strict-exit Exit with code 1 if any validation fails (for CI/CD)
361
- --fail-on <count> Exit with code 1 if failures exceed this count
362
- --fail-on-percentage <pct> Exit with code 1 if failure percentage exceeds this value
363
-
364
- ${this.logger.color("SECURITY OPTIONS:","yellow")}
365
- --allow-protocol <proto> Permit a URL protocol beyond http/https (repeatable, e.g. ftp)
366
- --allow-path Allow file paths outside the working directory
367
- --no-redact Disable secret redaction in output and saved files
368
-
369
- ${this.logger.color("SNAPSHOT OPTIONS:","yellow")}
370
- -s, --snapshot Enable snapshot testing
371
- -u, --update-snapshots Update all snapshots
372
- --update-failing Update only failing snapshots
373
- --snapshot-dir <dir> Custom snapshot directory (default: __snapshots__)
374
- --ci-snapshot Fail if snapshot is missing (CI mode)
375
-
376
- ${this.logger.color("DIFF OPTIONS:","yellow")}
377
- -d, --diff Enable response diffing (compare with baseline)
378
- --diff-save Save current run as baseline
379
- --diff-label <name> Label for current run (e.g., 'staging', 'v1.0')
380
- --diff-compare <label> Compare against this baseline label
381
- --diff-dir <dir> Baseline storage directory (default: __baselines__)
382
- --diff-output <format> Output format (terminal|json|markdown)
383
-
384
- ${this.logger.color("DIFF SUBCOMMAND:","yellow")}
385
- curl-runner diff <label1> <label2> [file.yaml]
386
- Compare two stored baselines without making requests
387
-
388
- ${this.logger.color("UPGRADE:","yellow")}
389
- curl-runner upgrade Upgrade to latest version (auto-detects install method)
390
- curl-runner upgrade --dry-run Preview upgrade command without executing
391
- curl-runner upgrade --force Force reinstall even if up to date
392
-
393
- ${this.logger.color("VALIDATE:","yellow")}
394
- curl-runner validate Validate YAML files against curl-runner schema
395
- curl-runner validate --fix Validate and auto-fix issues where possible
396
- curl-runner validate -q Only show files with issues
397
-
398
- ${this.logger.color("CONVERT:","yellow")}
399
- curl-runner convert curl "<cmd>" Convert curl command to YAML
400
- curl-runner convert file <sh> Convert shell script to YAML (batch)
401
- curl-runner convert yaml <yaml> Convert YAML to curl command(s)
402
-
403
- ${this.logger.color("WIZARD:","yellow")}
404
- curl-runner init Quick create a new YAML file
405
- curl-runner init --wizard Full interactive wizard
406
- curl-runner init <url> Quick create with URL
407
- curl-runner edit <file.yaml> Edit existing YAML file
408
-
409
- ${this.logger.color("EXAMPLES:","yellow")}
410
- # Run all YAML files in current directory
411
- curl-runner
412
-
413
- # Run specific file
414
- curl-runner api-tests.yaml
415
-
416
- # Run all files in a directory
417
- curl-runner examples/
418
-
419
- # Run all files in multiple directories
420
- curl-runner tests/ examples/
421
-
422
- # Run all files recursively in parallel
423
- curl-runner --all -p
424
-
425
- # Run in parallel with max 5 concurrent requests
426
- curl-runner -p --max-concurrent 5 tests.yaml
427
-
428
- # Run directory recursively
429
- curl-runner --all examples/
430
-
431
- # Run with verbose output and continue on errors
432
- curl-runner tests/*.yaml -vc
433
-
434
- # Dry run - show curl commands without executing
435
- curl-runner api.yaml --dry-run
436
-
437
- # Use HTTP/2 for all requests
438
- curl-runner api.yaml --http2
439
-
440
- # Enable connection pooling with HTTP/2 multiplexing
441
- curl-runner api.yaml -p --connection-pool
442
-
443
- # Connection pooling with custom settings
444
- curl-runner api.yaml -p --connection-pool --max-streams 20
445
-
446
- # Run with minimal pretty output (only status and errors)
447
- curl-runner --output-format pretty --pretty-level minimal test.yaml
448
-
449
- # Run with detailed pretty output (show all information)
450
- curl-runner --output-format pretty --pretty-level detailed test.yaml
451
-
452
- # CI/CD: Fail if any validation fails (strict mode)
453
- curl-runner tests/ --strict-exit
454
-
455
- # CI/CD: Run all tests but fail if any validation fails
456
- curl-runner tests/ --continue-on-error --strict-exit
457
-
458
- # CI/CD: Allow up to 2 failures
459
- curl-runner tests/ --fail-on 2
460
-
461
- # CI/CD: Allow up to 10% failures
462
- curl-runner tests/ --fail-on-percentage 10
463
-
464
- # Watch mode - re-run on file changes
465
- curl-runner api.yaml --watch
466
-
467
- # Watch with custom debounce
468
- curl-runner tests/ -w --watch-debounce 500
469
-
470
- # Profile mode - run request 100 times for latency stats
471
- curl-runner api.yaml -P 100
472
-
473
- # Profile with 5 warmup iterations and histogram
474
- curl-runner api.yaml --profile 50 --profile-warmup 5 --profile-histogram
475
-
476
- # Profile with concurrent iterations and export
477
- curl-runner api.yaml -P 100 --profile-concurrency 10 --profile-export results.json
478
-
479
- # Snapshot testing - save and compare responses
480
- curl-runner api.yaml --snapshot
481
-
482
- # Update all snapshots
483
- curl-runner api.yaml -su
484
-
485
- # CI mode - fail if snapshot missing
486
- curl-runner api.yaml --snapshot --ci-snapshot
487
-
488
- # Response diffing - save baseline for staging
489
- curl-runner api.yaml --diff-save --diff-label staging
490
-
491
- # Compare current run against staging baseline
492
- curl-runner api.yaml --diff --diff-compare staging
493
-
494
- # Compare staging vs production baselines (offline)
495
- curl-runner diff staging production api.yaml
496
-
497
- # Auto-diff: creates baseline on first run, compares on subsequent runs
498
- curl-runner api.yaml --diff
499
-
500
- # Diff with JSON output for CI
501
- curl-runner api.yaml --diff --diff-compare staging --diff-output json
502
-
503
- # Create new YAML file with wizard
504
- curl-runner init --wizard
505
-
506
- # Quick create with URL
507
- curl-runner init https://api.example.com/users
508
-
509
- # Edit existing YAML file
510
- curl-runner edit api-test.yaml
511
-
512
- ${this.logger.color("YAML STRUCTURE:","yellow")}
513
- Single request:
514
- request:
515
- url: https://api.example.com
516
- method: GET
517
-
518
- Multiple requests:
519
- requests:
520
- - url: https://api.example.com/users
521
- method: GET
522
- - url: https://api.example.com/posts
523
- method: POST
524
- body: { title: "Test" }
525
-
526
- With global config:
527
- global:
528
- execution: parallel
529
- variables:
530
- BASE_URL: https://api.example.com
531
- requests:
532
- - url: \${BASE_URL}/users
533
- method: GET
534
- `)}}var w2=new M3;w2.run(process.argv.slice(2));
535
-
536
- //# debugId=867E14427AE7A0D764756E2164756E21
537
- //# sourceMappingURL=cli.js.map