stably 4.1.3 → 4.2.1

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/README.md CHANGED
@@ -35,22 +35,3 @@ Below is a short list of common commands. For a complete list, please use `stabl
35
35
  * `npx stably`: This starts our REPL which will help with test creation or modifications
36
36
  * `npx stably test`: Use this to run tests locally or in the CI
37
37
  * `npx stably --help`: Will print full list of commands
38
-
39
- ## Local development quickstart
40
- Follow these steps to run the CLI against a local API server or staging:
41
-
42
- 1. In the `noqa/app` repository, start the API server: `pnpm dev-api` (note the port, typically `8080`).
43
- 2. In `stably/packages/cli`, run one of the following:
44
- - `STABLY_API_URL=http://127.0.0.1:18080 pn dev:staging` when pointing to the staging PropelAuth backend.
45
- - `pn dev` to use the production backend.
46
- - `pn dev:staging` to use the staging backend.
47
- - Set `STABLY_API_URL` to target another backend, such as your local API server.
48
-
49
- ### Authentication
50
- You can authenticate via an organization token or OAuth:
51
-
52
- - **Org token auth:** Provide `STABLY_API_KEY` and `STABLY_PROJECT_ID`. Generate the key in the PropelAuth dashboard, ensuring the key and project belong to the same organization.
53
- - **OAuth:** Run `stably login` and follow the CLI prompt.
54
-
55
- ### Running from another directory
56
- Use the `-C` flag to run the CLI from a different working directory.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var e=require("commander"),t=require("buffer"),n=require("path"),r=require("child_process"),o=require("process"),s=require("url"),i=require("os"),a=require("fs");require("timers/promises");var c=require("util"),l=require("@anthropic-ai/claude-agent-sdk"),d=require("dotenv"),u=require("@clack/prompts"),p=require("picocolors"),f=require("readline/promises"),h=require("zod"),m=require("fs/promises"),_=require("open"),g=require("http"),E=require("crypto"),y=require("react"),b=require("react/jsx-runtime"),I=require("simple-git"),T=require("zod/v3"),v=require("@stablyhq/runner-sdk");function R(e){return e&&e.__esModule?e:{default:e}}var w=R(n),S=R(r),C=R(o),A=R(i),U=R(a),x=R(p),L=R(h),P=R(_),O=R(g),B=R(E),N=Object.create,D=Object.defineProperty,j=Object.getOwnPropertyDescriptor,k=Object.getOwnPropertyNames,M=Object.getPrototypeOf,$=Object.prototype.hasOwnProperty,H=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)(function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),G=(e,t)=>function(){return t||(0,e[k(e)[0]])((t={exports:{}}).exports,t),t.exports},K=(e,t,n)=>(n=null!=e?N(M(e)):{},((e,t,n,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of k(t))$.call(e,n)||void 0===n||D(e,n,{get:()=>t[n],enumerable:!(r=j(t,n))||r.enumerable});return e})(D(n,"default",{value:e,enumerable:!0}),e)),F=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(e,t){t.exports=o,o.sync=function(e,t){return r(n.statSync(e),e,t)};var n=H("fs");function r(e,t,n){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var n=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!n)return!0;if(-1!==(n=n.split(";")).indexOf(""))return!0;for(var r=0;r<n.length;r++){var o=n[r].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}(t,n)}function o(e,t,o){n.stat(e,function(n,s){o(n,!n&&r(s,e,t))})}}}),z=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js"(e,t){t.exports=r,r.sync=function(e,t){return o(n.statSync(e),t)};var n=H("fs");function r(e,t,r){n.stat(e,function(e,n){r(e,!e&&o(n,t))})}function o(e,t){return e.isFile()&&function(e,t){var n=e.mode,r=e.uid,o=e.gid,s=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),i=void 0!==t.gid?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8);return n&parseInt("001",8)||n&c&&o===i||n&a&&r===s||n&(a|c)&&0===s}(e,t)}}}),Y=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(e,t){var n;function r(e,t,o){if("function"==typeof t&&(o=t,t={}),!o){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(n,o){r(e,t||{},function(e,t){e?o(e):n(t)})})}n(e,t||{},function(e,n){e&&("EACCES"===e.code||t&&t.ignoreErrors)&&(e=null,n=!1),o(e,n)})}H("fs"),n="win32"===process.platform||global.TESTING_WINDOWS?F():z(),t.exports=r,r.sync=function(e,t){try{return n.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||"EACCES"===e.code)return!1;throw e}}}}),W=G({"node_modules/.pnpm/which@2.0.2/node_modules/which/which.js"(e,t){var n="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,r=H("path"),o=n?";":":",s=Y(),i=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),a=(e,t)=>{const r=t.colon||o,s=e.match(/\//)||n&&e.match(/\\/)?[""]:[...n?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],i=n?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=n?i.split(r):[""];return n&&-1!==e.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:s,pathExt:a,pathExtExe:i}},c=(e,t,n)=>{"function"==typeof t&&(n=t,t={}),t||(t={});const{pathEnv:o,pathExt:c,pathExtExe:l}=a(e,t),d=[],u=n=>new Promise((s,a)=>{if(n===o.length)return t.all&&d.length?s(d):a(i(e));const c=o[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=r.join(l,e),f=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;s(p(f,n,0))}),p=(e,n,r)=>new Promise((o,i)=>{if(r===c.length)return o(u(n+1));const a=c[r];s(e+a,{pathExt:l},(s,i)=>{if(!s&&i){if(!t.all)return o(e+a);d.push(e+a)}return o(p(e,n,r+1))})});return n?u(0).then(e=>n(null,e),n):u(0)};t.exports=c,c.sync=(e,t)=>{t=t||{};const{pathEnv:n,pathExt:o,pathExtExe:c}=a(e,t),l=[];for(let i=0;i<n.length;i++){const a=n[i],d=/^".*"$/.test(a)?a.slice(1,-1):a,u=r.join(d,e),p=!d&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;for(let e=0;e<o.length;e++){const n=p+o[e];try{if(s.sync(n,{pathExt:c})){if(!t.all)return n;l.push(n)}}catch(e){}}}if(t.all&&l.length)return l;if(t.nothrow)return null;throw i(e)}}}),V=G({"node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js"(e,t){var n=(e={})=>{const t=e.env||process.env;return"win32"!==(e.platform||process.platform)?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"};t.exports=n,t.exports.default=n}}),q=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){var n=H("path"),r=W(),o=V();function s(e,t){const s=e.options.env||process.env,i=process.cwd(),a=null!=e.options.cwd,c=a&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(e.options.cwd)}catch(e){}let l;try{l=r.sync(e.command,{path:s[o({env:s})],pathExt:t?n.delimiter:void 0})}catch(e){}finally{c&&process.chdir(i)}return l&&(l=n.resolve(a?e.options.cwd:"",l)),l}t.exports=function(e){return s(e)||s(e,!0)}}}),J=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js"(e,t){var n=/([()\][%!^"`<>&|;, *?])/g;t.exports.command=function(e){return e.replace(n,"^$1")},t.exports.argument=function(e,t){return e=(e=`"${e=(e=(e=`${e}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(n,"^$1"),t&&(e=e.replace(n,"^$1")),e}}}),X=G({"node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(e,t){t.exports=/^#!(.*)/}}),Q=G({"node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js"(e,t){var n=X();t.exports=(e="")=>{const t=e.match(n);if(!t)return null;const[r,o]=t[0].replace(/#! ?/,"").split(" "),s=r.split("/").pop();return"env"===s?o:o?`${s} ${o}`:s}}}),Z=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(e,t){var n=H("fs"),r=Q();t.exports=function(e){const t=Buffer.alloc(150);let o;try{o=n.openSync(e,"r"),n.readSync(o,t,0,150,0),n.closeSync(o)}catch(e){}return r(t.toString())}}}),ee=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(e,t){var n=H("path"),r=q(),o=J(),s=Z(),i="win32"===process.platform,a=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;t.exports=function(e,t,l){t&&!Array.isArray(t)&&(l=t,t=null);const d={command:e,args:t=t?t.slice(0):[],options:l=Object.assign({},l),file:void 0,original:{command:e,args:t}};return l.shell?d:function(e){if(!i)return e;const t=function(e){e.file=r(e);const t=e.file&&s(e.file);return t?(e.args.unshift(e.file),e.command=t,r(e)):e.file}(e),l=!a.test(t);if(e.options.forceShell||l){const r=c.test(t);e.command=n.normalize(e.command),e.command=o.command(e.command),e.args=e.args.map(e=>o.argument(e,r));const s=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${s}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}(d)}}}),te=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js"(e,t){var n="win32"===process.platform;function r(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function o(e,t){return n&&1===e&&!t.file?r(t.original,"spawn"):null}t.exports={hookChildProcess:function(e,t){if(!n)return;const r=e.emit;e.emit=function(n,s){if("exit"===n){const n=o(s,t);if(n)return r.call(e,"error",n)}return r.apply(e,arguments)}},verifyENOENT:o,verifyENOENTSync:function(e,t){return n&&1===e&&!t.file?r(t.original,"spawnSync"):null},notFoundError:r}}}),ne=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(e,t){var n=H("child_process"),r=ee(),o=te();function s(e,t,s){const i=r(e,t,s),a=n.spawn(i.command,i.args,i.options);return o.hookChildProcess(a,i),a}t.exports=s,t.exports.spawn=s,t.exports.sync=function(e,t,s){const i=r(e,t,s),a=n.spawnSync(i.command,i.args,i.options);return a.error=a.error||o.verifyENOENTSync(a.status,i),a},t.exports._parse=r,t.exports._enoent=o}}),re=G({"node_modules/.pnpm/merge-stream@2.0.0/node_modules/merge-stream/index.js"(e,t){var{PassThrough:n}=H("stream");t.exports=function(){var e=[],t=new n({objectMode:!0});return t.setMaxListeners(0),t.add=r,t.isEmpty=function(){return 0==e.length},t.on("unpipe",o),Array.prototype.slice.call(arguments).forEach(r),t;function r(n){return Array.isArray(n)?(n.forEach(r),this):(e.push(n),n.once("end",o.bind(null,n)),n.once("error",t.emit.bind(t,"error")),n.pipe(t,{end:!1}),this)}function o(n){!(e=e.filter(function(e){return e!==n})).length&&t.readable&&t.end()}}}}),oe=G({"node_modules/.pnpm/java-properties@1.0.2/node_modules/java-properties/dist-node/index.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.of=e.PropertiesFile=void 0;var t,n=(t=H("fs"))&&t.__esModule?t:{default:t},r=class{constructor(...e){this.objs={},e.length&&this.of.apply(this,e)}makeKeys(e){if(e&&0!==e.indexOf("#")){let t=["=",":"].map(t=>e.indexOf(t)).filter(e=>e>-1),n=Math.min(...t),r=e.substring(0,n).trim(),o=e.substring(n+1).trim();if(this.objs.hasOwnProperty(r))if(Array.isArray(this.objs[r]))this.objs[r].push(o);else{let e=this.objs[r];this.objs[r]=[e,o]}else{const e=o.replace(/"/g,'\\"').replace(/\\:/g,":").replace(/\\=/g,"=");this.objs[r]=unescape(JSON.parse('"'+e+'"'))}}}addFile(e){let t=n.default.readFileSync(e,"utf-8").split(/\r?\n/),r=this;for(let e=0;e<t.length;e++){let n=t[e];for(;"\\"===n.substring(n.length-1);)n=n.slice(0,-1),n+=t[e+1].trim(),e++;r.makeKeys(n)}}of(...e){for(let t=0;t<e.length;t++)this.addFile(e[t])}get(e,t){if(this.objs.hasOwnProperty(e)){if(Array.isArray(this.objs[e])){let t=[];for(let n=0;n<this.objs[e].length;n++)t[n]=this.interpolate(this.objs[e][n]);return t}return void 0===this.objs[e]?"":this.interpolate(this.objs[e])}return t}getLast(e,t){if(this.objs.hasOwnProperty(e)){if(Array.isArray(this.objs[e])){var n=this.objs[e].length;return this.interpolate(this.objs[e][n-1])}return void 0===this.objs[e]?"":this.interpolate(this.objs[e])}return t}getFirst(e,t){return this.objs.hasOwnProperty(e)?Array.isArray(this.objs[e])?this.interpolate(this.objs[e][0]):void 0===this.objs[e]?"":this.interpolate(this.objs[e]):t}getInt(e,t){let n=this.getLast(e);return n?parseInt(n,10):t}getFloat(e,t){let n=this.getLast(e);return n?parseFloat(n):t}getBoolean(e,t){let n=this.getLast(e);return n?!/^(false|0)$/i.test(r=n)&&!!r:t||!1;var r}set(e,t){this.objs[e]=t}interpolate(e){let t=this;return e.replace(/\\\\/g,"\\").replace(/\$\{([A-Za-z0-9\.\-\_]*)\}/g,function(e){return t.getLast(e.substring(2,e.length-1))})}getKeys(){let e=[];for(let t in this.objs)e.push(t);return e}getMatchingKeys(e){let t=[];for(let n in this.objs)-1!==n.search(e)&&t.push(n);return t}reset(){this.objs={}}};e.PropertiesFile=r,e.of=function(...e){let t=new r;return t.of.apply(t,e),t}}}),se={detect:({env:e})=>Boolean(e.APPVEYOR),configuration({env:e}){const t=e.APPVEYOR_PULL_REQUEST_NUMBER,n=Boolean(t);return{name:"Appveyor",service:"appveyor",commit:e.APPVEYOR_REPO_COMMIT,tag:e.APPVEYOR_REPO_TAG_NAME,build:e.APPVEYOR_BUILD_NUMBER,buildUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/${e.APPVEYOR_BUILD_VERSION}`,branch:e.APPVEYOR_REPO_BRANCH,job:e.APPVEYOR_JOB_NUMBER,jobUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/job/${e.APPVEYOR_JOB_ID}`,pr:t,isPr:n,prBranch:e.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH,slug:e.APPVEYOR_REPO_NAME,root:e.APPVEYOR_BUILD_FOLDER}}};function ie(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function ae(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var ce={detect:({env:e})=>Boolean(e.BUILD_BUILDURI),configuration({env:e}){const t=e.SYSTEM_PULLREQUEST_PULLREQUESTID,n=Boolean(t);return{name:"Azure Pipelines",service:"azurePipelines",commit:e.BUILD_SOURCEVERSION,build:e.BUILD_BUILDNUMBER,branch:ae(n?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:n,prBranch:ae(n?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},le={detect:({env:e})=>Boolean(e.bamboo_agentId),configuration:({env:e})=>({name:"Bamboo",service:"bamboo",commit:e.bamboo_planRepository_1_revision,build:e.bamboo_buildNumber,buildUrl:e.bamboo_buildResultsUrl,branch:e.bamboo_planRepository_1_branchName,job:e.bamboo_buildKey,root:e.bamboo_build_working_directory})},de={detect:({env:e})=>Boolean(e.BITBUCKET_BUILD_NUMBER),configuration:({env:e})=>({name:"Bitbucket Pipelines",service:"bitbucket",commit:e.BITBUCKET_COMMIT,tag:e.BITBUCKET_TAG,build:e.BITBUCKET_BUILD_NUMBER,buildUrl:`https://bitbucket.org/${e.BITBUCKET_REPO_FULL_NAME}/addon/pipelines/home#!/results/${e.BITBUCKET_BUILD_NUMBER}`,branch:e.BITBUCKET_BRANCH,slug:e.BITBUCKET_REPO_FULL_NAME,root:e.BITBUCKET_CLONE_DIR})},ue={detect:({env:e})=>Boolean(e.BITRISE_IO),configuration({env:e}){const t="false"===e.BITRISE_PULL_REQUEST?void 0:e.BITRISE_PULL_REQUEST,n=Boolean(t);return{name:"Bitrise",service:"bitrise",commit:e.BITRISE_GIT_COMMIT,tag:e.BITRISE_GIT_TAG,build:e.BITRISE_BUILD_NUMBER,buildUrl:e.BITRISE_BUILD_URL,branch:n?e.BITRISEIO_GIT_BRANCH_DEST:e.BITRISE_GIT_BRANCH,pr:t,isPr:n,prBranch:n?e.BITRISE_GIT_BRANCH:void 0,slug:e.BITRISE_APP_SLUG}}},pe={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=ie(e.BUDDY_EXECUTION_PULL_REQUEST_ID),n=Boolean(t);return{name:"Buddy",service:"buddy",commit:e.BUDDY_EXECUTION_REVISION,tag:e.BUDDY_EXECUTION_TAG,build:e.BUDDY_EXECUTION_ID,buildUrl:e.BUDDY_EXECUTION_URL,branch:n?e.BUDDY_EXECUTION_PULL_REQUEST_HEAD_BRANCH:e.BUDDY_EXECUTION_BRANCH,pr:t,isPr:n,slug:e.BUDDY_REPO_SLUG}}},fe=K(ne());function he(e={}){const{env:t=process.env,platform:n=process.platform}=e;return"win32"!==n?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"}var me=(e,t)=>({name:`SIGRT${t+1}`,number:_e+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),_e=34,ge=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}],Ee=()=>{const e=(()=>{const e=64-_e+1;return Array.from({length:e},me)})();return[...ge,...e].map(ye)},ye=({name:e,number:t,description:n,action:r,forced:o=!1,standard:s})=>{const{signals:{[e]:a}}=i.constants,c=void 0!==a;return{name:e,number:c?a:t,description:n,supported:c,action:r,forced:o,standard:s}},be=({name:e,number:t,description:n,supported:r,action:o,forced:s,standard:i})=>[e,{name:e,number:t,description:n,supported:r,action:o,forced:s,standard:i}],Ie=(()=>{const e=Ee();return Object.fromEntries(e.map(be))})();(()=>{const e=Ee(),t=Array.from({length:65},(t,n)=>((e,t)=>{const n=((e,t)=>{const n=t.find(({name:t})=>i.constants.signals[t]===e);return void 0!==n?n:t.find(t=>t.number===e)})(e,t);if(void 0===n)return{};const{name:r,description:o,supported:s,action:a,forced:c,standard:l}=n;return{[e]:{name:r,number:e,description:o,supported:s,action:a,forced:c,standard:l}}})(n,e));Object.assign({},...t)})();var Te=({stdout:e,stderr:t,all:n,error:r,signal:o,exitCode:s,command:i,escapedCommand:a,timedOut:c,isCanceled:l,killed:d,parsed:{options:{timeout:u,cwd:p=C.default.cwd()}}})=>{s=null===s?void 0:s;const f=void 0===(o=null===o?void 0:o)?void 0:Ie[o].description,h=(({timedOut:e,timeout:t,errorCode:n,signal:r,signalDescription:o,exitCode:s,isCanceled:i})=>e?`timed out after ${t} milliseconds`:void 0!==n?`failed with ${n}`:void 0!==r?`was killed with ${r} (${o})`:void 0!==s?`failed with exit code ${s}`:"failed")({timedOut:c,timeout:u,errorCode:r&&r.code,signal:o,signalDescription:f,exitCode:s,isCanceled:l}),m=`Command ${h}: ${i}`,_="[object Error]"===Object.prototype.toString.call(r),g=_?`${m}\n${r.message}`:m,E=[g,t,e].filter(Boolean).join("\n");return _?(r.originalMessage=r.message,r.message=E):r=new Error(E),r.shortMessage=g,r.command=i,r.escapedCommand=a,r.exitCode=s,r.signal=o,r.signalDescription=f,r.stdout=e,r.stderr=t,r.cwd=p,void 0!==n&&(r.all=n),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=Boolean(c),r.isCanceled=l,r.killed=d&&!c,r},ve=["stdin","stdout","stderr"],Re=[];Re.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&Re.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&Re.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var we=e=>!!e&&"object"==typeof e&&"function"==typeof e.removeListener&&"function"==typeof e.emit&&"function"==typeof e.reallyExit&&"function"==typeof e.listeners&&"function"==typeof e.kill&&"number"==typeof e.pid&&"function"==typeof e.on,Se=Symbol.for("signal-exit emitter"),Ce=globalThis,Ae=Object.defineProperty.bind(Object),Ue=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Ce[Se])return Ce[Se];Ae(Ce,Se,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){const n=this.listeners[e],r=n.indexOf(t);-1!==r&&(0===r&&1===n.length?n.length=0:n.splice(r,1))}emit(e,t,n){if(this.emitted[e])return!1;this.emitted[e]=!0;let r=!1;for(const o of this.listeners[e])r=!0===o(t,n)||r;return"exit"===e&&(r=this.emit("afterExit",t,n)||r),r}},xe=class{},Le=globalThis.process;we(Le)?new class extends xe{#e="win32"===Le.platform?"SIGINT":"SIGHUP";#t=new Ue;#n;#r;#o;#s={};#i=!1;constructor(e){super(),this.#n=e,this.#s={};for(const t of Re)this.#s[t]=()=>{const n=this.#n.listeners(t);let{count:r}=this.#t;const o=e;if("object"==typeof o.__signal_exit_emitter__&&"number"==typeof o.__signal_exit_emitter__.count&&(r+=o.__signal_exit_emitter__.count),n.length===r){this.unload();const n=this.#t.emit("exit",null,t),r="SIGHUP"===t?this.#e:t;n||e.kill(e.pid,r)}};this.#o=e.reallyExit,this.#r=e.emit}onExit(e,t){if(!we(this.#n))return()=>{};!1===this.#i&&this.load();const n=t?.alwaysLast?"afterExit":"exit";return this.#t.on(n,e),()=>{this.#t.removeListener(n,e),0===this.#t.listeners.exit.length&&0===this.#t.listeners.afterExit.length&&this.unload()}}load(){if(!this.#i){this.#i=!0,this.#t.count+=1;for(const e of Re)try{const t=this.#s[e];t&&this.#n.on(e,t)}catch(e){}this.#n.emit=(e,...t)=>this.#a(e,...t),this.#n.reallyExit=e=>this.#c(e)}}unload(){this.#i&&(this.#i=!1,Re.forEach(e=>{const t=this.#s[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#n.removeListener(e,t)}catch(e){}}),this.#n.emit=this.#r,this.#n.reallyExit=this.#o,this.#t.count-=1)}#c(e){return we(this.#n)?(this.#n.exitCode=e||0,this.#t.emit("exit",this.#n.exitCode,null),this.#o.call(this.#n,this.#n.exitCode)):0}#a(e,...t){const n=this.#r;if("exit"===e&&we(this.#n)){"number"==typeof t[0]&&(this.#n.exitCode=t[0]);const r=n.call(this.#n,e,...t);return this.#t.emit("exit",this.#n.exitCode,null),r}return n.call(this.#n,e,...t)}}(Le):new class extends xe{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,K(re());var Pe=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Pe,e)]);var Oe=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Be=/^[\w.-]+$/,Ne=c.debuglog("execa").enabled,De=(e,t)=>String(e).padStart(t,"0"),je=(e,t,n={})=>{const r=fe.default._parse(e,t,n);return e=r.command,t=r.args,(n={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(n=r.options).cwd||C.default.cwd(),execPath:C.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Ne,...n}).env=(({env:e,extendEnv:t,preferLocal:n,localDir:r,execPath:o})=>{const i=t?{...C.default.env,...e}:e;return n?(({env:e=C.default.env,...t}={})=>{const n=he({env:e={...e}});return t.path=e[n],e[n]=(({cwd:e=C.default.cwd(),path:t=C.default.env[he()],preferLocal:n=!0,execPath:r=C.default.execPath,addExecPath:o=!0}={})=>{const i=e instanceof URL?s.fileURLToPath(e):e,a=w.default.resolve(i),c=[];return n&&((e,t)=>{let n;for(;n!==t;)e.push(w.default.join(t,"node_modules/.bin")),n=t,t=w.default.resolve(t,"..")})(c,a),o&&((e,t,n)=>{const r=t instanceof URL?s.fileURLToPath(t):t;e.push(w.default.resolve(n,r,".."))})(c,r,a),[...c,t].join(w.default.delimiter)})(t),e})({env:i,cwd:r,execPath:o}):i})(n),n.stdio=(e=>{if(!e)return;const{stdio:t}=e;if(void 0===t)return ve.map(t=>e[t]);if((e=>ve.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${ve.map(e=>`\`${e}\``).join(", ")}`);if("string"==typeof t)return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);const n=Math.max(t.length,ve.length);return Array.from({length:n},(e,n)=>t[n])})(n),"win32"===C.default.platform&&"cmd"===w.default.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:n,parsed:r}},ke=(e,n,r)=>"string"==typeof n||t.Buffer.isBuffer(n)?e.stripFinalNewline?function(e){const t="string"==typeof e?"\n":"\n".charCodeAt(),n="string"==typeof e?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===n&&(e=e.slice(0,-1)),e}(n):n:void 0===r?void 0:"";function Me(e,t,n){const r=je(e,t,n),o=((e,t)=>Oe(e,t).join(" "))(e,t),s=((e,t)=>Oe(e,t).map(e=>(e=>"string"!=typeof e||Be.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&C.default.stderr.write(`[${(()=>{const e=new Date;return`${De(e.getHours(),2)}:${De(e.getMinutes(),2)}:${De(e.getSeconds(),2)}.${De(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(s,r.options);const i=(e=>{const t=(({input:e,inputFile:t})=>"string"!=typeof t?e:((e=>{if(void 0!==e)throw new TypeError("The `input` and `inputFile` options cannot be both set.")})(e),a.readFileSync(t)))(e);if(null!==(n=t)&&"object"==typeof n&&"function"==typeof n.pipe)throw new TypeError("The `input` option cannot be a stream in sync mode");var n;return t})(r.options);let c;try{c=S.default.spawnSync(r.file,r.args,{...r.options,input:i})}catch(e){throw Te({error:e,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1})}const l=ke(r.options,c.stdout,c.error),d=ke(r.options,c.stderr,c.error);if(c.error||0!==c.status||null!==c.signal){const e=Te({stdout:l,stderr:d,error:c.error,signal:c.signal,exitCode:c.status,command:o,escapedCommand:s,parsed:r,timedOut:c.error&&"ETIMEDOUT"===c.error.code,isCanceled:!1,killed:null!==c.signal});if(!r.options.reject)return e;throw e}return{command:o,escapedCommand:s,exitCode:0,stdout:l,stderr:d,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}function $e(e){try{return Me("git",["rev-parse","HEAD"],e).stdout}catch{return}}function He(e){try{const t=Me("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=Me("git",["show","-s","--pretty=%d","HEAD"],e).stdout.replace(/^\(|\)$/g,"").split(", ").find(e=>e.startsWith("origin/"));return t?t.match(/^origin\/(?<branch>.+)/)[1]:void 0}return t}catch{return}}var Ge=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,Ke=/^\/(.*)\.git$/;function Fe(e){if(e){if(e.match(Ge))return e.replace(Ge,"$1");try{return new URL(e).pathname.replace(Ke,"$1")}catch{return}}}var ze={detect:({env:e})=>Boolean(e.BUILDKITE),configuration({env:e}){const t="false"===e.BUILDKITE_PULL_REQUEST?void 0:e.BUILDKITE_PULL_REQUEST,n=Boolean(t);return{name:"Buildkite",service:"buildkite",build:e.BUILDKITE_BUILD_NUMBER,buildUrl:e.BUILDKITE_BUILD_URL,commit:e.BUILDKITE_COMMIT,tag:e.BUILDKITE_TAG,branch:n?e.BUILDKITE_PULL_REQUEST_BASE_BRANCH:e.BUILDKITE_BRANCH,slug:Fe(e.BUILDKITE_REPO),pr:t,isPr:n,prBranch:n?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},Ye={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||ie(e.CIRCLE_PULL_REQUEST||e.CI_PULL_REQUEST),n=Boolean(t);return{name:"CircleCI",service:"circleci",build:e.CIRCLE_BUILD_NUM,buildUrl:e.CIRCLE_BUILD_URL,job:`${e.CIRCLE_BUILD_NUM}.${e.CIRCLE_NODE_INDEX}`,commit:e.CIRCLE_SHA1,tag:e.CIRCLE_TAG,branch:n?void 0:e.CIRCLE_BRANCH,pr:t,isPr:n,prBranch:n?e.CIRCLE_BRANCH:void 0,slug:`${e.CIRCLE_PROJECT_USERNAME}/${e.CIRCLE_PROJECT_REPONAME}`}}},We="https://cirrus-ci.com",Ve={detect:({env:e})=>Boolean(e.CIRRUS_CI),configuration({env:e}){const t=e.CIRRUS_PR,n=Boolean(t);return{name:"Cirrus CI",service:"cirrus",commit:e.CIRRUS_CHANGE_IN_REPO,tag:e.CIRRUS_TAG,build:e.CIRRUS_BUILD_ID,buildUrl:`${We}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${We}/task/${e.CIRRUS_TASK_ID}`,branch:n?e.CIRRUS_BASE_BRANCH:e.CIRRUS_BRANCH,pr:t,isPr:n,prBranch:n?e.CIRRUS_BRANCH:void 0,slug:e.CIRRUS_REPO_FULL_NAME,root:e.CIRRUS_WORKING_DIR}}},qe={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:$e({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:He({env:e,cwd:t}),buildUrl:`https://console.aws.amazon.com/codebuild/home?region=${e.AWS_REGION}#/builds/${e.CODEBUILD_BUILD_ID}/view/new`,root:e.PWD})},Je={detect:({env:e})=>Boolean(e.CF_BUILD_ID),configuration({env:e}){const t=e.CF_PULL_REQUEST_NUMBER,n=Boolean(t);return{name:"Codefresh",service:"codefresh",commit:e.CF_REVISION,build:e.CF_BUILD_ID,buildUrl:e.CF_BUILD_URL,branch:n?e.CF_PULL_REQUEST_TARGET:e.CF_BRANCH,pr:t,isPr:n,prBranch:n?e.CF_BRANCH:void 0,slug:`${e.CF_REPO_OWNER}/${e.CF_REPO_NAME}`,root:e.CF_VOLUME_PATH}}},Xe={detect:({env:e})=>Boolean(e.DRONE),configuration({env:e}){const t="pull_request"===e.DRONE_BUILD_EVENT;return{name:"Drone",service:"drone",commit:e.DRONE_COMMIT_SHA,tag:e.DRONE_TAG,build:e.DRONE_BUILD_NUMBER,buildUrl:e.DRONE_BUILD_LINK,branch:t?e.DRONE_TARGET_BRANCH:e.DRONE_BRANCH,job:e.DRONE_JOB_NUMBER,jobUrl:e.DRONE_BUILD_LINK,pr:e.DRONE_PULL_REQUEST,isPr:t,prBranch:t?e.DRONE_SOURCE_BRANCH:void 0,slug:`${e.DRONE_REPO_OWNER}/${e.DRONE_REPO_NAME}`,root:e.DRONE_WORKSPACE}}},Qe=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(a.readFileSync(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?ae(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},Ze={detect:({env:e})=>Boolean(e.GITHUB_ACTIONS),configuration({env:e,cwd:t}){const n="pull_request"===e.GITHUB_EVENT_NAME||"pull_request_target"===e.GITHUB_EVENT_NAME,r=ae("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(a.readFileSync(e.GITHUB_EVENT_PATH,"utf-8")):void 0;return t&&t.pull_request?t.pull_request.number:void 0})(e)}/merge`:e.GITHUB_REF);return{name:"GitHub Actions",service:"github",commit:e.GITHUB_SHA,build:e.GITHUB_RUN_ID,buildUrl:`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`,isPr:n,branch:r,prBranch:n?r:void 0,slug:e.GITHUB_REPOSITORY,root:e.GITHUB_WORKSPACE,...n?Qe({env:e}):void 0}}},et={detect:({env:e})=>Boolean(e.GITLAB_CI),configuration({env:e}){const t=e.CI_MERGE_REQUEST_ID,n=Boolean(t);return{name:"GitLab CI/CD",service:"gitlab",commit:e.CI_COMMIT_SHA,tag:e.CI_COMMIT_TAG,build:e.CI_PIPELINE_ID,buildUrl:`${e.CI_PROJECT_URL}/pipelines/${e.CI_PIPELINE_ID}`,job:e.CI_JOB_ID,jobUrl:`${e.CI_PROJECT_URL}/-/jobs/${e.CI_JOB_ID}`,branch:n?e.CI_MERGE_REQUEST_TARGET_BRANCH_NAME:e.CI_COMMIT_REF_NAME,pr:t,isPr:n,prBranch:e.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME,slug:e.CI_PROJECT_PATH,root:e.CI_PROJECT_DIR}}},tt={detect:({env:e})=>Boolean(e.JENKINS_URL),configuration({env:e,cwd:t}){const n=e.ghprbPullId||e.gitlabMergeRequestId||e.CHANGE_ID,r=Boolean(n),o=e.GIT_LOCAL_BRANCH||e.GIT_BRANCH||e.gitlabBranch||e.BRANCH_NAME;return{name:"Jenkins",service:"jenkins",commit:e.ghprbActualCommit||e.GIT_COMMIT||$e({env:e,cwd:t}),branch:r?e.ghprbTargetBranch||e.gitlabTargetBranch:o,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,root:e.WORKSPACE,pr:n,isPr:r,prBranch:r?e.ghprbSourceBranch||e.gitlabSourceBranch||o:void 0}}},nt={detect:({env:e})=>"true"===e.NETLIFY,configuration({env:e}){const t="true"===e.PULL_REQUEST;return{name:"Netlify",service:"netlify",commit:e.COMMIT_REF,build:e.DEPLOY_ID,buildUrl:`https://app.netlify.com/sites/${e.SITE_NAME}/deploys/${e.DEPLOY_ID}`,branch:t?void 0:e.HEAD,pr:e.REVIEW_ID,isPr:t,prBranch:t?e.HEAD:void 0,slug:e.REPOSITORY_URL.match(/[^/:]+\/[^/]+?$/)[0],root:e.PWD}}},rt={detect:({env:e})=>Boolean(e.DISTELLI_APPNAME),configuration:({env:e})=>({name:"Puppet",service:"puppet",build:e.DISTELLI_BUILDNUM,buildUrl:e.DISTELLI_RELEASE,commit:e.DISTELLI_RELREVISION,branch:e.DISTELLI_RELBRANCH,root:e.DISTELLI_INSTALLHOME})},ot={detect:({env:e})=>Boolean(e.SAILCI),configuration({env:e}){const t=e.SAIL_PULL_REQUEST_NUMBER,n=Boolean(t);return{name:"Sail CI",service:"sail",commit:e.SAIL_COMMIT_SHA,branch:n?void 0:e.SAIL_COMMIT_BRANCH,pr:t,isPr:n,slug:`${e.SAIL_REPO_OWNER}/${e.SAIL_REPO_NAME}`,root:e.SAIL_CLONE_DIR}}},st={detect:({env:e})=>Boolean(e.SCREWDRIVER),configuration({env:e}){const t=e.SD_PULL_REQUEST,n=Boolean(t);return{name:"Screwdriver.cd",service:"screwdriver",branch:n?e.PR_BASE_BRANCH_NAME:e.GIT_BRANCH,prBranch:n?e.PR_BRANCH_NAME:void 0,commit:e.SD_BUILD_SHA,build:e.SD_BUILD_ID,buildUrl:e.SD_UI_BUILD_URL,job:e.SD_JOB_ID,pr:t,isPr:n,slug:e.SD_PIPELINE_NAME,root:e.SD_ROOT_DIR}}},it={detect:({env:e})=>Boolean(e.SCRUTINIZER),configuration({env:e}){const t=e.SCRUTINIZER_PR_NUMBER,n=Boolean(t);return{name:"Scrutinizer",service:"scrutinizer",commit:e.SCRUTINIZER_SHA1,build:e.SCRUTINIZER_INSPECTION_UUID,branch:e.SCRUTINIZER_BRANCH,pr:t,isPr:n,prBranch:e.SCRUTINIZER_PR_SOURCE_BRANCH}}},at={detect:({env:e})=>Boolean(e.SEMAPHORE),configuration({env:e,cwd:t}){const n=e.SEMAPHORE_GIT_PR_NUMBER||e.PULL_REQUEST_NUMBER,r=Boolean(n);return{name:"Semaphore",service:"semaphore",commit:e.SEMAPHORE_GIT_SHA||$e({env:e,cwd:t}),tag:e.SEMAPHORE_GIT_TAG_NAME,build:e.SEMAPHORE_JOB_ID||e.SEMAPHORE_BUILD_NUMBER,branch:e.SEMAPHORE_GIT_BRANCH||(r?void 0:e.BRANCH_NAME),pr:n,isPr:r,prBranch:e.SEMAPHORE_GIT_PR_BRANCH||(r?e.BRANCH_NAME:void 0),slug:e.SEMAPHORE_GIT_REPO_SLUG||e.SEMAPHORE_REPO_SLUG,root:e.SEMAPHORE_GIT_DIR||e.SEMAPHORE_PROJECT_DIR}}},ct={detect:({env:e})=>Boolean(e.SHIPPABLE),configuration({env:e}){const t="true"===e.IS_PULL_REQUEST?e.PULL_REQUEST:void 0,n=Boolean(t);return{name:"Shippable",service:"shippable",commit:e.COMMIT,tag:e.GIT_TAG_NAME,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,branch:n?e.BASE_BRANCH:e.BRANCH,job:e.JOB_NUMBER,pr:t,isPr:n,prBranch:n?e.HEAD_BRANCH:void 0,slug:e.SHIPPABLE_REPO_SLUG,root:e.SHIPPABLE_BUILD_DIR}}},lt=K(oe()),dt={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},ut=e=>{try{return lt.default.of(e)}catch{return}},pt=({env:e,cwd:t})=>{const n=e.TEAMCITY_BUILD_PROPERTIES_FILE?ut(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,r=n?n.get("teamcity.configuration.properties.file"):void 0,o=r?ut(r):r;return Object.fromEntries(Object.keys(dt).map(r=>[r,(n?n.get(dt[r]):void 0)||(o?o.get(dt[r]):void 0)||("branch"===r?He({env:e,cwd:t}):void 0)]))},ft={appveyor:se,azurePipelines:ce,bamboo:le,bitbucket:de,bitrise:ue,buddy:pe,buildkite:ze,circleci:Ye,cirrus:Ve,cloudflarePages:{detect:({env:e})=>"1"===e.CF_PAGES,configuration:({env:e})=>({name:"Cloudflare Pages",service:"cloudflarePages",commit:e.CF_PAGES_COMMIT_SHA,branch:e.CF_PAGES_BRANCH,root:e.PWD})},codebuild:qe,codefresh:Je,codeship:{detect:({env:e})=>e.CI_NAME&&"codeship"===e.CI_NAME,configuration:({env:e})=>({name:"Codeship",service:"codeship",build:e.CI_BUILD_NUMBER,buildUrl:e.CI_BUILD_URL,commit:e.CI_COMMIT_ID,branch:e.CI_BRANCH,slug:e.CI_REPO_NAME})},drone:Xe,github:Ze,gitlab:et,jenkins:tt,netlify:nt,puppet:rt,sail:ot,screwdriver:st,scrutinizer:it,semaphore:at,shippable:ct,teamcity:{detect:({env:e})=>Boolean(e.TEAMCITY_VERSION),configuration:({env:e,cwd:t})=>({name:"TeamCity",service:"teamcity",commit:e.BUILD_VCS_NUMBER,build:e.BUILD_NUMBER,slug:e.TEAMCITY_BUILDCONF_NAME,...pt({env:e,cwd:t})})},travis:{detect:({env:e})=>Boolean(e.TRAVIS),configuration({env:e}){const t="false"===e.TRAVIS_PULL_REQUEST?void 0:e.TRAVIS_PULL_REQUEST,n=Boolean(t);return{name:"Travis CI",service:"travis",commit:e.TRAVIS_COMMIT,tag:e.TRAVIS_TAG,build:e.TRAVIS_BUILD_NUMBER,buildUrl:e.TRAVIS_BUILD_WEB_URL,branch:e.TRAVIS_BRANCH,job:e.TRAVIS_JOB_NUMBER,jobUrl:e.TRAVIS_JOB_WEB_URL,pr:t,isPr:n,prBranch:e.TRAVIS_PULL_REQUEST_BRANCH,slug:e.TRAVIS_REPO_SLUG,root:e.TRAVIS_BUILD_DIR}}},vela:{detect:({env:e})=>Boolean(e.VELA),configuration({env:e}){const t="pull_request"===e.VELA_BUILD_EVENT;return{name:"Vela",service:"vela",branch:t?e.VELA_PULL_REQUEST_TARGET:e.VELA_BUILD_BRANCH,commit:e.VELA_BUILD_COMMIT,tag:e.VELA_BUILD_TAG,build:e.VELA_BUILD_NUMBER,buildUrl:e.VELA_BUILD_LINK,job:void 0,jobUrl:void 0,isPr:t,pr:e.VELA_BUILD_PULL_REQUEST,prBranch:e.VELA_PULL_REQUEST_SOURCE,slug:e.VELA_REPO_FULL_NAME,root:e.VELA_BUILD_WORKSPACE}}},vercel:{detect:({env:e})=>Boolean(e.VERCEL)||Boolean(e.NOW_GITHUB_DEPLOYMENT),configuration({env:e}){const t="Vercel",n="vercel";return e.VERCEL?{name:t,service:n,commit:e.VERCEL_GIT_COMMIT_SHA,branch:e.VERCEL_GIT_COMMIT_REF,slug:`${e.VERCEL_GIT_REPO_OWNER}/${e.VERCEL_GIT_REPO_SLUG}`}:{name:t,service:n,commit:e.NOW_GITHUB_COMMIT_SHA,branch:e.NOW_GITHUB_COMMIT_REF,slug:`${e.NOW_GITHUB_ORG}/${e.NOW_GITHUB_REPO}`}}},wercker:{detect:({env:e})=>Boolean(e.WERCKER_MAIN_PIPELINE_STARTED),configuration:({env:e})=>({name:"Wercker",service:"wercker",commit:e.WERCKER_GIT_COMMIT,build:e.WERCKER_MAIN_PIPELINE_STARTED,buildUrl:e.WERCKER_RUN_URL,branch:e.WERCKER_GIT_BRANCH,slug:`${e.WERCKER_GIT_OWNER}/${e.WERCKER_GIT_REPOSITORY}`,root:e.WERCKER_ROOT})},woodpecker:{detect:({env:e})=>e.CI&&"woodpecker"===e.CI,configuration({env:e}){const t="pull_request"===e.CI_PIPELINE_EVENT;return{name:"Woodpecker CI",service:"woodpecker",commit:e.CI_COMMIT_SHA,tag:e.CI_COMMIT_TAG,build:e.CI_PIPELINE_NUMBER,buildUrl:e.CI_PIPELINE_URL,branch:t?e.CI_COMMIT_TARGET_BRANCH:e.CI_COMMIT_BRANCH,job:e.CI_STEP_NUMBER,jobUrl:e.CI_STEP_URL,pr:e.CI_COMMIT_PULL_REQUEST,isPr:t,prBranch:t?e.CI_COMMIT_SOURCE_BRANCH:void 0,slug:`${e.CI_REPO_OWNER}/${e.CI_REPO_NAME}`,root:e.CI_WORKSPACE}}},jetbrainsSpace:{detect:({env:e})=>Boolean(e.JB_SPACE_EXECUTION_NUMBER),configuration({env:e}){const t=e.JB_SPACE_PROJECT_KEY,n=e.JB_SPACE_GIT_REPOSITORY_NAME;return{name:"JetBrains Space",service:"jetbrainsSpace",commit:e.JB_SPACE_GIT_REVISION,build:e.JB_SPACE_EXECUTION_NUMBER,branch:ae(e.JB_SPACE_GIT_BRANCH),slug:t&&n?`${t.toLowerCase()}/${n}`:void 0}}}},ht={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},mt=({allowReserved:e,explode:t,name:n,style:r,value:o})=>{if(!t){const t=(e?o:o.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(r));switch(r){case"label":return`.${t}`;case"matrix":return`;${n}=${t}`;case"simple":return t;default:return`${n}=${t}`}}const s=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),i=o.map(t=>"label"===r||"simple"===r?e?t:encodeURIComponent(t):_t({allowReserved:e,name:n,value:t})).join(s);return"label"===r||"matrix"===r?s+i:i},_t=({allowReserved:e,name:t,value:n})=>{if(null==n)return"";if("object"==typeof n)throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?n:encodeURIComponent(n)}`},gt=({allowReserved:e,explode:t,name:n,style:r,value:o,valueOnly:s})=>{if(o instanceof Date)return s?o.toISOString():`${n}=${o.toISOString()}`;if("deepObject"!==r&&!t){let t=[];Object.entries(o).forEach(([n,r])=>{t=[...t,n,e?r:encodeURIComponent(r)]});const s=t.join(",");switch(r){case"form":return`${n}=${s}`;case"label":return`.${s}`;case"matrix":return`;${n}=${s}`;default:return s}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),a=Object.entries(o).map(([t,o])=>_t({allowReserved:e,name:"deepObject"===r?`${n}[${t}]`:t,value:o})).join(i);return"label"===r||"matrix"===r?i+a:a},Et=/\{[^{}]+\}/g;function yt(e){const t=void 0!==e.body;return t&&e.bodySerializer?"serializedBody"in e?void 0!==e.serializedBody&&""!==e.serializedBody?e.serializedBody:null:""!==e.body?e.body:null:t?e.body:void 0}var bt,It=async(e,t)=>{const n="function"==typeof t?await t(e):t;if(n)return"bearer"===e.scheme?`Bearer ${n}`:"basic"===e.scheme?`Basic ${btoa(n)}`:n},Tt=({parameters:e={},...t}={})=>n=>{const r=[];if(n&&"object"==typeof n)for(const o in n){const s=n[o];if(null==s)continue;const i=e[o]||t;if(Array.isArray(s)){const e=mt({allowReserved:i.allowReserved,explode:!0,name:o,style:"form",value:s,...i.array});e&&r.push(e)}else if("object"==typeof s){const e=gt({allowReserved:i.allowReserved,explode:!0,name:o,style:"deepObject",value:s,...i.object});e&&r.push(e)}else{const e=_t({allowReserved:i.allowReserved,name:o,value:s});e&&r.push(e)}}return r.join("&")},vt=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),Rt=e=>(({baseUrl:e,path:t,query:n,querySerializer:r,url:o})=>{let s=(e??"")+(o.startsWith("/")?o:`/${o}`);t&&(s=(({path:e,url:t})=>{let n=t;const r=t.match(Et);if(r)for(const t of r){let r=!1,o=t.substring(1,t.length-1),s="simple";o.endsWith("*")&&(r=!0,o=o.substring(0,o.length-1)),o.startsWith(".")?(o=o.substring(1),s="label"):o.startsWith(";")&&(o=o.substring(1),s="matrix");const i=e[o];if(null==i)continue;if(Array.isArray(i)){n=n.replace(t,mt({explode:r,name:o,style:s,value:i}));continue}if("object"==typeof i){n=n.replace(t,gt({explode:r,name:o,style:s,value:i,valueOnly:!0}));continue}if("matrix"===s){n=n.replace(t,`;${_t({name:o,value:i})}`);continue}const a=encodeURIComponent("label"===s?`.${i}`:i);n=n.replace(t,a)}return n})({path:t,url:s}));let i=n?r(n):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(s+=`?${i}`),s})({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:Tt(e.querySerializer),url:e.url}),wt=(e,t)=>{const n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=Ct(e.headers,t.headers),n},St=e=>{const t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},Ct=(...e)=>{const t=new Headers;for(const n of e){if(!n)continue;const e=n instanceof Headers?St(n):Object.entries(n);for(const[n,r]of e)if(null===r)t.delete(n);else if(Array.isArray(r))for(const e of r)t.append(n,e);else void 0!==r&&t.set(n,"object"==typeof r?JSON.stringify(r):r)}return t},At=class{fns=[];clear(){this.fns=[]}eject(e){const t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){const t=this.getInterceptorIndex(e);return Boolean(this.fns[t])}getInterceptorIndex(e){return"number"==typeof e?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){const n=this.getInterceptorIndex(e);return!!this.fns[n]&&(this.fns[n]=t,e)}use(e){return this.fns.push(e),this.fns.length-1}},Ut=Tt({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),xt={"Content-Type":"application/json"},Lt=(e={})=>({...ht,headers:xt,parseAs:"auto",querySerializer:Ut,...e}),Pt=(e={})=>{let t=wt(Lt(),e);const n=()=>({...t}),r={error:new At,request:new At,response:new At},o=async e=>{const n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:Ct(t.headers,e.headers),serializedBody:void 0};return n.security&&await(async({security:e,...t})=>{for(const n of e){if(vt(t,n.name))continue;const e=await It(n,t.auth);if(!e)continue;const r=n.name??"Authorization";switch(n.in){case"query":t.query||(t.query={}),t.query[r]=e;break;case"cookie":t.headers.append("Cookie",`${r}=${e}`);break;default:t.headers.set(r,e)}}})({...n,security:n.security}),n.requestValidator&&await n.requestValidator(n),void 0!==n.body&&n.bodySerializer&&(n.serializedBody=n.bodySerializer(n.body)),void 0!==n.body&&""!==n.serializedBody||n.headers.delete("Content-Type"),{opts:n,url:Rt(n)}},s=async e=>{const{opts:t,url:n}=await o(e),s={redirect:"follow",...t,body:yt(t)};let i=new Request(n,s);for(const e of r.request.fns)e&&(i=await e(i,t));const a=t.fetch;let c;try{c=await a(i)}catch(e){let n=e;for(const o of r.error.fns)o&&(n=await o(e,void 0,i,t));if(n=n||{},t.throwOnError)throw n;return"data"===t.responseStyle?void 0:{error:n,request:i,response:void 0}}for(const e of r.response.fns)e&&(c=await e(c,i,t));const l={request:i,response:c};if(c.ok){const e=("auto"===t.parseAs?(e=>{if(!e)return"stream";const t=e.split(";")[0]?.trim();return t?t.startsWith("application/json")||t.endsWith("+json")?"json":"multipart/form-data"===t?"formData":["application/","audio/","image/","video/"].some(e=>t.startsWith(e))?"blob":t.startsWith("text/")?"text":void 0:void 0})(c.headers.get("Content-Type")):t.parseAs)??"json";if(204===c.status||"0"===c.headers.get("Content-Length")){let n;switch(e){case"arrayBuffer":case"blob":case"text":n=await c[e]();break;case"formData":n=new FormData;break;case"stream":n=c.body;break;default:n={}}return"data"===t.responseStyle?n:{data:n,...l}}let n;switch(e){case"arrayBuffer":case"blob":case"formData":case"json":case"text":n=await c[e]();break;case"stream":return"data"===t.responseStyle?c.body:{data:c.body,...l}}return"json"===e&&(t.responseValidator&&await t.responseValidator(n),t.responseTransformer&&(n=await t.responseTransformer(n))),"data"===t.responseStyle?n:{data:n,...l}}const d=await c.text();let u;try{u=JSON.parse(d)}catch{}const p=u??d;let f=p;for(const e of r.error.fns)e&&(f=await e(p,c,i,t));if(f=f||{},t.throwOnError)throw f;return"data"===t.responseStyle?void 0:{error:f,...l}},i=e=>t=>s({...t,method:e}),a=e=>async t=>{const{opts:n,url:s}=await o(t);return(({onRequest:e,onSseError:t,onSseEvent:n,responseTransformer:r,responseValidator:o,sseDefaultRetryDelay:s,sseMaxRetryAttempts:i,sseMaxRetryDelay:a,sseSleepFn:c,url:l,...d})=>{let u;const p=c??(e=>new Promise(t=>setTimeout(t,e))),f=async function*(){let c=s??3e3,f=0;const h=d.signal??(new AbortController).signal;for(;!h.aborted;){f++;const s=d.headers instanceof Headers?d.headers:new Headers(d.headers);void 0!==u&&s.set("Last-Event-ID",u);try{const t={redirect:"follow",...d,body:d.serializedBody,headers:s,signal:h};let i=new Request(l,t);e&&(i=await e(l,t));const a=d.fetch??globalThis.fetch,p=await a(i);if(!p.ok)throw new Error(`SSE failed: ${p.status} ${p.statusText}`);if(!p.body)throw new Error("No body in SSE response");const f=p.body.pipeThrough(new TextDecoderStream).getReader();let m="";const _=()=>{try{f.cancel()}catch{}};h.addEventListener("abort",_);try{for(;;){const{done:e,value:t}=await f.read();if(e)break;m+=t;const s=m.split("\n\n");m=s.pop()??"";for(const e of s){const t=e.split("\n"),s=[];let i,a;for(const e of t)if(e.startsWith("data:"))s.push(e.replace(/^data:\s*/,""));else if(e.startsWith("event:"))i=e.replace(/^event:\s*/,"");else if(e.startsWith("id:"))u=e.replace(/^id:\s*/,"");else if(e.startsWith("retry:")){const t=Number.parseInt(e.replace(/^retry:\s*/,""),10);Number.isNaN(t)||(c=t)}let l=!1;if(s.length){const e=s.join("\n");try{a=JSON.parse(e),l=!0}catch{a=e}}l&&(o&&await o(a),r&&(a=await r(a))),n?.({data:a,event:i,id:u,retry:c}),s.length&&(yield a)}}}finally{h.removeEventListener("abort",_),f.releaseLock()}break}catch(e){if(t?.(e),void 0!==i&&f>=i)break;const n=Math.min(c*2**(f-1),a??3e4);await p(n)}}}();return{stream:f}})({...n,body:n.body,headers:n.headers,method:e,onRequest:async(e,t)=>{let o=new Request(e,t);for(const e of r.request.fns)e&&(o=await e(o,n));return o},url:s})};return{buildUrl:Rt,connect:i("CONNECT"),delete:i("DELETE"),get:i("GET"),getConfig:n,head:i("HEAD"),interceptors:r,options:i("OPTIONS"),patch:i("PATCH"),post:i("POST"),put:i("PUT"),request:s,setConfig:e=>(t=wt(t,e),n()),sse:{connect:a("CONNECT"),delete:a("DELETE"),get:a("GET"),head:a("HEAD"),options:a("OPTIONS"),patch:a("PATCH"),post:a("POST"),put:a("PUT"),trace:a("TRACE")},trace:i("TRACE")}},Ot=Pt(Lt({baseUrl:"https://api.stably.ai"})),Bt="x-stably-org-id",Nt="4.1.3",Dt=process.env.STABLY_API_URL||"https://api.stably.ai",jt=process.env.AUTH_URL||"https://auth.stably.ai",kt=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",Mt=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",$t="http://localhost:9876/auth/callback",Ht=()=>bt||(bt=Pt(Lt({baseUrl:Dt,headers:{"X-STABLY-CLI-VERSION":Nt,"X-STABLY-SOURCE":"cli"}}))),Gt=async(e,t)=>{const n=await(r={body:{accessToken:e,orgId:t},client:Ht()},(r.client??Ot).post({url:"/internal/v1/cli/exchange-token",...r,headers:{"Content-Type":"application/json",...r.headers}}));var r;if(401===n.response.status)throw new Error("Invalid or expired access token");if(403===n.response.status)throw new Error("You do not have access to this organization");if(n.error)throw new Error(`Failed to exchange token: ${n.response.status}`);return n.data},Kt=h.z.object({org_id:h.z.string(),org_name:h.z.string()}),Ft=h.z.object({email:h.z.string(),org_id_to_org_member_info:h.z.record(h.z.string(),Kt).optional(),org_member_info:Kt.optional(),user_id:h.z.string()});h.z.object({email:h.z.string(),firstName:h.z.string().optional(),lastName:h.z.string().optional(),organizations:h.z.array(h.z.object({id:h.z.string(),name:h.z.string()})),userId:h.z.string()});var zt=e=>{const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const n=t[1].replace(/-/g,"+").replace(/_/g,"/"),r=Buffer.from(n,"base64").toString("utf-8");return JSON.parse(r)},Yt=e=>{try{const t=Ft.parse(zt(e)),n=t.org_id_to_org_member_info?Object.entries(t.org_id_to_org_member_info).map(([e,t])=>({id:e,name:t.org_name})):t.org_member_info?[{id:t.org_member_info.org_id,name:t.org_member_info.org_name}]:[];return{email:t.email,organizations:n,userId:t.user_id}}catch(e){throw new Error(`Failed to decode token: ${e instanceof Error?e.message:"Unknown error"}`)}},Wt=w.default.join(A.default.homedir(),".stably"),Vt=w.default.join(Wt,"auth.json"),qt=".stably",Jt="project.json",Xt=L.default.object({accessToken:L.default.string(),expiresAt:L.default.number(),idToken:L.default.string().optional(),refreshToken:L.default.string()}),Qt=L.default.object({orgId:L.default.string(),orgName:L.default.string(),projectId:L.default.string(),projectName:L.default.string()}),Zt=async()=>{try{const e=await m.readFile(Vt,"utf-8");return Xt.parse(JSON.parse(e))}catch{return}},en=async e=>{await m.mkdir(Wt,{recursive:!0}),await m.writeFile(Vt,JSON.stringify(e,null,2),{mode:384})},tn=async()=>{try{await m.unlink(Vt)}catch{}},nn=async e=>{let t=e;const{root:n}=w.default.parse(t);for(;t!==n;){const e=w.default.join(t,qt);try{return await m.access(e),e}catch{t=w.default.dirname(t)}}},rn=async()=>{try{const e=await nn(process.cwd());if(!e)return;const t=w.default.join(e,Jt),n=await m.readFile(t,"utf-8");return Qt.parse(JSON.parse(n))}catch{return}},on=async()=>{try{const e=await nn(process.cwd());e&&await m.unlink(w.default.join(e,Jt))}catch{}},sn=e=>Date.now()>=e.expiresAt-3e5,an=async e=>{const t=new URLSearchParams({client_id:kt,grant_type:"refresh_token",refresh_token:e}),n=await fetch(`${jt}/propelauth/oauth/token`,{body:t.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!n.ok)throw new Error(`Token refresh failed: ${n.status}`);const r=await n.json();return{accessToken:r.access_token,expiresAt:Date.now()+1e3*r.expires_in,refreshToken:r.refresh_token}},cn=e=>`\n<!DOCTYPE html>\n<html>\n<head>\n <title>Authentication Failed Stably CLI</title>\n <style>\n * { box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: #000;\n color: #fafafa;\n }\n .container {\n text-align: center;\n padding: 48px;\n max-width: 400px;\n }\n .icon {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: #ef4444;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 24px; height: 24px; }\n .title {\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 8px;\n letter-spacing: -0.5px;\n }\n .subtitle {\n color: #888;\n font-size: 14px;\n margin: 0 0 32px;\n line-height: 1.5;\n }\n .error-box {\n background: rgba(239, 68, 68, 0.1);\n border: 1px solid rgba(239, 68, 68, 0.3);\n border-radius: 8px;\n padding: 16px;\n margin-bottom: 24px;\n }\n .error-label {\n font-size: 11px;\n font-weight: 600;\n color: #ef4444;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 8px;\n }\n .error-message {\n font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;\n font-size: 13px;\n color: #fafafa;\n word-break: break-word;\n }\n .hint {\n color: #666;\n font-size: 13px;\n }\n .hint code {\n background: #111;\n border: 1px solid #333;\n border-radius: 4px;\n padding: 2px 6px;\n font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;\n font-size: 12px;\n color: #888;\n }\n .brand {\n margin-top: 32px;\n font-size: 12px;\n color: #444;\n letter-spacing: 0.5px;\n }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="icon">\n <svg fill="none" stroke="#000" stroke-width="3" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>\n </svg>\n </div>\n <h1 class="title">Authentication Failed</h1>\n <p class="subtitle">Something went wrong during login.</p>\n <div class="error-box">\n <div class="error-label">Error</div>\n <div class="error-message">${e}</div>\n </div>\n <p class="hint">Run <code>stably login</code> to try again.</p>\n <div class="brand">STABLY</div>\n </div>\n</body>\n</html>\n`,ln=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(n)},dn=(e,t)=>{const n=new URLSearchParams({client_id:kt,code_challenge:e,code_challenge_method:"S256",redirect_uri:$t,response_type:"code",state:t});return`${jt}/propelauth/oauth/authorize?${n.toString()}`},un=async e=>{const t=u.spinner();let n;t.start("Loading user info...");try{n=Yt(e.accessToken),t.stop(x.default.green(`✓ Logged in as ${x.default.cyan(n.email)}`))}catch(e){t.stop(x.default.red("✗ Failed to load user info"));const n=e instanceof Error?e.message:"Unknown error";return u.log.error(n),{success:!1}}const r=await(async e=>{if(0===e.length)return void u.log.error("You don't belong to any organizations.");if(1===e.length)return u.log.info(`Using organization: ${x.default.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return u.log.info(`Auto-selecting organization: ${x.default.cyan(e[0].name)}`),e[0];const t=await u.select({message:"Select an organization",options:e.map(e=>({label:e.name,value:e.id}))});return u.isCancel(t)?void 0:e.find(e=>e.id===t)})(n.organizations);if(!r)return u.log.warn("Organization selection cancelled."),{success:!1};let o;t.start("Getting org credentials...");try{const n=await Gt(e.accessToken,r.id);o={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(x.default.green("✓ Credentials obtained"))}catch(e){t.stop(x.default.red("✗ Failed to get org credentials"));const n=e instanceof Error?e.message:"Unknown error";return u.log.error(n),{success:!1}}const s=await(async(e,t)=>{const n=u.spinner();let r;n.start("Loading projects...");try{r=await(async({accessToken:e,orgId:t})=>{const n=await(r={auth:`Bearer ${e}`,client:Ht(),path:{orgId:t}},(r.client??Ot).get({security:[{name:"authorization",type:"apiKey"}],url:"/internal/v1/cli/orgs/{orgId}/projects",...r}));var r;if(401===n.response.status)throw new Error("Invalid or expired access token");if(403===n.response.status)throw new Error("You do not have access to this organization");if(n.error)throw new Error(`Failed to list projects: ${n.response.status}`);return n.data.projects})({accessToken:e,orgId:t}),n.stop(x.default.green("✓ Projects loaded"))}catch(e){n.stop(x.default.red("✗ Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void u.log.error(t)}if(0===r.length)return u.log.error("No projects found in this organization."),void u.log.info(`Create a project at ${x.default.underline(x.default.cyan("https://app.stably.ai"))}`);if(1===r.length)return u.log.info(`Using project: ${x.default.cyan(r[0].name)}`),r[0];if(!process.stdin.isTTY)return u.log.info(`Auto-selecting project: ${x.default.cyan(r[0].name)}`),r[0];const o=await u.select({message:"Select a project",options:r.map(e=>({label:e.name,value:e.id}))});return u.isCancel(o)?void 0:r.find(e=>e.id===o)})(o.accessToken,r.id);return s?(await(async e=>{const t=w.default.join(process.cwd(),qt),n=w.default.join(t,Jt);await m.mkdir(t,{recursive:!0}),await m.writeFile(n,JSON.stringify(e,null,2)),await(async e=>{const t=w.default.join(e,".gitignore");try{if((await m.readFile(t,"utf-8")).split("\n").some(e=>".stably"===e.trim()))return;await m.appendFile(t,"\n# Stably CLI\n.stably\n")}catch{await m.writeFile(t,"# Stably CLI\n.stably\n")}})(process.cwd())})({orgId:r.id,orgName:r.name,projectId:s.id,projectName:s.name}),u.log.info(x.default.dim("Linked this directory to your Stably project.")),{scopedTokens:o,success:!0}):(u.log.warn("Project selection cancelled."),{success:!1})},pn=async()=>{const e=await Zt();if(e){if(!sn(e)){if(await rn())return void u.outro(x.default.yellow("You are already logged in. Run `stably logout` first to log out."));u.log.info("You are logged in but haven't selected a project yet.");const t=await un(e);return void(t.success?(await en(t.scopedTokens),u.outro(x.default.green("Setup complete! You can now use Stably CLI."))):u.outro(x.default.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=u.spinner();t.start("Refreshing session...");try{const n=await an(e.refreshToken);t.stop(x.default.green("✓ Session refreshed"));const r=await rn();if(r){t.start("Getting org credentials...");try{const e=await Gt(n.accessToken,r.orgId),o={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:n.idToken,refreshToken:n.refreshToken};await en(o),t.stop(x.default.green("✓ Credentials obtained")),u.outro(x.default.green("Login successful"))}catch{await en(n),t.stop(x.default.yellow("Using full credentials")),u.outro(x.default.green("Login successful"))}}else{const e=await un(n);e.success?(await en(e.scopedTokens),u.outro(x.default.green("Setup complete! You can now use Stably CLI."))):u.outro(x.default.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(x.default.yellow("Session expired, proceeding with fresh login...")),await tn(),await on()}}const{authorizeUrl:t,waitForCallback:n}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:n}=(()=>{const e=B.default.randomBytes(32).toString("base64url"),t=(n=e,B.default.createHash("sha256").update(n).digest("base64url"));var n;const r=B.default.randomBytes(16).toString("base64url");return{authorizeUrl:dn(t,r),codeVerifier:e,state:r}})();return{authorizeUrl:e,waitForCallback:async()=>(async(e,t)=>{const n=await(r=e,new Promise((e,t)=>{const n=setTimeout(()=>{i.close(),e({error:"Login timed out",success:!1})},3e5),o=()=>{clearTimeout(n)},i=O.default.createServer((t,n)=>{const a=new s.URL(t.url||"","http://localhost:9876");if("/auth/callback"!==a.pathname)return n.writeHead(404),void n.end("Not found");const c=a.searchParams.get("code"),l=a.searchParams.get("state"),d=a.searchParams.get("error");return d?(ln(n,400,cn(d)),o(),i.close(),void e({error:d,success:!1})):c&&l?l!==r?(ln(n,400,cn("Invalid state parameter (possible CSRF attack)")),o(),i.close(),void e({error:"State mismatch",success:!1})):(ln(n,200,'\n<!DOCTYPE html>\n<html>\n<head>\n <title>Authenticated Stably CLI</title>\n <style>\n * { box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: #000;\n color: #fafafa;\n }\n .container {\n text-align: center;\n padding: 48px;\n max-width: 400px;\n }\n .icon {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: #22c55e;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 24px; height: 24px; }\n .title {\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 8px;\n letter-spacing: -0.5px;\n }\n .subtitle {\n color: #888;\n font-size: 14px;\n margin: 0 0 32px;\n line-height: 1.5;\n }\n .terminal {\n background: #111;\n border: 1px solid #333;\n border-radius: 8px;\n padding: 16px;\n text-align: left;\n font-family: \'SF Mono\', \'Fira Code\', \'Consolas\', monospace;\n font-size: 13px;\n }\n .terminal-header {\n display: flex;\n gap: 6px;\n margin-bottom: 12px;\n }\n .terminal-dot {\n width: 10px;\n height: 10px;\n border-radius: 50%;\n background: #333;\n }\n .terminal-line {\n color: #888;\n }\n .terminal-line .prompt { color: #888; }\n .terminal-line .cmd { color: #fafafa; }\n .terminal-line.success { color: #22c55e; }\n .brand {\n margin-top: 32px;\n font-size: 12px;\n color: #444;\n letter-spacing: 0.5px;\n }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="icon">\n <svg fill="none" stroke="#000" stroke-width="3" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>\n </svg>\n </div>\n <h1 class="title">Authenticated</h1>\n <p class="subtitle">You can close this tab and return to your terminal.</p>\n <div class="terminal">\n <div class="terminal-header">\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n </div>\n <div class="terminal-line"><span class="prompt">$</span> <span class="cmd">stably login</span></div>\n <div class="terminal-line success">Logged in successfully</div>\n </div>\n <div class="brand">STABLY</div>\n </div>\n</body>\n</html>\n'),o(),i.close(),void e({code:c,state:l,success:!0})):(ln(n,400,cn("Missing code or state parameter")),o(),i.close(),void e({error:"Missing code or state parameter",success:!1}))});i.on("error",e=>{o(),"EADDRINUSE"!==e.code?t(new Error(`Failed to start callback server: ${e.message}`)):t(new Error("Port 9876 is already in use. Please close the application using it and try again."))}),i.listen(9876)}));var r;if(!n.success)throw new Error(n.error);return(async(e,t)=>{const n=new URLSearchParams({client_id:kt,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:$t}),r=await fetch(`${jt}/propelauth/oauth/token`,{body:n.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!r.ok){const e=await r.text();throw new Error(`Token exchange failed: ${r.status} ${e}`)}const o=await r.json();return{accessToken:o.access_token,expiresAt:Date.now()+1e3*o.expires_in,idToken:o.id_token,refreshToken:o.refresh_token}})(n.code,t)})(n,t)}})();u.log.info("Opening browser for authentication..."),u.log.info(x.default.dim("If browser doesn't open, visit:")),u.log.info(x.default.underline(x.default.cyan(t)));try{await P.default(t)}catch{u.log.warn("Could not open browser automatically. Please open the URL above manually.")}const r=u.spinner();let o;r.start("Waiting for authentication...");try{o=await n(),r.stop(x.default.green("✓ Authentication successful"))}catch(e){r.stop(x.default.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";u.outro(x.default.red(`Login failed: ${t}`)),process.exit(1)}const i=await un(o);i.success?(await en(i.scopedTokens),u.outro(x.default.green("Setup complete! You can now use Stably CLI."))):(u.outro(x.default.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},fn=()=>{const e=process.env.STABLY_API_KEY,t=process.env.STABLY_PROJECT_ID;if(e&&t)return{apiKey:e,projectId:t}},hn=async()=>{const e=await Zt();if(e){if(!sn(e)){const t=await rn();if(t&&"full"===(e=>{try{const t=Ft.parse(zt(e));if(t.org_id_to_org_member_info)return"full";if(t.org_member_info)return"org"}catch{return"unknown"}return"unknown"})(e.accessToken))try{const n=await Gt(e.accessToken,t.orgId),r={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await en(r),r}catch{return e}return e}try{const t=await an(e.refreshToken),n=await rn();if(n)try{const e=await Gt(t.accessToken,n.orgId),r={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await en(r),r}catch{return await en(t),t}return await en(t),t}catch{return}}},mn=async(e={})=>{const t=fn();if(t)return{auth:t,type:"env"};let n=await hn(),r=n?await rn():void 0;const o=process.stdin.isTTY&&process.stdout.isTTY;if((!n||!r)&&e.autoLogin&&o){n?u.log.info("You are logged in but need to select an organization and project."):u.log.info("You are not logged in."),u.log.info("Press Enter to log in."),process.stdout.write(`${x.default.dim("Alternatively, set environment variables for an org API key:")}\n${x.default.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=f.createInterface({input:process.stdin,output:process.stdout});try{await e.question(x.default.dim("Press Enter to continue... "))}finally{e.close()}await pn(),n=await hn(),r=n?await rn():void 0}return n||(u.outro(x.default.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),r||(u.outro(x.default.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),{auth:{accessToken:n.accessToken,context:r},type:"oauth"}},_n=e=>e?{[Bt]:e}:void 0,gn=h.z.object({context:h.z.string().min(1)});function En(e){return/^\.env(\..*)?$/.test(e)}function yn(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}function bn({input:e,pathKey:t}){if(!yn(e))return{decision:"block",reason:`Invalid tool call format: Expected an object with 'tool_input' property. Please ensure the tool call follows the correct structure: { tool_input: { ${t}: "path/to/file" } }`,success:!1,systemMessage:"Tool call blocked due to invalid input format"};const n=e.tool_input;return t in n?"string"==typeof n[t]?{path:n[t],success:!0}:{decision:"block",reason:`Invalid tool call format: The '${t}' parameter must be a string containing the file path, but received ${typeof n[t]}. Please provide a valid file path as a string. Example: { tool_input: { ${t}: "src/example.ts" } }`,success:!1,systemMessage:"Tool call blocked due to invalid parameter type"}:{decision:"block",reason:`Invalid tool call format: Missing required parameter '${t}'. Please provide the file path using the '${t}' parameter. Example: { tool_input: { ${t}: "path/to/file" } }`,success:!1,systemMessage:"Tool call blocked due to missing required parameters"}}function In({action:e,fileCheck:t,getBlockMessage:n,pathKey:r}){return async o=>{const s=bn({input:o,pathKey:r});if(!s.success)return s;const i=s.path.replace(/\\/g,"/"),a=i.split("/").pop()||i;return t(a)?{decision:"block",reason:n("reading"===e?"Access to":"writing"===e?"Writing to":"editing"===e?"Editing":"Searching in"),systemMessage:"AI blocked due to accessing sensitive content"}:{decision:"approve"}}}function Tn({action:e,pathKey:t}){return In({action:e,fileCheck:En,getBlockMessage:e=>`${e} .env files is not allowed. Environment variables and secrets should be managed in Stably's Test Data section instead. You can access these values using process.env in your test code.`,pathKey:t})}function vn({action:e,pathKey:t}){return In({action:e,fileCheck:e=>".gitignore"===e,getBlockMessage:()=>"Modifying .gitignore is not allowed. The .gitignore file is managed by the system and cannot be changed.",pathKey:t})}function Rn({action:e,pathKey:t}){return In({action:e,fileCheck:e=>".gitattributes"===e,getBlockMessage:()=>"Modifying .gitattributes is not allowed. The .gitattributes file is managed by the system and cannot be changed.",pathKey:t})}function wn({action:e,pathKey:t}){return In({action:e,fileCheck:e=>".lfsconfig"===e,getBlockMessage:()=>"Modifying .lfsconfig is not allowed. The .lfsconfig file is managed by the system and cannot be changed.",pathKey:t})}var Sn=/\.(spec|test)\.(c|m)?(ts|tsx|js|jsx)$/;function Cn({pathKey:e}){return async t=>{const n=bn({input:t,pathKey:e});if(!n.success)return n;const r=n.path.replace(/\\/g,"/").split("/").pop()||n.path;return Sn.test(r)?r.endsWith(".spec.ts")?{decision:"approve"}:{decision:"block",reason:`Test files must use the .spec.ts extension. The file "${r}" is not supported by Stably. Please use ".spec.ts" as the extension instead.`,systemMessage:"Tool call blocked due to unsupported test file extension"}:{decision:"approve"}}}function An({action:e,pathKey:t,workDir:r}){return async o=>{const s=bn({input:o,pathKey:t});if(!s.success)return s;const i=s.path;try{return function({targetPath:e,workDir:t}){const r=function(e){if(a.existsSync(e))return a.realpathSync.native(e);let t=e;const r=[];for(;!a.existsSync(t);){const o=n.dirname(t);if(o===t)return n.resolve(e);r.unshift(t.slice(o.length+1)),t=o}const o=a.realpathSync.native(t);return r.length>0?n.resolve(o,...r):o}(e),o=a.realpathSync.native(t),s=r.endsWith(n.sep)?r:r+n.sep,i=o.endsWith(n.sep)?o:o+n.sep;return s.startsWith(i)||r===o}({targetPath:n.resolve(r,i),workDir:r})?{decision:"approve"}:{decision:"block",reason:`${"reading"===e?"Accessing":"writing"===e?"Writing to":"editing"===e?"Editing":"Searching in"} files outside the workspace is not allowed. The path "${i}" resolves to a location outside your workspace directory. Please only access files within your workspace.`,systemMessage:"Tool call blocked due to path traversal attempt"}}catch(e){return{decision:"block",reason:`Unable to validate file path "${i}". Please ensure the path is valid and try again. Error: ${e instanceof Error?e.message:"Unknown error"}`,systemMessage:"Tool call blocked due to path validation error"}}}}var Un=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},xn=e=>null!=e&&"object"==typeof e&&"tool_response"in e,Ln=e=>{if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.tool_response)?t.tool_response:void 0},Pn=e=>{const t=Ln(e);if(t)return t.filter(Un).map(e=>e.text).join("\n")||void 0},On=/\u001b\[[0-9;]*m/g,Bn=e=>e.replace(On,""),Nn=/\$\{process\.env\.([A-Z_][A-Z0-9_]*)\}/g;function Dn({envVars:e}){return async t=>{if(!yn(t))return{decision:"approve"};const n=t.tool_input,r="string"==typeof n.text?n.text:void 0;if(!r)return{decision:"approve"};const o=r.replace(Nn,(t,n)=>{const r=e[n];return null!=r?r:t});return o===r?{decision:"approve"}:{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",reason:"Evaluated environment variable placeholders in browser text input.",updatedInput:{...n,text:o}}}}}function jn({onResult:e}){return async t=>{if(!xn(t))return{decision:"approve"};const n=Pn(t);if(!n)return{decision:"approve"};const r=function(e){const t=Bn(e),n=t.split(/Running \d+ tests? using \d+ workers?/).at(-1)??t,r=parseInt(n.match(/(\d+)\s+passed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0"),o=parseInt(n.match(/(\d+)\s+failed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0");if(0===r&&0===o)return;const s=[r>0?`${r} test${1===r?"":"s"} passed ✓`:void 0,o>0?`${o} test${1===o?"":"s"} failed ✗`:void 0].filter(e=>void 0!==e).join(", ");if(0===o)return s;const i=n.split(/\n\s+\d+\)\s+\[id=/).slice(1).map(e=>e.match(/\n\s{4}((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/)?.[1]?.trim()).filter(e=>void 0!==e);return 0===i.length?s:`${s}\n${i.map(e=>` - ${e}`).join("\n")}`}(n);return r&&e(r),{decision:"approve"}}}function kn({onResult:e}){return async t=>{if(!xn(t))return{decision:"approve"};const n=Pn(t);if(!n)return{decision:"approve"};const r=function(e){const t=Bn(e);if(t.match(/### Paused on error:/)){const e=t.match(/### Paused on error:\s*\n((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/);return e?`Test paused on error - ${e[1].trim()}`:"Test paused on error"}const n=t.match(/(\d+)\s+passed/);if(n){const e=parseInt(n[1]);return`${e} test${1===e?"":"s"} passed ✓`}}(n);return r&&e(r),{decision:"approve"}}}var Mn=class{queue=[];pendingResolve=void 0;done=!1;canSend=!0;[Symbol.asyncIterator](){return this}pushText(e){const t=e.trim();t&&!this.done&&(this.queue.push(t),this.maybeFlush())}allowNextTurn(){this.done||(this.canSend=!0,this.maybeFlush())}finish(){this.done=!0,this.pendingResolve&&(this.pendingResolve({done:!0,value:void 0}),this.pendingResolve=void 0)}maybeFlush(){if(!this.pendingResolve)return;if(!this.canSend)return;const e=this.queue.shift();if(void 0===e)return;const t={message:{content:[{text:e,type:"text"}],role:"user"},parent_tool_use_id:null,type:"user",session_id:""};this.canSend=!1,this.pendingResolve({done:!1,value:t}),this.pendingResolve=void 0}next(){return this.done?Promise.resolve({done:!0,value:void 0}):new Promise(e=>{this.pendingResolve=e,this.maybeFlush()})}},$n=10240,Hn=async({defaultContent:e,fileName:t,filePath:n})=>{try{const e=(await m.stat(n)).size,r=await m.readFile(n,"utf-8"),o=Buffer.byteLength(r,"utf-8");if(o<=$n)return r;const s=(e=>{const t=e.split("\n"),n=[];let r=!1,o=!1,s=0,i=!1;for(let e=0;e<t.length;e++){const a=t[e],c=a.trim();c.startsWith("/*")&&(r=!0),c.includes("*/")?r=!1:r||c.startsWith("//")&&!c.startsWith("///")||(c.startsWith("import ")||c.startsWith("export ")?(n.push(a),i=!0):i&&""===c?(n.push(a),i=!1):(i=!1,c.startsWith("type ")||c.startsWith("interface ")?n.push(a):c.startsWith("function ")||c.startsWith("const ")||c.startsWith("async function ")||c.startsWith("export function ")||c.startsWith("export const ")||c.startsWith("test.describe(")||c.startsWith("test(")?(n.push(a),o=!0,s=(a.match(/{/g)||[]).length-(a.match(/}/g)||[]).length,0===s&&(c.endsWith(";")||c.endsWith(","))&&(o=!1)):o?(s+=(a.match(/{/g)||[]).length,s-=(a.match(/}/g)||[]).length,0===s&&c.includes("}")?(n.push(a),o=!1):s>0&&" // ... implementation omitted ..."!==n.at(-1)&&n.push(" // ... implementation omitted ...")):c.match(/^[a-zA-Z_]+:/)&&n.push(a)))}return n.join("\n")})(r),i=Buffer.byteLength(s,"utf-8");return i<=$n?s:s.slice(0,$n)+`\n\n... [TRUNCATED: File "${t}" at ${n} was ${e} bytes (${o} bytes as UTF-8), reduced to ~${i} bytes of essential content, then truncated to 10240 bytes] ...`}catch(t){let n;if(t&&"object"==typeof t&&"code"in t){const e=t.code;"string"==typeof e&&(n=e)}return e}},Gn=async({defaultContent:e,dirName:t,dirPath:n})=>{try{const e=await m.readdir(n);return e.length>0?e.join("\n"):"(empty)"}catch(t){let n;if(t&&"object"==typeof t&&"code"in t){const e=t.code;"string"==typeof e&&(n=e)}return e}},Kn=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__test-doc-sync__"],Fn=["planner_","generator_"],zn=(e,t)=>{const n=t.find(t=>e.startsWith(t));return n?e.slice(n.length):e},Yn=T.z.object({bucket:T.z.string(),key:T.z.string()}),Wn=T.z.object({diffBucketPath:Yn,expiresInSeconds:T.z.number(),key:T.z.string(),uploadUrl:T.z.string()}),Vn=["test","bug","other"],qn={bug:"Application code defect; behavior diverges from expected requirements.",other:"External dependencies, environment, or infra issues outside test/app code.",test:"Test code is incorrect, out-of-date, or missing necessary setup."},Jn=e=>qn[e],{zSuiteAutoHealReport:Xn}=function(e){const t=e.enum(Vn),n=["Classification of the root cause:","",`- test: ${Jn("test")}`,`- bug: ${Jn("bug")}`,`- other: ${Jn("other")}`].join("\n"),r=e.object({erroredUrl:e.string().optional(),issueType:t.describe(n),relatedTestCaseIds:e.array(e.string()).min(1).describe("List of ALL test case IDs impacted by this root cause and fix (must be existing IDs only)."),rootCause:e.string().describe("Brief explanation of what happened (1-2 sentences).")}),o=e.discriminatedUnion("result",[r.extend({fixApplied:e.string().describe("What fix was applied (brief, specific)."),result:e.literal("fixed")}),r.extend({followUpActions:e.string().optional().describe("Optional list of follow-up actions for any unfixed issues or missing data."),reasonNotFixed:e.string().describe("Why it could not be auto-fixed (brief)."),result:e.literal("unfixed")})]);return{zAutoHealReport:o,zIssueCategory:t,zSuiteAutoHealReport:e.object({issues:e.array(o).min(1).describe("List of all auto-heal issues/outcomes for this suite."),summary:e.string().min(3).describe("High-level summary (2-3 sentences) of the suite auto-heal results.")})}}(T.z),Qn=({authHeader:e,orgId:t,runId:n})=>l.createSdkMcpServer({name:"auto-heal-report",tools:[l.tool("generate-report",["After attempting to fix all broken tests (skip only those truly infeasible), generate and return a suite auto-heal report in the required schema.","","Ensure the payload matches zSuiteAutoHealReport exactly; include every issue discovered."].join("\n"),{report:Xn},async({report:r})=>{const o=I.simpleGit({baseDir:process.cwd(),maxConcurrentProcesses:1}),s=await o.diff(),i=Xn.parse(r);try{await(async({authHeader:e,orgId:t,report:n,runId:r})=>{const o=await(s={auth:e,body:{report:JSON.stringify(n)},client:Ht(),headers:_n(t),path:{runId:r}},(s.client??Ot).post({security:[{name:"authorization",type:"apiKey"}],url:"/internal/v1/cli/runs/{runId}/autoheal-report",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to upload auto-heal report (${o.response.status})`)})({authHeader:e,orgId:t,report:i,runId:n});const{uploadUrl:r}=await(async({authHeader:e,contentType:t="text/plain",orgId:n,runId:r})=>{const o=await(s={auth:e,body:{contentType:t},client:Ht(),headers:_n(n),path:{runId:r}},(s.client??Ot).post({security:[{name:"authorization",type:"apiKey"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/upload-url",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to presign diff upload (${o.response.status})`);const i=Wn.parse(o.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}})({authHeader:e,contentType:"text/plain",orgId:t,runId:n});await(async({contentType:e="text/plain",diff:t,uploadUrl:n})=>{const r=await fetch(n,{body:t,headers:{"Content-Type":e},method:"PUT"});if(!r.ok)throw new Error(`Failed to upload diff (${r.status})`)})({contentType:"text/plain",diff:s,uploadUrl:r})}catch(e){return{content:[{text:"Error: Failed to upload auto-heal report or diff. Please surface this to the user, and terminate the session.",type:"text"}]}}return{content:[{text:"Auto-heal report generated. You may terminate this session now.",type:"text"}]}})],version:"0.0.1"}),Zn=e=>e.replace(/Bearer\s+[A-Za-z0-9._-]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{16,}\b/g,"[redacted]").replace(/\bstably_[A-Za-z0-9_-]{16,}\b/g,"[redacted]"),er=(e,t)=>({message:Zn(e),status:t?.status,statusText:t?.statusText}),tr=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_FOUNDRY_API_KEY","ANTHROPIC_MODEL","ANTHROPIC_SMALL_FAST_MODEL","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","AWS_BEARER_TOKEN_BEDROCK","BASH_DEFAULT_TIMEOUT_MS","BASH_MAX_OUTPUT_LENGTH","BASH_MAX_TIMEOUT_MS","CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR","CLAUDE_CODE_API_KEY_HELPER_TTL_MS","CLAUDE_CODE_CLIENT_CERT","CLAUDE_CODE_CLIENT_KEY_PASSPHRASE","CLAUDE_CODE_CLIENT_KEY","CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_DISABLE_TERMINAL_TITLE","CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL","CLAUDE_CODE_MAX_OUTPUT_TOKENS","CLAUDE_CODE_SHELL_PREFIX","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SUBAGENT_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX","CLAUDE_CONFIG_DIR","DISABLE_AUTOUPDATER","DISABLE_BUG_COMMAND","DISABLE_COST_WARNINGS","DISABLE_ERROR_REPORTING","DISABLE_NON_ESSENTIAL_MODEL_CALLS","DISABLE_PROMPT_CACHING","DISABLE_PROMPT_CACHING_HAIKU","DISABLE_PROMPT_CACHING_OPUS","DISABLE_PROMPT_CACHING_SONNET","DISABLE_TELEMETRY","HTTP_PROXY","HTTPS_PROXY","MAX_MCP_OUTPUT_TOKENS","MAX_THINKING_TOKENS","MCP_TIMEOUT","MCP_TOOL_TIMEOUT","NO_PROXY","SLASH_COMMAND_TOOL_CHAR_BUDGET","USE_BUILTIN_RIPGREP","VERTEX_REGION_CLAUDE_3_5_HAIKU","VERTEX_REGION_CLAUDE_3_7_SONNET","VERTEX_REGION_CLAUDE_4_0_OPUS","VERTEX_REGION_CLAUDE_4_0_SONNET","VERTEX_REGION_CLAUDE_4_1_OPUS"]),nr=["mcp__playwright-test","Read","Write","Edit","Glob","Grep"],rr=async e=>{const t=await mn({autoLogin:"chat"===e.mode}),n=(e=>"env"===e.type?e.auth.apiKey:`Bearer ${e.auth.accessToken}`)(t),r="oauth"===t.type?t.auth.context.orgId:void 0,o=w.default.resolve(process.cwd()),s=w.default.join(o,".env"),i=U.default.existsSync(s)&&U.default.statSync(s).isFile()?d.parse(U.default.readFileSync(s,"utf8")):{},a="chat"!==e.mode,c="chat"===e.mode?new Mn:void 0,u="chat"===e.mode?e.getHelpText:void 0,p={log:[],promptDisplay:"chat"===e.mode?"Ask Stably to build tests for you":"fix"===e.mode?"Fixing broken tests":(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)||"<empty prompt>",status:"running"};let f,h=a,m=!1;const _={current:e=>{}},{addTool:g,addToolResult:E,appendText:I,appendUserMessage:T,cleanup:v,setStatus:R}=await(async(e,t)=>{const{Box:n,Static:r,Text:o,render:s,useInput:i}=await import("ink"),a=({label:e})=>{const[t,n]=y.useState(0);return y.useEffect(()=>{const e=setInterval(()=>n(e=>(e+1)%l.length),80);return()=>clearInterval(e)},[]),b.jsxs(o,{color:"yellow",children:[l[t]," ",e]})},c=()=>{const[e,t]=y.useState(!0);return y.useEffect(()=>{const e=setInterval(()=>t(e=>!e),500);return()=>clearInterval(e)},[]),e?b.jsx(o,{inverse:!0,children:" "}):b.jsx(o,{children:" "})},l=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],d=e=>"tool"===e.kind?b.jsxs(o,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?b.jsx(o,{color:"gray",children:e.content},e.id):"user"===e.kind?b.jsxs(o,{color:"cyan",children:["You: ",e.content]},e.id):b.jsx(o,{children:e.content},e.id),u=({onSend:e,state:t})=>{const[s,l]=y.useState(""),u=y.useRef(0),p=t.log.at(-1),f="text"===p?.kind&&"running"===t.status?t.log.length-1:t.log.length;y.useEffect(()=>{t.log.length<u.current&&(u.current=0),f>u.current&&(u.current=f)},[t.log.length,f]);const h=t.log.slice(0,u.current),m=t.log.slice(u.current);i((t,n)=>{if(e&&(!n.ctrl||"c"!==t)){if(n.return){const t=s.trim();return t&&e(t),void l("")}n.backspace||n.delete?l(e=>e.slice(0,-1)):l(e=>`${e}${t}`)}},{isActive:!!e});const _=y.useMemo(()=>"running"===t.status?b.jsx(a,{label:"Working"}):"success"!==t.status?b.jsx(o,{color:"red",children:"✖ Failed"}):void 0,[t.status]),g=!!e&&"running"===t.status&&0===t.log.length&&!t.resultText&&!t.errorText,E="running"===t.status&&!g||t.log.length>0||t.resultText||t.errorText||"running"!==t.status;return b.jsxs(n,{flexDirection:"column",children:[b.jsxs(n,{flexDirection:"column",flexShrink:0,children:[b.jsx(o,{color:"cyan",bold:!0,children:"Stably Agent"}),t.promptDisplay&&b.jsx(n,{flexDirection:"column",marginTop:1,children:b.jsx(o,{color:"gray",children:t.promptDisplay})})]}),h.length>0&&b.jsx(r,{items:h,children:e=>d(e)}),m.length>0&&b.jsx(n,{flexDirection:"column",children:m.map(e=>d(e))}),"error"===t.status&&t.errorText&&b.jsx(n,{marginTop:1,children:b.jsx(o,{color:"red",children:t.errorText})}),E&&b.jsx(n,{flexDirection:"column",flexShrink:0,marginTop:1,children:_}),e&&b.jsxs(n,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[b.jsx(o,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),b.jsxs(o,{children:[b.jsx(o,{color:"yellow",children:">"})," ",s,b.jsx(c,{})]})]})]})};let p=e;const f=s(b.jsx(u,{onSend:t?.onSend,state:p})),h=()=>{p={...p},f.rerender(b.jsx(u,{onSend:t?.onSend,state:p}))};return{addTool:({rawName:e,toolInput:t})=>{const n=(e=>{const t=zn(e,Kn);return zn(t,Fn).split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")})(e),r=((e,t)=>{if(!t||"object"!=typeof t)return;const n=t;if("Read"!==e&&"Write"!==e&&"Edit"!==e){if("Glob"===e||"Grep"===e)return"string"==typeof n.pattern?n.pattern:void 0;if("mcp__playwright-test__test_run"!==e&&"test_run"!==e)return"mcp__playwright-test__generator_setup_page"===e||"generator_setup_page"===e?"string"==typeof n.seedFile?n.seedFile:"tests/seed.spec.ts":"mcp__playwright-test__generator_write_test"===e||"generator_write_test"===e?"string"==typeof n.fileName?n.fileName:void 0:"Bash"===e&&"string"==typeof n.command?n.command:void 0;if(Array.isArray(n.locations)){const e=n.locations.filter(e=>"string"==typeof e);return e.length>0?e.join(", "):void 0}}else if("string"==typeof n.file_path)return n.file_path.split("/").at(-1)??void 0})(e,t),o=r?`${n} (${r})`:n;p.log=[...p.log,{content:o,id:p.log.length,kind:"tool"}],h()},addToolResult:({message:e})=>{p.log=[...p.log,{content:e,id:p.log.length,kind:"tool_result"}],h()},appendText:({text:e})=>{if(!e)return;const t=p.log.at(-1),n=t&&"text"===t.kind?e:e.replace(/^\s*\n+/,"");t&&"text"===t.kind?p.log=[...p.log.slice(0,-1),{...t,content:`${t.content}${n}`}]:p.log=[...p.log,{content:n,id:p.log.length,kind:"text"}],h()},appendUserMessage:({text:e})=>{e&&(p.log=[...p.log,{content:e,id:p.log.length,kind:"user"}],h())},cleanup:async()=>{f.unmount(),await f.waitUntilExit()},setStatus:({error:e,result:t,status:n})=>{p.errorText=e,p.resultText=t,p.status=n,h()}}})(p,"chat"===e.mode?{onSend:e=>_.current(e)}:void 0);let S=p.status;const C=({error:e,result:t,status:n})=>{S=n,R({error:e,result:t,status:n})};_.current=e=>{if("/help"===e.trim()){h&&c&&(m=!0,f?.interrupt?.(),c.allowNextTurn(),h=!1),"running"===S&&C({status:"success"}),T({text:e});const t=u?.();return void I({text:t??"Help is not available in this session."})}c&&(h&&(m=!0,f?.interrupt?.(),c.allowNextTurn(),h=!1),C({status:"running"}),T({text:e}),c.pushText(e),h=!0)};const A=await(async()=>{if("single"===e.mode)return Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;if("fix"===e.mode)try{return await(async({authHeader:e,orgId:t,runId:n})=>{const r=await(o={auth:e,client:Ht(),headers:_n(t),path:{runId:n}},(o.client??Ot).get({security:[{name:"authorization",type:"apiKey"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...o}));var o;if(404===r.response.status)throw new Error(`Run ID "${n}" was not found.`);if(401===r.response.status)throw new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===r.response.status)throw new Error(r.error?.error??"Failed to fetch autoheal context (422).");if(!r.error){const e=gn.safeParse(r.data);if(e.success)return e.data.context;throw new Error("Autoheal context response missing or invalid context.")}throw new Error("Failed to fetch autoheal context")})({authHeader:n,orgId:r,runId:e.runId})}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";C({error:t,status:"error"}),await v(),process.exit(1)}return""})(),x=await async function(e){const t=w.default.resolve(e),n=w.default.join(t,"tests"),r=w.default.join(n,"helpers"),o=w.default.join(n,"assets"),s=w.default.join(t,"playwright.config.ts"),i=w.default.join(n,"seed.spec.ts"),[a,c,l,d,u,p]=await Promise.all([Gn({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),Gn({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:n}),Gn({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:r}),Gn({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:o}),Hn({defaultContent:"File does not exist or could not be read",fileName:"playwright.config.ts",filePath:s}),Hn({defaultContent:"File does not exist or could not be read",fileName:"seed.spec.ts",filePath:i})]);return{absolutePath:t,directories:{assets:d,helpers:l,root:a,tests:c},files:{playwrightConfig:u,seedSpec:p}}}(o),L=await(async({allowedEnvVars:e,mode:t,workspaceInfo:n,authHeader:r})=>{const o=Ht(),s=await(i={client:o,body:{mode:t,workspaceInfo:n,allowedEnvVars:e},headers:{authorization:r}},(i.client??Ot).post({security:[{name:"authorization",type:"apiKey"}],url:"/internal/v1/cli/prompts/system",...i,headers:{"Content-Type":"application/json",...i.headers}}));var i;if(s.error)throw new Error(`Failed to fetch system prompt: ${JSON.stringify(s.error)}`);return s.data.systemPrompt})({allowedEnvVars:Object.keys(i),mode:e.mode,workspaceInfo:x,authHeader:n}),P=await async function({auth:e,client:t,source:n,metadata:r}){try{const s=await(o={auth:e,client:t,body:{source:n,metadata:r??{}}},(o.client??Ot).post({security:[{name:"authorization",type:"apiKey"}],url:"/v1/proxy/api-key",...o,headers:{"Content-Type":"application/json",...o.headers}})),i=s.response;if(s.error){const e="object"==typeof s.error&&"error"in s.error?s.error.error:"Unknown error";return{error:er(e,i)}}return s.data?{key:s.data.key}:{error:er("No data in response",i)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:er(t)}}var o}({auth:n,client:Ht(),source:"cli"}),O=P.key;if(!O){const e=P.error?.message;C({error:e?`Unable to make AI calls: ${e}`:"Unable to make AI calls. Check if you are authenticated.",status:"error"}),await v(),process.exit(1)}const B=Object.fromEntries(Object.entries(process.env).filter(([e])=>!tr.has(e)));f=l.query({options:{allowedTools:[...nr,..."fix"===e.mode?["mcp__auto-heal-report"]:[]],cwd:o,env:{...B,ANTHROPIC_API_KEY:O,ANTHROPIC_BASE_URL:Mt},hooks:{PostToolUse:[{hooks:[async e=>{const t=Ln(e);if(!t)return{decision:"approve"};let n=!1;const r=t.map(e=>Un(e)?e.text.length<=4e4?e:(n=!0,{...e,text:`${e.text.slice(0,4e4)}...[truncated to 40000 characters]`}):e);return n?{decision:"approve",hookSpecificOutput:{hookEventName:"PostToolUse",updatedMCPToolOutput:r}}:{decision:"approve"}}],matcher:"mcp__playwright-test__.*"},{matcher:"mcp__playwright-test__test_run",hooks:[jn({onResult:e=>E({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[kn({onResult:e=>E({message:e})})]}],PreToolUse:[{hooks:[An({action:"writing",pathKey:"file_path",workDir:o}),vn({action:"writing",pathKey:"file_path"}),Rn({action:"writing",pathKey:"file_path"}),wn({action:"writing",pathKey:"file_path"}),Tn({action:"writing",pathKey:"file_path"}),Cn({pathKey:"file_path"})],matcher:"Write"},{hooks:[An({action:"editing",pathKey:"file_path",workDir:o}),vn({action:"editing",pathKey:"file_path"}),Rn({action:"editing",pathKey:"file_path"}),wn({action:"editing",pathKey:"file_path"}),Tn({action:"editing",pathKey:"file_path"}),Cn({pathKey:"file_path"})],matcher:"Edit"},{hooks:[Cn({pathKey:"fileName"})],matcher:"mcp__playwright-test__generator_write_test"},{hooks:[An({action:"reading",pathKey:"file_path",workDir:o}),Tn({action:"reading",pathKey:"file_path"})],matcher:"Read"},{hooks:[An({action:"searching",pathKey:"path",workDir:o}),Tn({action:"searching",pathKey:"path"})],matcher:"Grep"},{matcher:"mcp__playwright-test__browser_type",hooks:[Dn({envVars:i})]}]},includePartialMessages:!0,mcpServers:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx"},..."fix"===e.mode?{"auto-heal-report":Qn({authHeader:n,orgId:r,runId:e.runId})}:{}},model:"claude-opus-4-5-20251101",systemPrompt:L},prompt:c??A});const N=async()=>{try{await(f?.interrupt?.())}catch{}c?.finish(),await v(),process.exit(1)};process.on("SIGINT",N);try{for await(const e of f){if("stream_event"===e.type){const{event:t}=e;if("content_block_delta"===t?.type){const{delta:e}=t;"text_delta"===e?.type&&e.text&&I({text:e.text})}"message_stop"===t?.type&&c&&c.allowNextTurn();continue}if("assistant"===e.type){const{content:t}=e.message??{};if(Array.isArray(t))for(const e of t)"tool_use"===e?.type&&g({rawName:e.name,toolInput:e.input});continue}if("result"!==e.type);else{if(a){"success"===e.subtype?C({status:"success"}):m||(C({error:"Run failed.",status:"error"}),process.exitCode=1),m=!1;break}"success"!==e.subtype?m||(C({error:"Run failed.",status:"error"}),process.exitCode=1):C({status:"success"}),h=!1,m=!1,c?.allowNextTurn()}}}catch(e){m||(C({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1)}finally{h=!1,m=!1,process.off("SIGINT",N),c?.finish(),await v()}},or=[".ts",".js",".mts",".mjs",".cts",".cjs"],sr=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}];async function ir({overrideArgs:e,subcommand:t}){const o=process.argv,s=o.findIndex((e,n)=>n>1&&e===t),i=-1===s?[]:o.slice(s+1),c="--"===i[0]?i.slice(1):i,l=e??[],d=new Set(l.map(e=>{const[t]=e.split("=");return t})),u=c.filter(e=>{const[t]=e.split("=");return!d.has(t)}),p=[t,...l,...u],f="test"===t?await(async()=>{const e=process.env.STABLY_API_KEY,t=process.env.STABLY_PROJECT_ID;if(e&&t)return{STABLY_API_KEY:e,STABLY_PROJECT_ID:t};const n=await(async()=>{const e=fn();if(e)return{auth:e,type:"env"};const t=await hn(),n=t?await rn():void 0;return t&&n?{auth:{accessToken:t.accessToken,context:n},type:"oauth"}:void 0})();if(!n)return;const r=t??(e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId)(n);if(!r)return;const o=e??("env"===n.type?n.auth.apiKey:await(async(e,t)=>{try{return(await(async({accessToken:e,projectId:t})=>{const n=await(r={auth:`Bearer ${e}`,client:Ht(),path:{projectId:t}},(r.client??Ot).post({security:[{name:"authorization",type:"apiKey"}],url:"/internal/v1/cli/projects/{projectId}/api-key",...r}));var r;if(401===n.response.status)throw new Error("Invalid or expired access token");if(403===n.response.status)throw new Error("You do not have access to this project");if(n.error)throw new Error(`Failed to get API key: ${n.response.status}`);return n.data})({accessToken:e,projectId:t})).apiKey}catch{return e}})(n.auth.accessToken,r));return o?{STABLY_API_KEY:o,STABLY_PROJECT_ID:r}:void 0})():void 0,h="test"===t?function(e){const t=process.cwd(),r=e=>function(e){let t=n.resolve(e);for(;;){if([n.join(t,"node_modules","@stablyai","playwright-test"),n.join(t,"node_modules",".pnpm","@stablyai+playwright-test")].some(e=>a.existsSync(e)))return!0;const e=n.dirname(t);if(e===t)return!1;t=e}}(e),o=(e,t)=>{try{return function({baseConfigPath:e,projectDir:t}){const r=n.join(t,".stably-playwright-wrapper.config.ts"),o=`\n// Auto-generated wrapper config by Stably CLI\n// This file injects the Stably reporter and ensures trace is enabled\nimport { defineConfig } from '@playwright/test';\nimport baseConfig from './${n.relative(n.dirname(r),e).replace(/\\/g,"/")}';\n\n// Inline type definitions to avoid import failures when @stablyai/playwright-test is not installed\ntype StablyNotificationConfig = {\n email?: { to: string[]; notifyOnStart?: boolean; notifyOnResult?: 'all' | 'failures-only' | null } | null;\n slack?: { channelName: string; notifyOnStart?: boolean; notifyOnResult?: 'all' | 'failures-only' } | null;\n};\n\ntype ProjectNotificationConfig = {\n projectName: string;\n notifications: StablyNotificationConfig;\n};\n\n// Dynamically import stablyReporter to handle cases where it's not installed\nlet stablyReporter: ((options?: { apiKey?: string; projectId?: string; notificationConfigs?: ProjectNotificationConfig[] }) => [string, unknown]) | undefined;\ntry {\n stablyReporter = require('@stablyai/playwright-test').stablyReporter;\n} catch {\n // @stablyai/playwright-test not installed - reporter injection will be skipped\n}\n\n// Extract notification configs from projects that have stably.notifications defined\n// This runs at config-load time before Playwright strips custom properties\nconst extractNotificationConfigs = (): ProjectNotificationConfig[] | undefined => {\n const projects = baseConfig.projects;\n if (!projects || !Array.isArray(projects)) return undefined;\n \n const configs = projects\n .map((p: { name?: string; stably?: { notifications?: StablyNotificationConfig } }) => {\n const notifications = p.stably?.notifications;\n return notifications ? { projectName: p.name ?? '', notifications } : undefined;\n })\n .filter((config): config is ProjectNotificationConfig => config != null);\n \n return configs.length > 0 ? configs : undefined;\n};\n\nconst hasStablyReporter = (reporters: unknown): boolean => {\n if (!Array.isArray(reporters)) return false;\n return reporters.some((reporter) => {\n if (typeof reporter === 'string') {\n return reporter.includes('stablyai') || reporter.includes('stably');\n }\n if (Array.isArray(reporter) && typeof reporter[0] === 'string') {\n return reporter[0].includes('stablyai') || reporter[0].includes('stably');\n }\n return false;\n });\n};\n\nconst buildReporterList = () => {\n const existingReporters = baseConfig.reporter;\n \n // If stablyReporter is not available, just use existing reporters\n if (!stablyReporter) {\n return existingReporters;\n }\n \n // If already has stably reporter, don't add another\n if (hasStablyReporter(existingReporters)) {\n return existingReporters;\n }\n \n // Create the stably reporter entry with notification configs\n const stablyReporterEntry = stablyReporter({\n apiKey: process.env.STABLY_API_KEY,\n projectId: process.env.STABLY_PROJECT_ID,\n notificationConfigs: extractNotificationConfigs(),\n });\n \n // Merge with existing reporters\n if (!existingReporters) {\n return [stablyReporterEntry];\n }\n \n if (Array.isArray(existingReporters)) {\n return [...existingReporters, stablyReporterEntry];\n }\n \n // Single reporter as string - convert to tuple format [name, {}]\n return [[existingReporters, {}], stablyReporterEntry];\n};\n\nexport default defineConfig({\n ...baseConfig,\n use: {\n ...baseConfig.use,\n trace: 'on',\n },\n reporter: buildReporterList(),\n});\n`.trim(),s=n.dirname(r);return a.existsSync(s)||a.mkdirSync(s,{recursive:!0}),a.writeFileSync(r,o,"utf-8"),r}({baseConfigPath:e,projectDir:t})}catch{return}};if(e.some(e=>"--config"===e||"-c"===e||e.startsWith("--config=")||e.startsWith("-c="))){const s=e.findIndex(e=>"--config"===e||"-c"===e);if(-1!==s&&e[s+1]){const i=n.resolve(t,e[s+1]),a=n.dirname(i);if(!r(a))return;const c=o(i,a);if(!c)return;return e[s+1]=c,c}const i=e.findIndex(e=>e.startsWith("--config=")||e.startsWith("-c="));if(-1!==i){const s=n.resolve(t,e[i].split("=")[1]),a=n.dirname(s);if(!r(a))return;const c=o(s,a);if(!c)return;const l=e[i].startsWith("--config=")?"--config=":"-c=";return e[i]=`${l}${c}`,c}}const s=function(e){const t=n.resolve(e);if(a.existsSync(t))for(const e of or){const r=n.join(t,`playwright.config${e}`);if(a.existsSync(r))return r}}(t);if(!s)return;const i=n.dirname(s);if(!r(i))return;const c=o(s,i);return c?(e.push("--config",c),c):void 0}(p):void 0;!function(e,t={}){const o=function(e=process.cwd()){let t=n.resolve(e);for(;;){const e=ar(t);if(e){const r={...e.dependencies,...e.devDependencies},o="@playwright/test"in r?"@playwright/test":"playwright"in r?"playwright":void 0;if(o){const e=cr(t),r=n.join(t,"node_modules"),s=n.join(r,o);return{inNodeModules:a.existsSync(s),installed:!0,packageManager:e,packageName:o}}}const r=n.dirname(t);if(r===t)return{inNodeModules:!1,installed:!1,packageManager:void 0};t=r}}();o.installed||process.exit(1),o.inNodeModules||process.exit(1);const{packageManager:s}=o;s||process.exit(1);const[i,...c]=function(e){if("npm"===e)return["npx","playwright"];if("pnpm"===e)return["pnpm","exec","playwright"];if("yarn"===e)return["yarn","playwright"];throw new Error("Package manager not supported")}(s),l=[i,...c.slice(0,-1)].join(" "),d=t.env?{...process.env,...t.env}:process.env,u=r.spawn(i,[...c,...e],{stdio:["inherit","pipe","pipe"],env:{...d,...process.env.CI?{}:{FORCE_COLOR:"1"}}}),p=(e,t)=>{let n=e.toString();for(const e of sr)n=n.replaceAll(`${l} playwright ${e.name}`,`${l} stably ${e.name}`).replaceAll(`npx playwright ${e.name}`,`npx stably ${e.name}`);if("yarn"===s){const e=n.split("\n");e.length>0&&e[0].includes("/.bin/playwright")&&e.shift();const r=e.join("\n");return void t.write(r)}t.write(n)};u.stdout?.on("data",e=>{p(e,process.stdout)}),u.stderr?.on("data",e=>{p(e,process.stderr)}),u.on("close",e=>{t.onClose?.(),process.exit(e??0)})}(p,{env:f,onClose:()=>{var e;(e=h)&&a.existsSync(e)&&a.rmSync(e)}})}function ar(e){const t=n.join(e,"package.json");let r;try{r=a.readFileSync(t,"utf-8")}catch{return}try{return JSON.parse(r)}catch{return}}function cr(e){const t=[["npm","package-lock.json"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"]];for(const[r,o]of t)if(a.existsSync(n.join(e,o)))return r}var lr=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);-1!==lr&&process.argv[lr+1]&&(process.chdir(process.argv[lr+1]),process.argv.splice(lr,2));var dr=new e.Command;dr.name("stably").description("AI-assisted Playwright testing CLI").version(Nt),dr.enablePositionalOptions(),dr.showHelpAfterError(),dr.exitOverride();var ur=[];dr.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{ur.push(e)}});var pr=()=>{const e=dr.helpInformation().trimEnd();return e?`${e}\n`:""},fr=(e,t)=>{let n=e;for(const e of t){const t=n.commands.find(t=>t.name()===e||t.aliases().includes(e));if(!t)return;n=t}return n},hr=()=>{process.stdout.write(pr())};dr.command("help").description("Show help for a command or subcommand").argument("[command...]","Command path to show help for (e.g. create test)").action(e=>{if(!e||0===e.length)return void hr();const t=fr(dr,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),hr(),void(process.exitCode=1);var n;n=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(n))}),dr.action(()=>rr({mode:"chat",getHelpText:pr})),dr.command("login").description("Authenticate with Stably in your browser").action(pn),dr.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=await Zt();if(!e)return void u.outro(x.default.yellow("You are not logged in."));const t=u.spinner();t.start("Logging out..."),await(async e=>{try{await fetch(`${jt}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(e.refreshToken),await tn(),await on(),t.stop(x.default.green("✓ Logged out")),u.outro(x.default.green("You have been logged out successfully."))}),dr.command("whoami").description("Show auth status and current project").action(async()=>{u.log.info(`${x.default.bold("CLI Version:")} ${x.default.cyan(Nt)}`);const e=fn();if(e)return u.log.info(x.default.dim("Authentication: Environment variables")),u.log.info(` ${x.default.bold("API Key:")} ${x.default.cyan(e.apiKey.slice(0,8))}...`),u.log.info(` ${x.default.bold("Project ID:")} ${x.default.cyan(e.projectId)}`),void u.outro(x.default.green("Authenticated via environment variables"));const t=await Zt();if(!t)return void u.outro(x.default.yellow("Not logged in. Run `stably login` to authenticate."));let n;try{n=Yt(t.accessToken).email}catch{n=void 0}const r=await rn();if(!r)return u.log.info(x.default.dim("Authentication: OAuth (not linked to a project)")),n&&u.log.info(` ${x.default.bold("Email:")} ${x.default.cyan(n)}`),void u.outro(x.default.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const o=await(async()=>nn(process.cwd()))(),s=o?w.default.dirname(o):process.cwd(),i=w.default.relative(process.cwd(),s)||".";u.log.info(x.default.dim("Authentication: OAuth")),n&&u.log.info(` ${x.default.bold("Email:")} ${x.default.cyan(n)}`),u.log.info(` ${x.default.bold("Organization:")} ${x.default.cyan(r.orgName)}`),u.log.info(` ${x.default.bold("Project:")} ${x.default.cyan(r.projectName)}`),u.log.info(` ${x.default.bold("Linked at:")} ${x.default.dim(i)}`),u.outro(x.default.green("Authenticated"))}),dr.command("tunnel",{hidden:!0}).description("Expose a local server with a secure tunnel URL").option("-p, --port <number>","Local port to expose","3000").action(async e=>{u.intro(`Starting development server for port ${e.port}...`);const t=await mn(),n="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),r=u.spinner();r.start("Starting development server...");const o=await v.startTunnel(`http://localhost:${e.port}`,{subdomain:n});r.stop(`Your local environment is available at: ${x.default.underline(x.default.cyan(o.url))}`)}),dr.command("create").description("Create tests from a prompt (use: create test)").command("test").description("Generate a Playwright test from a prompt").argument("<prompt...>","Prompt describing the test to generate").action(e=>rr({mode:"single",prompt:e})),dr.command("fix").description("Fix failing Playwright tests using debug context").argument("[runId]","Run ID for the failing test suite (defaults to CI's unique runId if available)").action(e=>{const t=e??function(){if(process.env.CI_BUILD_ID)return process.env.CI_BUILD_ID;const e=(({env:e=process.env,cwd:t=process.cwd()}={})=>{for(const n of Object.keys(ft))if(ft[n].detect({env:e,cwd:t}))return{isCi:!0,...ft[n].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(n={env:e,cwd:t},{commit:$e(n),branch:He(n)})};var n})();if(!e.isCi)return;const t=function(e){switch(e){case"github":return process.env.GITHUB_RUN_ATTEMPT;case"azure-devops":return process.env.SYSTEM_JOBATTEMPT;case"bitbucket":return process.env.BITBUCKET_STEP_RUN_NUMBER;default:return}}(e.service),n=[e.service,"slug"in e?e.slug:void 0,"build"in e?String(e.build):void 0,"job"in e?String(e.job):void 0,t&&String(t)].filter(Boolean);return n.length>0?n.join("-"):void 0}();return t||(process.stderr.write("Run ID is required. Provide <runId>.\n"),process.exit(1)),rr({mode:"fix",runId:t})}),sr.forEach(({args:e,description:t,name:n})=>{dr.command(n).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>ir({overrideArgs:e,subcommand:n}))});var mr=()=>{0!==ur.length&&(process.stderr.write(ur.join("")),ur=[])};(async()=>{try{await dr.parseAsync(process.argv)}catch(e){if(!(e=>!!e&&"object"==typeof e&&"code"in e)(e))throw mr(),e;const t="number"==typeof e.exitCode?e.exitCode:1,n=process.argv.slice(2).find(e=>!e.startsWith("-")),r=!!n&&!!fr(dr,[n]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&n&&!r)return ur=[],process.stderr.write(`command '${n}' not found\n`),hr(),void(process.exitCode=t);mr(),process.exitCode=t}})();
2
+ "use strict";var e=require("commander"),t=require("buffer"),n=require("path"),r=require("child_process"),o=require("process"),s=require("url"),i=require("os"),a=require("fs");require("timers/promises");var c=require("util"),l=require("@anthropic-ai/claude-agent-sdk"),d=require("dotenv"),u=require("@clack/prompts"),p=require("picocolors"),f=require("readline/promises"),m=require("zod"),h=require("fs/promises"),_=require("open"),g=require("http"),E=require("crypto"),y=require("react"),I=require("react/jsx-runtime"),b=require("simple-git"),T=require("zod/v3"),v=require("@stablyhq/runner-sdk");function R(e){return e&&e.__esModule?e:{default:e}}var w=R(n),S=R(r),C=R(o),A=R(i),x=R(a),U=R(p),P=R(m),L=R(_),O=R(g),B=R(E),N=Object.create,D=Object.defineProperty,j=Object.getOwnPropertyDescriptor,k=Object.getOwnPropertyNames,M=Object.getPrototypeOf,$=Object.prototype.hasOwnProperty,H=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)(function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),G=(e,t)=>function(){return t||(0,e[k(e)[0]])((t={exports:{}}).exports,t),t.exports},F=(e,t,n)=>(n=null!=e?N(M(e)):{},((e,t,n,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of k(t))$.call(e,n)||void 0===n||D(e,n,{get:()=>t[n],enumerable:!(r=j(t,n))||r.enumerable});return e})(D(n,"default",{value:e,enumerable:!0}),e)),z=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(e,t){t.exports=o,o.sync=function(e,t){return r(n.statSync(e),e,t)};var n=H("fs");function r(e,t,n){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var n=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!n)return!0;if(-1!==(n=n.split(";")).indexOf(""))return!0;for(var r=0;r<n.length;r++){var o=n[r].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}(t,n)}function o(e,t,o){n.stat(e,function(n,s){o(n,!n&&r(s,e,t))})}}}),Y=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js"(e,t){t.exports=r,r.sync=function(e,t){return o(n.statSync(e),t)};var n=H("fs");function r(e,t,r){n.stat(e,function(e,n){r(e,!e&&o(n,t))})}function o(e,t){return e.isFile()&&function(e,t){var n=e.mode,r=e.uid,o=e.gid,s=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),i=void 0!==t.gid?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8);return n&parseInt("001",8)||n&c&&o===i||n&a&&r===s||n&(a|c)&&0===s}(e,t)}}}),K=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(e,t){var n;function r(e,t,o){if("function"==typeof t&&(o=t,t={}),!o){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(n,o){r(e,t||{},function(e,t){e?o(e):n(t)})})}n(e,t||{},function(e,n){e&&("EACCES"===e.code||t&&t.ignoreErrors)&&(e=null,n=!1),o(e,n)})}H("fs"),n="win32"===process.platform||global.TESTING_WINDOWS?z():Y(),t.exports=r,r.sync=function(e,t){try{return n.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||"EACCES"===e.code)return!1;throw e}}}}),V=G({"node_modules/.pnpm/which@2.0.2/node_modules/which/which.js"(e,t){var n="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,r=H("path"),o=n?";":":",s=K(),i=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),a=(e,t)=>{const r=t.colon||o,s=e.match(/\//)||n&&e.match(/\\/)?[""]:[...n?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],i=n?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=n?i.split(r):[""];return n&&-1!==e.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:s,pathExt:a,pathExtExe:i}},c=(e,t,n)=>{"function"==typeof t&&(n=t,t={}),t||(t={});const{pathEnv:o,pathExt:c,pathExtExe:l}=a(e,t),d=[],u=n=>new Promise((s,a)=>{if(n===o.length)return t.all&&d.length?s(d):a(i(e));const c=o[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=r.join(l,e),f=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;s(p(f,n,0))}),p=(e,n,r)=>new Promise((o,i)=>{if(r===c.length)return o(u(n+1));const a=c[r];s(e+a,{pathExt:l},(s,i)=>{if(!s&&i){if(!t.all)return o(e+a);d.push(e+a)}return o(p(e,n,r+1))})});return n?u(0).then(e=>n(null,e),n):u(0)};t.exports=c,c.sync=(e,t)=>{t=t||{};const{pathEnv:n,pathExt:o,pathExtExe:c}=a(e,t),l=[];for(let i=0;i<n.length;i++){const a=n[i],d=/^".*"$/.test(a)?a.slice(1,-1):a,u=r.join(d,e),p=!d&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;for(let e=0;e<o.length;e++){const n=p+o[e];try{if(s.sync(n,{pathExt:c})){if(!t.all)return n;l.push(n)}}catch(e){}}}if(t.all&&l.length)return l;if(t.nothrow)return null;throw i(e)}}}),W=G({"node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js"(e,t){var n=(e={})=>{const t=e.env||process.env;return"win32"!==(e.platform||process.platform)?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"};t.exports=n,t.exports.default=n}}),q=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){var n=H("path"),r=V(),o=W();function s(e,t){const s=e.options.env||process.env,i=process.cwd(),a=null!=e.options.cwd,c=a&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(e.options.cwd)}catch(e){}let l;try{l=r.sync(e.command,{path:s[o({env:s})],pathExt:t?n.delimiter:void 0})}catch(e){}finally{c&&process.chdir(i)}return l&&(l=n.resolve(a?e.options.cwd:"",l)),l}t.exports=function(e){return s(e)||s(e,!0)}}}),J=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js"(e,t){var n=/([()\][%!^"`<>&|;, *?])/g;t.exports.command=function(e){return e.replace(n,"^$1")},t.exports.argument=function(e,t){return e=(e=`"${e=(e=(e=`${e}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(n,"^$1"),t&&(e=e.replace(n,"^$1")),e}}}),X=G({"node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(e,t){t.exports=/^#!(.*)/}}),Q=G({"node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js"(e,t){var n=X();t.exports=(e="")=>{const t=e.match(n);if(!t)return null;const[r,o]=t[0].replace(/#! ?/,"").split(" "),s=r.split("/").pop();return"env"===s?o:o?`${s} ${o}`:s}}}),Z=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(e,t){var n=H("fs"),r=Q();t.exports=function(e){const t=Buffer.alloc(150);let o;try{o=n.openSync(e,"r"),n.readSync(o,t,0,150,0),n.closeSync(o)}catch(e){}return r(t.toString())}}}),ee=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(e,t){var n=H("path"),r=q(),o=J(),s=Z(),i="win32"===process.platform,a=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;t.exports=function(e,t,l){t&&!Array.isArray(t)&&(l=t,t=null);const d={command:e,args:t=t?t.slice(0):[],options:l=Object.assign({},l),file:void 0,original:{command:e,args:t}};return l.shell?d:function(e){if(!i)return e;const t=function(e){e.file=r(e);const t=e.file&&s(e.file);return t?(e.args.unshift(e.file),e.command=t,r(e)):e.file}(e),l=!a.test(t);if(e.options.forceShell||l){const r=c.test(t);e.command=n.normalize(e.command),e.command=o.command(e.command),e.args=e.args.map(e=>o.argument(e,r));const s=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${s}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}(d)}}}),te=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js"(e,t){var n="win32"===process.platform;function r(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function o(e,t){return n&&1===e&&!t.file?r(t.original,"spawn"):null}t.exports={hookChildProcess:function(e,t){if(!n)return;const r=e.emit;e.emit=function(n,s){if("exit"===n){const n=o(s,t);if(n)return r.call(e,"error",n)}return r.apply(e,arguments)}},verifyENOENT:o,verifyENOENTSync:function(e,t){return n&&1===e&&!t.file?r(t.original,"spawnSync"):null},notFoundError:r}}}),ne=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(e,t){var n=H("child_process"),r=ee(),o=te();function s(e,t,s){const i=r(e,t,s),a=n.spawn(i.command,i.args,i.options);return o.hookChildProcess(a,i),a}t.exports=s,t.exports.spawn=s,t.exports.sync=function(e,t,s){const i=r(e,t,s),a=n.spawnSync(i.command,i.args,i.options);return a.error=a.error||o.verifyENOENTSync(a.status,i),a},t.exports._parse=r,t.exports._enoent=o}}),re=G({"node_modules/.pnpm/merge-stream@2.0.0/node_modules/merge-stream/index.js"(e,t){var{PassThrough:n}=H("stream");t.exports=function(){var e=[],t=new n({objectMode:!0});return t.setMaxListeners(0),t.add=r,t.isEmpty=function(){return 0==e.length},t.on("unpipe",o),Array.prototype.slice.call(arguments).forEach(r),t;function r(n){return Array.isArray(n)?(n.forEach(r),this):(e.push(n),n.once("end",o.bind(null,n)),n.once("error",t.emit.bind(t,"error")),n.pipe(t,{end:!1}),this)}function o(n){!(e=e.filter(function(e){return e!==n})).length&&t.readable&&t.end()}}}}),oe=G({"node_modules/.pnpm/java-properties@1.0.2/node_modules/java-properties/dist-node/index.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.of=e.PropertiesFile=void 0;var t,n=(t=H("fs"))&&t.__esModule?t:{default:t},r=class{constructor(...e){this.objs={},e.length&&this.of.apply(this,e)}makeKeys(e){if(e&&0!==e.indexOf("#")){let t=["=",":"].map(t=>e.indexOf(t)).filter(e=>e>-1),n=Math.min(...t),r=e.substring(0,n).trim(),o=e.substring(n+1).trim();if(this.objs.hasOwnProperty(r))if(Array.isArray(this.objs[r]))this.objs[r].push(o);else{let e=this.objs[r];this.objs[r]=[e,o]}else{const e=o.replace(/"/g,'\\"').replace(/\\:/g,":").replace(/\\=/g,"=");this.objs[r]=unescape(JSON.parse('"'+e+'"'))}}}addFile(e){let t=n.default.readFileSync(e,"utf-8").split(/\r?\n/),r=this;for(let e=0;e<t.length;e++){let n=t[e];for(;"\\"===n.substring(n.length-1);)n=n.slice(0,-1),n+=t[e+1].trim(),e++;r.makeKeys(n)}}of(...e){for(let t=0;t<e.length;t++)this.addFile(e[t])}get(e,t){if(this.objs.hasOwnProperty(e)){if(Array.isArray(this.objs[e])){let t=[];for(let n=0;n<this.objs[e].length;n++)t[n]=this.interpolate(this.objs[e][n]);return t}return void 0===this.objs[e]?"":this.interpolate(this.objs[e])}return t}getLast(e,t){if(this.objs.hasOwnProperty(e)){if(Array.isArray(this.objs[e])){var n=this.objs[e].length;return this.interpolate(this.objs[e][n-1])}return void 0===this.objs[e]?"":this.interpolate(this.objs[e])}return t}getFirst(e,t){return this.objs.hasOwnProperty(e)?Array.isArray(this.objs[e])?this.interpolate(this.objs[e][0]):void 0===this.objs[e]?"":this.interpolate(this.objs[e]):t}getInt(e,t){let n=this.getLast(e);return n?parseInt(n,10):t}getFloat(e,t){let n=this.getLast(e);return n?parseFloat(n):t}getBoolean(e,t){let n=this.getLast(e);return n?!/^(false|0)$/i.test(r=n)&&!!r:t||!1;var r}set(e,t){this.objs[e]=t}interpolate(e){let t=this;return e.replace(/\\\\/g,"\\").replace(/\$\{([A-Za-z0-9\.\-\_]*)\}/g,function(e){return t.getLast(e.substring(2,e.length-1))})}getKeys(){let e=[];for(let t in this.objs)e.push(t);return e}getMatchingKeys(e){let t=[];for(let n in this.objs)-1!==n.search(e)&&t.push(n);return t}reset(){this.objs={}}};e.PropertiesFile=r,e.of=function(...e){let t=new r;return t.of.apply(t,e),t}}}),se={detect:({env:e})=>Boolean(e.APPVEYOR),configuration({env:e}){const t=e.APPVEYOR_PULL_REQUEST_NUMBER,n=Boolean(t);return{name:"Appveyor",service:"appveyor",commit:e.APPVEYOR_REPO_COMMIT,tag:e.APPVEYOR_REPO_TAG_NAME,build:e.APPVEYOR_BUILD_NUMBER,buildUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/${e.APPVEYOR_BUILD_VERSION}`,branch:e.APPVEYOR_REPO_BRANCH,job:e.APPVEYOR_JOB_NUMBER,jobUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/job/${e.APPVEYOR_JOB_ID}`,pr:t,isPr:n,prBranch:e.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH,slug:e.APPVEYOR_REPO_NAME,root:e.APPVEYOR_BUILD_FOLDER}}};function ie(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function ae(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var ce={detect:({env:e})=>Boolean(e.BUILD_BUILDURI),configuration({env:e}){const t=e.SYSTEM_PULLREQUEST_PULLREQUESTID,n=Boolean(t);return{name:"Azure Pipelines",service:"azurePipelines",commit:e.BUILD_SOURCEVERSION,build:e.BUILD_BUILDNUMBER,branch:ae(n?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:n,prBranch:ae(n?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},le={detect:({env:e})=>Boolean(e.bamboo_agentId),configuration:({env:e})=>({name:"Bamboo",service:"bamboo",commit:e.bamboo_planRepository_1_revision,build:e.bamboo_buildNumber,buildUrl:e.bamboo_buildResultsUrl,branch:e.bamboo_planRepository_1_branchName,job:e.bamboo_buildKey,root:e.bamboo_build_working_directory})},de={detect:({env:e})=>Boolean(e.BITBUCKET_BUILD_NUMBER),configuration:({env:e})=>({name:"Bitbucket Pipelines",service:"bitbucket",commit:e.BITBUCKET_COMMIT,tag:e.BITBUCKET_TAG,build:e.BITBUCKET_BUILD_NUMBER,buildUrl:`https://bitbucket.org/${e.BITBUCKET_REPO_FULL_NAME}/addon/pipelines/home#!/results/${e.BITBUCKET_BUILD_NUMBER}`,branch:e.BITBUCKET_BRANCH,slug:e.BITBUCKET_REPO_FULL_NAME,root:e.BITBUCKET_CLONE_DIR})},ue={detect:({env:e})=>Boolean(e.BITRISE_IO),configuration({env:e}){const t="false"===e.BITRISE_PULL_REQUEST?void 0:e.BITRISE_PULL_REQUEST,n=Boolean(t);return{name:"Bitrise",service:"bitrise",commit:e.BITRISE_GIT_COMMIT,tag:e.BITRISE_GIT_TAG,build:e.BITRISE_BUILD_NUMBER,buildUrl:e.BITRISE_BUILD_URL,branch:n?e.BITRISEIO_GIT_BRANCH_DEST:e.BITRISE_GIT_BRANCH,pr:t,isPr:n,prBranch:n?e.BITRISE_GIT_BRANCH:void 0,slug:e.BITRISE_APP_SLUG}}},pe={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=ie(e.BUDDY_EXECUTION_PULL_REQUEST_ID),n=Boolean(t);return{name:"Buddy",service:"buddy",commit:e.BUDDY_EXECUTION_REVISION,tag:e.BUDDY_EXECUTION_TAG,build:e.BUDDY_EXECUTION_ID,buildUrl:e.BUDDY_EXECUTION_URL,branch:n?e.BUDDY_EXECUTION_PULL_REQUEST_HEAD_BRANCH:e.BUDDY_EXECUTION_BRANCH,pr:t,isPr:n,slug:e.BUDDY_REPO_SLUG}}},fe=F(ne());function me(e={}){const{env:t=process.env,platform:n=process.platform}=e;return"win32"!==n?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"}var he=(e,t)=>({name:`SIGRT${t+1}`,number:_e+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),_e=34,ge=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}],Ee=()=>{const e=(()=>{const e=64-_e+1;return Array.from({length:e},he)})();return[...ge,...e].map(ye)},ye=({name:e,number:t,description:n,action:r,forced:o=!1,standard:s})=>{const{signals:{[e]:a}}=i.constants,c=void 0!==a;return{name:e,number:c?a:t,description:n,supported:c,action:r,forced:o,standard:s}},Ie=({name:e,number:t,description:n,supported:r,action:o,forced:s,standard:i})=>[e,{name:e,number:t,description:n,supported:r,action:o,forced:s,standard:i}],be=(()=>{const e=Ee();return Object.fromEntries(e.map(Ie))})();(()=>{const e=Ee(),t=Array.from({length:65},(t,n)=>((e,t)=>{const n=((e,t)=>{const n=t.find(({name:t})=>i.constants.signals[t]===e);return void 0!==n?n:t.find(t=>t.number===e)})(e,t);if(void 0===n)return{};const{name:r,description:o,supported:s,action:a,forced:c,standard:l}=n;return{[e]:{name:r,number:e,description:o,supported:s,action:a,forced:c,standard:l}}})(n,e));Object.assign({},...t)})();var Te=({stdout:e,stderr:t,all:n,error:r,signal:o,exitCode:s,command:i,escapedCommand:a,timedOut:c,isCanceled:l,killed:d,parsed:{options:{timeout:u,cwd:p=C.default.cwd()}}})=>{s=null===s?void 0:s;const f=void 0===(o=null===o?void 0:o)?void 0:be[o].description,m=(({timedOut:e,timeout:t,errorCode:n,signal:r,signalDescription:o,exitCode:s,isCanceled:i})=>e?`timed out after ${t} milliseconds`:void 0!==n?`failed with ${n}`:void 0!==r?`was killed with ${r} (${o})`:void 0!==s?`failed with exit code ${s}`:"failed")({timedOut:c,timeout:u,errorCode:r&&r.code,signal:o,signalDescription:f,exitCode:s,isCanceled:l}),h=`Command ${m}: ${i}`,_="[object Error]"===Object.prototype.toString.call(r),g=_?`${h}\n${r.message}`:h,E=[g,t,e].filter(Boolean).join("\n");return _?(r.originalMessage=r.message,r.message=E):r=new Error(E),r.shortMessage=g,r.command=i,r.escapedCommand=a,r.exitCode=s,r.signal=o,r.signalDescription=f,r.stdout=e,r.stderr=t,r.cwd=p,void 0!==n&&(r.all=n),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=Boolean(c),r.isCanceled=l,r.killed=d&&!c,r},ve=["stdin","stdout","stderr"],Re=[];Re.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&Re.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&Re.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var we=e=>!!e&&"object"==typeof e&&"function"==typeof e.removeListener&&"function"==typeof e.emit&&"function"==typeof e.reallyExit&&"function"==typeof e.listeners&&"function"==typeof e.kill&&"number"==typeof e.pid&&"function"==typeof e.on,Se=Symbol.for("signal-exit emitter"),Ce=globalThis,Ae=Object.defineProperty.bind(Object),xe=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Ce[Se])return Ce[Se];Ae(Ce,Se,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){const n=this.listeners[e],r=n.indexOf(t);-1!==r&&(0===r&&1===n.length?n.length=0:n.splice(r,1))}emit(e,t,n){if(this.emitted[e])return!1;this.emitted[e]=!0;let r=!1;for(const o of this.listeners[e])r=!0===o(t,n)||r;return"exit"===e&&(r=this.emit("afterExit",t,n)||r),r}},Ue=class{},Pe=globalThis.process;we(Pe)?new class extends Ue{#e="win32"===Pe.platform?"SIGINT":"SIGHUP";#t=new xe;#n;#r;#o;#s={};#i=!1;constructor(e){super(),this.#n=e,this.#s={};for(const t of Re)this.#s[t]=()=>{const n=this.#n.listeners(t);let{count:r}=this.#t;const o=e;if("object"==typeof o.__signal_exit_emitter__&&"number"==typeof o.__signal_exit_emitter__.count&&(r+=o.__signal_exit_emitter__.count),n.length===r){this.unload();const n=this.#t.emit("exit",null,t),r="SIGHUP"===t?this.#e:t;n||e.kill(e.pid,r)}};this.#o=e.reallyExit,this.#r=e.emit}onExit(e,t){if(!we(this.#n))return()=>{};!1===this.#i&&this.load();const n=t?.alwaysLast?"afterExit":"exit";return this.#t.on(n,e),()=>{this.#t.removeListener(n,e),0===this.#t.listeners.exit.length&&0===this.#t.listeners.afterExit.length&&this.unload()}}load(){if(!this.#i){this.#i=!0,this.#t.count+=1;for(const e of Re)try{const t=this.#s[e];t&&this.#n.on(e,t)}catch(e){}this.#n.emit=(e,...t)=>this.#a(e,...t),this.#n.reallyExit=e=>this.#c(e)}}unload(){this.#i&&(this.#i=!1,Re.forEach(e=>{const t=this.#s[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#n.removeListener(e,t)}catch(e){}}),this.#n.emit=this.#r,this.#n.reallyExit=this.#o,this.#t.count-=1)}#c(e){return we(this.#n)?(this.#n.exitCode=e||0,this.#t.emit("exit",this.#n.exitCode,null),this.#o.call(this.#n,this.#n.exitCode)):0}#a(e,...t){const n=this.#r;if("exit"===e&&we(this.#n)){"number"==typeof t[0]&&(this.#n.exitCode=t[0]);const r=n.call(this.#n,e,...t);return this.#t.emit("exit",this.#n.exitCode,null),r}return n.call(this.#n,e,...t)}}(Pe):new class extends Ue{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,F(re());var Le=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Le,e)]);var Oe=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Be=/^[\w.-]+$/,Ne=c.debuglog("execa").enabled,De=(e,t)=>String(e).padStart(t,"0"),je=(e,t,n={})=>{const r=fe.default._parse(e,t,n);return e=r.command,t=r.args,(n={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(n=r.options).cwd||C.default.cwd(),execPath:C.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Ne,...n}).env=(({env:e,extendEnv:t,preferLocal:n,localDir:r,execPath:o})=>{const i=t?{...C.default.env,...e}:e;return n?(({env:e=C.default.env,...t}={})=>{const n=me({env:e={...e}});return t.path=e[n],e[n]=(({cwd:e=C.default.cwd(),path:t=C.default.env[me()],preferLocal:n=!0,execPath:r=C.default.execPath,addExecPath:o=!0}={})=>{const i=e instanceof URL?s.fileURLToPath(e):e,a=w.default.resolve(i),c=[];return n&&((e,t)=>{let n;for(;n!==t;)e.push(w.default.join(t,"node_modules/.bin")),n=t,t=w.default.resolve(t,"..")})(c,a),o&&((e,t,n)=>{const r=t instanceof URL?s.fileURLToPath(t):t;e.push(w.default.resolve(n,r,".."))})(c,r,a),[...c,t].join(w.default.delimiter)})(t),e})({env:i,cwd:r,execPath:o}):i})(n),n.stdio=(e=>{if(!e)return;const{stdio:t}=e;if(void 0===t)return ve.map(t=>e[t]);if((e=>ve.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${ve.map(e=>`\`${e}\``).join(", ")}`);if("string"==typeof t)return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);const n=Math.max(t.length,ve.length);return Array.from({length:n},(e,n)=>t[n])})(n),"win32"===C.default.platform&&"cmd"===w.default.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:n,parsed:r}},ke=(e,n,r)=>"string"==typeof n||t.Buffer.isBuffer(n)?e.stripFinalNewline?function(e){const t="string"==typeof e?"\n":"\n".charCodeAt(),n="string"==typeof e?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===n&&(e=e.slice(0,-1)),e}(n):n:void 0===r?void 0:"";function Me(e,t,n){const r=je(e,t,n),o=((e,t)=>Oe(e,t).join(" "))(e,t),s=((e,t)=>Oe(e,t).map(e=>(e=>"string"!=typeof e||Be.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&C.default.stderr.write(`[${(()=>{const e=new Date;return`${De(e.getHours(),2)}:${De(e.getMinutes(),2)}:${De(e.getSeconds(),2)}.${De(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(s,r.options);const i=(e=>{const t=(({input:e,inputFile:t})=>"string"!=typeof t?e:((e=>{if(void 0!==e)throw new TypeError("The `input` and `inputFile` options cannot be both set.")})(e),a.readFileSync(t)))(e);if(null!==(n=t)&&"object"==typeof n&&"function"==typeof n.pipe)throw new TypeError("The `input` option cannot be a stream in sync mode");var n;return t})(r.options);let c;try{c=S.default.spawnSync(r.file,r.args,{...r.options,input:i})}catch(e){throw Te({error:e,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1})}const l=ke(r.options,c.stdout,c.error),d=ke(r.options,c.stderr,c.error);if(c.error||0!==c.status||null!==c.signal){const e=Te({stdout:l,stderr:d,error:c.error,signal:c.signal,exitCode:c.status,command:o,escapedCommand:s,parsed:r,timedOut:c.error&&"ETIMEDOUT"===c.error.code,isCanceled:!1,killed:null!==c.signal});if(!r.options.reject)return e;throw e}return{command:o,escapedCommand:s,exitCode:0,stdout:l,stderr:d,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}function $e(e){try{return Me("git",["rev-parse","HEAD"],e).stdout}catch{return}}function He(e){try{const t=Me("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=Me("git",["show","-s","--pretty=%d","HEAD"],e).stdout.replace(/^\(|\)$/g,"").split(", ").find(e=>e.startsWith("origin/"));return t?t.match(/^origin\/(?<branch>.+)/)[1]:void 0}return t}catch{return}}var Ge=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,Fe=/^\/(.*)\.git$/;function ze(e){if(e){if(e.match(Ge))return e.replace(Ge,"$1");try{return new URL(e).pathname.replace(Fe,"$1")}catch{return}}}var Ye={detect:({env:e})=>Boolean(e.BUILDKITE),configuration({env:e}){const t="false"===e.BUILDKITE_PULL_REQUEST?void 0:e.BUILDKITE_PULL_REQUEST,n=Boolean(t);return{name:"Buildkite",service:"buildkite",build:e.BUILDKITE_BUILD_NUMBER,buildUrl:e.BUILDKITE_BUILD_URL,commit:e.BUILDKITE_COMMIT,tag:e.BUILDKITE_TAG,branch:n?e.BUILDKITE_PULL_REQUEST_BASE_BRANCH:e.BUILDKITE_BRANCH,slug:ze(e.BUILDKITE_REPO),pr:t,isPr:n,prBranch:n?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},Ke={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||ie(e.CIRCLE_PULL_REQUEST||e.CI_PULL_REQUEST),n=Boolean(t);return{name:"CircleCI",service:"circleci",build:e.CIRCLE_BUILD_NUM,buildUrl:e.CIRCLE_BUILD_URL,job:`${e.CIRCLE_BUILD_NUM}.${e.CIRCLE_NODE_INDEX}`,commit:e.CIRCLE_SHA1,tag:e.CIRCLE_TAG,branch:n?void 0:e.CIRCLE_BRANCH,pr:t,isPr:n,prBranch:n?e.CIRCLE_BRANCH:void 0,slug:`${e.CIRCLE_PROJECT_USERNAME}/${e.CIRCLE_PROJECT_REPONAME}`}}},Ve="https://cirrus-ci.com",We={detect:({env:e})=>Boolean(e.CIRRUS_CI),configuration({env:e}){const t=e.CIRRUS_PR,n=Boolean(t);return{name:"Cirrus CI",service:"cirrus",commit:e.CIRRUS_CHANGE_IN_REPO,tag:e.CIRRUS_TAG,build:e.CIRRUS_BUILD_ID,buildUrl:`${Ve}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${Ve}/task/${e.CIRRUS_TASK_ID}`,branch:n?e.CIRRUS_BASE_BRANCH:e.CIRRUS_BRANCH,pr:t,isPr:n,prBranch:n?e.CIRRUS_BRANCH:void 0,slug:e.CIRRUS_REPO_FULL_NAME,root:e.CIRRUS_WORKING_DIR}}},qe={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:$e({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:He({env:e,cwd:t}),buildUrl:`https://console.aws.amazon.com/codebuild/home?region=${e.AWS_REGION}#/builds/${e.CODEBUILD_BUILD_ID}/view/new`,root:e.PWD})},Je={detect:({env:e})=>Boolean(e.CF_BUILD_ID),configuration({env:e}){const t=e.CF_PULL_REQUEST_NUMBER,n=Boolean(t);return{name:"Codefresh",service:"codefresh",commit:e.CF_REVISION,build:e.CF_BUILD_ID,buildUrl:e.CF_BUILD_URL,branch:n?e.CF_PULL_REQUEST_TARGET:e.CF_BRANCH,pr:t,isPr:n,prBranch:n?e.CF_BRANCH:void 0,slug:`${e.CF_REPO_OWNER}/${e.CF_REPO_NAME}`,root:e.CF_VOLUME_PATH}}},Xe={detect:({env:e})=>Boolean(e.DRONE),configuration({env:e}){const t="pull_request"===e.DRONE_BUILD_EVENT;return{name:"Drone",service:"drone",commit:e.DRONE_COMMIT_SHA,tag:e.DRONE_TAG,build:e.DRONE_BUILD_NUMBER,buildUrl:e.DRONE_BUILD_LINK,branch:t?e.DRONE_TARGET_BRANCH:e.DRONE_BRANCH,job:e.DRONE_JOB_NUMBER,jobUrl:e.DRONE_BUILD_LINK,pr:e.DRONE_PULL_REQUEST,isPr:t,prBranch:t?e.DRONE_SOURCE_BRANCH:void 0,slug:`${e.DRONE_REPO_OWNER}/${e.DRONE_REPO_NAME}`,root:e.DRONE_WORKSPACE}}},Qe=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(a.readFileSync(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?ae(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},Ze={detect:({env:e})=>Boolean(e.GITHUB_ACTIONS),configuration({env:e,cwd:t}){const n="pull_request"===e.GITHUB_EVENT_NAME||"pull_request_target"===e.GITHUB_EVENT_NAME,r=ae("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(a.readFileSync(e.GITHUB_EVENT_PATH,"utf-8")):void 0;return t&&t.pull_request?t.pull_request.number:void 0})(e)}/merge`:e.GITHUB_REF);return{name:"GitHub Actions",service:"github",commit:e.GITHUB_SHA,build:e.GITHUB_RUN_ID,buildUrl:`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`,isPr:n,branch:r,prBranch:n?r:void 0,slug:e.GITHUB_REPOSITORY,root:e.GITHUB_WORKSPACE,...n?Qe({env:e}):void 0}}},et={detect:({env:e})=>Boolean(e.GITLAB_CI),configuration({env:e}){const t=e.CI_MERGE_REQUEST_ID,n=Boolean(t);return{name:"GitLab CI/CD",service:"gitlab",commit:e.CI_COMMIT_SHA,tag:e.CI_COMMIT_TAG,build:e.CI_PIPELINE_ID,buildUrl:`${e.CI_PROJECT_URL}/pipelines/${e.CI_PIPELINE_ID}`,job:e.CI_JOB_ID,jobUrl:`${e.CI_PROJECT_URL}/-/jobs/${e.CI_JOB_ID}`,branch:n?e.CI_MERGE_REQUEST_TARGET_BRANCH_NAME:e.CI_COMMIT_REF_NAME,pr:t,isPr:n,prBranch:e.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME,slug:e.CI_PROJECT_PATH,root:e.CI_PROJECT_DIR}}},tt={detect:({env:e})=>Boolean(e.JENKINS_URL),configuration({env:e,cwd:t}){const n=e.ghprbPullId||e.gitlabMergeRequestId||e.CHANGE_ID,r=Boolean(n),o=e.GIT_LOCAL_BRANCH||e.GIT_BRANCH||e.gitlabBranch||e.BRANCH_NAME;return{name:"Jenkins",service:"jenkins",commit:e.ghprbActualCommit||e.GIT_COMMIT||$e({env:e,cwd:t}),branch:r?e.ghprbTargetBranch||e.gitlabTargetBranch:o,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,root:e.WORKSPACE,pr:n,isPr:r,prBranch:r?e.ghprbSourceBranch||e.gitlabSourceBranch||o:void 0}}},nt={detect:({env:e})=>"true"===e.NETLIFY,configuration({env:e}){const t="true"===e.PULL_REQUEST;return{name:"Netlify",service:"netlify",commit:e.COMMIT_REF,build:e.DEPLOY_ID,buildUrl:`https://app.netlify.com/sites/${e.SITE_NAME}/deploys/${e.DEPLOY_ID}`,branch:t?void 0:e.HEAD,pr:e.REVIEW_ID,isPr:t,prBranch:t?e.HEAD:void 0,slug:e.REPOSITORY_URL.match(/[^/:]+\/[^/]+?$/)[0],root:e.PWD}}},rt={detect:({env:e})=>Boolean(e.DISTELLI_APPNAME),configuration:({env:e})=>({name:"Puppet",service:"puppet",build:e.DISTELLI_BUILDNUM,buildUrl:e.DISTELLI_RELEASE,commit:e.DISTELLI_RELREVISION,branch:e.DISTELLI_RELBRANCH,root:e.DISTELLI_INSTALLHOME})},ot={detect:({env:e})=>Boolean(e.SAILCI),configuration({env:e}){const t=e.SAIL_PULL_REQUEST_NUMBER,n=Boolean(t);return{name:"Sail CI",service:"sail",commit:e.SAIL_COMMIT_SHA,branch:n?void 0:e.SAIL_COMMIT_BRANCH,pr:t,isPr:n,slug:`${e.SAIL_REPO_OWNER}/${e.SAIL_REPO_NAME}`,root:e.SAIL_CLONE_DIR}}},st={detect:({env:e})=>Boolean(e.SCREWDRIVER),configuration({env:e}){const t=e.SD_PULL_REQUEST,n=Boolean(t);return{name:"Screwdriver.cd",service:"screwdriver",branch:n?e.PR_BASE_BRANCH_NAME:e.GIT_BRANCH,prBranch:n?e.PR_BRANCH_NAME:void 0,commit:e.SD_BUILD_SHA,build:e.SD_BUILD_ID,buildUrl:e.SD_UI_BUILD_URL,job:e.SD_JOB_ID,pr:t,isPr:n,slug:e.SD_PIPELINE_NAME,root:e.SD_ROOT_DIR}}},it={detect:({env:e})=>Boolean(e.SCRUTINIZER),configuration({env:e}){const t=e.SCRUTINIZER_PR_NUMBER,n=Boolean(t);return{name:"Scrutinizer",service:"scrutinizer",commit:e.SCRUTINIZER_SHA1,build:e.SCRUTINIZER_INSPECTION_UUID,branch:e.SCRUTINIZER_BRANCH,pr:t,isPr:n,prBranch:e.SCRUTINIZER_PR_SOURCE_BRANCH}}},at={detect:({env:e})=>Boolean(e.SEMAPHORE),configuration({env:e,cwd:t}){const n=e.SEMAPHORE_GIT_PR_NUMBER||e.PULL_REQUEST_NUMBER,r=Boolean(n);return{name:"Semaphore",service:"semaphore",commit:e.SEMAPHORE_GIT_SHA||$e({env:e,cwd:t}),tag:e.SEMAPHORE_GIT_TAG_NAME,build:e.SEMAPHORE_JOB_ID||e.SEMAPHORE_BUILD_NUMBER,branch:e.SEMAPHORE_GIT_BRANCH||(r?void 0:e.BRANCH_NAME),pr:n,isPr:r,prBranch:e.SEMAPHORE_GIT_PR_BRANCH||(r?e.BRANCH_NAME:void 0),slug:e.SEMAPHORE_GIT_REPO_SLUG||e.SEMAPHORE_REPO_SLUG,root:e.SEMAPHORE_GIT_DIR||e.SEMAPHORE_PROJECT_DIR}}},ct={detect:({env:e})=>Boolean(e.SHIPPABLE),configuration({env:e}){const t="true"===e.IS_PULL_REQUEST?e.PULL_REQUEST:void 0,n=Boolean(t);return{name:"Shippable",service:"shippable",commit:e.COMMIT,tag:e.GIT_TAG_NAME,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,branch:n?e.BASE_BRANCH:e.BRANCH,job:e.JOB_NUMBER,pr:t,isPr:n,prBranch:n?e.HEAD_BRANCH:void 0,slug:e.SHIPPABLE_REPO_SLUG,root:e.SHIPPABLE_BUILD_DIR}}},lt=F(oe()),dt={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},ut=e=>{try{return lt.default.of(e)}catch{return}},pt=({env:e,cwd:t})=>{const n=e.TEAMCITY_BUILD_PROPERTIES_FILE?ut(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,r=n?n.get("teamcity.configuration.properties.file"):void 0,o=r?ut(r):r;return Object.fromEntries(Object.keys(dt).map(r=>[r,(n?n.get(dt[r]):void 0)||(o?o.get(dt[r]):void 0)||("branch"===r?He({env:e,cwd:t}):void 0)]))},ft={appveyor:se,azurePipelines:ce,bamboo:le,bitbucket:de,bitrise:ue,buddy:pe,buildkite:Ye,circleci:Ke,cirrus:We,cloudflarePages:{detect:({env:e})=>"1"===e.CF_PAGES,configuration:({env:e})=>({name:"Cloudflare Pages",service:"cloudflarePages",commit:e.CF_PAGES_COMMIT_SHA,branch:e.CF_PAGES_BRANCH,root:e.PWD})},codebuild:qe,codefresh:Je,codeship:{detect:({env:e})=>e.CI_NAME&&"codeship"===e.CI_NAME,configuration:({env:e})=>({name:"Codeship",service:"codeship",build:e.CI_BUILD_NUMBER,buildUrl:e.CI_BUILD_URL,commit:e.CI_COMMIT_ID,branch:e.CI_BRANCH,slug:e.CI_REPO_NAME})},drone:Xe,github:Ze,gitlab:et,jenkins:tt,netlify:nt,puppet:rt,sail:ot,screwdriver:st,scrutinizer:it,semaphore:at,shippable:ct,teamcity:{detect:({env:e})=>Boolean(e.TEAMCITY_VERSION),configuration:({env:e,cwd:t})=>({name:"TeamCity",service:"teamcity",commit:e.BUILD_VCS_NUMBER,build:e.BUILD_NUMBER,slug:e.TEAMCITY_BUILDCONF_NAME,...pt({env:e,cwd:t})})},travis:{detect:({env:e})=>Boolean(e.TRAVIS),configuration({env:e}){const t="false"===e.TRAVIS_PULL_REQUEST?void 0:e.TRAVIS_PULL_REQUEST,n=Boolean(t);return{name:"Travis CI",service:"travis",commit:e.TRAVIS_COMMIT,tag:e.TRAVIS_TAG,build:e.TRAVIS_BUILD_NUMBER,buildUrl:e.TRAVIS_BUILD_WEB_URL,branch:e.TRAVIS_BRANCH,job:e.TRAVIS_JOB_NUMBER,jobUrl:e.TRAVIS_JOB_WEB_URL,pr:t,isPr:n,prBranch:e.TRAVIS_PULL_REQUEST_BRANCH,slug:e.TRAVIS_REPO_SLUG,root:e.TRAVIS_BUILD_DIR}}},vela:{detect:({env:e})=>Boolean(e.VELA),configuration({env:e}){const t="pull_request"===e.VELA_BUILD_EVENT;return{name:"Vela",service:"vela",branch:t?e.VELA_PULL_REQUEST_TARGET:e.VELA_BUILD_BRANCH,commit:e.VELA_BUILD_COMMIT,tag:e.VELA_BUILD_TAG,build:e.VELA_BUILD_NUMBER,buildUrl:e.VELA_BUILD_LINK,job:void 0,jobUrl:void 0,isPr:t,pr:e.VELA_BUILD_PULL_REQUEST,prBranch:e.VELA_PULL_REQUEST_SOURCE,slug:e.VELA_REPO_FULL_NAME,root:e.VELA_BUILD_WORKSPACE}}},vercel:{detect:({env:e})=>Boolean(e.VERCEL)||Boolean(e.NOW_GITHUB_DEPLOYMENT),configuration({env:e}){const t="Vercel",n="vercel";return e.VERCEL?{name:t,service:n,commit:e.VERCEL_GIT_COMMIT_SHA,branch:e.VERCEL_GIT_COMMIT_REF,slug:`${e.VERCEL_GIT_REPO_OWNER}/${e.VERCEL_GIT_REPO_SLUG}`}:{name:t,service:n,commit:e.NOW_GITHUB_COMMIT_SHA,branch:e.NOW_GITHUB_COMMIT_REF,slug:`${e.NOW_GITHUB_ORG}/${e.NOW_GITHUB_REPO}`}}},wercker:{detect:({env:e})=>Boolean(e.WERCKER_MAIN_PIPELINE_STARTED),configuration:({env:e})=>({name:"Wercker",service:"wercker",commit:e.WERCKER_GIT_COMMIT,build:e.WERCKER_MAIN_PIPELINE_STARTED,buildUrl:e.WERCKER_RUN_URL,branch:e.WERCKER_GIT_BRANCH,slug:`${e.WERCKER_GIT_OWNER}/${e.WERCKER_GIT_REPOSITORY}`,root:e.WERCKER_ROOT})},woodpecker:{detect:({env:e})=>e.CI&&"woodpecker"===e.CI,configuration({env:e}){const t="pull_request"===e.CI_PIPELINE_EVENT;return{name:"Woodpecker CI",service:"woodpecker",commit:e.CI_COMMIT_SHA,tag:e.CI_COMMIT_TAG,build:e.CI_PIPELINE_NUMBER,buildUrl:e.CI_PIPELINE_URL,branch:t?e.CI_COMMIT_TARGET_BRANCH:e.CI_COMMIT_BRANCH,job:e.CI_STEP_NUMBER,jobUrl:e.CI_STEP_URL,pr:e.CI_COMMIT_PULL_REQUEST,isPr:t,prBranch:t?e.CI_COMMIT_SOURCE_BRANCH:void 0,slug:`${e.CI_REPO_OWNER}/${e.CI_REPO_NAME}`,root:e.CI_WORKSPACE}}},jetbrainsSpace:{detect:({env:e})=>Boolean(e.JB_SPACE_EXECUTION_NUMBER),configuration({env:e}){const t=e.JB_SPACE_PROJECT_KEY,n=e.JB_SPACE_GIT_REPOSITORY_NAME;return{name:"JetBrains Space",service:"jetbrainsSpace",commit:e.JB_SPACE_GIT_REVISION,build:e.JB_SPACE_EXECUTION_NUMBER,branch:ae(e.JB_SPACE_GIT_BRANCH),slug:t&&n?`${t.toLowerCase()}/${n}`:void 0}}}},mt={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},ht=({allowReserved:e,explode:t,name:n,style:r,value:o})=>{if(!t){const t=(e?o:o.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(r));switch(r){case"label":return`.${t}`;case"matrix":return`;${n}=${t}`;case"simple":return t;default:return`${n}=${t}`}}const s=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),i=o.map(t=>"label"===r||"simple"===r?e?t:encodeURIComponent(t):_t({allowReserved:e,name:n,value:t})).join(s);return"label"===r||"matrix"===r?s+i:i},_t=({allowReserved:e,name:t,value:n})=>{if(null==n)return"";if("object"==typeof n)throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?n:encodeURIComponent(n)}`},gt=({allowReserved:e,explode:t,name:n,style:r,value:o,valueOnly:s})=>{if(o instanceof Date)return s?o.toISOString():`${n}=${o.toISOString()}`;if("deepObject"!==r&&!t){let t=[];Object.entries(o).forEach(([n,r])=>{t=[...t,n,e?r:encodeURIComponent(r)]});const s=t.join(",");switch(r){case"form":return`${n}=${s}`;case"label":return`.${s}`;case"matrix":return`;${n}=${s}`;default:return s}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),a=Object.entries(o).map(([t,o])=>_t({allowReserved:e,name:"deepObject"===r?`${n}[${t}]`:t,value:o})).join(i);return"label"===r||"matrix"===r?i+a:a},Et=/\{[^{}]+\}/g;function yt(e){const t=void 0!==e.body;return t&&e.bodySerializer?"serializedBody"in e?void 0!==e.serializedBody&&""!==e.serializedBody?e.serializedBody:null:""!==e.body?e.body:null:t?e.body:void 0}var It,bt=async(e,t)=>{const n="function"==typeof t?await t(e):t;if(n)return"bearer"===e.scheme?`Bearer ${n}`:"basic"===e.scheme?`Basic ${btoa(n)}`:n},Tt=({parameters:e={},...t}={})=>n=>{const r=[];if(n&&"object"==typeof n)for(const o in n){const s=n[o];if(null==s)continue;const i=e[o]||t;if(Array.isArray(s)){const e=ht({allowReserved:i.allowReserved,explode:!0,name:o,style:"form",value:s,...i.array});e&&r.push(e)}else if("object"==typeof s){const e=gt({allowReserved:i.allowReserved,explode:!0,name:o,style:"deepObject",value:s,...i.object});e&&r.push(e)}else{const e=_t({allowReserved:i.allowReserved,name:o,value:s});e&&r.push(e)}}return r.join("&")},vt=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),Rt=e=>(({baseUrl:e,path:t,query:n,querySerializer:r,url:o})=>{let s=(e??"")+(o.startsWith("/")?o:`/${o}`);t&&(s=(({path:e,url:t})=>{let n=t;const r=t.match(Et);if(r)for(const t of r){let r=!1,o=t.substring(1,t.length-1),s="simple";o.endsWith("*")&&(r=!0,o=o.substring(0,o.length-1)),o.startsWith(".")?(o=o.substring(1),s="label"):o.startsWith(";")&&(o=o.substring(1),s="matrix");const i=e[o];if(null==i)continue;if(Array.isArray(i)){n=n.replace(t,ht({explode:r,name:o,style:s,value:i}));continue}if("object"==typeof i){n=n.replace(t,gt({explode:r,name:o,style:s,value:i,valueOnly:!0}));continue}if("matrix"===s){n=n.replace(t,`;${_t({name:o,value:i})}`);continue}const a=encodeURIComponent("label"===s?`.${i}`:i);n=n.replace(t,a)}return n})({path:t,url:s}));let i=n?r(n):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(s+=`?${i}`),s})({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:Tt(e.querySerializer),url:e.url}),wt=(e,t)=>{const n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=Ct(e.headers,t.headers),n},St=e=>{const t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},Ct=(...e)=>{const t=new Headers;for(const n of e){if(!n)continue;const e=n instanceof Headers?St(n):Object.entries(n);for(const[n,r]of e)if(null===r)t.delete(n);else if(Array.isArray(r))for(const e of r)t.append(n,e);else void 0!==r&&t.set(n,"object"==typeof r?JSON.stringify(r):r)}return t},At=class{fns=[];clear(){this.fns=[]}eject(e){const t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){const t=this.getInterceptorIndex(e);return Boolean(this.fns[t])}getInterceptorIndex(e){return"number"==typeof e?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){const n=this.getInterceptorIndex(e);return!!this.fns[n]&&(this.fns[n]=t,e)}use(e){return this.fns.push(e),this.fns.length-1}},xt=Tt({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Ut={"Content-Type":"application/json"},Pt=(e={})=>({...mt,headers:Ut,parseAs:"auto",querySerializer:xt,...e}),Lt=(e={})=>{let t=wt(Pt(),e);const n=()=>({...t}),r={error:new At,request:new At,response:new At},o=async e=>{const n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:Ct(t.headers,e.headers),serializedBody:void 0};return n.security&&await(async({security:e,...t})=>{for(const n of e){if(vt(t,n.name))continue;const e=await bt(n,t.auth);if(!e)continue;const r=n.name??"Authorization";switch(n.in){case"query":t.query||(t.query={}),t.query[r]=e;break;case"cookie":t.headers.append("Cookie",`${r}=${e}`);break;default:t.headers.set(r,e)}}})({...n,security:n.security}),n.requestValidator&&await n.requestValidator(n),void 0!==n.body&&n.bodySerializer&&(n.serializedBody=n.bodySerializer(n.body)),void 0!==n.body&&""!==n.serializedBody||n.headers.delete("Content-Type"),{opts:n,url:Rt(n)}},s=async e=>{const{opts:t,url:n}=await o(e),s={redirect:"follow",...t,body:yt(t)};let i=new Request(n,s);for(const e of r.request.fns)e&&(i=await e(i,t));const a=t.fetch;let c;try{c=await a(i)}catch(e){let n=e;for(const o of r.error.fns)o&&(n=await o(e,void 0,i,t));if(n=n||{},t.throwOnError)throw n;return"data"===t.responseStyle?void 0:{error:n,request:i,response:void 0}}for(const e of r.response.fns)e&&(c=await e(c,i,t));const l={request:i,response:c};if(c.ok){const e=("auto"===t.parseAs?(e=>{if(!e)return"stream";const t=e.split(";")[0]?.trim();return t?t.startsWith("application/json")||t.endsWith("+json")?"json":"multipart/form-data"===t?"formData":["application/","audio/","image/","video/"].some(e=>t.startsWith(e))?"blob":t.startsWith("text/")?"text":void 0:void 0})(c.headers.get("Content-Type")):t.parseAs)??"json";if(204===c.status||"0"===c.headers.get("Content-Length")){let n;switch(e){case"arrayBuffer":case"blob":case"text":n=await c[e]();break;case"formData":n=new FormData;break;case"stream":n=c.body;break;default:n={}}return"data"===t.responseStyle?n:{data:n,...l}}let n;switch(e){case"arrayBuffer":case"blob":case"formData":case"json":case"text":n=await c[e]();break;case"stream":return"data"===t.responseStyle?c.body:{data:c.body,...l}}return"json"===e&&(t.responseValidator&&await t.responseValidator(n),t.responseTransformer&&(n=await t.responseTransformer(n))),"data"===t.responseStyle?n:{data:n,...l}}const d=await c.text();let u;try{u=JSON.parse(d)}catch{}const p=u??d;let f=p;for(const e of r.error.fns)e&&(f=await e(p,c,i,t));if(f=f||{},t.throwOnError)throw f;return"data"===t.responseStyle?void 0:{error:f,...l}},i=e=>t=>s({...t,method:e}),a=e=>async t=>{const{opts:n,url:s}=await o(t);return(({onRequest:e,onSseError:t,onSseEvent:n,responseTransformer:r,responseValidator:o,sseDefaultRetryDelay:s,sseMaxRetryAttempts:i,sseMaxRetryDelay:a,sseSleepFn:c,url:l,...d})=>{let u;const p=c??(e=>new Promise(t=>setTimeout(t,e))),f=async function*(){let c=s??3e3,f=0;const m=d.signal??(new AbortController).signal;for(;!m.aborted;){f++;const s=d.headers instanceof Headers?d.headers:new Headers(d.headers);void 0!==u&&s.set("Last-Event-ID",u);try{const t={redirect:"follow",...d,body:d.serializedBody,headers:s,signal:m};let i=new Request(l,t);e&&(i=await e(l,t));const a=d.fetch??globalThis.fetch,p=await a(i);if(!p.ok)throw new Error(`SSE failed: ${p.status} ${p.statusText}`);if(!p.body)throw new Error("No body in SSE response");const f=p.body.pipeThrough(new TextDecoderStream).getReader();let h="";const _=()=>{try{f.cancel()}catch{}};m.addEventListener("abort",_);try{for(;;){const{done:e,value:t}=await f.read();if(e)break;h+=t;const s=h.split("\n\n");h=s.pop()??"";for(const e of s){const t=e.split("\n"),s=[];let i,a;for(const e of t)if(e.startsWith("data:"))s.push(e.replace(/^data:\s*/,""));else if(e.startsWith("event:"))i=e.replace(/^event:\s*/,"");else if(e.startsWith("id:"))u=e.replace(/^id:\s*/,"");else if(e.startsWith("retry:")){const t=Number.parseInt(e.replace(/^retry:\s*/,""),10);Number.isNaN(t)||(c=t)}let l=!1;if(s.length){const e=s.join("\n");try{a=JSON.parse(e),l=!0}catch{a=e}}l&&(o&&await o(a),r&&(a=await r(a))),n?.({data:a,event:i,id:u,retry:c}),s.length&&(yield a)}}}finally{m.removeEventListener("abort",_),f.releaseLock()}break}catch(e){if(t?.(e),void 0!==i&&f>=i)break;const n=Math.min(c*2**(f-1),a??3e4);await p(n)}}}();return{stream:f}})({...n,body:n.body,headers:n.headers,method:e,onRequest:async(e,t)=>{let o=new Request(e,t);for(const e of r.request.fns)e&&(o=await e(o,n));return o},url:s})};return{buildUrl:Rt,connect:i("CONNECT"),delete:i("DELETE"),get:i("GET"),getConfig:n,head:i("HEAD"),interceptors:r,options:i("OPTIONS"),patch:i("PATCH"),post:i("POST"),put:i("PUT"),request:s,setConfig:e=>(t=wt(t,e),n()),sse:{connect:a("CONNECT"),delete:a("DELETE"),get:a("GET"),head:a("HEAD"),options:a("OPTIONS"),patch:a("PATCH"),post:a("POST"),put:a("PUT"),trace:a("TRACE")},trace:i("TRACE")}},Ot=Lt(Pt({baseUrl:"https://api.stably.ai"})),Bt="x-stably-org-id",Nt="4.2.1",Dt=process.env.STABLY_API_URL||"https://api.stably.ai",jt=process.env.AUTH_URL||"https://auth.stably.ai",kt=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",Mt=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",$t="http://localhost:9876/auth/callback",Ht=()=>It||(It=Lt(Pt({baseUrl:Dt,headers:{"X-STABLY-CLI-VERSION":Nt,"X-STABLY-SOURCE":"cli"}}))),Gt=async(e,t)=>{const n=await(r={body:{accessToken:e,orgId:t},client:Ht()},(r.client??Ot).post({url:"/internal/v1/cli/exchange-token",...r,headers:{"Content-Type":"application/json",...r.headers}}));var r;if(401===n.response.status)throw new Error("Invalid or expired access token");if(403===n.response.status)throw new Error("You do not have access to this organization");if(n.error)throw new Error(`Failed to exchange token: ${n.response.status}`);return n.data},Ft=m.z.object({org_id:m.z.string(),org_name:m.z.string()}),zt=m.z.object({email:m.z.string(),org_id_to_org_member_info:m.z.record(m.z.string(),Ft).optional(),org_member_info:Ft.optional(),user_id:m.z.string()});m.z.object({email:m.z.string(),firstName:m.z.string().optional(),lastName:m.z.string().optional(),organizations:m.z.array(m.z.object({id:m.z.string(),name:m.z.string()})),userId:m.z.string()});var Yt=e=>{const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const n=t[1].replace(/-/g,"+").replace(/_/g,"/"),r=Buffer.from(n,"base64").toString("utf-8");return JSON.parse(r)},Kt=e=>{try{const t=zt.parse(Yt(e)),n=t.org_id_to_org_member_info?Object.entries(t.org_id_to_org_member_info).map(([e,t])=>({id:e,name:t.org_name})):t.org_member_info?[{id:t.org_member_info.org_id,name:t.org_member_info.org_name}]:[];return{email:t.email,organizations:n,userId:t.user_id}}catch(e){throw new Error(`Failed to decode token: ${e instanceof Error?e.message:"Unknown error"}`)}},Vt=w.default.join(A.default.homedir(),".stably"),Wt=w.default.join(Vt,"auth.json"),qt=".stably",Jt="project.json",Xt=P.default.object({accessToken:P.default.string(),expiresAt:P.default.number(),idToken:P.default.string().optional(),refreshToken:P.default.string()}),Qt=P.default.object({orgId:P.default.string(),orgName:P.default.string(),projectId:P.default.string(),projectName:P.default.string()}),Zt=async()=>{try{const e=await h.readFile(Wt,"utf-8");return Xt.parse(JSON.parse(e))}catch{return}},en=async e=>{await h.mkdir(Vt,{recursive:!0}),await h.writeFile(Wt,JSON.stringify(e,null,2),{mode:384})},tn=async()=>{try{await h.unlink(Wt)}catch{}},nn=async e=>{let t=e;const{root:n}=w.default.parse(t);for(;t!==n;){const e=w.default.join(t,qt);try{return await h.access(e),e}catch{t=w.default.dirname(t)}}},rn=async()=>{try{const e=await nn(process.cwd());if(!e)return;const t=w.default.join(e,Jt),n=await h.readFile(t,"utf-8");return Qt.parse(JSON.parse(n))}catch{return}},on=async()=>{try{const e=await nn(process.cwd());e&&await h.unlink(w.default.join(e,Jt))}catch{}},sn=e=>Date.now()>=e.expiresAt-3e5,an=async e=>{const t=new URLSearchParams({client_id:kt,grant_type:"refresh_token",refresh_token:e}),n=await fetch(`${jt}/propelauth/oauth/token`,{body:t.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!n.ok)throw new Error(`Token refresh failed: ${n.status}`);const r=await n.json();return{accessToken:r.access_token,expiresAt:Date.now()+1e3*r.expires_in,refreshToken:r.refresh_token}},cn=e=>`\n<!DOCTYPE html>\n<html>\n<head>\n <title>Authentication Failed Stably CLI</title>\n <style>\n * { box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: #000;\n color: #fafafa;\n }\n .container {\n text-align: center;\n padding: 48px;\n max-width: 400px;\n }\n .icon {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: #ef4444;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 24px; height: 24px; }\n .title {\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 8px;\n letter-spacing: -0.5px;\n }\n .subtitle {\n color: #888;\n font-size: 14px;\n margin: 0 0 32px;\n line-height: 1.5;\n }\n .error-box {\n background: rgba(239, 68, 68, 0.1);\n border: 1px solid rgba(239, 68, 68, 0.3);\n border-radius: 8px;\n padding: 16px;\n margin-bottom: 24px;\n }\n .error-label {\n font-size: 11px;\n font-weight: 600;\n color: #ef4444;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 8px;\n }\n .error-message {\n font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;\n font-size: 13px;\n color: #fafafa;\n word-break: break-word;\n }\n .hint {\n color: #666;\n font-size: 13px;\n }\n .hint code {\n background: #111;\n border: 1px solid #333;\n border-radius: 4px;\n padding: 2px 6px;\n font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;\n font-size: 12px;\n color: #888;\n }\n .brand {\n margin-top: 32px;\n font-size: 12px;\n color: #444;\n letter-spacing: 0.5px;\n }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="icon">\n <svg fill="none" stroke="#000" stroke-width="3" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>\n </svg>\n </div>\n <h1 class="title">Authentication Failed</h1>\n <p class="subtitle">Something went wrong during login.</p>\n <div class="error-box">\n <div class="error-label">Error</div>\n <div class="error-message">${e}</div>\n </div>\n <p class="hint">Run <code>stably login</code> to try again.</p>\n <div class="brand">STABLY</div>\n </div>\n</body>\n</html>\n`,ln=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(n)},dn=(e,t)=>{const n=new URLSearchParams({client_id:kt,code_challenge:e,code_challenge_method:"S256",redirect_uri:$t,response_type:"code",state:t});return`${jt}/propelauth/oauth/authorize?${n.toString()}`},un=async e=>{const t=u.spinner();let n;t.start("Loading user info...");try{n=Kt(e.accessToken),t.stop(U.default.green(`✓ Logged in as ${U.default.cyan(n.email)}`))}catch(e){t.stop(U.default.red("✗ Failed to load user info"));const n=e instanceof Error?e.message:"Unknown error";return u.log.error(n),{success:!1}}const r=await(async e=>{if(0===e.length)return void u.log.error("You don't belong to any organizations.");if(1===e.length)return u.log.info(`Using organization: ${U.default.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return u.log.info(`Auto-selecting organization: ${U.default.cyan(e[0].name)}`),e[0];const t=await u.select({message:"Select an organization",options:e.map(e=>({label:e.name,value:e.id}))});return u.isCancel(t)?void 0:e.find(e=>e.id===t)})(n.organizations);if(!r)return u.log.warn("Organization selection cancelled."),{success:!1};let o;t.start("Getting org credentials...");try{const n=await Gt(e.accessToken,r.id);o={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(U.default.green("✓ Credentials obtained"))}catch(e){t.stop(U.default.red("✗ Failed to get org credentials"));const n=e instanceof Error?e.message:"Unknown error";return u.log.error(n),{success:!1}}const s=await(async(e,t)=>{const n=u.spinner();let r;n.start("Loading projects...");try{r=await(async({accessToken:e,orgId:t})=>{const n=await(r={auth:`Bearer ${e}`,client:Ht(),path:{orgId:t}},(r.client??Ot).get({security:[{name:"authorization",type:"apiKey"}],url:"/internal/v1/cli/orgs/{orgId}/projects",...r}));var r;if(401===n.response.status)throw new Error("Invalid or expired access token");if(403===n.response.status)throw new Error("You do not have access to this organization");if(n.error)throw new Error(`Failed to list projects: ${n.response.status}`);return n.data.projects})({accessToken:e,orgId:t}),n.stop(U.default.green("✓ Projects loaded"))}catch(e){n.stop(U.default.red("✗ Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void u.log.error(t)}if(0===r.length)return u.log.error("No projects found in this organization."),void u.log.info(`Create a project at ${U.default.underline(U.default.cyan("https://app.stably.ai"))}`);if(1===r.length)return u.log.info(`Using project: ${U.default.cyan(r[0].name)}`),r[0];if(!process.stdin.isTTY)return u.log.info(`Auto-selecting project: ${U.default.cyan(r[0].name)}`),r[0];const o=await u.select({message:"Select a project",options:r.map(e=>({label:e.name,value:e.id}))});return u.isCancel(o)?void 0:r.find(e=>e.id===o)})(o.accessToken,r.id);return s?(await(async e=>{const t=w.default.join(process.cwd(),qt),n=w.default.join(t,Jt);await h.mkdir(t,{recursive:!0}),await h.writeFile(n,JSON.stringify(e,null,2)),await(async e=>{const t=w.default.join(e,".gitignore");try{if((await h.readFile(t,"utf-8")).split("\n").some(e=>".stably"===e.trim()))return;await h.appendFile(t,"\n# Stably CLI\n.stably\n")}catch{await h.writeFile(t,"# Stably CLI\n.stably\n")}})(process.cwd())})({orgId:r.id,orgName:r.name,projectId:s.id,projectName:s.name}),u.log.info(U.default.dim("Linked this directory to your Stably project.")),{scopedTokens:o,success:!0}):(u.log.warn("Project selection cancelled."),{success:!1})},pn=async()=>{const e=await Zt();if(e){if(!sn(e)){if(await rn())return void u.outro(U.default.yellow("You are already logged in. Run `stably logout` first to log out."));u.log.info("You are logged in but haven't selected a project yet.");const t=await un(e);return void(t.success?(await en(t.scopedTokens),u.outro(U.default.green("Setup complete! You can now use Stably CLI."))):u.outro(U.default.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=u.spinner();t.start("Refreshing session...");try{const n=await an(e.refreshToken);t.stop(U.default.green("✓ Session refreshed"));const r=await rn();if(r){t.start("Getting org credentials...");try{const e=await Gt(n.accessToken,r.orgId),o={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:n.idToken,refreshToken:n.refreshToken};await en(o),t.stop(U.default.green("✓ Credentials obtained")),u.outro(U.default.green("Login successful"))}catch{await en(n),t.stop(U.default.yellow("Using full credentials")),u.outro(U.default.green("Login successful"))}}else{const e=await un(n);e.success?(await en(e.scopedTokens),u.outro(U.default.green("Setup complete! You can now use Stably CLI."))):u.outro(U.default.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(U.default.yellow("Session expired, proceeding with fresh login...")),await tn(),await on()}}const{authorizeUrl:t,waitForCallback:n}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:n}=(()=>{const e=B.default.randomBytes(32).toString("base64url"),t=(n=e,B.default.createHash("sha256").update(n).digest("base64url"));var n;const r=B.default.randomBytes(16).toString("base64url");return{authorizeUrl:dn(t,r),codeVerifier:e,state:r}})();return{authorizeUrl:e,waitForCallback:async()=>(async(e,t)=>{const n=await(r=e,new Promise((e,t)=>{const n=setTimeout(()=>{i.close(),e({error:"Login timed out",success:!1})},3e5),o=()=>{clearTimeout(n)},i=O.default.createServer((t,n)=>{const a=new s.URL(t.url||"","http://localhost:9876");if("/auth/callback"!==a.pathname)return n.writeHead(404),void n.end("Not found");const c=a.searchParams.get("code"),l=a.searchParams.get("state"),d=a.searchParams.get("error");return d?(ln(n,400,cn(d)),o(),i.close(),void e({error:d,success:!1})):c&&l?l!==r?(ln(n,400,cn("Invalid state parameter (possible CSRF attack)")),o(),i.close(),void e({error:"State mismatch",success:!1})):(ln(n,200,'\n<!DOCTYPE html>\n<html>\n<head>\n <title>Authenticated Stably CLI</title>\n <style>\n * { box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: #000;\n color: #fafafa;\n }\n .container {\n text-align: center;\n padding: 48px;\n max-width: 400px;\n }\n .icon {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: #22c55e;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 24px; height: 24px; }\n .title {\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 8px;\n letter-spacing: -0.5px;\n }\n .subtitle {\n color: #888;\n font-size: 14px;\n margin: 0 0 32px;\n line-height: 1.5;\n }\n .terminal {\n background: #111;\n border: 1px solid #333;\n border-radius: 8px;\n padding: 16px;\n text-align: left;\n font-family: \'SF Mono\', \'Fira Code\', \'Consolas\', monospace;\n font-size: 13px;\n }\n .terminal-header {\n display: flex;\n gap: 6px;\n margin-bottom: 12px;\n }\n .terminal-dot {\n width: 10px;\n height: 10px;\n border-radius: 50%;\n background: #333;\n }\n .terminal-line {\n color: #888;\n }\n .terminal-line .prompt { color: #888; }\n .terminal-line .cmd { color: #fafafa; }\n .terminal-line.success { color: #22c55e; }\n .brand {\n margin-top: 32px;\n font-size: 12px;\n color: #444;\n letter-spacing: 0.5px;\n }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="icon">\n <svg fill="none" stroke="#000" stroke-width="3" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>\n </svg>\n </div>\n <h1 class="title">Authenticated</h1>\n <p class="subtitle">You can close this tab and return to your terminal.</p>\n <div class="terminal">\n <div class="terminal-header">\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n </div>\n <div class="terminal-line"><span class="prompt">$</span> <span class="cmd">stably login</span></div>\n <div class="terminal-line success">Logged in successfully</div>\n </div>\n <div class="brand">STABLY</div>\n </div>\n</body>\n</html>\n'),o(),i.close(),void e({code:c,state:l,success:!0})):(ln(n,400,cn("Missing code or state parameter")),o(),i.close(),void e({error:"Missing code or state parameter",success:!1}))});i.on("error",e=>{o(),"EADDRINUSE"!==e.code?t(new Error(`Failed to start callback server: ${e.message}`)):t(new Error("Port 9876 is already in use. Please close the application using it and try again."))}),i.listen(9876)}));var r;if(!n.success)throw new Error(n.error);return(async(e,t)=>{const n=new URLSearchParams({client_id:kt,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:$t}),r=await fetch(`${jt}/propelauth/oauth/token`,{body:n.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!r.ok){const e=await r.text();throw new Error(`Token exchange failed: ${r.status} ${e}`)}const o=await r.json();return{accessToken:o.access_token,expiresAt:Date.now()+1e3*o.expires_in,idToken:o.id_token,refreshToken:o.refresh_token}})(n.code,t)})(n,t)}})();u.log.info("Opening browser for authentication..."),u.log.info(U.default.dim("If browser doesn't open, visit:")),u.log.info(U.default.underline(U.default.cyan(t)));try{await L.default(t)}catch{u.log.warn("Could not open browser automatically. Please open the URL above manually.")}const r=u.spinner();let o;r.start("Waiting for authentication...");try{o=await n(),r.stop(U.default.green("✓ Authentication successful"))}catch(e){r.stop(U.default.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";u.outro(U.default.red(`Login failed: ${t}`)),process.exit(1)}const i=await un(o);i.success?(await en(i.scopedTokens),u.outro(U.default.green("Setup complete! You can now use Stably CLI."))):(u.outro(U.default.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},fn=()=>{const e=process.env.STABLY_API_KEY,t=process.env.STABLY_PROJECT_ID;if(e&&t)return{apiKey:e,projectId:t}},mn=async()=>{const e=await Zt();if(e){if(!sn(e)){const t=await rn();if(t&&"full"===(e=>{try{const t=zt.parse(Yt(e));if(t.org_id_to_org_member_info)return"full";if(t.org_member_info)return"org"}catch{return"unknown"}return"unknown"})(e.accessToken))try{const n=await Gt(e.accessToken,t.orgId),r={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await en(r),r}catch{return e}return e}try{const t=await an(e.refreshToken),n=await rn();if(n)try{const e=await Gt(t.accessToken,n.orgId),r={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await en(r),r}catch{return await en(t),t}return await en(t),t}catch{return}}},hn=async(e={})=>{const t=fn();if(t)return{auth:t,type:"env"};let n=await mn(),r=n?await rn():void 0;const o=process.stdin.isTTY&&process.stdout.isTTY;if((!n||!r)&&e.autoLogin&&o){n?u.log.info("You are logged in but need to select an organization and project."):u.log.info("You are not logged in."),u.log.info("Press Enter to log in."),process.stdout.write(`${U.default.dim("Alternatively, set environment variables for an org API key:")}\n${U.default.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=f.createInterface({input:process.stdin,output:process.stdout});try{await e.question(U.default.dim("Press Enter to continue... "))}finally{e.close()}await pn(),n=await mn(),r=n?await rn():void 0}return n||(u.outro(U.default.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),r||(u.outro(U.default.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),{auth:{accessToken:n.accessToken,context:r},type:"oauth"}},_n=e=>e?{...process.env,...e}:process.env,gn=async()=>{const e=process.env.STABLY_API_KEY,t=process.env.STABLY_PROJECT_ID;if(e&&t)return{STABLY_API_KEY:e,STABLY_PROJECT_ID:t};const n=await(async()=>{const e=fn();if(e)return{auth:e,type:"env"};const t=await mn(),n=t?await rn():void 0;return t&&n?{auth:{accessToken:t.accessToken,context:n},type:"oauth"}:void 0})();if(!n)return;const r=t??(e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId)(n);if(!r)return;const o=e??("env"===n.type?n.auth.apiKey:await(async(e,t)=>{try{return(await(async({accessToken:e,projectId:t})=>{const n=await(r={auth:`Bearer ${e}`,client:Ht(),path:{projectId:t}},(r.client??Ot).post({security:[{name:"authorization",type:"apiKey"}],url:"/internal/v1/cli/projects/{projectId}/api-key",...r}));var r;if(401===n.response.status)throw new Error("Invalid or expired access token");if(403===n.response.status)throw new Error("You do not have access to this project");if(n.error)throw new Error(`Failed to get API key: ${n.response.status}`);return n.data})({accessToken:e,projectId:t})).apiKey}catch{return e}})(n.auth.accessToken,r));return o?{STABLY_API_KEY:o,STABLY_PROJECT_ID:r}:void 0},En=e=>e?{[Bt]:e}:void 0,yn=m.z.object({context:m.z.string().min(1)}),In=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},bn=e=>null!=e&&"object"==typeof e&&"tool_response"in e,Tn=e=>{if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.tool_response)?t.tool_response:void 0},vn=e=>{const t=Tn(e);if(t)return t.filter(In).map(e=>e.text).join("\n")||void 0},Rn=/\u001b\[[0-9;]*m/g,wn=e=>e.replace(Rn,""),Sn=/\$\{process\.env\.([A-Z_][A-Z0-9_]*)\}/g;function Cn({envVars:e}){return async t=>{if(!function(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}(t))return{decision:"approve"};const n=t.tool_input,r="string"==typeof n.text?n.text:void 0;if(!r)return{decision:"approve"};const o=r.replace(Sn,(t,n)=>{const r=e[n];return null!=r?r:t});return o===r?{decision:"approve"}:{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",reason:"Evaluated environment variable placeholders in browser text input.",updatedInput:{...n,text:o}}}}}function An({onResult:e}){return async t=>{if(!bn(t))return{decision:"approve"};const n=vn(t);if(!n)return{decision:"approve"};const r=function(e){const t=wn(e),n=t.split(/Running \d+ tests? using \d+ workers?/).at(-1)??t,r=parseInt(n.match(/(\d+)\s+passed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0"),o=parseInt(n.match(/(\d+)\s+failed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0");if(0===r&&0===o)return;const s=[r>0?`${r} test${1===r?"":"s"} passed ✓`:void 0,o>0?`${o} test${1===o?"":"s"} failed ✗`:void 0].filter(e=>void 0!==e).join(", ");if(0===o)return s;const i=n.split(/\n\s+\d+\)\s+\[id=/).slice(1).map(e=>e.match(/\n\s{4}((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/)?.[1]?.trim()).filter(e=>void 0!==e);return 0===i.length?s:`${s}\n${i.map(e=>` - ${e}`).join("\n")}`}(n);return r&&e(r),{decision:"approve"}}}function xn({onResult:e}){return async t=>{if(!bn(t))return{decision:"approve"};const n=vn(t);if(!n)return{decision:"approve"};const r=function(e){const t=wn(e);if(t.match(/### Paused on error:/)){const e=t.match(/### Paused on error:\s*\n((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/);return e?`Test paused on error - ${e[1].trim()}`:"Test paused on error"}const n=t.match(/(\d+)\s+passed/);if(n){const e=parseInt(n[1]);return`${e} test${1===e?"":"s"} passed ✓`}}(n);return r&&e(r),{decision:"approve"}}}var Un=class{queue=[];pendingResolve=void 0;done=!1;canSend=!0;[Symbol.asyncIterator](){return this}pushText(e){const t=e.trim();t&&!this.done&&(this.queue.push(t),this.maybeFlush())}allowNextTurn(){this.done||(this.canSend=!0,this.maybeFlush())}finish(){this.done=!0,this.pendingResolve&&(this.pendingResolve({done:!0,value:void 0}),this.pendingResolve=void 0)}maybeFlush(){if(!this.pendingResolve)return;if(!this.canSend)return;const e=this.queue.shift();if(void 0===e)return;const t={message:{content:[{text:e,type:"text"}],role:"user"},parent_tool_use_id:null,type:"user",session_id:""};this.canSend=!1,this.pendingResolve({done:!1,value:t}),this.pendingResolve=void 0}next(){return this.done?Promise.resolve({done:!0,value:void 0}):new Promise(e=>{this.pendingResolve=e,this.maybeFlush()})}},Pn=10240,Ln=async({defaultContent:e,fileName:t,filePath:n})=>{try{const e=(await h.stat(n)).size,r=await h.readFile(n,"utf-8"),o=Buffer.byteLength(r,"utf-8");if(o<=Pn)return r;const s=(e=>{const t=e.split("\n"),n=[];let r=!1,o=!1,s=0,i=!1;for(let e=0;e<t.length;e++){const a=t[e],c=a.trim();c.startsWith("/*")&&(r=!0),c.includes("*/")?r=!1:r||c.startsWith("//")&&!c.startsWith("///")||(c.startsWith("import ")||c.startsWith("export ")?(n.push(a),i=!0):i&&""===c?(n.push(a),i=!1):(i=!1,c.startsWith("type ")||c.startsWith("interface ")?n.push(a):c.startsWith("function ")||c.startsWith("const ")||c.startsWith("async function ")||c.startsWith("export function ")||c.startsWith("export const ")||c.startsWith("test.describe(")||c.startsWith("test(")?(n.push(a),o=!0,s=(a.match(/{/g)||[]).length-(a.match(/}/g)||[]).length,0===s&&(c.endsWith(";")||c.endsWith(","))&&(o=!1)):o?(s+=(a.match(/{/g)||[]).length,s-=(a.match(/}/g)||[]).length,0===s&&c.includes("}")?(n.push(a),o=!1):s>0&&" // ... implementation omitted ..."!==n.at(-1)&&n.push(" // ... implementation omitted ...")):c.match(/^[a-zA-Z_]+:/)&&n.push(a)))}return n.join("\n")})(r),i=Buffer.byteLength(s,"utf-8");return i<=Pn?s:s.slice(0,Pn)+`\n\n... [TRUNCATED: File "${t}" at ${n} was ${e} bytes (${o} bytes as UTF-8), reduced to ~${i} bytes of essential content, then truncated to 10240 bytes] ...`}catch(n){let r;if(n&&"object"==typeof n&&"code"in n){const e=n.code;"string"==typeof e&&(r=e)}return"ENOENT"!==r&&console.warn(`Failed to read ${t}: ${n}`),e}},On=async({defaultContent:e,dirName:t,dirPath:n})=>{try{const e=await h.readdir(n);return e.length>0?e.join("\n"):"(empty)"}catch(n){let r;if(n&&"object"==typeof n&&"code"in n){const e=n.code;"string"==typeof e&&(r=e)}return"ENOENT"!==r&&console.warn(`Failed to read ${t}: ${n}`),e}},Bn=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__test-doc-sync__"],Nn=["planner_","generator_"],Dn=(e,t)=>{const n=t.find(t=>e.startsWith(t));return n?e.slice(n.length):e},jn=e=>{const t=Dn(e,Bn);return Dn(t,Nn).split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")},kn=(e,t)=>{if(!t||"object"!=typeof t)return;const n=t;if("Read"!==e&&"Write"!==e&&"Edit"!==e){if("Glob"===e||"Grep"===e)return"string"==typeof n.pattern?n.pattern:void 0;if("mcp__playwright-test__test_run"!==e&&"test_run"!==e)return"mcp__playwright-test__generator_setup_page"===e||"generator_setup_page"===e?"string"==typeof n.seedFile?n.seedFile:"tests/seed.spec.ts":"mcp__playwright-test__generator_write_test"===e||"generator_write_test"===e?"string"==typeof n.fileName?n.fileName:void 0:"Bash"===e&&"string"==typeof n.command?n.command:void 0;if(Array.isArray(n.locations)){const e=n.locations.filter(e=>"string"==typeof e);return e.length>0?e.join(", "):void 0}}else if("string"==typeof n.file_path)return n.file_path.split("/").at(-1)??void 0},Mn=T.z.object({bucket:T.z.string(),key:T.z.string()}),$n=T.z.object({diffBucketPath:Mn,expiresInSeconds:T.z.number(),key:T.z.string(),uploadUrl:T.z.string()}),Hn=["test","bug","other"],Gn={bug:"Application code defect; behavior diverges from expected requirements.",other:"External dependencies, environment, or infra issues outside test/app code.",test:"Test code is incorrect, out-of-date, or missing necessary setup."},Fn=e=>Gn[e],{zSuiteAutoHealReport:zn}=function(e){const t=e.enum(Hn),n=["Classification of the root cause:","",`- test: ${Fn("test")}`,`- bug: ${Fn("bug")}`,`- other: ${Fn("other")}`].join("\n"),r=e.object({erroredUrl:e.string().optional(),issueType:t.describe(n),relatedTestCaseIds:e.array(e.string()).min(1).describe("List of ALL test case IDs impacted by this root cause and fix (must be existing IDs only)."),rootCause:e.string().describe("Brief explanation of what happened (1-2 sentences).")}),o=e.discriminatedUnion("result",[r.extend({fixApplied:e.string().describe("What fix was applied (brief, specific)."),result:e.literal("fixed")}),r.extend({followUpActions:e.string().optional().describe("Optional list of follow-up actions for any unfixed issues or missing data."),reasonNotFixed:e.string().describe("Why it could not be auto-fixed (brief)."),result:e.literal("unfixed")})]);return{zAutoHealReport:o,zIssueCategory:t,zSuiteAutoHealReport:e.object({issues:e.array(o).min(1).describe("List of all auto-heal issues/outcomes for this suite."),summary:e.string().min(3).describe("High-level summary (2-3 sentences) of the suite auto-heal results.")})}}(T.z),Yn=({authHeader:e,orgId:t,runId:n})=>l.createSdkMcpServer({name:"auto-heal-report",tools:[l.tool("generate-report",["After attempting to fix all broken tests (skip only those truly infeasible), generate and return a suite auto-heal report in the required schema.","","Ensure the payload matches zSuiteAutoHealReport exactly; include every issue discovered."].join("\n"),{report:zn},async({report:r})=>{const o=b.simpleGit({baseDir:process.cwd(),maxConcurrentProcesses:1}),s=await o.diff(),i=zn.parse(r);try{await(async({authHeader:e,orgId:t,report:n,runId:r})=>{const o=await(s={auth:e,body:{report:JSON.stringify(n)},client:Ht(),headers:En(t),path:{runId:r}},(s.client??Ot).post({security:[{name:"authorization",type:"apiKey"}],url:"/internal/v1/cli/runs/{runId}/autoheal-report",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to upload auto-heal report (${o.response.status})`)})({authHeader:e,orgId:t,report:i,runId:n});const{uploadUrl:r}=await(async({authHeader:e,contentType:t="text/plain",orgId:n,runId:r})=>{const o=await(s={auth:e,body:{contentType:t},client:Ht(),headers:En(n),path:{runId:r}},(s.client??Ot).post({security:[{name:"authorization",type:"apiKey"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/upload-url",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to presign diff upload (${o.response.status})`);const i=$n.parse(o.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}})({authHeader:e,contentType:"text/plain",orgId:t,runId:n});await(async({contentType:e="text/plain",diff:t,uploadUrl:n})=>{const r=await fetch(n,{body:t,headers:{"Content-Type":e},method:"PUT"});if(!r.ok)throw new Error(`Failed to upload diff (${r.status})`)})({contentType:"text/plain",diff:s,uploadUrl:r})}catch(e){return{content:[{text:"Error: Failed to upload auto-heal report or diff. Please surface this to the user, and terminate the session.",type:"text"}]}}return{content:[{text:"Auto-heal report generated. You may terminate this session now.",type:"text"}]}})],version:"0.0.1"}),Kn=({onComplete:e})=>l.createSdkMcpServer({name:"session-control",tools:[l.tool("complete_session",["Call this tool when you have completed your task and the session should end.","Use this instead of waiting for the user to manually terminate.","Only call this when you are confident the task is fully complete."].join("\n"),{summary:T.z.string().describe("A brief summary of what was accomplished")},async({summary:t})=>(e(),`Session complete: ${t}`))]}),Vn=e=>e.replace(/Bearer\s+[A-Za-z0-9._-]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{16,}\b/g,"[redacted]").replace(/\bstably_[A-Za-z0-9_-]{16,}\b/g,"[redacted]"),Wn=(e,t)=>({message:Vn(e),status:t?.status,statusText:t?.statusText}),qn=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_FOUNDRY_API_KEY","ANTHROPIC_MODEL","ANTHROPIC_SMALL_FAST_MODEL","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","AWS_BEARER_TOKEN_BEDROCK","BASH_DEFAULT_TIMEOUT_MS","BASH_MAX_OUTPUT_LENGTH","BASH_MAX_TIMEOUT_MS","CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR","CLAUDE_CODE_API_KEY_HELPER_TTL_MS","CLAUDE_CODE_CLIENT_CERT","CLAUDE_CODE_CLIENT_KEY_PASSPHRASE","CLAUDE_CODE_CLIENT_KEY","CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_DISABLE_TERMINAL_TITLE","CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL","CLAUDE_CODE_MAX_OUTPUT_TOKENS","CLAUDE_CODE_SHELL_PREFIX","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SUBAGENT_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX","CLAUDE_CONFIG_DIR","DISABLE_AUTOUPDATER","DISABLE_BUG_COMMAND","DISABLE_COST_WARNINGS","DISABLE_ERROR_REPORTING","DISABLE_NON_ESSENTIAL_MODEL_CALLS","DISABLE_PROMPT_CACHING","DISABLE_PROMPT_CACHING_HAIKU","DISABLE_PROMPT_CACHING_OPUS","DISABLE_PROMPT_CACHING_SONNET","DISABLE_TELEMETRY","HTTP_PROXY","HTTPS_PROXY","MAX_MCP_OUTPUT_TOKENS","MAX_THINKING_TOKENS","MCP_TIMEOUT","MCP_TOOL_TIMEOUT","NO_PROXY","SLASH_COMMAND_TOOL_CHAR_BUDGET","USE_BUILTIN_RIPGREP","VERTEX_REGION_CLAUDE_3_5_HAIKU","VERTEX_REGION_CLAUDE_3_7_SONNET","VERTEX_REGION_CLAUDE_4_0_OPUS","VERTEX_REGION_CLAUDE_4_0_SONNET","VERTEX_REGION_CLAUDE_4_1_OPUS"]),Jn=["Bash","Read","Write","Edit","Glob","Grep"],Xn=["mcp__playwright-test"],Qn=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],Zn=async e=>{const t=await hn({autoLogin:"chat"===e.mode}),n=(e=>"env"===e.type?e.auth.apiKey:`Bearer ${e.auth.accessToken}`)(t),r="oauth"===t.type?t.auth.context.orgId:void 0,o=w.default.resolve(process.cwd()),s=w.default.join(o,".env"),i=x.default.existsSync(s)&&x.default.statSync(s).isFile()?d.parse(x.default.readFileSync(s,"utf8")):{},a="chat"!==e.mode&&"init"!==e.mode,c="chat"===e.mode||"init"===e.mode?new Un:void 0,u="chat"===e.mode?e.getHelpText:void 0,p={log:[],promptDisplay:"chat"===e.mode?"Ask Stably to build tests for you":"init"===e.mode?"Setting up Playwright and Stably SDK":"fix"===e.mode?"Fixing broken tests":(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)||"<empty prompt>",status:"running"};let f,m=a,h=!1;const _={current:e=>{}},{addTool:g,addToolResult:E,appendText:b,appendUserMessage:T,cleanup:v,setExiting:R,setStatus:S,showPermissionPrompt:C}=await(async(e,t)=>{const{Box:n,Static:r,Text:o,render:s,useInput:i}=await import("ink"),a=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],c=()=>I.jsx(o,{inverse:!0,children:" "}),l=(({Box:e,Text:t,useInput:n},r)=>function({onChoice:o,prompt:s}){const[i,a]=y.useState(0),[c,l]=y.useState(!1),[d,u]=y.useState(""),p=[{label:"Yes, allow this once",value:"allow"},{label:"Yes, always allow for this session",value:"always"},{label:"No, tell AI what to do differently",value:"deny_with_message"}];n((e,t)=>{if(c)return t.return?void o("deny_with_message",d||"User denied this action"):t.escape?(l(!1),void u("")):t.backspace||t.delete?void u(e=>e.slice(0,-1)):void(t.ctrl||t.meta||u(t=>`${t}${e}`));if(t.upArrow)return void a(e=>e>0?e-1:p.length-1);if(t.downArrow)return void a(e=>e<p.length-1?e+1:0);if(t.return){const e=p[i];return"deny_with_message"===e.value?void l(!0):void o(e.value)}const n=parseInt(e,10);if(n>=1&&n<=p.length){const e=p[n-1];if("deny_with_message"===e.value)return void l(!0);o(e.value)}});const f=jn(s.toolName),m=kn(s.toolName,s.input);return I.jsxs(e,{borderColor:"yellow",borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[I.jsx(t,{bold:!0,color:"yellow",children:"Permission Required"}),I.jsxs(e,{flexDirection:"column",marginTop:1,children:[I.jsx(t,{color:"magenta",children:f}),null!=m&&I.jsxs(t,{color:"gray",children:[" ",m]})]}),null!=s.decisionReason&&I.jsx(e,{marginTop:1,children:I.jsxs(t,{color:"gray",children:["Reason: ",s.decisionReason]})}),c?I.jsxs(e,{flexDirection:"column",marginTop:1,children:[I.jsx(t,{color:"gray",children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),I.jsxs(t,{children:[I.jsx(t,{color:"yellow",children:">"})," ",d,I.jsx(r,{})]})]}):I.jsxs(e,{flexDirection:"column",marginTop:1,children:[I.jsx(t,{color:"gray",children:"Use ↑↓ arrows or number keys to select:"}),p.map((e,n)=>I.jsx(t,{children:I.jsxs(t,{color:n===i?"cyan":void 0,children:[n===i?"❯":" "," ",n+1,". ",e.label]})},e.value))]})]})})({Box:n,Text:o,useInput:i},c),d=(({Cursor:e,inkComponents:{Box:t,Static:n,Text:r,useInput:o},PermissionPrompt:s,Spinner:i})=>{const a=e=>"tool"===e.kind?I.jsxs(r,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?I.jsx(r,{color:"gray",children:e.content},e.id):"user"===e.kind?I.jsxs(r,{color:"cyan",children:["You: ",e.content]},e.id):I.jsx(r,{children:e.content},e.id);return function({onPermissionChoice:c,onSend:l,showSpinnerImmediately:d,state:u}){const[p,f]=y.useState(""),m=y.useRef(0),h=u.log.at(-1),_="text"===h?.kind&&"running"===u.status?u.log.length-1:u.log.length;y.useEffect(()=>{u.log.length<m.current&&(m.current=0),_>m.current&&(m.current=_)},[u.log.length,_]);const g=u.log.slice(0,m.current),E=u.log.slice(m.current),b=!!u.permissionPrompt;o((e,t)=>{if(l&&!b&&(!t.ctrl||"c"!==e)){if(t.return){const e=p.trim();return e&&l(e),void f("")}t.backspace||t.delete?f(e=>e.slice(0,-1)):f(t=>`${t}${e}`)}},{isActive:!!l&&!b});const T=y.useMemo(()=>"running"===u.status?I.jsx(i,{label:"Working"}):"success"!==u.status?I.jsx(r,{color:"red",children:"✖ Failed"}):void 0,[u.status]),v=!(d||!l||"running"!==u.status||0!==u.log.length||u.resultText||u.errorText),R="running"===u.status&&!v||u.log.length>0||u.resultText||u.errorText||"running"!==u.status;return I.jsxs(t,{flexDirection:"column",children:[I.jsx(n,{items:["header"],children:()=>I.jsxs(t,{flexDirection:"column",flexShrink:0,children:[I.jsx(r,{color:"cyan",bold:!0,children:"Stably Agent"}),I.jsx(t,{flexDirection:"column",marginTop:1,children:I.jsx(r,{color:"gray",children:u.promptDisplay})})]},"header")}),g.length>0&&I.jsx(n,{items:g,children:e=>a(e)}),E.length>0&&I.jsx(t,{flexDirection:"column",children:E.map(e=>a(e))}),"error"===u.status&&u.errorText&&I.jsx(t,{marginTop:1,children:I.jsx(r,{color:"red",children:u.errorText})}),R&&I.jsx(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:T}),null!=u.permissionPrompt&&null!=c&&I.jsx(s,{onChoice:c,prompt:u.permissionPrompt}),null!=l&&null==u.permissionPrompt&&!u.isExiting&&I.jsxs(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[I.jsx(r,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),I.jsxs(r,{children:[I.jsx(r,{color:"yellow",children:">"})," ",p,I.jsx(e,{})]})]})]})}})({Cursor:c,inkComponents:{Box:n,Static:r,Text:o,useInput:i},PermissionPrompt:l,Spinner:({label:e})=>{const[t,n]=y.useState(0);return y.useEffect(()=>{const e=setInterval(()=>n(e=>(e+1)%a.length),80);return()=>clearInterval(e)},[]),I.jsxs(o,{color:"yellow",children:[a[t]," ",e]})}});let u=e;const p={current:(e,t)=>{}},f=s(I.jsx(d,{onPermissionChoice:(e,t)=>p.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:u})),m=()=>{u={...u},f.rerender(I.jsx(d,{onPermissionChoice:(e,t)=>p.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:u}))},h=({text:e})=>{e&&(u.log=[...u.log,{content:e,id:u.log.length,kind:"user"}],m())};return{addTool:({rawName:e,toolInput:t})=>{const n=jn(e),r=kn(e,t),o=r?`${n} (${r})`:n;u.log=[...u.log,{content:o,id:u.log.length,kind:"tool"}],m()},addToolResult:({message:e})=>{u.log=[...u.log,{content:e,id:u.log.length,kind:"tool_result"}],m()},appendText:({text:e})=>{if(!e)return;const t=u.log.at(-1),n=t&&"text"===t.kind?e:e.replace(/^\s*\n+/,"");t&&"text"===t.kind?u.log=[...u.log.slice(0,-1),{...t,content:`${t.content}${n}`}]:u.log=[...u.log,{content:n,id:u.log.length,kind:"text"}],m()},appendUserMessage:h,cleanup:async()=>{f.unmount(),await f.waitUntilExit()},setExiting:()=>{u.isExiting=!0,m()},setStatus:({error:e,result:t,status:n})=>{u.errorText=e,u.resultText=t,u.status=n,m()},showPermissionPrompt:e=>new Promise(t=>{p.current=(n,r)=>{if(u.permissionPrompt=void 0,m(),"allow"===n)t({behavior:"allow",updatedInput:e.input});else if("always"===n)t({behavior:"allow",updatedInput:e.input,updatedPermissions:e.suggestions});else{const e=r??"User denied this action";h({text:e}),t({behavior:"deny",message:e,interrupt:!1})}},u.permissionPrompt={...e,resolve:t},m()})}})(p,"chat"===e.mode||"init"===e.mode?{onSend:e=>_.current(e),showSpinnerImmediately:"init"===e.mode}:void 0);let A=p.status;const U=({error:e,result:t,status:n})=>{A=n,S({error:e,result:t,status:n})};_.current=e=>{if("/help"===e.trim()){m&&c&&(h=!0,f?.interrupt?.(),c.allowNextTurn(),m=!1),"running"===A&&U({status:"success"}),T({text:e});const t=u?.();return void b({text:t??"Help is not available in this session."})}c&&(m&&(h=!0,f?.interrupt?.(),c.allowNextTurn(),m=!1),U({status:"running"}),T({text:e}),c.pushText(e),m=!0)};const P=await(async()=>{if("single"===e.mode)return Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;if("fix"===e.mode)try{return await(async({authHeader:e,orgId:t,runId:n})=>{const r=await(o={auth:e,client:Ht(),headers:En(t),path:{runId:n}},(o.client??Ot).get({security:[{name:"authorization",type:"apiKey"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...o}));var o;if(404===r.response.status)throw new Error(`Run ID "${n}" was not found.`);if(401===r.response.status)throw new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===r.response.status)throw new Error(r.error?.error??"Failed to fetch autoheal context (422).");if(!r.error){const e=yn.safeParse(r.data);if(e.success)return e.data.context;throw new Error("Autoheal context response missing or invalid context.")}throw new Error("Failed to fetch autoheal context")})({authHeader:n,orgId:r,runId:e.runId})}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";U({error:t,status:"error"}),await v(),process.exit(1)}return"init"===e.mode?"Please analyze this project and set up Playwright with the Stably SDK. Check for existing configurations and install the necessary dependencies.":""})(),L=await async function(e){const t=w.default.resolve(e),n=w.default.join(t,"tests"),r=w.default.join(n,"helpers"),o=w.default.join(n,"assets"),s=w.default.join(t,"playwright.config.ts"),i=w.default.join(n,"seed.spec.ts"),[a,c,l,d,u,p]=await Promise.all([On({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),On({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:n}),On({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:r}),On({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:o}),Ln({defaultContent:"File does not exist or could not be read",fileName:"playwright.config.ts",filePath:s}),Ln({defaultContent:"File does not exist or could not be read",fileName:"seed.spec.ts",filePath:i})]);return{absolutePath:t,directories:{assets:d,helpers:l,root:a,tests:c},files:{playwrightConfig:u,seedSpec:p}}}(o),O=await(async({allowedEnvVars:e,mode:t,workspaceInfo:n,authHeader:r})=>{const o=Ht(),s=await(i={client:o,body:{mode:t,workspaceInfo:n,allowedEnvVars:e},headers:{authorization:r}},(i.client??Ot).post({security:[{name:"authorization",type:"apiKey"}],url:"/internal/v1/cli/prompts/system",...i,headers:{"Content-Type":"application/json",...i.headers}}));var i;if(s.error)throw new Error(`Failed to fetch system prompt: ${JSON.stringify(s.error)}`);return s.data.systemPrompt})({allowedEnvVars:Object.keys(i),mode:e.mode,workspaceInfo:L,authHeader:n}),B=await async function({auth:e,client:t,source:n,metadata:r,duration:o}){try{const i=await(s={auth:e,client:t,body:{source:n,metadata:r??{},duration:o}},(s.client??Ot).post({security:[{name:"authorization",type:"apiKey"}],url:"/v1/proxy/api-key",...s,headers:{"Content-Type":"application/json",...s.headers}})),a=i.response;if(i.error){const e="object"==typeof i.error&&"error"in i.error?i.error.error:"Unknown error";return{error:Wn(e,a)}}return i.data?{key:i.data.key}:{error:Wn("No data in response",a)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:Wn(t)}}var s}({auth:n,client:Ht(),source:"cli"}),N=B.key;if(!N){const e=B.error?.message;U({error:e?`Unable to make AI calls: ${e}`:"Unable to make AI calls. Check if you are authenticated.",status:"error"}),await v(),process.exit(1)}const D=Object.fromEntries(Object.entries(process.env).filter(([e])=>!qn.has(e))),j=await gn(),k=j?Object.fromEntries(Object.entries(_n(j)).filter(e=>null!=e[1])):void 0,M="init"===e.mode,$="fix"===e.mode,H="chat"===e.mode,G=M?Qn:[...Jn,...$?["mcp__auto-heal-report"]:[]],F=M?Qn:Xn,z=M?{"session-control":Kn({onComplete:()=>{U({status:"success"}),R(),c?.finish(),process.exit(0)}})}:$?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:k},"auto-heal-report":Yn({authHeader:n,orgId:r,runId:e.runId})}:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:k}},Y=M?[]:[{hooks:[async e=>{const t=Tn(e);if(!t)return{decision:"approve"};let n=!1;const r=t.map(e=>In(e)?e.text.length<=4e4?e:(n=!0,{...e,text:`${e.text.slice(0,4e4)}...[truncated to 40000 characters]`}):e);return n?{decision:"approve",hookSpecificOutput:{hookEventName:"PostToolUse",updatedMCPToolOutput:r}}:{decision:"approve"}}],matcher:"mcp__playwright-test__.*"},{matcher:"mcp__playwright-test__test_run",hooks:[An({onResult:e=>E({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[xn({onResult:e=>E({message:e})})]}],K=M?[]:[{matcher:"mcp__playwright-test__browser_type",hooks:[Cn({envVars:i})]}];f=l.query({options:{tools:G,allowedTools:F,canUseTool:async(e,t,{suggestions:n,decisionReason:r})=>H||M?C({decisionReason:r,input:t,suggestions:n,toolName:e}):{behavior:"allow",updatedInput:t},cwd:o,env:{...D,ANTHROPIC_API_KEY:N,ANTHROPIC_BASE_URL:Mt},hooks:{PostToolUse:Y,PreToolUse:K},includePartialMessages:!0,mcpServers:z,model:"claude-opus-4-5-20251101",permissionMode:"default",systemPrompt:O},prompt:c??P}),"init"===e.mode&&c&&c.pushText(P);const V=async()=>{try{process.stdout.write("\r")}catch{}R();try{await(f?.interrupt?.())}catch{}c?.finish(),await v(),process.exit(1)};process.on("SIGINT",V);try{for await(const e of f){if("stream_event"===e.type){const{event:t}=e;if("content_block_delta"===t?.type){const{delta:e}=t;"text_delta"===e?.type&&e.text&&b({text:e.text})}"message_stop"===t?.type&&c&&c.allowNextTurn();continue}if("assistant"===e.type){const{content:t}=e.message??{};if(Array.isArray(t))for(const e of t)if("tool_use"===e?.type){if(e.name.startsWith("mcp__session-control__"))continue;g({rawName:e.name,toolInput:e.input})}continue}if("result"!==e.type);else{if(a){"success"===e.subtype?U({status:"success"}):h||(U({error:"Run failed.",status:"error"}),process.exitCode=1),h=!1;break}"success"!==e.subtype?h||(U({error:"Run failed.",status:"error"}),process.exitCode=1):U({status:"success"}),m=!1,h=!1,c?.allowNextTurn()}}}catch(e){h||(U({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1)}finally{m=!1,h=!1,process.off("SIGINT",V),c?.finish(),await v()}},er=[".ts",".js",".mts",".mjs",".cts",".cjs"],tr=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}];function nr(e){const t=n.join(e,"package.json");let r;try{r=a.readFileSync(t,"utf-8")}catch{return}try{return JSON.parse(r)}catch{return}}function rr(e){const t=[["npm","package-lock.json"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"]];for(const[r,o]of t)if(a.existsSync(n.join(e,o)))return r}var or=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);-1!==or&&process.argv[or+1]&&(process.chdir(process.argv[or+1]),process.argv.splice(or,2));var sr=new e.Command;sr.name("stably").description("AI-assisted Playwright testing CLI").version(Nt),sr.enablePositionalOptions(),sr.showHelpAfterError(),sr.exitOverride();var ir=[];sr.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{ir.push(e)}});var ar=()=>{const e=sr.helpInformation().trimEnd();return e?`${e}\n`:""},cr=(e,t)=>{let n=e;for(const e of t){const t=n.commands.find(t=>t.name()===e||t.aliases().includes(e));if(!t)return;n=t}return n},lr=()=>{process.stdout.write(ar())};sr.command("help").description("Show help for a command or subcommand").argument("[command...]","Command path to show help for (e.g. create test)").action(e=>{if(!e||0===e.length)return void lr();const t=cr(sr,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),lr(),void(process.exitCode=1);var n;n=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(n))}),sr.action(()=>Zn({mode:"chat",getHelpText:ar})),sr.command("login").description("Authenticate with Stably in your browser").action(pn),sr.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=await Zt();if(!e)return void u.outro(U.default.yellow("You are not logged in."));const t=u.spinner();t.start("Logging out..."),await(async e=>{try{await fetch(`${jt}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(e.refreshToken),await tn(),await on(),t.stop(U.default.green("✓ Logged out")),u.outro(U.default.green("You have been logged out successfully."))}),sr.command("whoami").description("Show auth status and current project").action(async()=>{u.log.info(`${U.default.bold("CLI Version:")} ${U.default.cyan(Nt)}`);const e=fn();if(e)return u.log.info(U.default.dim("Authentication: Environment variables")),u.log.info(` ${U.default.bold("API Key:")} ${U.default.cyan(e.apiKey.slice(0,8))}...`),u.log.info(` ${U.default.bold("Project ID:")} ${U.default.cyan(e.projectId)}`),void u.outro(U.default.green("Authenticated via environment variables"));const t=await Zt();if(!t)return void u.outro(U.default.yellow("Not logged in. Run `stably login` to authenticate."));let n;try{n=Kt(t.accessToken).email}catch{n=void 0}const r=await rn();if(!r)return u.log.info(U.default.dim("Authentication: OAuth (not linked to a project)")),n&&u.log.info(` ${U.default.bold("Email:")} ${U.default.cyan(n)}`),void u.outro(U.default.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const o=await(async()=>nn(process.cwd()))(),s=o?w.default.dirname(o):process.cwd(),i=w.default.relative(process.cwd(),s)||".";u.log.info(U.default.dim("Authentication: OAuth")),n&&u.log.info(` ${U.default.bold("Email:")} ${U.default.cyan(n)}`),u.log.info(` ${U.default.bold("Organization:")} ${U.default.cyan(r.orgName)}`),u.log.info(` ${U.default.bold("Project:")} ${U.default.cyan(r.projectName)}`),u.log.info(` ${U.default.bold("Linked at:")} ${U.default.dim(i)}`),u.outro(U.default.green("Authenticated"))}),sr.command("tunnel",{hidden:!0}).description("Expose a local server with a secure tunnel URL").option("-p, --port <number>","Local port to expose","3000").action(async e=>{u.intro(`Starting development server for port ${e.port}...`);const t=await hn(),n="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),r=u.spinner();r.start("Starting development server...");const o=await v.startTunnel(`http://localhost:${e.port}`,{subdomain:n});r.stop(`Your local environment is available at: ${U.default.underline(U.default.cyan(o.url))}`)}),sr.command("create").description("Create tests from a prompt (use: create test)").command("test").description("Generate a Playwright test from a prompt").argument("<prompt...>","Prompt describing the test to generate").action(e=>Zn({mode:"single",prompt:e})),sr.command("fix").description("Fix failing Playwright tests using debug context").argument("[runId]","Run ID for the failing test suite (defaults to CI's unique runId if available)").action(e=>{const t=e??function(){if(process.env.CI_BUILD_ID)return process.env.CI_BUILD_ID;const e=(({env:e=process.env,cwd:t=process.cwd()}={})=>{for(const n of Object.keys(ft))if(ft[n].detect({env:e,cwd:t}))return{isCi:!0,...ft[n].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(n={env:e,cwd:t},{commit:$e(n),branch:He(n)})};var n})();if(!e.isCi)return;const t=function(e){switch(e){case"github":return process.env.GITHUB_RUN_ATTEMPT;case"azure-devops":return process.env.SYSTEM_JOBATTEMPT;case"bitbucket":return process.env.BITBUCKET_STEP_RUN_NUMBER;default:return}}(e.service),n=[e.service,"slug"in e?e.slug:void 0,"build"in e?String(e.build):void 0,"job"in e?String(e.job):void 0,t&&String(t)].filter(Boolean);return n.length>0?n.join("-"):void 0}();return t||(process.stderr.write("Run ID is required. Provide <runId>.\n"),process.exit(1)),Zn({mode:"fix",runId:t})}),sr.command("init").description("Initialize Playwright and Stably SDK in your project").action(()=>Zn({mode:"init"})),tr.forEach(({args:e,description:t,name:o})=>{sr.command(o).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>async function({overrideArgs:e,subcommand:t}){const o=process.argv,s=o.findIndex((e,n)=>n>1&&e===t),i=-1===s?[]:o.slice(s+1),c="--"===i[0]?i.slice(1):i,l=e??[],d=new Set(l.map(e=>{const[t]=e.split("=");return t})),u=c.filter(e=>{const[t]=e.split("=");return!d.has(t)}),p=[t,...l,...u],f="test"===t?await gn():void 0,m="test"===t?function(e){const t=process.cwd(),r=e=>{const t=function(e){let t=n.resolve(e);for(;;){if([n.join(t,"node_modules","@stablyai","playwright-test"),n.join(t,"node_modules",".pnpm","@stablyai+playwright-test")].some(e=>a.existsSync(e)))return!0;const e=n.dirname(t);if(e===t)return!1;t=e}}(e);return t||(console.warn("⚠️ @stablyai/playwright-test is not installed. Stably reporter will not be injected."),console.warn(" Install it with: npm install @stablyai/playwright-test"),console.warn(" Reference: https://docs.stably.ai/getting-started/sdk-setup-guide\n")),t},o=(e,t)=>{try{return function({baseConfigPath:e,projectDir:t}){const r=n.join(t,".stably-playwright-wrapper.config.ts"),o=`\n// Auto-generated wrapper config by Stably CLI\n// This file injects the Stably reporter and ensures trace is enabled\nimport { defineConfig } from '@playwright/test';\nimport baseConfig from './${n.relative(n.dirname(r),e).replace(/\\/g,"/")}';\n\n// Inline type definitions to avoid import failures when @stablyai/playwright-test is not installed\ntype StablyNotificationConfig = {\n email?: { to: string[]; notifyOnStart?: boolean; notifyOnResult?: 'all' | 'failures-only' | null } | null;\n slack?: { channelName: string; notifyOnStart?: boolean; notifyOnResult?: 'all' | 'failures-only' } | null;\n};\n\ntype ProjectNotificationConfig = {\n projectName: string;\n notifications: StablyNotificationConfig;\n};\n\n// Dynamically import stablyReporter to handle cases where it's not installed\nlet stablyReporter: ((options?: { apiKey?: string; projectId?: string; notificationConfigs?: ProjectNotificationConfig[] }) => [string, unknown]) | undefined;\ntry {\n stablyReporter = require('@stablyai/playwright-test').stablyReporter;\n} catch {\n // @stablyai/playwright-test not installed - reporter injection will be skipped\n}\n\n// Extract notification configs from projects that have stably.notifications defined\n// This runs at config-load time before Playwright strips custom properties\nconst extractNotificationConfigs = (): ProjectNotificationConfig[] | undefined => {\n const projects = baseConfig.projects;\n if (!projects || !Array.isArray(projects)) return undefined;\n \n const configs = projects\n .map((p: { name?: string; stably?: { notifications?: StablyNotificationConfig } }) => {\n const notifications = p.stably?.notifications;\n return notifications ? { projectName: p.name ?? '', notifications } : undefined;\n })\n .filter((config): config is ProjectNotificationConfig => config != null);\n \n return configs.length > 0 ? configs : undefined;\n};\n\nconst hasStablyReporter = (reporters: unknown): boolean => {\n if (!Array.isArray(reporters)) return false;\n return reporters.some((reporter) => {\n if (typeof reporter === 'string') {\n return reporter.includes('stablyai') || reporter.includes('stably');\n }\n if (Array.isArray(reporter) && typeof reporter[0] === 'string') {\n return reporter[0].includes('stablyai') || reporter[0].includes('stably');\n }\n return false;\n });\n};\n\nconst buildReporterList = () => {\n const existingReporters = baseConfig.reporter;\n \n // If stablyReporter is not available, just use existing reporters\n if (!stablyReporter) {\n return existingReporters;\n }\n \n // If already has stably reporter, don't add another\n if (hasStablyReporter(existingReporters)) {\n return existingReporters;\n }\n \n // Create the stably reporter entry with notification configs\n const stablyReporterEntry = stablyReporter({\n apiKey: process.env.STABLY_API_KEY,\n projectId: process.env.STABLY_PROJECT_ID,\n notificationConfigs: extractNotificationConfigs(),\n });\n \n // Merge with existing reporters\n if (!existingReporters) {\n return [stablyReporterEntry];\n }\n \n if (Array.isArray(existingReporters)) {\n return [...existingReporters, stablyReporterEntry];\n }\n \n // Single reporter as string - convert to tuple format [name, {}]\n return [[existingReporters, {}], stablyReporterEntry];\n};\n\nexport default defineConfig({\n ...baseConfig,\n use: {\n ...baseConfig.use,\n trace: 'on',\n },\n reporter: buildReporterList(),\n});\n`.trim(),s=n.dirname(r);return a.existsSync(s)||a.mkdirSync(s,{recursive:!0}),a.writeFileSync(r,o,"utf-8"),r}({baseConfigPath:e,projectDir:t})}catch{return void console.warn("⚠️ Could not create Stably wrapper config. Reporter injection skipped.")}};if(e.some(e=>"--config"===e||"-c"===e||e.startsWith("--config=")||e.startsWith("-c="))){const s=e.findIndex(e=>"--config"===e||"-c"===e);if(-1!==s&&e[s+1]){const i=n.resolve(t,e[s+1]),a=n.dirname(i);if(!r(a))return;const c=o(i,a);if(!c)return;return e[s+1]=c,c}const i=e.findIndex(e=>e.startsWith("--config=")||e.startsWith("-c="));if(-1!==i){const s=n.resolve(t,e[i].split("=")[1]),a=n.dirname(s);if(!r(a))return;const c=o(s,a);if(!c)return;const l=e[i].startsWith("--config=")?"--config=":"-c=";return e[i]=`${l}${c}`,c}}const s=function(e){const t=n.resolve(e);if(a.existsSync(t))for(const e of er){const r=n.join(t,`playwright.config${e}`);if(a.existsSync(r))return r}}(t);if(!s)return;const i=n.dirname(s);if(!r(i))return;const c=o(s,i);return c?(e.push("--config",c),c):void 0}(p):void 0;!function(e,t={}){const o=function(e=process.cwd()){let t=n.resolve(e);for(;;){const e=nr(t);if(e){const r={...e.dependencies,...e.devDependencies},o="@playwright/test"in r?"@playwright/test":"playwright"in r?"playwright":void 0;if(o){const e=rr(t),r=n.join(t,"node_modules"),s=n.join(r,o);return{inNodeModules:a.existsSync(s),installed:!0,packageManager:e,packageName:o}}}const r=n.dirname(t);if(r===t)return{inNodeModules:!1,installed:!1,packageManager:void 0};t=r}}();o.installed||(console.error("Playwright is not installed. Please install it in your project.\nReference: https://docs.stably.ai/getting-started/sdk-setup-guide#auto-setup-recommended"),process.exit(1)),o.inNodeModules||(console.error("Playwright is present in your project, but not in node_modules. Please install your dependencies before proceeding."),process.exit(1));const{packageManager:s}=o;s||(console.error("Playwright installation not found. Could not determine your package manager (tried pnpm, yarn, and npm)."),process.exit(1));const[i,...c]=function(e){if("npm"===e)return["npx","playwright"];if("pnpm"===e)return["pnpm","exec","playwright"];if("yarn"===e)return["yarn","playwright"];throw new Error("Package manager not supported")}(s),l=[i,...c.slice(0,-1)].join(" "),d=_n(t.env),u=r.spawn(i,[...c,...e],{stdio:["inherit","pipe","pipe"],env:{...d,...process.env.CI?{}:{FORCE_COLOR:"1"}}}),p=(e,t)=>{let n=e.toString();for(const e of tr)n=n.replaceAll(`${l} playwright ${e.name}`,`${l} stably ${e.name}`).replaceAll(`npx playwright ${e.name}`,`npx stably ${e.name}`);if("yarn"===s){const e=n.split("\n");e.length>0&&e[0].includes("/.bin/playwright")&&e.shift();const r=e.join("\n");return void t.write(r)}t.write(n)};u.stdout?.on("data",e=>{p(e,process.stdout)}),u.stderr?.on("data",e=>{p(e,process.stderr)}),u.on("close",e=>{t.onClose?.(),process.exit(e??0)})}(p,{env:f,onClose:()=>{var e;(e=m)&&a.existsSync(e)&&a.rmSync(e)}})}({overrideArgs:e,subcommand:o}))});var dr=()=>{0!==ir.length&&(process.stderr.write(ir.join("")),ir=[])};(async()=>{try{await sr.parseAsync(process.argv)}catch(e){if(!(e=>!!e&&"object"==typeof e&&"code"in e)(e))throw dr(),e;const t="number"==typeof e.exitCode?e.exitCode:1,n=process.argv.slice(2).find(e=>!e.startsWith("-")),r=!!n&&!!cr(sr,[n]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&n&&!r)return ir=[],process.stderr.write(`command '${n}' not found\n`),lr(),void(process.exitCode=t);dr(),process.exitCode=t}})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stably",
3
- "version": "4.1.3",
3
+ "version": "4.2.1",
4
4
  "packageManager": "pnpm@10.24.0",
5
5
  "description": "AI-powered E2E Playwright testing CLI. Stably can understand your codebase, edit/run tests, and handle complex test scenarios for you.",
6
6
  "main": "dist/index.js",