@earlyai/cli 2.4.3 → 2.4.4

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.
Files changed (2) hide show
  1. package/dist/index.cjs +5 -4
  2. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -17,7 +17,7 @@ Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._life
17
17
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
18
18
  - ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let o=!1,s=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function l(e,t){let n=r.resolve(e,t);if(i.existsSync(n))return n;if(s.includes(r.extname(t)))return;let a=s.find(e=>i.existsSync(`${n}${e}`));if(a)return`${n}${a}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let u=e._executableFile||`${this._name}-${e._name}`,d=this._executableDir||``;if(this._scriptPath){let e;try{e=i.realpathSync(this._scriptPath)}catch{e=this._scriptPath}d=r.resolve(r.dirname(e),d)}if(d){let t=l(d,u);if(!t&&!e._executableFile&&this._scriptPath){let n=r.basename(this._scriptPath,r.extname(this._scriptPath));n!==this._name&&(t=l(d,`${n}-${e._name}`))}u=t||u}o=s.includes(r.extname(u));let f;a.platform===`win32`?(this._checkForMissingExecutable(u,d,e._name),t.unshift(u),t=h(a.execArgv).concat(t),f=n.spawn(a.execPath,t,{stdio:`inherit`})):o?(t.unshift(u),t=h(a.execArgv).concat(t),f=n.spawn(a.argv[0],t,{stdio:`inherit`})):f=n.spawn(u,t,{stdio:`inherit`}),f.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{a.on(e,()=>{f.killed===!1&&f.exitCode===null&&f.kill(e)})});let p=this._exitCallback;f.on(`close`,e=>{e??=1,p?p(new c(e,`commander.executeSubCommandAsync`,`(close)`)):a.exit(e)}),f.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(u,d,e._name);else if(t.code===`EACCES`)throw Error(`'${u}' not executable`);if(!p)a.exit(1);else{let e=new c(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,p(e)}}),this.runningCommand=f}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)===void 0?!1:this.getOptionValueSource(t)!==`default`});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(e){return e.length>1&&e[0]===`-`}let a=e=>/^-\d*\.?\d+(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,o=null,s=null,c=0;for(;c<e.length||s;){let l=s??e[c++];if(s=null,l===`--`){r===n&&r.push(l),r.push(...e.slice(c));break}if(o&&(!i(l)||a(l))){this.emit(`option:${o.name()}`,l);continue}if(o=null,i(l)){let t=this._findOption(l);if(t){if(t.required){let n=e[c++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!i(e[c])||a(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(l.length>2&&l[0]===`-`&&l[1]!==`-`){let e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),s=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let e=l.indexOf(`=`),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&a(l))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}else if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
19
19
  `),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in a.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,a.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new f(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`implied`)})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:`commander.missingArgument`})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(e,t){let n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName();return this.getOptionValueSource(r)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=p(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=`error: too many arguments${this.parent?` for '${this.name()}'`:``}. Expected ${t} argument${n} but got ${e.length}.`;this.error(r,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=p(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t||=`-V, --version`,n||=`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>s(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=r.basename(e,r.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e||={};let t=!!e.error,n,r,i;return t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(a.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
20
- Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function h(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function g(){if(a.env.NO_COLOR||a.env.FORCE_COLOR===`0`||a.env.FORCE_COLOR===`false`)return!1;if(a.env.FORCE_COLOR||a.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=m,e.useColor=g}));const{program:ne,createCommand:N,createArgument:P,createOption:F,CommanderError:I,InvalidArgumentError:re,InvalidOptionArgumentError:ie,Command:L,Argument:R,Option:ae,Help:z}=u(s((e=>{let{Argument:t}=A(),{Command:n}=M(),{CommanderError:r,InvalidArgumentError:i}=k(),{Help:a}=ee(),{Option:o}=j();e.program=new n,e.createCommand=e=>new n(e),e.createOption=(e,t)=>new o(e,t),e.createArgument=(e,n)=>new t(e,n),e.Command=n,e.Option=o,e.Argument=t,e.Help=a,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i}))(),1).default;var oe=`2.4.3`,se=s((e=>{let t=e=>e!=null,n=e=>typeof e==`object`&&!!e,r=e=>Array.isArray(e),i=e=>e instanceof Map,a=e=>e instanceof Set,o=e=>e instanceof Date,s=e=>typeof e==`number`,c=e=>typeof e==`string`,l=e=>typeof e==`boolean`,u=e=>e instanceof Error,d=e=>t(e)?c(e)||r(e)?e.length===0:i(e)||a(e)?e.size===0:o(e)?!1:n(e)?Object.keys(e).length===0:!1:!0,f=e=>u(e)?e.message:`error is not Instance of Error`,p=(e,t)=>{let n=new Set(e);for(let e of n)t.includes(e)||n.delete(e);return[...n]},m=async(e,t)=>{let n=await Promise.all(e.map(e=>t(e)));return e.filter((e,t)=>n[t])},h=(e,t)=>{let n=[];for(let r of e)n.some(e=>t(r,e))||n.push(r);return n},g=e=>[...new Set(e)],_=async e=>Promise.all(e.map(e=>new Promise((t,n)=>e().then(e=>e?t(e):n(e)).catch(e=>n(e))))).then(()=>!0).catch(e=>{if(!l(e))throw e;return e}),v=e=>e.trim().replaceAll(/([\da-z])([A-Z])/g,`$1-$2`).replaceAll(/([A-Z])([A-Z][\da-z])/g,`$1-$2`).replaceAll(/[\s_]+/g,`-`).toLowerCase(),y=e=>e.replaceAll(/[\s-]+/g,` `).split(` `).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(``),b=e=>{let t=0;for(let n=0;n<e.length;n++){let r=e.codePointAt(n)??0;t=Math.trunc(t*31+r)}return t>>>0},x=(...e)=>{let n={};for(let r of e)for(let e in r)t(r[e])&&(n[e]=r[e]);return n},S=(e,t)=>r(e)?e.map(e=>S(e,t)):n(e)?Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)).map(([e,n])=>[e,S(n,t)])):e,C=(e,t)=>{let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}},w=(e,t)=>{let n=!1;return(...r)=>{n||(e(...r),n=!0,setTimeout(()=>{n=!1},t))}};var T=class{listeners=[];addListener(e){this.listeners.push(e)}notifyAll(e){for(let t of this.listeners)t(e)}clear(){this.listeners.length=0}},E=class{set=new Set;constructor(e=[]){for(let t of e)this.safeAdd(t)}safeAdd(e){return t(e)?(this.set.add(e),!0):!1}has(e){return t(e)?this.set.has(e):!1}delete(e){return t(e)?this.set.delete(e):!1}clear(){this.set.clear()}get size(){return this.set.size}values(){return this.set.values()}toSet(){return structuredClone(this.set)}[Symbol.iterator](){return this.set[Symbol.iterator]()}concatSet(e){for(let t of e)this.safeAdd(t)}};e.Observer=T,e.SafeSet=E,e.arePromiseFnsTruthy=_,e.debounce=C,e.fastHash=b,e.filterAsync=m,e.getErrorMessage=f,e.intersection=p,e.isArray=r,e.isBoolean=l,e.isDate=o,e.isDefined=t,e.isEmpty=d,e.isError=u,e.isMap=i,e.isNumber=s,e.isObject=n,e.isSet=a,e.isString=c,e.merge=x,e.removeNestedField=S,e.throttle=w,e.toCamelCase=y,e.toKebabCase=v,e.uniq=g,e.uniqWith=h})),B=se();function ce(e,t,n,{key:r=``,prefix:i=`EARLY`,parser:a,def:o,isRequired:s=!1,envName:c}={}){let l=new ae(t,n);a&&l.argParser(a),s&&l.makeOptionMandatory(!0);let u=c??(()=>{let n=[];for(let t=e;t&&(0,B.isDefined)(t.name());t=t.parent)t.parent&&n.unshift(t.name());return[i,...n,r||t.split(/[ ,|]/)[1].replace(/^--?/,``)].join(`_`).replaceAll(/[- ]/g,`_`).toUpperCase()})();return l.env(u),(0,B.isDefined)(o)&&l.default(o),e.addOption(l),l}function le(e){return(typeof e==`object`&&!!e||typeof e==`function`)&&typeof e.then==`function`}function ue(e){switch(typeof e){case`string`:case`symbol`:return e.toString();case`function`:return e.name;default:throw Error(`Unexpected ${typeof e} service id type`)}}const de=Symbol.for(`@inversifyjs/common/islazyServiceIdentifier`);var fe=class{[de];#e;constructor(e){this.#e=e,this[de]=!0}static is(e){return typeof e==`object`&&!!e&&!0===e[de]}unwrap(){return this.#e()}};function pe(e,t,n){return Reflect.getOwnMetadata(t,e,n)}function me(e,t,n,r){Reflect.defineMetadata(t,n,e,r)}function he(e,t,n,r,i){let a=r(pe(e,t,i)??n());Reflect.defineMetadata(t,a,e,i)}function ge(e){return Object.getPrototypeOf(e.prototype)?.constructor}const _e=`@inversifyjs/container/bindingId`;function ve(){let e=pe(Object,_e)??0;return e===2**53-1?me(Object,_e,-(2**53-1)):he(Object,_e,()=>e,e=>e+1),e}const ye={Request:`Request`,Singleton:`Singleton`,Transient:`Transient`},be={ConstantValue:`ConstantValue`,DynamicValue:`DynamicValue`,Factory:`Factory`,Instance:`Instance`,Provider:`Provider`,ResolvedValue:`ResolvedValue`,ServiceRedirection:`ServiceRedirection`};function*xe(...e){for(let t of e)yield*t}var Se=class e{#e;#t;#n;constructor(e){this.#e=new Map,this.#t={};for(let t of Reflect.ownKeys(e))this.#t[t]=new Map;this.#n=e}add(e,t){this.#a(e).push(t);for(let n of Reflect.ownKeys(t))this.#o(n,t[n]).push(e)}clone(){let e=this.#r(),t=this.#i(),n=Reflect.ownKeys(this.#n),r=this._buildNewInstance(this.#n);this.#u(this.#e,r.#e,e,t);for(let t of n)this.#l(this.#t[t],r.#t[t],e);return r}get(e,t){return this.#t[e].get(t)}getAllKeys(e){return this.#t[e].keys()}removeByRelation(e,t){let n=this.get(e,t);if(n===void 0)return;let r=new Set(n);for(let n of r){let r=this.#e.get(n);if(r===void 0)throw Error(`Expecting model relation, none found`);for(let i of r)i[e]===t&&this.#d(n,i);this.#e.delete(n)}}_buildNewInstance(t){return new e(t)}_cloneModel(e){return e}_cloneRelation(e){return e}#r(){let e=new Map;for(let t of this.#e.keys()){let n=this._cloneModel(t);e.set(t,n)}return e}#i(){let e=new Map;for(let t of this.#e.values())for(let n of t){let t=this._cloneRelation(n);e.set(n,t)}return e}#a(e){let t=this.#e.get(e);return t===void 0&&(t=[],this.#e.set(e,t)),t}#o(e,t){let n=this.#t[e].get(t);return n===void 0&&(n=[],this.#t[e].set(t,n)),n}#s(e,t){let n=t.get(e);if(n===void 0)throw Error(`Expecting model to be cloned, none found`);return n}#c(e,t){let n=t.get(e);if(n===void 0)throw Error(`Expecting relation to be cloned, none found`);return n}#l(e,t,n){for(let[r,i]of e){let e=[];for(let t of i)e.push(this.#s(t,n));t.set(r,e)}}#u(e,t,n,r){for(let[i,a]of e){let e=[];for(let t of a)e.push(this.#c(t,r));t.set(this.#s(i,n),e)}}#d(e,t){for(let n of Reflect.ownKeys(t))this.#f(e,n,t[n])}#f(e,t,n){let r=this.#t[t].get(n);if(r!==void 0){let i=r.indexOf(e);i!==-1&&r.splice(i,1),r.length===0&&this.#t[t].delete(n)}}},Ce;(function(e){e.moduleId=`moduleId`,e.serviceId=`serviceId`})(Ce||={});var we=class e{#e;#t;constructor(e,t){this.#e=t??new Se({moduleId:{isOptional:!0},serviceId:{isOptional:!1}}),this.#t=e}static build(t){return new e(t)}add(e,t){this.#e.add(e,t)}clone(){return new e(this.#t,this.#e.clone())}get(e){let t=[],n=this.#e.get(Ce.serviceId,e);n!==void 0&&t.push(n);let r=this.#t()?.get(e);if(r!==void 0&&t.push(r),t.length!==0)return xe(...t)}removeAllByModuleId(e){this.#e.removeByRelation(Ce.moduleId,e)}removeAllByServiceId(e){this.#e.removeByRelation(Ce.serviceId,e)}};const Te=`@inversifyjs/core/classMetadataReflectKey`;function Ee(){return{constructorArguments:[],lifecycle:{postConstructMethodNames:new Set,preDestroyMethodNames:new Set},properties:new Map,scope:void 0}}const De=`@inversifyjs/core/pendingClassMetadataCountReflectKey`,Oe=Symbol.for(`@inversifyjs/core/InversifyCoreError`);var ke=class e extends Error{[Oe];kind;constructor(e,t,n){super(t,n),this[Oe]=!0,this.kind=e}static is(e){return typeof e==`object`&&!!e&&!0===e[Oe]}static isErrorOfKind(t,n){return e.is(t)&&t.kind===n}},Ae,je,Me,Ne,Pe;function Fe(e){let t=pe(e,Te)??Ee();if(!function(e){let t=pe(e,De);return t!==void 0&&t!==0}(e))return function(e,t){let n=[];if(t.length<e.length)throw new ke(Ae.missingInjectionDecorator,`Found unexpected missing metadata on type "${e.name}". "${e.name}" constructor requires at least ${e.length.toString()} arguments, found ${t.length.toString()} instead.\nAre you using @inject, @multiInject or @unmanaged decorators in every non optional constructor argument?\n\nIf you're using typescript and want to rely on auto injection, set "emitDecoratorMetadata" compiler option to true`);for(let e=0;e<t.length;++e)t[e]===void 0&&n.push(e);if(n.length>0)throw new ke(Ae.missingInjectionDecorator,`Found unexpected missing metadata on type "${e.name}" at constructor indexes "${n.join(`", "`)}".\n\nAre you using @inject, @multiInject or @unmanaged decorators at those indexes?\n\nIf you're using typescript and want to rely on auto injection, set "emitDecoratorMetadata" compiler option to true`)}(e,t.constructorArguments),t;(function(e,t){let n=[];for(let r=0;r<t.constructorArguments.length;++r){let i=t.constructorArguments[r];i!==void 0&&i.kind!==je.unknown||n.push(` - Missing or incomplete metadata for type "${e.name}" at constructor argument with index ${r.toString()}.\nEvery constructor parameter must be decorated either with @inject, @multiInject or @unmanaged decorator.`)}for(let[r,i]of t.properties)i.kind===je.unknown&&n.push(` - Missing or incomplete metadata for type "${e.name}" at property "${r.toString()}".\nThis property must be decorated either with @inject or @multiInject decorator.`);throw n.length===0?new ke(Ae.unknown,`Unexpected class metadata for type "${e.name}" with uncompletion traces.\nThis might be caused by one of the following reasons:\n\n1. A third party library is targeting inversify reflection metadata.\n2. A bug is causing the issue. Consider submiting an issue to fix it.`):new ke(Ae.missingInjectionDecorator,`Invalid class metadata at type ${e.name}:\n\n${n.join(`
20
+ Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function h(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function g(){if(a.env.NO_COLOR||a.env.FORCE_COLOR===`0`||a.env.FORCE_COLOR===`false`)return!1;if(a.env.FORCE_COLOR||a.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=m,e.useColor=g}));const{program:ne,createCommand:N,createArgument:P,createOption:F,CommanderError:I,InvalidArgumentError:re,InvalidOptionArgumentError:ie,Command:L,Argument:R,Option:ae,Help:z}=u(s((e=>{let{Argument:t}=A(),{Command:n}=M(),{CommanderError:r,InvalidArgumentError:i}=k(),{Help:a}=ee(),{Option:o}=j();e.program=new n,e.createCommand=e=>new n(e),e.createOption=(e,t)=>new o(e,t),e.createArgument=(e,n)=>new t(e,n),e.Command=n,e.Option=o,e.Argument=t,e.Help=a,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i}))(),1).default;var oe=`2.4.4`,se=s((e=>{let t=e=>e!=null,n=e=>typeof e==`object`&&!!e,r=e=>Array.isArray(e),i=e=>e instanceof Map,a=e=>e instanceof Set,o=e=>e instanceof Date,s=e=>typeof e==`number`,c=e=>typeof e==`string`,l=e=>typeof e==`boolean`,u=e=>e instanceof Error,d=e=>t(e)?c(e)||r(e)?e.length===0:i(e)||a(e)?e.size===0:o(e)?!1:n(e)?Object.keys(e).length===0:!1:!0,f=e=>u(e)?e.message:`error is not Instance of Error`,p=(e,t)=>{let n=new Set(e);for(let e of n)t.includes(e)||n.delete(e);return[...n]},m=async(e,t)=>{let n=await Promise.all(e.map(e=>t(e)));return e.filter((e,t)=>n[t])},h=(e,t)=>{let n=[];for(let r of e)n.some(e=>t(r,e))||n.push(r);return n},g=e=>[...new Set(e)],_=async e=>Promise.all(e.map(e=>new Promise((t,n)=>e().then(e=>e?t(e):n(e)).catch(e=>n(e))))).then(()=>!0).catch(e=>{if(!l(e))throw e;return e}),v=e=>e.trim().replaceAll(/([\da-z])([A-Z])/g,`$1-$2`).replaceAll(/([A-Z])([A-Z][\da-z])/g,`$1-$2`).replaceAll(/[\s_]+/g,`-`).toLowerCase(),y=e=>e.replaceAll(/[\s-]+/g,` `).split(` `).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(``),b=e=>{let t=0;for(let n=0;n<e.length;n++){let r=e.codePointAt(n)??0;t=Math.trunc(t*31+r)}return t>>>0},x=(...e)=>{let n={};for(let r of e)for(let e in r)t(r[e])&&(n[e]=r[e]);return n},S=(e,t)=>r(e)?e.map(e=>S(e,t)):n(e)?Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)).map(([e,n])=>[e,S(n,t)])):e,C=(e,t)=>{let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}},w=(e,t)=>{let n=!1;return(...r)=>{n||(e(...r),n=!0,setTimeout(()=>{n=!1},t))}};var T=class{listeners=[];addListener(e){this.listeners.push(e)}notifyAll(e){for(let t of this.listeners)t(e)}clear(){this.listeners.length=0}},E=class{set=new Set;constructor(e=[]){for(let t of e)this.safeAdd(t)}safeAdd(e){return t(e)?(this.set.add(e),!0):!1}has(e){return t(e)?this.set.has(e):!1}delete(e){return t(e)?this.set.delete(e):!1}clear(){this.set.clear()}get size(){return this.set.size}values(){return this.set.values()}toSet(){return structuredClone(this.set)}[Symbol.iterator](){return this.set[Symbol.iterator]()}concatSet(e){for(let t of e)this.safeAdd(t)}};e.Observer=T,e.SafeSet=E,e.arePromiseFnsTruthy=_,e.debounce=C,e.fastHash=b,e.filterAsync=m,e.getErrorMessage=f,e.intersection=p,e.isArray=r,e.isBoolean=l,e.isDate=o,e.isDefined=t,e.isEmpty=d,e.isError=u,e.isMap=i,e.isNumber=s,e.isObject=n,e.isSet=a,e.isString=c,e.merge=x,e.removeNestedField=S,e.throttle=w,e.toCamelCase=y,e.toKebabCase=v,e.uniq=g,e.uniqWith=h})),B=se();function ce(e,t,n,{key:r=``,prefix:i=`EARLY`,parser:a,def:o,isRequired:s=!1,envName:c}={}){let l=new ae(t,n);a&&l.argParser(a),s&&l.makeOptionMandatory(!0);let u=c??(()=>{let n=[];for(let t=e;t&&(0,B.isDefined)(t.name());t=t.parent)t.parent&&n.unshift(t.name());return[i,...n,r||t.split(/[ ,|]/)[1].replace(/^--?/,``)].join(`_`).replaceAll(/[- ]/g,`_`).toUpperCase()})();return l.env(u),(0,B.isDefined)(o)&&l.default(o),e.addOption(l),l}function le(e){return(typeof e==`object`&&!!e||typeof e==`function`)&&typeof e.then==`function`}function ue(e){switch(typeof e){case`string`:case`symbol`:return e.toString();case`function`:return e.name;default:throw Error(`Unexpected ${typeof e} service id type`)}}const de=Symbol.for(`@inversifyjs/common/islazyServiceIdentifier`);var fe=class{[de];#e;constructor(e){this.#e=e,this[de]=!0}static is(e){return typeof e==`object`&&!!e&&!0===e[de]}unwrap(){return this.#e()}};function pe(e,t,n){return Reflect.getOwnMetadata(t,e,n)}function me(e,t,n,r){Reflect.defineMetadata(t,n,e,r)}function he(e,t,n,r,i){let a=r(pe(e,t,i)??n());Reflect.defineMetadata(t,a,e,i)}function ge(e){return Object.getPrototypeOf(e.prototype)?.constructor}const _e=`@inversifyjs/container/bindingId`;function ve(){let e=pe(Object,_e)??0;return e===2**53-1?me(Object,_e,-(2**53-1)):he(Object,_e,()=>e,e=>e+1),e}const ye={Request:`Request`,Singleton:`Singleton`,Transient:`Transient`},be={ConstantValue:`ConstantValue`,DynamicValue:`DynamicValue`,Factory:`Factory`,Instance:`Instance`,Provider:`Provider`,ResolvedValue:`ResolvedValue`,ServiceRedirection:`ServiceRedirection`};function*xe(...e){for(let t of e)yield*t}var Se=class e{#e;#t;#n;constructor(e){this.#e=new Map,this.#t={};for(let t of Reflect.ownKeys(e))this.#t[t]=new Map;this.#n=e}add(e,t){this.#a(e).push(t);for(let n of Reflect.ownKeys(t))this.#o(n,t[n]).push(e)}clone(){let e=this.#r(),t=this.#i(),n=Reflect.ownKeys(this.#n),r=this._buildNewInstance(this.#n);this.#u(this.#e,r.#e,e,t);for(let t of n)this.#l(this.#t[t],r.#t[t],e);return r}get(e,t){return this.#t[e].get(t)}getAllKeys(e){return this.#t[e].keys()}removeByRelation(e,t){let n=this.get(e,t);if(n===void 0)return;let r=new Set(n);for(let n of r){let r=this.#e.get(n);if(r===void 0)throw Error(`Expecting model relation, none found`);for(let i of r)i[e]===t&&this.#d(n,i);this.#e.delete(n)}}_buildNewInstance(t){return new e(t)}_cloneModel(e){return e}_cloneRelation(e){return e}#r(){let e=new Map;for(let t of this.#e.keys()){let n=this._cloneModel(t);e.set(t,n)}return e}#i(){let e=new Map;for(let t of this.#e.values())for(let n of t){let t=this._cloneRelation(n);e.set(n,t)}return e}#a(e){let t=this.#e.get(e);return t===void 0&&(t=[],this.#e.set(e,t)),t}#o(e,t){let n=this.#t[e].get(t);return n===void 0&&(n=[],this.#t[e].set(t,n)),n}#s(e,t){let n=t.get(e);if(n===void 0)throw Error(`Expecting model to be cloned, none found`);return n}#c(e,t){let n=t.get(e);if(n===void 0)throw Error(`Expecting relation to be cloned, none found`);return n}#l(e,t,n){for(let[r,i]of e){let e=[];for(let t of i)e.push(this.#s(t,n));t.set(r,e)}}#u(e,t,n,r){for(let[i,a]of e){let e=[];for(let t of a)e.push(this.#c(t,r));t.set(this.#s(i,n),e)}}#d(e,t){for(let n of Reflect.ownKeys(t))this.#f(e,n,t[n])}#f(e,t,n){let r=this.#t[t].get(n);if(r!==void 0){let i=r.indexOf(e);i!==-1&&r.splice(i,1),r.length===0&&this.#t[t].delete(n)}}},Ce;(function(e){e.moduleId=`moduleId`,e.serviceId=`serviceId`})(Ce||={});var we=class e{#e;#t;constructor(e,t){this.#e=t??new Se({moduleId:{isOptional:!0},serviceId:{isOptional:!1}}),this.#t=e}static build(t){return new e(t)}add(e,t){this.#e.add(e,t)}clone(){return new e(this.#t,this.#e.clone())}get(e){let t=[],n=this.#e.get(Ce.serviceId,e);n!==void 0&&t.push(n);let r=this.#t()?.get(e);if(r!==void 0&&t.push(r),t.length!==0)return xe(...t)}removeAllByModuleId(e){this.#e.removeByRelation(Ce.moduleId,e)}removeAllByServiceId(e){this.#e.removeByRelation(Ce.serviceId,e)}};const Te=`@inversifyjs/core/classMetadataReflectKey`;function Ee(){return{constructorArguments:[],lifecycle:{postConstructMethodNames:new Set,preDestroyMethodNames:new Set},properties:new Map,scope:void 0}}const De=`@inversifyjs/core/pendingClassMetadataCountReflectKey`,Oe=Symbol.for(`@inversifyjs/core/InversifyCoreError`);var ke=class e extends Error{[Oe];kind;constructor(e,t,n){super(t,n),this[Oe]=!0,this.kind=e}static is(e){return typeof e==`object`&&!!e&&!0===e[Oe]}static isErrorOfKind(t,n){return e.is(t)&&t.kind===n}},Ae,je,Me,Ne,Pe;function Fe(e){let t=pe(e,Te)??Ee();if(!function(e){let t=pe(e,De);return t!==void 0&&t!==0}(e))return function(e,t){let n=[];if(t.length<e.length)throw new ke(Ae.missingInjectionDecorator,`Found unexpected missing metadata on type "${e.name}". "${e.name}" constructor requires at least ${e.length.toString()} arguments, found ${t.length.toString()} instead.\nAre you using @inject, @multiInject or @unmanaged decorators in every non optional constructor argument?\n\nIf you're using typescript and want to rely on auto injection, set "emitDecoratorMetadata" compiler option to true`);for(let e=0;e<t.length;++e)t[e]===void 0&&n.push(e);if(n.length>0)throw new ke(Ae.missingInjectionDecorator,`Found unexpected missing metadata on type "${e.name}" at constructor indexes "${n.join(`", "`)}".\n\nAre you using @inject, @multiInject or @unmanaged decorators at those indexes?\n\nIf you're using typescript and want to rely on auto injection, set "emitDecoratorMetadata" compiler option to true`)}(e,t.constructorArguments),t;(function(e,t){let n=[];for(let r=0;r<t.constructorArguments.length;++r){let i=t.constructorArguments[r];i!==void 0&&i.kind!==je.unknown||n.push(` - Missing or incomplete metadata for type "${e.name}" at constructor argument with index ${r.toString()}.\nEvery constructor parameter must be decorated either with @inject, @multiInject or @unmanaged decorator.`)}for(let[r,i]of t.properties)i.kind===je.unknown&&n.push(` - Missing or incomplete metadata for type "${e.name}" at property "${r.toString()}".\nThis property must be decorated either with @inject or @multiInject decorator.`);throw n.length===0?new ke(Ae.unknown,`Unexpected class metadata for type "${e.name}" with uncompletion traces.\nThis might be caused by one of the following reasons:\n\n1. A third party library is targeting inversify reflection metadata.\n2. A bug is causing the issue. Consider submiting an issue to fix it.`):new ke(Ae.missingInjectionDecorator,`Invalid class metadata at type ${e.name}:\n\n${n.join(`
21
21
 
22
22
  `)}`)})(e,t)}function Ie(e,t){let n=Fe(t).scope??e.scope;return{cache:{isRight:!1,value:void 0},id:ve(),implementationType:t,isSatisfiedBy:()=>!0,moduleId:void 0,onActivation:void 0,onDeactivation:void 0,scope:n,serviceIdentifier:t,type:be.Instance}}function Le(e){return e.isRight?{isRight:!0,value:e.value}:e}function Re(e){switch(e.type){case be.ConstantValue:case be.DynamicValue:return function(e){return{cache:Le(e.cache),id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type,value:e.value}}(e);case be.Factory:return function(e){return{cache:Le(e.cache),factory:e.factory,id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case be.Instance:return function(e){return{cache:Le(e.cache),id:e.id,implementationType:e.implementationType,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case be.Provider:return function(e){return{cache:Le(e.cache),id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,provider:e.provider,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case be.ResolvedValue:return function(e){return{cache:Le(e.cache),factory:e.factory,id:e.id,isSatisfiedBy:e.isSatisfiedBy,metadata:e.metadata,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case be.ServiceRedirection:return function(e){return{id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,serviceIdentifier:e.serviceIdentifier,targetServiceIdentifier:e.targetServiceIdentifier,type:e.type}}(e)}}(function(e){e[e.injectionDecoratorConflict=0]=`injectionDecoratorConflict`,e[e.missingInjectionDecorator=1]=`missingInjectionDecorator`,e[e.planning=2]=`planning`,e[e.resolution=3]=`resolution`,e[e.unknown=4]=`unknown`})(Ae||={}),function(e){e[e.unknown=32]=`unknown`}(je||={}),function(e){e.id=`id`,e.moduleId=`moduleId`,e.serviceId=`serviceId`}(Me||={});var ze=class e extends Se{_buildNewInstance(t){return new e(t)}_cloneModel(e){return Re(e)}},Be=class e{#e;#t;#n;constructor(e,t,n){this.#t=n??new ze({id:{isOptional:!1},moduleId:{isOptional:!0},serviceId:{isOptional:!1}}),this.#n=e,this.#e=t}static build(t,n){return new e(t,n)}clone(){return new e(this.#n,this.#e,this.#t.clone())}get(e){let t=this.getNonParentBindings(e)??this.#n()?.get(e);if(t!==void 0)return t;let n=this.#r(e);return n===void 0?n:[n]}*getChained(e){let t=this.getNonParentBindings(e);t!==void 0&&(yield*t);let n=this.#n();if(n===void 0){if(t===void 0){let t=this.#r(e);t!==void 0&&(yield t)}}else yield*n.getChained(e)}getBoundServices(){let e=new Set(this.#t.getAllKeys(Me.serviceId)),t=this.#n();if(t!==void 0)for(let n of t.getBoundServices())e.add(n);return e}getById(e){return this.#t.get(Me.id,e)??this.#n()?.getById(e)}getByModuleId(e){return this.#t.get(Me.moduleId,e)??this.#n()?.getByModuleId(e)}getNonParentBindings(e){return this.#t.get(Me.serviceId,e)}getNonParentBoundServices(){return this.#t.getAllKeys(Me.serviceId)}removeById(e){this.#t.removeByRelation(Me.id,e)}removeAllByModuleId(e){this.#t.removeByRelation(Me.moduleId,e)}removeAllByServiceId(e){this.#t.removeByRelation(Me.serviceId,e)}set(e){let t={[Me.id]:e.id,[Me.serviceId]:e.serviceIdentifier};e.moduleId!==void 0&&(t[Me.moduleId]=e.moduleId),this.#t.add(e,t)}#r(e){if(this.#e===void 0||typeof e!=`function`)return;let t=Ie(this.#e,e);return this.set(t),t}};(function(e){e.moduleId=`moduleId`,e.serviceId=`serviceId`})(Ne||={});var Ve=class e{#e;#t;constructor(e,t){this.#e=t??new Se({moduleId:{isOptional:!0},serviceId:{isOptional:!1}}),this.#t=e}static build(t){return new e(t)}add(e,t){this.#e.add(e,t)}clone(){return new e(this.#t,this.#e.clone())}get(e){let t=[],n=this.#e.get(Ne.serviceId,e);n!==void 0&&t.push(n);let r=this.#t()?.get(e);if(r!==void 0&&t.push(r),t.length!==0)return xe(...t)}removeAllByModuleId(e){this.#e.removeByRelation(Ne.moduleId,e)}removeAllByServiceId(e){this.#e.removeByRelation(Ne.serviceId,e)}};function He(){return 0}function V(e){return t=>{t!==void 0&&t.kind===je.unknown&&he(e,De,He,e=>e-1)}}function Ue(e,t){return(...n)=>r=>{if(r===void 0)return e(...n);if(r.kind===Pe.unmanaged)throw new ke(Ae.injectionDecoratorConflict,`Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found`);return t(r,...n)}}function We(e){if(e.kind!==je.unknown&&!0!==e.isFromTypescriptParamType)throw new ke(Ae.injectionDecoratorConflict,`Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found`)}(function(e){e[e.multipleInjection=0]=`multipleInjection`,e[e.singleInjection=1]=`singleInjection`,e[e.unmanaged=2]=`unmanaged`})(Pe||={});const Ge=Ue(function(e,t,n){return e===Pe.multipleInjection?{chained:n?.chained??!1,kind:e,name:void 0,optional:!1,tags:new Map,value:t}:{kind:e,name:void 0,optional:!1,tags:new Map,value:t}},function(e,t,n,r){return We(e),t===Pe.multipleInjection?{...e,chained:r?.chained??!1,kind:t,value:n}:{...e,kind:t,value:n}});function Ke(e,t){return n=>{let r=n.properties.get(t);return n.properties.set(t,e(r)),n}}var qe;function Je(e,t,n,r){if(ke.isErrorOfKind(r,Ae.injectionDecoratorConflict)){let i=function(e,t,n){if(n===void 0){if(t===void 0)throw new ke(Ae.unknown,`Unexpected undefined property and index values`);return{kind:qe.property,property:t,targetClass:e.constructor}}return typeof n==`number`?{index:n,kind:qe.parameter,targetClass:e}:{kind:qe.method,method:t,targetClass:e}}(e,t,n);throw new ke(Ae.injectionDecoratorConflict,`Unexpected injection error.\n\nCause:\n\n${r.message}\n\nDetails\n\n${function(e){switch(e.kind){case qe.method:return`[class: "${e.targetClass.name}", method: "${e.method.toString()}"]`;case qe.parameter:return`[class: "${e.targetClass.name}", index: "${e.index.toString()}"]`;case qe.property:return`[class: "${e.targetClass.name}", property: "${e.property.toString()}"]`}}(i)}`,{cause:r})}throw r}function Ye(e,t){return(n,r,i)=>{try{i===void 0?function(e,t){let n=Xe(e,t);return(e,t)=>{he(e.constructor,Te,Ee,Ke(n(e),t))}}(e,t)(n,r):typeof i==`number`?function(e,t){let n=Xe(e,t);return(e,t,r)=>{if(!function(e,t){return typeof e==`function`&&t===void 0}(e,t))throw new ke(Ae.injectionDecoratorConflict,`Found an @inject decorator in a non constructor parameter.\nFound @inject decorator at method "${t?.toString()??``}" at class "${e.constructor.name}"`);he(e,Te,Ee,function(e,t){return n=>{let r=n.constructorArguments[t];return n.constructorArguments[t]=e(r),n}}(n(e),r))}}(e,t)(n,r,i):function(e,t){let n=Xe(e,t);return(e,t,r)=>{if(!function(e){return e.set!==void 0}(r))throw new ke(Ae.injectionDecoratorConflict,`Found an @inject decorator in a non setter property method.\nFound @inject decorator at method "${t.toString()}" at class "${e.constructor.name}"`);he(e.constructor,Te,Ee,Ke(n(e),t))}}(e,t)(n,r,i)}catch(e){Je(n,r,i,e)}}}function Xe(e,t){return n=>{let r=t(n);return t=>(r(t),e(t))}}function Ze(e){return Ye(Ge(Pe.singleInjection,e),V)}(function(e){e[e.method=0]=`method`,e[e.parameter=1]=`parameter`,e[e.property=2]=`property`})(qe||={});const Qe=`@inversifyjs/core/classIsInjectableFlagReflectKey`,H=[Array,BigInt,Boolean,Function,Number,Object,String];function $e(e){let t=pe(e,`design:paramtypes`);t!==void 0&&he(e,Te,Ee,function(e){return t=>(e.forEach((e,n)=>{var r;t.constructorArguments[n]!==void 0||(r=e,H.includes(r))||(t.constructorArguments[n]=function(e){return{isFromTypescriptParamType:!0,kind:Pe.singleInjection,name:void 0,optional:!1,tags:new Map,value:e}}(e))}),t)}(t))}function et(e){return t=>{(function(e){if(pe(e,Qe)!==void 0)throw new ke(Ae.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${e.name}"`);me(e,Qe,!0)})(t),$e(t),e!==void 0&&he(t,Te,Ee,t=>({...t,scope:e}))}}function tt(e,t,n){let r;return e.extendConstructorArguments??!0?(r=[...t.constructorArguments],n.constructorArguments.map((e,t)=>{r[t]=e})):r=n.constructorArguments,r}function nt(e,t,n){return e?new Set([...t,...n]):n}function rt(e,t,n){let r=e.lifecycle?.extendPostConstructMethods??!0,i=nt(e.lifecycle?.extendPreDestroyMethods??!0,t.lifecycle.preDestroyMethodNames,n.lifecycle.preDestroyMethodNames);return{postConstructMethodNames:nt(r,t.lifecycle.postConstructMethodNames,n.lifecycle.postConstructMethodNames),preDestroyMethodNames:i}}function it(e,t,n){let r;return r=e.extendProperties??!0?new Map(xe(t.properties,n.properties)):n.properties,r}function at(e){return t=>{he(t,Te,Ee,function(e,t){return n=>({constructorArguments:tt(e,t,n),lifecycle:rt(e,t,n),properties:it(e,t,n),scope:n.scope})}(e,Fe(e.type)))}}function ot(e){return t=>{let n=ge(t);if(n===void 0)throw new ke(Ae.injectionDecoratorConflict,`Expected base type for type "${t.name}", none found.`);at({...e,type:n})(t)}}function st(e){return t=>{let n=[],r=ge(t);for(;r!==void 0&&r!==Object;){let e=r;n.push(e),r=ge(e)}n.reverse();for(let r of n)at({...e,type:r})(t)}}function U(e){return t=>{t===void 0&&he(e,De,He,e=>e+1)}}function ct(e){return t=>{let n=t??{kind:je.unknown,name:void 0,optional:!1,tags:new Map};if(n.kind===Pe.unmanaged)throw new ke(Ae.injectionDecoratorConflict,`Unexpected injection found. Found @unmanaged injection with additional @named, @optional, @tagged or @targetName injections`);return e(n)}}function lt(e){if(e.optional)throw new ke(Ae.injectionDecoratorConflict,`Unexpected duplicated optional decorator`);return e.optional=!0,e}function ut(){return Ye(ct(lt),U)}var dt;function ft(e){return e instanceof Error?e instanceof RangeError&&/stack space|call stack|too much recursion/i.test(e.message)||e.name===`InternalError`&&/too much recursion/.test(e.message):!1}function pt(e,t){if(ft(t)){let n=function(e){let t=[...e];return t.length===0?`(No dependency trace)`:t.map(ue).join(` -> `)}(function(e){let t=new Set;for(let n of e.servicesBranch){if(t.has(n))return[...t,n];t.add(n)}return[...t]}(e));throw new ke(Ae.planning,`Circular dependency found: ${n}`,{cause:t})}throw t}(function(e){e[e.multipleInjection=0]=`multipleInjection`,e[e.singleInjection=1]=`singleInjection`})(dt||={});const mt=Symbol.for(`@inversifyjs/core/LazyPlanServiceNode`);var ht=class{[mt];_serviceIdentifier;_serviceNode;constructor(e,t){this[mt]=!0,this._serviceNode=e,this._serviceIdentifier=t}get bindings(){return this._getNode().bindings}get isContextFree(){return this._getNode().isContextFree}get serviceIdentifier(){return this._serviceIdentifier}set bindings(e){this._getNode().bindings=e}set isContextFree(e){this._getNode().isContextFree=e}static is(e){return typeof e==`object`&&!!e&&!0===e[mt]}invalidate(){this._serviceNode=void 0}isExpanded(){return this._serviceNode!==void 0}_getNode(){return this._serviceNode===void 0&&(this._serviceNode=this._buildPlanServiceNode()),this._serviceNode}},gt=class e{#e;constructor(e){this.#e=e}get name(){return this.#e.elem.name}get serviceIdentifier(){return this.#e.elem.serviceIdentifier}get tags(){return this.#e.elem.tags}getAncestor(){if(this.#e.elem.getAncestorsCalled=!0,this.#e.previous!==void 0)return new e(this.#e.previous)}};function _t(e,t,n){let r=n?.customServiceIdentifier??t.serviceIdentifier,i=(!0===n?.chained?[...e.operations.getBindingsChained(r)]:[...e.operations.getBindings(r)??[]]).filter(e=>e.isSatisfiedBy(t));if(i.length===0&&e.autobindOptions!==void 0&&typeof r==`function`){let n=Ie(e.autobindOptions,r);e.operations.setBinding(n),n.isSatisfiedBy(t)&&i.push(n)}return i}var vt=class e{last;constructor(e){this.last=e}concat(t){return new e({elem:t,previous:this.last})}[Symbol.iterator](){let e=this.last;return{next:()=>{if(e===void 0)return{done:!0,value:void 0};let t=e.elem;return e=e.previous,{done:!1,value:t}}}}};function yt(e){let t=new Map;return e.rootConstraints.tag!==void 0&&t.set(e.rootConstraints.tag.key,e.rootConstraints.tag.value),new vt({elem:{getAncestorsCalled:!1,name:e.rootConstraints.name,serviceIdentifier:e.rootConstraints.serviceIdentifier,tags:t},previous:void 0})}function bt(e){return e.redirections!==void 0}function xt(e,t,n,r){let i=n.elem.serviceIdentifier,a=n.previous?.elem.serviceIdentifier;Array.isArray(e)?function(e,t,n,r,i,a){if(e.length!==0){let t=`Ambiguous bindings found for service: "${ue(a[a.length-1]??n)}".${Tt(a)}\n\nRegistered bindings:\n\n${e.map(e=>function(e){switch(e.type){case be.Instance:return`[ type: "${e.type}", serviceIdentifier: "${ue(e.serviceIdentifier)}", scope: "${e.scope}", implementationType: "${e.implementationType.name}" ]`;case be.ServiceRedirection:return`[ type: "${e.type}", serviceIdentifier: "${ue(e.serviceIdentifier)}", redirection: "${ue(e.targetServiceIdentifier)}" ]`;default:return`[ type: "${e.type}", serviceIdentifier: "${ue(e.serviceIdentifier)}", scope: "${e.scope}" ]`}}(e.binding)).join(`
23
23
  `)}\n\nTrying to resolve bindings for "${Ct(n,r)}".${wt(i)}`;throw new ke(Ae.planning,t)}t||St(n,r,i,a)}(e,t,i,a,n.elem,r):function(e,t,n,r,i,a){e!==void 0||t||St(n,r,i,a)}(e,t,i,a,n.elem,r)}function St(e,t,n,r){let i=`No bindings found for service: "${ue(r[r.length-1]??e)}".\n\nTrying to resolve bindings for "${Ct(e,t)}".${Tt(r)}${wt(n)}`;throw new ke(Ae.planning,i)}function Ct(e,t){return t===void 0?`${ue(e)} (Root service)`:ue(t)}function wt(e){let t=e.tags.size===0?``:`\n- tags:\n - ${[...e.tags.keys()].map(e=>e.toString()).join(`
@@ -32391,7 +32391,8 @@ var n=require(`buffer`),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.fr
32391
32391
  `))}_onEvent(e,t){function n(n){e===`error`&&!this.transports.includes(t)&&this.add(t),this.emit(e,n,t)}t[`__winston`+e]||(t[`__winston`+e]=n.bind(this),t.on(e,t[`__winston`+e]))}_addDefaultMeta(e){this.defaultMeta&&Object.assign(e,this.defaultMeta)}};function g(e,t){let n=e[t];return!n&&n!==0?null:n}Object.defineProperty(h.prototype,`transports`,{configurable:!1,enumerable:!0,get(){let{pipes:e}=this._readableState;return Array.isArray(e)?e:[e].filter(Boolean)}}),t.exports=h})),XZ=s(((e,t)=>{let{LEVEL:n}=pX(),r=RZ(),i=YZ(),a=jZ()(`winston:create-logger`);function o(e){return`is`+e.charAt(0).toUpperCase()+e.slice(1)+`Enabled`}t.exports=function(e={}){e.levels=e.levels||r.npm.levels;class t extends i{constructor(e){super(e)}}let s=new t(e);return Object.keys(e.levels).forEach(function(e){if(a(`Define prototype method for "%s"`,e),e===`log`){console.warn(`Level "log" not defined: conflicts with the method "log". Use a different level name.`);return}t.prototype[e]=function(...t){let r=this||s;if(t.length===1){let[i]=t,a=i&&i.message&&i||{message:i};return a.level=a[n]=e,r._addDefaultMeta(a),r.write(a),this||s}return t.length===0?(r.log(e,``),r):r.log(e,...t)},t.prototype[o(e)]=function(){return(this||s).isLevelEnabled(e)}}),s}})),ZZ=s(((e,t)=>{let n=XZ();t.exports=class{constructor(e={}){this.loggers=new Map,this.options=e}add(e,t){if(!this.loggers.has(e)){t=Object.assign({},t||this.options);let r=t.transports||this.options.transports;r?t.transports=Array.isArray(r)?r.slice():[r]:t.transports=[];let i=n(t);i.on(`close`,()=>this._delete(e)),this.loggers.set(e,i)}return this.loggers.get(e)}get(e,t){return this.add(e,t)}has(e){return!!this.loggers.has(e)}close(e){if(e)return this._removeLogger(e);this.loggers.forEach((e,t)=>this._removeLogger(t))}_removeLogger(e){this.loggers.has(e)&&(this.loggers.get(e).close(),this._delete(e))}_delete(e){this.loggers.delete(e)}}})),QZ=u(s((e=>{let t=MX(),{warn:n}=NX();e.version=PX().version,e.transports=LZ(),e.config=RZ(),e.addColors=t.levels,e.format=t.format,e.createLogger=XZ(),e.Logger=YZ(),e.ExceptionHandler=KZ(),e.RejectionHandler=JZ(),e.Container=ZZ(),e.Transport=XX(),e.loggers=new e.Container;let r=e.createLogger();Object.keys(e.config.npm.levels).concat([`log`,`query`,`stream`,`add`,`remove`,`clear`,`profile`,`startTimer`,`handleExceptions`,`unhandleExceptions`,`handleRejections`,`unhandleRejections`,`configure`,`child`]).forEach(t=>e[t]=(...e)=>r[t](...e)),Object.defineProperty(e,`level`,{get(){return r.level},set(e){r.level=e}}),Object.defineProperty(e,`exceptions`,{get(){return r.exceptions}}),Object.defineProperty(e,`rejections`,{get(){return r.rejections}}),[`exitOnError`].forEach(t=>{Object.defineProperty(e,t,{get(){return r[t]},set(e){r[t]=e}})}),Object.defineProperty(e,`default`,{get(){return{exceptionHandlers:r.exceptionHandlers,rejectionHandlers:r.rejectionHandlers,transports:r.transports}}}),n.deprecated(e,`setLevels`),n.forFunctions(e,`useFormat`,[`cli`]),n.forProperties(e,`useFormat`,[`padLevels`,`stripColors`]),n.forFunctions(e,`deprecated`,[`addRewriter`,`addFilter`,`clone`,`extend`]),n.forProperties(e,`deprecated`,[`emitErrs`,`levelLength`])}))());let $Z=function(e){return e.ERROR=`error`,e.WARN=`warn`,e.INFO=`info`,e.VERBOSE=`verbose`,e.DEBUG=`debug`,e}({});const eQ=$Z.INFO,tQ=$Z.VERBOSE,nQ=$Z.DEBUG;$Z.ERROR,$Z.WARN,$Z.INFO,$Z.VERBOSE,$Z.DEBUG;function rQ(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function iQ(e,t){return function(n,r){t(n,r,e)}}function aQ(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function oQ(...e){return e.map(e=>typeof e==`object`&&e?(0,S.inspect)(e,{depth:4,breakLength:80}):String(e)).join(` `)}let sQ=class{logger;isDebugMode;constructor(e){this.isDebugMode=String(e?.debug)===`true`,this.logger=QZ.createLogger({level:this.getLogLevel(e),transports:[new QZ.transports.Console({format:QZ.format.printf(({message:e})=>String(e??``))})]})}error(...e){this.logger.error(oQ(...e))}warn(...e){this.logger.warn(oQ(...e))}info(...e){this.logger.info(oQ(...e))}verbose(...e){this.logger.verbose(oQ(...e))}debug(...e){this.logger.debug(oQ(...e))}getLogLevel(e){return String(e?.debug)===`true`?nQ:String(e?.verbose)===`true`?tQ:eQ}};sQ=aQ([et(),iQ(0,Ze(lW.CliOptions)),iQ(0,ut()),rQ(`design:paramtypes`,[Object])],sQ);let cQ=class{config;constructor(e,t){this.logger=t,this.config=this.initializeConfig(e)}getConfig(){return this.config}maskedConfig(){let e=this.config.gitTopLevel;return this.config.command===dW.PROJECT?{...this.config,secretToken:`xxxx`,token:`xxxx`,...(0,B.isDefined)(e)&&{rootPath:uW.default.relative(e,this.config.rootPath)},...(0,B.isDefined)(this.config.targetDirectory)&&{targetDirectory:uW.default.normalize(this.config.targetDirectory)}}:{...this.config,secretToken:`xxxx`,token:`xxxx`,...(0,B.isDefined)(e)&&{rootPath:uW.default.relative(e,this.config.rootPath)}}}isDev(){return process.env.IS_DEV===`true`}getConfigValue(e){return this.config[e]}updateConfigValue(e,t){this.config[e]=t}getConfigValueOrThrow(e,t){let n=this.config[e];if(!(0,B.isDefined)(n)){let n=t??`Configuration key ${e} is required but not configured`;throw Error(n)}return n}initializeConfig(e){let t=this.getRawConfigFromInputs(e),n=ZY.parse(t);return this.capMaxTestables(n),this.logger.verbose(`Configuration validated successfully`),this.logger.debug(`Configuration: ${JSON.stringify(n,null,2)}`),n}capMaxTestables(e){e.command===dW.COVERAGE||e.maxTestables<=10||(this.logger.warn(`Capping maxTestables from ${e.maxTestables} to 10 (maximum allowed).`),e.maxTestables=10)}getRawConfigFromInputs(e){if(!e)throw Error(`CLI options are required but not provided`);let t={command:e.command,testStructure:e.testStructure,testFramework:e.testFramework,testSuffix:e.testSuffix,testFileName:e.testFileNaming,requestSource:cW.RequestSource.CLI,concurrency:e.maxConcurrency,backendURL:e.baseHost,secretToken:e.apiKey,autoCommit:e.autoCommit,token:e.token,testCommand:e.testCommand,coverageCommand:e.coverageCommand,lintCommand:e.lintCommand,prettierCommand:e.prettierCommand,disableLintRules:e.disableLintRules,refName:e.refName,baseRef:e.baseRef,gitOrg:e.gitOrg,gitRepo:e.gitRepo,gitUserEmail:e.gitUserEmail,gitUserName:e.gitUserName,SCMProvider:e.scmProvider,prNumber:e.prNumber,commitHash:e.commitHash,targetDirectory:e.targetDirectory,frequency:e.frequency,startTime:e.startTime,keepErrorTests:e.keepErrorTests,keepFailedTests:e.keepFailedTests,conditionalKeep:e.conditionalKeep,continueOnTestErrors:e.continueOnTestErrors,changedMethodsOnly:e.changedMethodsOnly,skipCoverageAfter:e.skipCoverageAfter,maxTestables:e.maxTestables,autoCommitSkipCi:e.autoCommitSkipCi,perFunctionTimeout:e.perFunctionTimeout,coverageThreshold:e.coverageThreshold,reuseCoverage:e.reuseCoverage,reuseCoverageMaxRuns:e.reuseCoverageMaxRuns,experimentalAgentSdk:e.experimentalAgentSdk,agentSdkModel:e.agentSdkModel,agentSdkBudget:e.agentSdkBudget,verbose:e.verbose,debug:e.debug,...this.isDev()&&{rootPath:e.rootPath}};return Object.fromEntries(Object.entries(t).filter(([,e])=>!(0,B.isEmpty)(e)))}};cQ=aQ([et(`Singleton`),iQ(0,Ze(lW.CliOptions)),iQ(1,Ze(sQ)),rQ(`design:paramtypes`,[Object,Object])],cQ);var lQ;let uQ=class{constructor(e,t){this.configService=e,this.logger=t}data={warnings:[]};setChangedFilesData(e){this.data.changedFiles=e}setCoverageData(e,t){this.data.coverage={before:e,after:t}}setPRCoverageData(e,t){this.data.prCoverage={before:e,after:t}}setCoverageSkipped(){this.data.coverageSkipped=!0}setCoverageBeforeSkipped(){this.data.coverageBeforeSkipped=!0}setTestGenerationData(e){this.data.testGeneration=e}setAutoCommitStatus(e){this.data.autoCommit={enabled:e}}addWarning(e){this.data.warnings.push({message:e})}getWorkflowRunOutput(){return{filesCount:this.data.changedFiles?.changedFilesCount??0,codeFileCount:this.data.changedFiles?.candidateFilesCount??0,methodsCount:this.data.changedFiles?.functionCount??0,publicMethodCount:this.data.changedFiles?.publicMethodCount??0,publicMethodBelowCoverageCount:this.data.changedFiles?.testablesToGenerateCount??0,generatedMethodsCount:this.data.testGeneration?.generated??0,successMethodsCount:this.data.testGeneration?.successMethodsCount??0,committedFilesCount:this.data.testGeneration?.committedFilesCount??0,numberOfGreenTests:this.data.testGeneration?.greenTests??0,numberOfRedTests:this.data.testGeneration?.redTests??0,publicMethods:this.data.changedFiles?.publicMethods,changedMethods:this.data.changedFiles?.changedMethods,methodsBelowCoverage:this.data.changedFiles?.methodsBelowCoverage}}generateMarkdownSummary(){let e=[];for(let t of this.data.warnings)e.push(`⚠️ ${t.message}`);if(e.push(``,`🧪 **Early Test Generation Agent**`,``),this.data.changedFiles){let{changedFilesCount:t,candidateFilesCount:n,functionCount:r,testablesToGenerateCount:i}=this.data.changedFiles;e.push(`- Changed files: ${t}`,`- Files with testable code: ${n}`,`- Total methods detected: ${r}`,`- Public methods below coverage threshold: ${i}`)}if(this.data.testGeneration){let{successMethodsCount:t,greenTests:n,redTests:r,skippedMethods:i}=this.data.testGeneration;e.push(`- Generated tests for ${t} methods`,`- Generated ${n} green unit tests`,`- Filtered ${r} red unit tests`,...(0,B.isDefined)(i)&&i>0?[`- Skipped ${i} methods (already tested)`]:[],`**Action Taken**`,``,`✅ Unit tests automatically generated for ${t} public functions below threshold.`)}if((0,B.isDefined)(this.data.autoCommit)&&this.data.autoCommit.enabled&&e.push(`📦 Test files have been auto-committed to this branch.`),(0,B.isDefined)(this.data.prCoverage)){let t=this.data.coverageBeforeSkipped??!1,n=this.data.coverageSkipped??!1,r=t?`Skipped`:`${this.data.prCoverage.before.percentage??0}%`,i=n?`Skipped`:`${this.data.prCoverage.after.percentage??0}%`;switch(this.configService.getConfigValue(`command`)){case dW.PR:e.push(``,`**📊 PR coverage before: `+r+`. PR coverage after: `+i+`.**`);break;case dW.COMMIT:e.push(``,`**📊 Commit coverage before: `+r+`. Commit coverage after: `+i+`.**`);break;case dW.PROJECT:e.push(``,`**📊 Project coverage before: `+r+`. Project coverage after: `+i+`.**`);break}}return e.push(``,`Early Agent is now guarding your coverage.`,"Early Trace ID: `"+this.configService.getConfigValue(`traceId`)+"`"),e.join(`
32392
32392
  `)}async addToJobSummary(){try{this.logger.info(`Successfully added summary to job summary`)}catch(e){this.logger.warn(`Failed to add summary to job summary: ${e instanceof Error?e.message:`Unknown error`}`)}}clear(){this.data={warnings:[]}}};uQ=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(sQ)),rQ(`design:paramtypes`,[typeof(lQ=cQ!==void 0&&cQ)==`function`?lQ:Object,Object])],uQ);const dQ={allowedExtensions:[`.ts`,`.tsx`,`.js`,`.jsx`,`.py`],excludePatterns:[`.test.`,`.spec.`,`.d.ts`,`jest.config`,`vitest.config`,`webpack.config`,`rollup.config`,`vite.config`,`tsconfig`,`eslint.config`,`prettier.config`,`babel.config`,`.eslintrc`,`.prettierrc`,`dist/`,`build/`,`out/`,`.next/`,`.nuxt/`,`.early.test`,`_test.py`,`conftest.py`,`__pycache__/`,`.venv/`]};let fQ=function(e){return e.Added=`added`,e.Modified=`modified`,e}({});var pQ,mQ;let hQ=class{constructor(e,t,n){this.configService=e,this.summaryService=t,this.logger=n}async safePostSummaryToPr(){try{if((0,B.isDefined)(this.configService.getConfigValue(`prNumber`)))await this.postSummaryToPr();else{let e=this.summaryService.generateMarkdownSummary();this.logger.info(e)}}catch(e){this.logger.error(`Failed to post summary to PR: ${e instanceof Error?e.message:`Unknown error`}`)}}async getChangedFilesWithStatus(){return(await this.getChangedFilesPR()).map(e=>({filePath:e,status:fQ.Modified}))}async getContributorAvatarUrl(){}};hQ=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(uQ)),iQ(2,Ze(sQ)),rQ(`design:paramtypes`,[typeof(pQ=cQ!==void 0&&cQ)==`function`?pQ:Object,typeof(mQ=uQ!==void 0&&uQ)==`function`?mQ:Object,Object])],hQ);const gQ=()=>H0.get(cQ),_Q=(0,S.promisify)(f.exec),vQ=async(e,t={})=>await _Q(e,{cwd:gQ().getConfig().rootPath,...t});var yQ,bQ;let xQ=class{constructor(e,t,n){this.configService=e,this.scmHostService=t,this.logger=n}async hydrateConfig(){let e=this.configService.getConfigValue(`commitHash`),t=await this.getGitInfo({authorSha:e});this.configService.updateConfigValue(`gitOrg`,t.owner),this.configService.updateConfigValue(`gitRepo`,t.repository),this.configService.updateConfigValue(`gitTopLevel`,t.topLevel),this.configService.updateConfigValue(`contributorName`,t.authorName),this.configService.updateConfigValue(`contributorEmail`,t.authorEmail)}async getGitInfo(e){try{let t=e?.authorSha,[n,r,i,a,o,s,c]=await Promise.all([this.getRefName(),this.getSha(),this.getRemoteUrl(),this.getTopLevel(),this.getCommitDate(),this.getCommitAuthorName(t),this.getCommitAuthorEmail(t)]),{owner:l,repository:u}=this.parseRemoteUrl(i);return{ref_name:n,repository:u,owner:l,sha:r,topLevel:a,remoteUrl:i,commitDate:o,authorName:s,authorEmail:c}}catch(e){return this.logger.warn(`Failed to get local Git info: ${e instanceof Error?e.message:`Unknown error`}`),{ref_name:``,repository:``,owner:``,sha:``,topLevel:``,remoteUrl:``,commitDate:``,authorName:``,authorEmail:``}}}async getRefName(){try{let{stdout:e}=await vQ(`git rev-parse --abbrev-ref HEAD`);return e.trim()}catch{return this.logger.warn(`Could not get ref_name from local Git`),``}}async getSha(){try{let{stdout:e}=await vQ(`git rev-parse HEAD`);return e.trim()}catch{return this.logger.warn(`Could not get SHA from local Git`),``}}async getRemoteUrl(){try{let{stdout:e}=await vQ(`git remote get-url origin`);return e.trim()}catch{return this.logger.warn(`Could not get remote URL from local Git`),``}}async getTopLevel(){try{let{stdout:e}=await vQ(`git rev-parse --show-toplevel`);return e.trim()}catch{return this.logger.warn(`Could not get top-level directory from local Git`),``}}parseRemoteUrl(e){if(!e)return{owner:``,repository:``};try{if(e.startsWith(`http`)){let t=new URL(e).pathname.split(`/`).filter(Boolean);if(t.length>=2)return{owner:t[0],repository:t[1].replace(`.git`,``)}}if(e.includes(`@`)&&e.includes(`:`)){let t=e.split(`:`);if(t.length===2){let e=t[1].split(`/`).filter(Boolean);if(e.length>=2)return{owner:e[0],repository:e[1].replace(`.git`,``)}}}return{owner:``,repository:``}}catch{return this.logger.warn(`Failed to parse remote URL: ${e}`),{owner:``,repository:``}}}async getEarlyFiles(e){let{stdout:t}=await vQ(`git ls-files --others --exclude-standard`),{stdout:n}=await vQ(`git diff --name-only --diff-filter=M`),r=[...new Set([...t.trim().split(`
32393
32393
  `),...n.trim().split(`
32394
- `)])].filter(Boolean).filter(e=>e.includes(`.early.`));return(0,B.isDefined)(e)&&e.absolute?r.map(e=>uW.default.resolve(this.configService.getConfigValue(`gitTopLevel`),e)):r}async commitFiles(e){try{await this.scmHostService.setupGit(),await vQ(`git fetch`),(0,B.isDefined)(e)&&(await vQ(`git checkout ${e}`),await vQ(`git branch --set-upstream-to=origin/${e}`),await vQ(`git pull`));let t=await this.getEarlyFiles();if(t.length===0)return this.logger.info(`No files to commit`),{committedFiles:[],error:``};for(let e of t)await vQ(`git add "${e}"`);let{name:n,email:r}=this.scmHostService.getGitCommiterInfo();await vQ(`git -c user.name="${n}" -c user.email="${r}" commit --no-verify -m "${this.configService.getConfigValue(`autoCommitSkipCi`)?`chore: add early-catch tests [skip ci]`:`chore: add early-catch tests`}"`),this.logger.info(`Committed ${t.length} files`),await vQ(`git push --no-verify`);let{stdout:i}=await vQ(`git rev-parse HEAD`);return{committedFiles:t,error:``,resultCommitSha:i.trim()}}catch(e){let t=e instanceof Error?e.message:`Unknown error`;return this.logger.error(`Failed to commit files: ${t}`),{committedFiles:[],error:t}}finally{await this.scmHostService.teardownGit()}}async checkRefExists(e){try{if(!e)return!1;let{origin:t}=this.scmHostService.getGitOrigin(),{stdout:n}=await vQ(`git ls-remote --heads --tags ${t} ${e}`);return n.trim().length>0}catch(t){return this.logger.warn(`Failed to check if reference '${e}' exists: ${t instanceof Error?t.message:`Unknown error`}`),!1}}async getChangedFilesForPR(e={}){return(await this.getChangedFilesForPRWithStatus(e)).map(e=>e.filePath)}async getChangedFilesForPRWithStatus(e={}){try{let t=await this.scmHostService.getChangedFilesWithStatus();if((0,B.isDefined)(e.absolute)&&e.absolute){let e=await this.getTopLevel();return t.map(t=>({filePath:uW.default.join(e,t.filePath),status:t.status}))}return t}catch(e){let t=e instanceof Error?e.message:`Unknown error`;throw this.logger.error(`Failed to get changed files for PR: ${t}`),Error(`Failed to get changed files for PR: ${t}`)}}async getChangedFilesForCommit(e={}){return(await this.getChangedFilesForCommitWithStatus(e)).map(e=>e.filePath)}async getChangedFilesForCommitWithStatus(e={}){let t=this.configService.getConfigValue(`commitHash`);if(!(0,B.isDefined)(t))throw Error(`commitHash config is required for commit file retrieval`);try{let n=this.configService.getConfigValue(`baseRef`),r;r=(0,B.isDefined)(n)?(await vQ(`git diff --name-status --diff-filter=AM "${await this.getBaseRevision({baseBranch:n})}...${t}"`)).stdout:(await vQ(`git diff-tree --no-commit-id --name-status -r --diff-filter=AM "${t}"`)).stdout;let i=r.trim().split(`
32394
+ `)])].filter(Boolean).filter(e=>e.includes(`.early.`)||uW.default.basename(e).startsWith(`test_early_`));return(0,B.isDefined)(e)&&e.absolute?r.map(e=>uW.default.resolve(this.configService.getConfigValue(`gitTopLevel`),e)):r}async commitFiles(e){try{await this.scmHostService.setupGit(),await vQ(`git fetch`),(0,B.isDefined)(e)&&(await vQ(`git checkout ${e}`),await vQ(`git branch --set-upstream-to=origin/${e}`),await vQ(`git pull`));let t=await this.getEarlyFiles();if(t.length===0)return this.logger.info(`No files to commit`),{committedFiles:[],error:``};let{stdout:n}=await vQ(`git ls-files --others --exclude-standard`),r=n.trim().split(`
32395
+ `).filter(Boolean),i=new Set(t.map(e=>uW.default.dirname(e))),a=new Set;for(let e of i){let t=e;for(;t&&t!==`.`;)a.add(t),t=uW.default.dirname(t)}let o=r.filter(e=>{let t=uW.default.basename(e);return t!==`__init__.py`&&t!==`conftest.py`?!1:a.has(uW.default.dirname(e))}),s=[...new Set([...t,...o])];for(let e of s)await vQ(`git add "${e}"`);let{name:c,email:l}=this.scmHostService.getGitCommiterInfo();await vQ(`git -c user.name="${c}" -c user.email="${l}" commit --no-verify -m "${this.configService.getConfigValue(`autoCommitSkipCi`)?`chore: add early-catch tests [skip ci]`:`chore: add early-catch tests`}"`),this.logger.info(`Committed ${t.length} files`),await vQ(`git push --no-verify`);let{stdout:u}=await vQ(`git rev-parse HEAD`);return{committedFiles:t,error:``,resultCommitSha:u.trim()}}catch(e){let t=e instanceof Error?e.message:`Unknown error`;return this.logger.error(`Failed to commit files: ${t}`),{committedFiles:[],error:t}}finally{await this.scmHostService.teardownGit()}}async checkRefExists(e){try{if(!e)return!1;let{origin:t}=this.scmHostService.getGitOrigin(),{stdout:n}=await vQ(`git ls-remote --heads --tags ${t} ${e}`);return n.trim().length>0}catch(t){return this.logger.warn(`Failed to check if reference '${e}' exists: ${t instanceof Error?t.message:`Unknown error`}`),!1}}async getChangedFilesForPR(e={}){return(await this.getChangedFilesForPRWithStatus(e)).map(e=>e.filePath)}async getChangedFilesForPRWithStatus(e={}){try{let t=await this.scmHostService.getChangedFilesWithStatus();if((0,B.isDefined)(e.absolute)&&e.absolute){let e=await this.getTopLevel();return t.map(t=>({filePath:uW.default.join(e,t.filePath),status:t.status}))}return t}catch(e){let t=e instanceof Error?e.message:`Unknown error`;throw this.logger.error(`Failed to get changed files for PR: ${t}`),Error(`Failed to get changed files for PR: ${t}`)}}async getChangedFilesForCommit(e={}){return(await this.getChangedFilesForCommitWithStatus(e)).map(e=>e.filePath)}async getChangedFilesForCommitWithStatus(e={}){let t=this.configService.getConfigValue(`commitHash`);if(!(0,B.isDefined)(t))throw Error(`commitHash config is required for commit file retrieval`);try{let n=this.configService.getConfigValue(`baseRef`),r;r=(0,B.isDefined)(n)?(await vQ(`git diff --name-status --diff-filter=AM "${await this.getBaseRevision({baseBranch:n})}...${t}"`)).stdout:(await vQ(`git diff-tree --no-commit-id --name-status -r --diff-filter=AM "${t}"`)).stdout;let i=r.trim().split(`
32395
32396
  `).filter(Boolean).map(e=>{let[t,n]=e.split(` `),r=t===`A`?fQ.Added:fQ.Modified;return{filePath:n??``,status:r}}).filter(e=>e.filePath.length>0);if((0,B.isDefined)(e.absolute)&&e.absolute){let e=await this.getTopLevel();return i.map(t=>({filePath:uW.default.join(e,t.filePath),status:t.status}))}return i}catch(e){let t=e instanceof Error?e.message:`Unknown error`;throw this.logger.error(`Failed to get changed files for commit: ${t}`),Error(`Failed to get changed files for commit: ${t}`)}}async getShaByDatetime(e,t){try{let{stdout:n}=await vQ(`git rev-list -1 --before="${t}" ${e}`);return n.trim()}catch{return this.logger.warn(`Could not get SHA from local Git by datetime: ${t} for: ${e}`),``}}async checkout(e){try{await vQ(`git checkout ${e}`),this.logger.info(`Git checkedout to: ${e}`)}catch(t){throw this.logger.error(`Could not checkout to ref: ${e}`),t}}async getCommitDate(){try{let{stdout:e}=await vQ(`git show -s --format=%cI HEAD`);return e.trim()}catch{return this.logger.warn(`Could not get commit date from local Git`),``}}async getFileAtRevision(e,t){try{let{stdout:n}=await vQ(`git show "${t}:${e}"`);return n}catch(n){return n instanceof Error&&(n.message.includes(`does not exist`)||n.message.includes(`exists on disk, but not in`))||this.logger.warn(`Failed to get file ${e} at revision ${t}: ${n instanceof Error?n.message:`Unknown error`}`),null}}async getMergeBase(e){try{try{await vQ(`git fetch origin ${e} --depth=1`)}catch{this.logger.warn(`Could not fetch ${e}, attempting to use local ref`)}let{stdout:t}=await vQ(`git merge-base HEAD origin/${e}`);return t.trim()}catch(t){throw this.logger.warn(`Failed to get merge base for branch ${e}: ${t instanceof Error?t.message:`Unknown error`}`),t}}async getDefaultBranch(){try{let{stdout:e}=await vQ(`git symbolic-ref refs/remotes/origin/HEAD`);return e.trim().replace(`refs/remotes/origin/`,``)}catch(e){return this.logger.debug(`Failed to get default branch, falling back to 'main': ${e instanceof Error?e.message:`Unknown error`}`),`main`}}async getBaseRevision(e){if((0,B.isDefined)(e.baseCommit))return e.baseCommit;if((0,B.isDefined)(e.baseBranch))return await vQ(`git fetch --no-tags origin "${`refs/heads/${e.baseBranch}:refs/remotes/origin/${e.baseBranch}`}"`),`origin/${e.baseBranch}`;let t=await this.getDefaultBranch();return await this.getMergeBase(t)}async getCommitMessage(e){try{let{stdout:t}=await vQ(`git log -1 --format=%s ${e??`HEAD`}`);return t.trim()}catch{return this.logger.warn(`Could not get commit message from local Git`),``}}async getCommitAuthorName(e){try{let{stdout:t}=await vQ(`git log -1 --format=%an ${e??`HEAD`}`);return t.trim()}catch{return this.logger.warn(`Could not get commit author name from local Git`),``}}async getCommitAuthorEmail(e){try{let{stdout:t}=await vQ(`git log -1 --format=%ae ${e??`HEAD`}`);return t.trim()}catch{return this.logger.warn(`Could not get commit author email from local Git`),``}}};xQ=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(lW.SCMHostService)),iQ(2,Ze(sQ)),rQ(`design:paramtypes`,[typeof(yQ=cQ!==void 0&&cQ)==`function`?yQ:Object,typeof(bQ=hQ!==void 0&&hQ)==`function`?bQ:Object,Object])],xQ);function SQ(e,t){return function(){return e.apply(t,arguments)}}const{toString:CQ}=Object.prototype,{getPrototypeOf:wQ}=Object,{iterator:TQ,toStringTag:EQ}=Symbol,DQ=(e=>t=>{let n=CQ.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),OQ=e=>(e=e.toLowerCase(),t=>DQ(t)===e),kQ=e=>t=>typeof t===e,{isArray:AQ}=Array,jQ=kQ(`undefined`);function MQ(e){return e!==null&&!jQ(e)&&e.constructor!==null&&!jQ(e.constructor)&&FQ(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const NQ=OQ(`ArrayBuffer`);function ote(e){let t;return t=typeof ArrayBuffer<`u`&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&NQ(e.buffer),t}const PQ=kQ(`string`),FQ=kQ(`function`),IQ=kQ(`number`),LQ=e=>typeof e==`object`&&!!e,RQ=e=>e===!0||e===!1,zQ=e=>{if(DQ(e)!==`object`)return!1;let t=wQ(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(EQ in e)&&!(TQ in e)},BQ=e=>{if(!LQ(e)||MQ(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},VQ=OQ(`Date`),HQ=OQ(`File`),UQ=OQ(`Blob`),WQ=OQ(`FileList`),GQ=e=>LQ(e)&&FQ(e.pipe),KQ=e=>{let t;return e&&(typeof FormData==`function`&&e instanceof FormData||FQ(e.append)&&((t=DQ(e))===`formdata`||t===`object`&&FQ(e.toString)&&e.toString()===`[object FormData]`))},qQ=OQ(`URLSearchParams`),[JQ,YQ,XQ,ZQ]=[`ReadableStream`,`Request`,`Response`,`Headers`].map(OQ),QQ=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,``);function $Q(e,t,{allOwnKeys:n=!1}={}){if(e==null)return;let r,i;if(typeof e!=`object`&&(e=[e]),AQ(e))for(r=0,i=e.length;r<i;r++)t.call(null,e[r],r,e);else{if(MQ(e))return;let i=n?Object.getOwnPropertyNames(e):Object.keys(e),a=i.length,o;for(r=0;r<a;r++)o=i[r],t.call(null,e[o],o,e)}}function e$(e,t){if(MQ(e))return null;t=t.toLowerCase();let n=Object.keys(e),r=n.length,i;for(;r-- >0;)if(i=n[r],t===i.toLowerCase())return i;return null}const t$=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:global,n$=e=>!jQ(e)&&e!==t$;function r$(){let{caseless:e,skipUndefined:t}=n$(this)&&this||{},n={},r=(r,i)=>{let a=e&&e$(n,i)||i;zQ(n[a])&&zQ(r)?n[a]=r$(n[a],r):zQ(r)?n[a]=r$({},r):AQ(r)?n[a]=r.slice():(!t||!jQ(r))&&(n[a]=r)};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&$Q(arguments[e],r);return n}const i$=(e,t,n,{allOwnKeys:r}={})=>($Q(t,(t,r)=>{n&&FQ(t)?e[r]=SQ(t,n):e[r]=t},{allOwnKeys:r}),e),a$=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),o$=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,`super`,{value:t.prototype}),n&&Object.assign(e.prototype,n)},s$=(e,t,n,r)=>{let i,a,o,s={};if(t||={},e==null)return t;do{for(i=Object.getOwnPropertyNames(e),a=i.length;a-- >0;)o=i[a],(!r||r(o,e,t))&&!s[o]&&(t[o]=e[o],s[o]=!0);e=n!==!1&&wQ(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},c$=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;let r=e.indexOf(t,n);return r!==-1&&r===n},l$=e=>{if(!e)return null;if(AQ(e))return e;let t=e.length;if(!IQ(t))return null;let n=Array(t);for(;t-- >0;)n[t]=e[t];return n},u$=(e=>t=>e&&t instanceof e)(typeof Uint8Array<`u`&&wQ(Uint8Array)),ste=(e,t)=>{let n=(e&&e[TQ]).call(e),r;for(;(r=n.next())&&!r.done;){let n=r.value;t.call(e,n[0],n[1])}},d$=(e,t)=>{let n,r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},cte=OQ(`HTMLFormElement`),lte=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,n){return t.toUpperCase()+n}),ute=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),dte=OQ(`RegExp`),f$=(e,t)=>{let n=Object.getOwnPropertyDescriptors(e),r={};$Q(n,(n,i)=>{let a;(a=t(n,i,e))!==!1&&(r[i]=a||n)}),Object.defineProperties(e,r)},p$=e=>{f$(e,(t,n)=>{if(FQ(e)&&[`arguments`,`caller`,`callee`].indexOf(n)!==-1)return!1;let r=e[n];if(FQ(r)){if(t.enumerable=!1,`writable`in t){t.writable=!1;return}t.set||=()=>{throw Error(`Can not rewrite read-only method '`+n+`'`)}}})},m$=(e,t)=>{let n={},r=e=>{e.forEach(e=>{n[e]=!0})};return AQ(e)?r(e):r(String(e).split(t)),n},h$=()=>{},g$=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function _$(e){return!!(e&&FQ(e.append)&&e[EQ]===`FormData`&&e[TQ])}const v$=e=>{let t=Array(10),n=(e,r)=>{if(LQ(e)){if(t.indexOf(e)>=0)return;if(MQ(e))return e;if(!(`toJSON`in e)){t[r]=e;let i=AQ(e)?[]:{};return $Q(e,(e,t)=>{let a=n(e,r+1);!jQ(a)&&(i[t]=a)}),t[r]=void 0,i}}return e};return n(e,0)},fte=OQ(`AsyncFunction`),pte=e=>e&&(LQ(e)||FQ(e))&&FQ(e.then)&&FQ(e.catch),y$=((e,t)=>e?setImmediate:t?((e,t)=>(t$.addEventListener(`message`,({source:n,data:r})=>{n===t$&&r===e&&t.length&&t.shift()()},!1),n=>{t.push(n),t$.postMessage(e,`*`)}))(`axios@${Math.random()}`,[]):e=>setTimeout(e))(typeof setImmediate==`function`,FQ(t$.postMessage));var b$={isArray:AQ,isArrayBuffer:NQ,isBuffer:MQ,isFormData:KQ,isArrayBufferView:ote,isString:PQ,isNumber:IQ,isBoolean:RQ,isObject:LQ,isPlainObject:zQ,isEmptyObject:BQ,isReadableStream:JQ,isRequest:YQ,isResponse:XQ,isHeaders:ZQ,isUndefined:jQ,isDate:VQ,isFile:HQ,isBlob:UQ,isRegExp:dte,isFunction:FQ,isStream:GQ,isURLSearchParams:qQ,isTypedArray:u$,isFileList:WQ,forEach:$Q,merge:r$,extend:i$,trim:QQ,stripBOM:a$,inherits:o$,toFlatObject:s$,kindOf:DQ,kindOfTest:OQ,endsWith:c$,toArray:l$,forEachEntry:ste,matchAll:d$,isHTMLForm:cte,hasOwnProperty:ute,hasOwnProp:ute,reduceDescriptors:f$,freezeMethods:p$,toObjectSet:m$,toCamelCase:lte,noop:h$,toFiniteNumber:g$,findKey:e$,global:t$,isContextDefined:n$,isSpecCompliantForm:_$,toJSONObject:v$,isAsyncFn:fte,isThenable:pte,setImmediate:y$,asap:typeof queueMicrotask<`u`?queueMicrotask.bind(t$):typeof process<`u`&&process.nextTick||y$,isIterable:e=>e!=null&&FQ(e[TQ])};function x$(e,t,n,r,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=Error().stack,this.message=e,this.name=`AxiosError`,t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),i&&(this.response=i,this.status=i.status?i.status:null)}b$.inherits(x$,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:b$.toJSONObject(this.config),code:this.code,status:this.status}}});const S$=x$.prototype,C$={};[`ERR_BAD_OPTION_VALUE`,`ERR_BAD_OPTION`,`ECONNABORTED`,`ETIMEDOUT`,`ERR_NETWORK`,`ERR_FR_TOO_MANY_REDIRECTS`,`ERR_DEPRECATED`,`ERR_BAD_RESPONSE`,`ERR_BAD_REQUEST`,`ERR_CANCELED`,`ERR_NOT_SUPPORT`,`ERR_INVALID_URL`].forEach(e=>{C$[e]={value:e}}),Object.defineProperties(x$,C$),Object.defineProperty(S$,`isAxiosError`,{value:!0}),x$.from=(e,t,n,r,i,a)=>{let o=Object.create(S$);b$.toFlatObject(e,o,function(e){return e!==Error.prototype},e=>e!==`isAxiosError`);let s=e&&e.message?e.message:`Error`,c=t==null&&e?e.code:t;return x$.call(o,s,c,n,r,i),e&&o.cause==null&&Object.defineProperty(o,`cause`,{value:e,configurable:!0}),o.name=e&&e.name||`Error`,a&&Object.assign(o,a),o};var w$=u(aH(),1).default;function T$(e){return b$.isPlainObject(e)||b$.isArray(e)}function E$(e){return b$.endsWith(e,`[]`)?e.slice(0,-2):e}function D$(e,t,n){return e?e.concat(t).map(function(e,t){return e=E$(e),!n&&t?`[`+e+`]`:e}).join(n?`.`:``):t}function O$(e){return b$.isArray(e)&&!e.some(T$)}const k$=b$.toFlatObject(b$,{},null,function(e){return/^is[A-Z]/.test(e)});function A$(e,t,n){if(!b$.isObject(e))throw TypeError(`target must be an object`);t||=new(w$||FormData),n=b$.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!b$.isUndefined(t[e])});let r=n.metaTokens,i=n.visitor||l,a=n.dots,o=n.indexes,s=(n.Blob||typeof Blob<`u`&&Blob)&&b$.isSpecCompliantForm(t);if(!b$.isFunction(i))throw TypeError(`visitor must be a function`);function c(e){if(e===null)return``;if(b$.isDate(e))return e.toISOString();if(b$.isBoolean(e))return e.toString();if(!s&&b$.isBlob(e))throw new x$(`Blob is not supported. Use a Buffer instead.`);return b$.isArrayBuffer(e)||b$.isTypedArray(e)?s&&typeof Blob==`function`?new Blob([e]):Buffer.from(e):e}function l(e,n,i){let s=e;if(e&&!i&&typeof e==`object`){if(b$.endsWith(n,`{}`))n=r?n:n.slice(0,-2),e=JSON.stringify(e);else if(b$.isArray(e)&&O$(e)||(b$.isFileList(e)||b$.endsWith(n,`[]`))&&(s=b$.toArray(e)))return n=E$(n),s.forEach(function(e,r){!(b$.isUndefined(e)||e===null)&&t.append(o===!0?D$([n],r,a):o===null?n:n+`[]`,c(e))}),!1}return T$(e)?!0:(t.append(D$(i,n,a),c(e)),!1)}let u=[],d=Object.assign(k$,{defaultVisitor:l,convertValue:c,isVisitable:T$});function f(e,n){if(!b$.isUndefined(e)){if(u.indexOf(e)!==-1)throw Error(`Circular reference detected in `+n.join(`.`));u.push(e),b$.forEach(e,function(e,r){(!(b$.isUndefined(e)||e===null)&&i.call(t,e,b$.isString(r)?r.trim():r,n,d))===!0&&f(e,n?n.concat(r):[r])}),u.pop()}}if(!b$.isObject(e))throw TypeError(`data must be an object`);return f(e),t}function j$(e){let t={"!":`%21`,"'":`%27`,"(":`%28`,")":`%29`,"~":`%7E`,"%20":`+`,"%00":`\0`};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function M$(e,t){this._pairs=[],e&&A$(e,this,t)}const N$=M$.prototype;N$.append=function(e,t){this._pairs.push([e,t])},N$.toString=function(e){let t=e?function(t){return e.call(this,t,j$)}:j$;return this._pairs.map(function(e){return t(e[0])+`=`+t(e[1])},``).join(`&`)};function P$(e){return encodeURIComponent(e).replace(/%3A/gi,`:`).replace(/%24/g,`$`).replace(/%2C/gi,`,`).replace(/%20/g,`+`)}function F$(e,t,n){if(!t)return e;let r=n&&n.encode||P$;b$.isFunction(n)&&(n={serialize:n});let i=n&&n.serialize,a;if(a=i?i(t,n):b$.isURLSearchParams(t)?t.toString():new M$(t,n).toString(r),a){let t=e.indexOf(`#`);t!==-1&&(e=e.slice(0,t)),e+=(e.indexOf(`?`)===-1?`?`:`&`)+a}return e}var I$=class{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&=[]}forEach(e){b$.forEach(this.handlers,function(t){t!==null&&e(t)})}},L$={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},mte=T.default.URLSearchParams;const R$=`abcdefghijklmnopqrstuvwxyz`,z$={DIGIT:`0123456789`,ALPHA:R$,ALPHA_DIGIT:R$+`ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`};var B$={isNode:!0,classes:{URLSearchParams:mte,FormData:w$,Blob:typeof Blob<`u`&&Blob||null},ALPHABET:z$,generateString:(e=16,t=z$.ALPHA_DIGIT)=>{let n=``,{length:r}=t,i=new Uint32Array(e);x.default.randomFillSync(i);for(let a=0;a<e;a++)n+=t[i[a]%r];return n},protocols:[`http`,`https`,`file`,`data`]},V$=c({hasBrowserEnv:()=>H$,hasStandardBrowserEnv:()=>W$,hasStandardBrowserWebWorkerEnv:()=>G$,navigator:()=>U$,origin:()=>K$});const H$=typeof window<`u`&&typeof document<`u`,U$=typeof navigator==`object`&&navigator||void 0,W$=H$&&(!U$||[`ReactNative`,`NativeScript`,`NS`].indexOf(U$.product)<0),G$=typeof WorkerGlobalScope<`u`&&self instanceof WorkerGlobalScope&&typeof self.importScripts==`function`,K$=H$&&window.location.href||`http://localhost`;var q$={...V$,...B$};function J$(e,t){return A$(e,new q$.classes.URLSearchParams,{visitor:function(e,t,n,r){return q$.isNode&&b$.isBuffer(e)?(this.append(t,e.toString(`base64`)),!1):r.defaultVisitor.apply(this,arguments)},...t})}function Y$(e){return b$.matchAll(/\w+|\[(\w*)]/g,e).map(e=>e[0]===`[]`?``:e[1]||e[0])}function X$(e){let t={},n=Object.keys(e),r,i=n.length,a;for(r=0;r<i;r++)a=n[r],t[a]=e[a];return t}function Z$(e){function t(e,n,r,i){let a=e[i++];if(a===`__proto__`)return!0;let o=Number.isFinite(+a),s=i>=e.length;return a=!a&&b$.isArray(r)?r.length:a,s?(b$.hasOwnProp(r,a)?r[a]=[r[a],n]:r[a]=n,!o):((!r[a]||!b$.isObject(r[a]))&&(r[a]=[]),t(e,n,r[a],i)&&b$.isArray(r[a])&&(r[a]=X$(r[a])),!o)}if(b$.isFormData(e)&&b$.isFunction(e.entries)){let n={};return b$.forEachEntry(e,(e,r)=>{t(Y$(e),r,n,0)}),n}return null}function Q$(e,t,n){if(b$.isString(e))try{return(t||JSON.parse)(e),b$.trim(e)}catch(e){if(e.name!==`SyntaxError`)throw e}return(n||JSON.stringify)(e)}const $$={transitional:L$,adapter:[`xhr`,`http`,`fetch`],transformRequest:[function(e,t){let n=t.getContentType()||``,r=n.indexOf(`application/json`)>-1,i=b$.isObject(e);if(i&&b$.isHTMLForm(e)&&(e=new FormData(e)),b$.isFormData(e))return r?JSON.stringify(Z$(e)):e;if(b$.isArrayBuffer(e)||b$.isBuffer(e)||b$.isStream(e)||b$.isFile(e)||b$.isBlob(e)||b$.isReadableStream(e))return e;if(b$.isArrayBufferView(e))return e.buffer;if(b$.isURLSearchParams(e))return t.setContentType(`application/x-www-form-urlencoded;charset=utf-8`,!1),e.toString();let a;if(i){if(n.indexOf(`application/x-www-form-urlencoded`)>-1)return J$(e,this.formSerializer).toString();if((a=b$.isFileList(e))||n.indexOf(`multipart/form-data`)>-1){let t=this.env&&this.env.FormData;return A$(a?{"files[]":e}:e,t&&new t,this.formSerializer)}}return i||r?(t.setContentType(`application/json`,!1),Q$(e)):e}],transformResponse:[function(e){let t=this.transitional||$$.transitional,n=t&&t.forcedJSONParsing,r=this.responseType===`json`;if(b$.isResponse(e)||b$.isReadableStream(e))return e;if(e&&b$.isString(e)&&(n&&!this.responseType||r)){let n=!(t&&t.silentJSONParsing)&&r;try{return JSON.parse(e,this.parseReviver)}catch(e){if(n)throw e.name===`SyntaxError`?x$.from(e,x$.ERR_BAD_RESPONSE,this,null,this.response):e}}return e}],timeout:0,xsrfCookieName:`XSRF-TOKEN`,xsrfHeaderName:`X-XSRF-TOKEN`,maxContentLength:-1,maxBodyLength:-1,env:{FormData:q$.classes.FormData,Blob:q$.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:`application/json, text/plain, */*`,"Content-Type":void 0}}};b$.forEach([`delete`,`get`,`head`,`post`,`put`,`patch`],e=>{$$.headers[e]={}});const hte=b$.toObjectSet([`age`,`authorization`,`content-length`,`content-type`,`etag`,`expires`,`from`,`host`,`if-modified-since`,`if-unmodified-since`,`last-modified`,`location`,`max-forwards`,`proxy-authorization`,`referer`,`retry-after`,`user-agent`]);var gte=e=>{let t={},n,r,i;return e&&e.split(`
32396
32397
  `).forEach(function(e){i=e.indexOf(`:`),n=e.substring(0,i).trim().toLowerCase(),r=e.substring(i+1).trim(),!(!n||t[n]&&hte[n])&&(n===`set-cookie`?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+`, `+r:r)}),t};const _te=Symbol(`internals`);function e1(e){return e&&String(e).trim().toLowerCase()}function t1(e){return e===!1||e==null?e:b$.isArray(e)?e.map(t1):String(e)}function n1(e){let t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const vte=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function r1(e,t,n,r,i){if(b$.isFunction(r))return r.call(this,t,n);if(i&&(t=n),b$.isString(t)){if(b$.isString(r))return t.indexOf(r)!==-1;if(b$.isRegExp(r))return r.test(t)}}function yte(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}function bte(e,t){let n=b$.toCamelCase(` `+t);[`get`,`set`,`has`].forEach(r=>{Object.defineProperty(e,r+n,{value:function(e,n,i){return this[r].call(this,t,e,n,i)},configurable:!0})})}var i1=class{constructor(e){e&&this.set(e)}set(e,t,n){let r=this;function i(e,t,n){let i=e1(t);if(!i)throw Error(`header name must be a non-empty string`);let a=b$.findKey(r,i);(!a||r[a]===void 0||n===!0||n===void 0&&r[a]!==!1)&&(r[a||t]=t1(e))}let a=(e,t)=>b$.forEach(e,(e,n)=>i(e,n,t));if(b$.isPlainObject(e)||e instanceof this.constructor)a(e,t);else if(b$.isString(e)&&(e=e.trim())&&!vte(e))a(gte(e),t);else if(b$.isObject(e)&&b$.isIterable(e)){let n={},r,i;for(let t of e){if(!b$.isArray(t))throw TypeError(`Object iterator must return a key-value pair`);n[i=t[0]]=(r=n[i])?b$.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}a(n,t)}else e!=null&&i(t,e,n);return this}get(e,t){if(e=e1(e),e){let n=b$.findKey(this,e);if(n){let e=this[n];if(!t)return e;if(t===!0)return n1(e);if(b$.isFunction(t))return t.call(this,e,n);if(b$.isRegExp(t))return t.exec(e);throw TypeError(`parser must be boolean|regexp|function`)}}}has(e,t){if(e=e1(e),e){let n=b$.findKey(this,e);return!!(n&&this[n]!==void 0&&(!t||r1(this,this[n],n,t)))}return!1}delete(e,t){let n=this,r=!1;function i(e){if(e=e1(e),e){let i=b$.findKey(n,e);i&&(!t||r1(n,n[i],i,t))&&(delete n[i],r=!0)}}return b$.isArray(e)?e.forEach(i):i(e),r}clear(e){let t=Object.keys(this),n=t.length,r=!1;for(;n--;){let i=t[n];(!e||r1(this,this[i],i,e,!0))&&(delete this[i],r=!0)}return r}normalize(e){let t=this,n={};return b$.forEach(this,(r,i)=>{let a=b$.findKey(n,i);if(a){t[a]=t1(r),delete t[i];return}let o=e?yte(i):String(i).trim();o!==i&&delete t[i],t[o]=t1(r),n[o]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let t=Object.create(null);return b$.forEach(this,(n,r)=>{n!=null&&n!==!1&&(t[r]=e&&b$.isArray(n)?n.join(`, `):n)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+`: `+t).join(`
32397
32398
  `)}getSetCookie(){return this.get(`set-cookie`)||[]}get[Symbol.toStringTag](){return`AxiosHeaders`}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){let n=new this(e);return t.forEach(e=>n.set(e)),n}static accessor(e){let t=(this[_te]=this[_te]={accessors:{}}).accessors,n=this.prototype;function r(e){let r=e1(e);t[r]||(bte(n,e),t[r]=!0)}return b$.isArray(e)?e.forEach(r):r(e),this}};i1.accessor([`Content-Type`,`Content-Length`,`Accept`,`Accept-Encoding`,`User-Agent`,`Authorization`]),b$.reduceDescriptors(i1.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[n]=e}}}),b$.freezeMethods(i1);function a1(e,t){let n=this||$$,r=t||n,i=i1.from(r.headers),a=r.data;return b$.forEach(e,function(e){a=e.call(n,a,i.normalize(),t?t.status:void 0)}),i.normalize(),a}function o1(e){return!!(e&&e.__CANCEL__)}function s1(e,t,n){x$.call(this,e??`canceled`,x$.ERR_CANCELED,t,n),this.name=`CanceledError`}b$.inherits(s1,x$,{__CANCEL__:!0});function c1(e,t,n){let r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new x$(`Request failed with status code `+n.status,[x$.ERR_BAD_REQUEST,x$.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function l1(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function xte(e,t){return t?e.replace(/\/?\/$/,``)+`/`+t.replace(/^\/+/,``):e}function u1(e,t,n){let r=!l1(t);return e&&(r||n==0)?xte(e,t):t}var d1=u(sH(),1),f1=u(oH(),1);const p1=`1.12.2`;function m1(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||``}const h1=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function g1(e,t,n){let r=n&&n.Blob||q$.classes.Blob,i=m1(e);if(t===void 0&&r&&(t=!0),i===`data`){e=i.length?e.slice(i.length+1):e;let n=h1.exec(e);if(!n)throw new x$(`Invalid URL`,x$.ERR_INVALID_URL);let a=n[1],o=n[2],s=n[3],c=Buffer.from(decodeURIComponent(s),o?`base64`:`utf8`);if(t){if(!r)throw new x$(`Blob is not supported`,x$.ERR_NOT_SUPPORT);return new r([c],{type:a})}return c}throw new x$(`Unsupported protocol `+i,x$.ERR_NOT_SUPPORT)}const _1=Symbol(`internals`);var v1=class extends D.default.Transform{constructor(e){e=b$.toFlatObject(e,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(e,t)=>!b$.isUndefined(t[e])),super({readableHighWaterMark:e.chunkSize});let t=this[_1]={timeWindow:e.timeWindow,chunkSize:e.chunkSize,maxRate:e.maxRate,minChunkSize:e.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on(`newListener`,e=>{e===`progress`&&(t.isCaptured||=!0)})}_read(e){let t=this[_1];return t.onReadCallback&&t.onReadCallback(),super._read(e)}_transform(e,t,n){let r=this[_1],i=r.maxRate,a=this.readableHighWaterMark,o=r.timeWindow,s=i/(1e3/o),c=r.minChunkSize===!1?0:Math.max(r.minChunkSize,s*.01),l=(e,t)=>{let n=Buffer.byteLength(e);r.bytesSeen+=n,r.bytes+=n,r.isCaptured&&this.emit(`progress`,r.bytesSeen),this.push(e)?process.nextTick(t):r.onReadCallback=()=>{r.onReadCallback=null,process.nextTick(t)}},u=(e,t)=>{let n=Buffer.byteLength(e),u=null,d=a,f,p=0;if(i){let e=Date.now();(!r.ts||(p=e-r.ts)>=o)&&(r.ts=e,f=s-r.bytes,r.bytes=f<0?-f:0,p=0),f=s-r.bytes}if(i){if(f<=0)return setTimeout(()=>{t(null,e)},o-p);f<d&&(d=f)}d&&n>d&&n-d>c&&(u=e.subarray(d),e=e.subarray(0,d)),l(e,u?()=>{process.nextTick(t,null,u)}:t)};u(e,function e(t,r){if(t)return n(t);r?u(r,e):n(null)})}};const{asyncIterator:y1}=Symbol,b1=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[y1]?yield*e[y1]():yield e},x1=q$.ALPHABET.ALPHA_DIGIT+`-_`,S1=typeof TextEncoder==`function`?new TextEncoder:new b.default.TextEncoder,C1=S1.encode(`\r
@@ -32408,7 +32409,7 @@ var n=require(`buffer`),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.fr
32408
32409
  `,`
32409
32410
  `)!==a.replaceAll(`\r
32410
32411
  `,`
32411
- `)}extractMethodText(e,t){return t.slice(e.startIndex,e.endIndex)}createChangedMethod(e,t,n){return{name:t.name,type:t.type,parentName:`parentName`in t?t.parentName:void 0,changeType:n,filePath:e,canCreateTests:t.canCreateTests}}};K0=aQ([et(),iQ(0,Ze(sQ)),rQ(`design:paramtypes`,[Object])],K0);var jte,Mte,Nte;let q0=class{constructor(e,t,n,r){this.gitService=e,this.changedMethodsDetector=t,this.tsAgent=n,this.logger=r}async execute(e,t,n){if(!(0,B.isDefined)(t.baseRevision))return{kept:e};let r=[...new Set(e.map(e=>e.filePath))],i=await this.detectChangedMethods(r,t.baseRevision,t.projectRootPath),a=new Set(i.filter(e=>e.changeType!==`deleted`&&e.canCreateTests).map(e=>`${e.filePath}:${e.name}:${e.parentName??``}`)),o=[],s=[];for(let t of e){let e=`${t.filePath}:${t.testable.name}:${`parentName`in t.testable?t.testable.parentName??``:``}`;a.has(e)?o.push(t):s.push(t)}return{kept:[...o,...s]}}async detectChangedMethods(e,t,n){let r=await this.gitService.getTopLevel(),i=[];for(let a of e){let e=await this.detectChangedMethodsForFile(a,t,n,r);i.push(...e)}return i}async detectChangedMethodsForFile(e,t,n,r){let i=null;try{let a=uW.default.isAbsolute(e)?e:uW.default.join(n,e),o=uW.default.relative(r,a),s=await this.gitService.getFileAtRevision(o,t),c=await this.getBaseMethodsFromContent(s,a,n);(0,B.isDefined)(c.temporaryFilePath)&&(i=c.temporaryFilePath);let l=await this.getCurrentMethods(a),u=await g.readFile(a,`utf8`);return this.changedMethodsDetector.detectChanges(e,c.methods,l,s,u)}catch(t){this.logger.warn(`Failed to detect changed methods for `+e+`: `+(t instanceof Error?t.message:`Unknown error`)+`. Changed-function detection disabled for this file — all its functions will be treated as changed. Fix: add 'fetch-depth: 0' to your checkout step.`);try{let t=uW.default.isAbsolute(e)?e:uW.default.join(n,e);return(await this.getCurrentMethods(t)).map(t=>({filePath:e,name:t.name,type:t.type,parentName:`parentName`in t?t.parentName:void 0,changeType:`modified`,canCreateTests:t.canCreateTests}))}catch{return[]}}finally{await this.cleanupTemporaryFile(i)}}async getBaseMethodsFromContent(e,t,n){if(!(0,B.isDefined)(e)||(0,B.isEmpty)(e))return{methods:[],temporaryFilePath:null};let r=p.default.resolve(n,`.early-temp`);await g.mkdir(r,{recursive:!0});let i=p.default.join(r,`base-${Date.now()}-${p.default.basename(t)}`);await g.writeFile(i,e);let a=i.replaceAll(`\\`,`/`);return{methods:((await this.tsAgent.getTestables(a))[0]?.[1]??[]).filter(e=>e.canCreateTests&&e.type!==`class`),temporaryFilePath:i}}async getCurrentMethods(e){let t=e.replaceAll(`\\`,`/`);return((await this.tsAgent.getTestables(t))[0]?.[1]??[]).filter(e=>e.canCreateTests&&e.type!==`class`)}async cleanupTemporaryFile(e){if((0,B.isDefined)(e))try{await g.unlink(e)}catch{}}};q0=aQ([et(),iQ(0,Ze(xQ)),iQ(1,Ze(K0)),iQ(2,Ze(lW.TSAgent)),iQ(3,Ze(sQ)),rQ(`design:paramtypes`,[typeof(jte=xQ!==void 0&&xQ)==`function`?jte:Object,typeof(Mte=K0!==void 0&&K0)==`function`?Mte:Object,typeof(Nte=cW.TSAgent!==void 0&&cW.TSAgent)==`function`?Nte:Object,Object])],q0);var J0;let Y0=class{constructor(e){this.configService=e}async execute(e,t,n){let r=t.coverageReport?.tree,i=t.coverageReport?.threshold??this.configService.getConfigValue(`coverageThreshold`)??0;if(!(0,B.isDefined)(r))return{kept:e};let a=[];for(let t of e){let e=this.findFileCoverage(r,t.filePath);if(!(0,B.isDefined)(e?.testables)){a.push(t);continue}let o=t.testable.type===`method`?t.testable.parentName:void 0,s=e.testables.find(e=>e.name===t.testable.name&&((0,B.isDefined)(o)?e.parentName===o:!(0,B.isDefined)(e.parentName)));if(!(0,B.isDefined)(s)||!(0,B.isDefined)(s.percentage)){a.push(t);continue}if(s.percentage>i){n.push({filePath:t.filePath,testableName:t.testable.name,reason:`above-coverage-threshold`});continue}a.push(t)}return{kept:a}}findFileCoverage(e,t){return e[t.startsWith(`/`)?t:`/${t}`]??null}};Y0=aQ([et(),iQ(0,Ze(cQ)),rQ(`design:paramtypes`,[typeof(J0=cQ!==void 0&&cQ)==`function`?J0:Object])],Y0);let X0=class{async execute(e,t,n){let r=[];for(let i of e){let e=i.filePath.toLowerCase(),a=dQ.allowedExtensions.some(t=>e.endsWith(t)),o=uW.default.isAbsolute(i.filePath)?uW.default.relative(t.gitTopLevel,i.filePath):i.filePath;if(!a){n.push({filePath:o,reason:`not-code-file`});continue}if(dQ.excludePatterns.some(t=>e.includes(t.toLowerCase()))){n.push({filePath:o,reason:`excluded-pattern`});continue}r.push(i)}return{kept:r}}};X0=aQ([et()],X0);var Z0;let Q0=class{constructor(e){this.configService=e}async execute(e,t,n){let r=this.configService.getConfigValue(`maxTestables`)??1/0;if(e.length<=r)return{kept:e};let i=e.slice(0,r);for(let t=r;t<e.length;t++){let r=e[t];n.push({filePath:r.filePath,testableName:r.testable.name,reason:`limit-reached`})}return{kept:i}}};Q0=aQ([et(),iQ(0,Ze(cQ)),rQ(`design:paramtypes`,[typeof(Z0=cQ!==void 0&&cQ)==`function`?Z0:Object])],Q0);var $0=u(Uz());function e2(e,t){let n=uW.default.relative(e,t);return n===``||!n.startsWith(`..`)&&!uW.default.isAbsolute(n)}function t2(e,t,n){let r=uW.default.isAbsolute(e)&&e2(n,e)?e:uW.default.join(n,e),i=(0,$0.default)(t,{cwd:m.default.existsSync(r)&&m.default.statSync(r).isDirectory()?r:uW.default.dirname(r)});return i!==null&&!e2(n,i)?null:i}function Pte(e,t){let n=[t2(e,`package.json`,t),t2(e,`project.json`,t)].filter(B.isDefined).filter(e=>e2(t,e));if(n.length===0)return t;let r=n.reduce((e,t)=>e.length>t.length?e:t,n[0]);return uW.default.dirname(r)}const n2=[`pyproject.toml`,`setup.py`,`setup.cfg`,`requirements.txt`],r2=[`package.json`,`tsconfig.json`],i2=[`.py`],a2=[`.ts`,`.tsx`,`.js`,`.jsx`];function o2(e,t){return t.some(t=>e.endsWith(t))}function s2(e){if(o2(e,i2))return`python`;if(o2(e,a2))return`typescript`}function c2(e,t){if(e&&t)return`mixed`;if(e)return`python`;if(t)return`typescript`}function l2(e){let t=m.default.readdirSync(e,{recursive:!0});return c2(t.some(e=>o2(e,i2)),t.some(e=>o2(e,a2)))}function u2(e){return c2(n2.some(t=>m.default.existsSync(uW.default.join(e,t))),r2.some(t=>m.default.existsSync(uW.default.join(e,t))))}function d2(e,t){if(t!==void 0&&t!==``){let n=uW.default.isAbsolute(t)?t:uW.default.join(e,t);return m.default.existsSync(n)&&m.default.statSync(n).isFile()?s2(n):m.default.existsSync(n)&&m.default.statSync(n).isDirectory()?l2(n):s2(t)??u2(e)}return u2(e)}const f2={detectProjectRoot(e,t,n){if(t.length===0)return n.verbose(`No changed files provided, using root path`),e;let r=t[0],i=Pte(uW.default.isAbsolute(r)?r:uW.default.join(e,r),e);return i===uW.default.normalize(e)?(n.verbose(`Using workspace root path`),e):(n.info(`Detected nested project root: ${i} (from file: ${r})`),i)}};function p2(e,t){let n=uW.default.relative(e,t);return n!==``&&!n.startsWith(`..`)&&!uW.default.isAbsolute(n)}let m2=class{constructor(e){this.logger=e}async execute(e,t,n){if((0,B.isEmpty)(e))return{kept:[],projectRootPath:t.rootPath};let r=e.map(e=>uW.default.isAbsolute(e.filePath)?e.filePath:uW.default.join(t.rootPath,e.filePath)),i=f2.detectProjectRoot(t.rootPath,r,this.logger),a=[];for(let[t,o]of e.entries()){let e=r[t];if(!p2(i,e)){n.push({filePath:o.filePath,reason:`outside-project`});continue}let s=uW.default.relative(i,e);a.push({filePath:s,status:o.status})}return{kept:a,projectRootPath:i}}};m2=aQ([et(),iQ(0,Ze(sQ)),rQ(`design:paramtypes`,[Object])],m2);let h2=class{constructor(e){this.tsAgent=e}async execute(e,t,n){let r=e.map(e=>e.filePath);if((0,B.isEmpty)(r))return{kept:[]};let i=await this.tsAgent.getTestableFileMap(r),a=[];for(let e of r){let r=this.getEntriesForFile(e,i,t.projectRootPath);if(!(0,B.isDefined)(r)||(0,B.isEmpty)(r)){n.push({filePath:e,reason:`no-testables`});continue}this.processEntriesForFile(e,r,a,n)||n.push({filePath:e,reason:`no-testables`})}return{kept:a}}processEntriesForFile(e,t,n,r){let i=!1;for(let a of t){let{testable:t}=a;if(!t.canCreateTests||t.type===`class`)continue;if(i=!0,(0,B.isDefined)(a.testPath)){r.push({filePath:e,testableName:t.name,reason:`has-test-file`});continue}let o=e.startsWith(`/`)?e.slice(1):e;n.push({filePath:o,testable:t})}return i}getEntriesForFile(e,t,n){if((0,B.isDefined)(t[e]))return t[e];let r=uW.default.resolve(n,e);if((0,B.isDefined)(t[r]))return t[r]}};h2=aQ([et(),iQ(0,Ze(lW.TSAgent)),rQ(`design:paramtypes`,[Object])],h2);var Fte,g2,_2,v2,y2,b2,x2;function Ite(e,t){return{async execute(n,r,i){return e(r)?t.execute(n,r,i):{kept:n}}}}let S2=class{filters;constructor(e,t,n,r,i,a,o,s){this.configService=e,this.tsAgent=t,this.fileNameFilter=n,this.projectRootFilter=r,this.testableMapFilter=i,this.changedMethodsFilter=a,this.coverageFilter=o,this.limitFilter=s,this.filters=[this.fileNameFilter,this.projectRootFilter,this.testableMapFilter,Ite(e=>e.changedMethodsOnly&&e.hasDiffContext,this.changedMethodsFilter),this.coverageFilter,this.limitFilter]}async getTestablesToGenerate(e){let t={rootPath:e.rootPath,projectRootPath:e.rootPath,gitTopLevel:e.gitTopLevel,changedMethodsOnly:e.changedMethodsOnly??!1,hasDiffContext:e.hasDiffContext,baseRevision:e.baseRevision,coverageReport:e.coverageReport};return this.runPipeline([...e.changedFiles],t)}async runPipeline(e,t){let n=[],r=e,i=t.projectRootPath;for(let e of this.filters){let a={...t,projectRootPath:i},o=await e.execute(r,a,n);if((0,B.isDefined)(o.projectRootPath)&&!(0,B.isEmpty)(o.projectRootPath)&&(i=o.projectRootPath,this.tsAgent.updateRootPath(i),this.configService.updateConfigValue(`rootPath`,i)),(0,B.isEmpty)(o.kept))return{testables:[],filteredOut:n,projectRootPath:i};r=o.kept}return{testables:r,filteredOut:n,projectRootPath:i}}};S2=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(lW.TSAgent)),iQ(2,Ze(X0)),iQ(3,Ze(m2)),iQ(4,Ze(h2)),iQ(5,Ze(q0)),iQ(6,Ze(Y0)),iQ(7,Ze(Q0)),rQ(`design:paramtypes`,[typeof(Fte=cQ!==void 0&&cQ)==`function`?Fte:Object,Object,typeof(g2=X0!==void 0&&X0)==`function`?g2:Object,typeof(_2=m2!==void 0&&m2)==`function`?_2:Object,typeof(v2=h2!==void 0&&h2)==`function`?v2:Object,typeof(y2=q0!==void 0&&q0)==`function`?y2:Object,typeof(b2=Y0!==void 0&&Y0)==`function`?b2:Object,typeof(x2=Q0!==void 0&&Q0)==`function`?x2:Object])],S2);var C2=u(lH(),1);const w2=`axios-retry`;function T2(e){return e.response||!e.code||[`ERR_CANCELED`,`ECONNABORTED`].includes(e.code)?!1:(0,C2.default)(e)}const E2=[`get`,`head`,`options`],D2=E2.concat([`put`,`delete`]);function O2(e){return e.code!==`ECONNABORTED`&&(!e.response||e.response.status===429||e.response.status>=500&&e.response.status<=599)}function k2(e){return e.config?.method?O2(e)&&E2.indexOf(e.config.method)!==-1:!1}function A2(e){return e.config?.method?O2(e)&&D2.indexOf(e.config.method)!==-1:!1}function j2(e){return T2(e)||A2(e)}function M2(e=void 0){let t=e?.response?.headers[`retry-after`];if(!t)return 0;let n=(Number(t)||0)*1e3;return n===0&&(n=(new Date(t).valueOf()||0)-Date.now()),Math.max(0,n)}function Lte(e=0,t=void 0){return Math.max(0,M2(t))}function N2(e=0,t=void 0,n=100){let r=2**e*n,i=Math.max(r,M2(t));return i+i*.2*Math.random()}function Rte(e=100){return(t=0,n=void 0)=>{let r=t*e;return Math.max(r,M2(n))}}const zte={retries:3,retryCondition:j2,retryDelay:Lte,shouldResetTimeout:!1,onRetry:()=>{},onMaxRetryTimesExceeded:()=>{},validateResponse:null};function P2(e,t){return{...zte,...t,...e[w2]}}function F2(e,t,n=!1){let r=P2(e,t||{});return r.retryCount=r.retryCount||0,(!r.lastRequestTime||n)&&(r.lastRequestTime=Date.now()),e[w2]=r,r}function I2(e,t){e.defaults.agent===t.agent&&delete t.agent,e.defaults.httpAgent===t.httpAgent&&delete t.httpAgent,e.defaults.httpsAgent===t.httpsAgent&&delete t.httpsAgent}async function L2(e,t){let{retries:n,retryCondition:r}=e,i=(e.retryCount||0)<n&&r(t);if(typeof i==`object`)try{return await i!==!1}catch{return!1}return i}async function R2(e,t,n,r){t.retryCount+=1;let{retryDelay:i,shouldResetTimeout:a,onRetry:o}=t,s=i(t.retryCount,n);if(I2(e,r),!a&&r.timeout&&t.lastRequestTime){let e=Date.now()-t.lastRequestTime,i=r.timeout-e-s;if(i<=0)return Promise.reject(n);r.timeout=i}return r.transformRequest=[e=>e],await o(t.retryCount,n,r),r.signal?.aborted?Promise.resolve(e(r)):new Promise(t=>{let n=()=>{clearTimeout(i),t(e(r))},i=setTimeout(()=>{t(e(r)),r.signal?.removeEventListener&&r.signal.removeEventListener(`abort`,n)},s);r.signal?.addEventListener&&r.signal.addEventListener(`abort`,n,{once:!0})})}async function z2(e,t){e.retryCount>=e.retries&&await e.onMaxRetryTimesExceeded(t,e.retryCount)}const B2=(e,t)=>({requestInterceptorId:e.interceptors.request.use(e=>(F2(e,t,!0),e[w2]?.validateResponse&&(e.validateStatus=()=>!1),e)),responseInterceptorId:e.interceptors.response.use(null,async n=>{let{config:r}=n;if(!r)return Promise.reject(n);let i=F2(r,t);return n.response&&i.validateResponse?.(n.response)?n.response:await L2(i,n)?R2(e,i,n,r):(await z2(i,n),Promise.reject(n))})});B2.isNetworkError=T2,B2.isSafeRequestError=k2,B2.isIdempotentRequestError=A2,B2.isNetworkOrIdempotentRequestError=j2,B2.exponentialDelay=N2,B2.linearDelay=Rte,B2.isRetryableError=O2;const V2=Error(`request for lock canceled`);var H2=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},U2=class{constructor(e,t=V2){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((n,r)=>{let i={resolve:n,reject:r,weight:e,priority:t},a=W2(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return H2(this,arguments,void 0,function*(e,t=1,n=0){let[r,i]=yield this.acquire(t,n);try{return yield e(r)}finally{i()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),Bte(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let n=this._weightedWaiters[t-1];if(!n)continue;let r=n.findIndex(t=>t.priority<=e);(r===-1?n:n.splice(0,r)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function Bte(e,t){let n=W2(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function W2(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var G2=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},K2=class{constructor(e){this._semaphore=new U2(1,e)}acquire(){return G2(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};new TextEncoder;const q2=new TextDecoder;function J2(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function Y2(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:q2.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=q2.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`).replace(/\s/g,``);try{return J2(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}var X2=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},Z2=class extends X2{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`};Symbol.asyncIterator;function Q2(e){return typeof e==`object`&&!!e}var $2=e=>{if(!Q2(e)||Object.prototype.toString.call(e)!==`[object Object]`)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t};function e4(e){if(typeof e!=`string`)throw new Z2(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new Z2(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new Z2(`Invalid JWT`);if(!t)throw new Z2(`JWTs must contain a payload`);let r;try{r=Y2(t)}catch{throw new Z2(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(q2.decode(r))}catch{throw new Z2(`Failed to parse the decoded payload as JSON`)}if(!$2(i))throw new Z2(`Invalid JWT Claims Set`);return i}const t4=e=>{let t=e4(e).exp;return(0,B.isDefined)(t)?t*1e3:null},n4=e=>{if(!(0,B.isDefined)(e))return!0;let t=t4(e);return(0,B.isDefined)(t)?t>Date.now():!0};let r4=class{jwtToken=null;refreshTokenCallback=null;observer=new B.Observer;refreshTokenMutex=new K2;setJWTToken(e){this.jwtToken=e,this.observer.notifyAll(e)}async getJWTToken(){return(0,B.isDefined)(this.jwtToken)?(this.isTokenValid()||await this.refreshTokenMutex.runExclusive(async()=>{if((0,B.isDefined)(this.refreshTokenCallback))return await this.refreshTokenCallback(),this.jwtToken}),this.jwtToken):null}onJWTTokenSave(e){this.observer.addListener(e)}isTokenValid(){return n4(this.jwtToken)}setRefreshTokenCallback(e){this.refreshTokenCallback=e}};r4=aQ([et(`Singleton`)],r4);var i4,a4;let o4=class{axiosInstance;constructor(e,t,n){this.configService=e,this.authStorage=t,this.logger=n,this.configService=e,this.axiosInstance=k0.create({baseURL:this.configService.getConfigValueOrThrow(`backendURL`),headers:{"Content-Type":`application/json`}}),B2(this.axiosInstance,{retries:3,retryDelay:B2.exponentialDelay,retryCondition:e=>k0.isAxiosError(e)&&B2.isNetworkOrIdempotentRequestError(e)||k0.isAxiosError(e)&&e.response?.status!==void 0&&e.response.status>=500||!1})}async getAuthHeaders(){let e={"x-request-source":cW.RequestSource.CLI},t=await this.authStorage.getJWTToken();return(0,B.isDefined)(t)&&(e.authorization=`Bearer ${t}`),e}async apiCall({url:e,method:t,data:n,config:r}){let i=new L0(await this.getAuthHeaders());if(r?.headers)for(let[e,t]of Object.entries(r.headers))i.set(e,t);let a={...r,method:t,url:e,data:n,headers:i};try{return await this.axiosInstance.request(a)}catch(t){this.handleError(e,t)}}async get(e,t){return(await this.apiCall({url:e,method:`GET`,config:t})).data}async post(e,t,n){return(await this.apiCall({url:e,method:`POST`,data:t,config:n})).data}async put(e,t,n){return(await this.apiCall({url:e,method:`PUT`,data:t,config:n})).data}async delete(e,t){return(await this.apiCall({url:e,method:`DELETE`,config:t})).data}async patch(e,t,n){return(await this.apiCall({url:e,method:`PATCH`,data:t,config:n})).data}async head(e,t){return this.apiCall({url:e,method:`HEAD`,config:t})}async options(e,t){return this.apiCall({url:e,method:`OPTIONS`,config:t})}handleCustomErrors(e,t){if(e===R0.Conflict){if(t===`workflow_is_cancelled`)throw this.logger.warn(`Agent flow canceled`),new W0(R0.Conflict,t);if(t===`duplicated_by_sha_workflow`)throw this.logger.warn(`Duplicated SHA workflow`),new G0(R0.Conflict,t)}}handleError(e,t){if(k0.isAxiosError(t))if((0,B.isDefined)(t.response)){let{status:e,statusText:n,data:r}=t.response;throw this.handleCustomErrors(e,r.message),new U0(e,`API request failed: ${e} ${n} - ${JSON.stringify(r)}`)}else if((0,B.isDefined)(t.request))throw Error(`API request failed: No response received from ${e}`);else throw Error(`API request failed: ${t instanceof Error?t.message:`Unknown error`}`);else if(t instanceof Error)throw TypeError(`API request failed: ${t.message}`);else throw TypeError(`API request failed: Unknown error occurred`)}};o4=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(r4)),iQ(2,Ze(sQ)),rQ(`design:paramtypes`,[typeof(i4=cQ!==void 0&&cQ)==`function`?i4:Object,typeof(a4=r4!==void 0&&r4)==`function`?a4:Object,Object])],o4);var s4,c4,l4;let u4=class{constructor(e,t,n){this.configService=e,this.apiService=t,this.authStorage=n,this.authStorage.setRefreshTokenCallback(async()=>{await this.login()})}async login(){let e=this.configService.getConfigValueOrThrow(`secretToken`,`API key is required but not configured`);try{let{idToken:t}=await this.apiService.post(`auth/v2/sign-in-with-secret-token`,{secret:e});return this.authStorage.setJWTToken(t),t}catch{throw Error(`Failed to get JWT token by secret`)}}};u4=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(o4)),iQ(2,Ze(r4)),rQ(`design:paramtypes`,[typeof(s4=cQ!==void 0&&cQ)==`function`?s4:Object,typeof(c4=o4!==void 0&&o4)==`function`?c4:Object,typeof(l4=r4!==void 0&&r4)==`function`?l4:Object])],u4);let d4=function(e){return e.PR=`PR`,e.COMMIT=`COMMIT`,e.PROJECT=`PROJECT`,e.COVERAGE=`COVERAGE`,e}({});var f4,p4;let m4=class{constructor(e,t){this.apiService=e,this.configService=t}mapCommandToType(e){switch(e){case dW.PR:return d4.PR;case dW.COMMIT:return d4.COMMIT;case dW.PROJECT:return d4.PROJECT;case dW.COVERAGE:return d4.COVERAGE}}async logStartOperation(e){let t=this.configService.getConfig(),n={type:this.mapCommandToType(t.command),owner:e.owner,repo:e.repository,sourceRef:e.ref_name,commitSha:e.sha,commitDate:e.commitDate,traceId:this.configService.getConfigValue(`traceId`),config:this.configService.maskedConfig(),operationStartedAt:new Date().toISOString(),version:t.cliVersion};return(await this.apiService.post(`api/v1/workflows/open`,n)).id}async logEndOperation(e,t,n,r){await this.apiService.patch(`api/v1/workflows/close/${e}`,{operationEndedAt:new Date().toISOString(),failureReason:t,runOutput:n,resultCommitSha:r})}async saveCoverageToWorkflow(e,t,{coverage:n,prCoverage:r,methodsAffected:i,committedFiles:a}){await this.apiService.patch(`api/v1/workflows/${e}/coverage`,{type:t,coverage:n,prCoverage:r,methodsAffected:i,committedFiles:a})}async getCoverageFromWorkflowOrUndefined(e){if(!this.configService.getConfigValue(`reuseCoverage`)||!(0,B.isDefined)(e))return;let t=this.configService.getConfigValue(`reuseCoverageMaxRuns`),n=await this.apiService.post(`api/v1/workflows/${e}/reuse-coverage`,{limit:t});if((0,B.isDefined)(n.coverageBefore))return n.coverageBefore}};m4=aQ([et(),iQ(0,Ze(o4)),iQ(1,Ze(cQ)),rQ(`design:paramtypes`,[typeof(f4=o4!==void 0&&o4)==`function`?f4:Object,typeof(p4=cQ!==void 0&&cQ)==`function`?p4:Object])],m4);var h4;let g4=class{constructor(e,t){this.tsAgent=e,this.logger=t}async analyzeChangedMethods(e,t,n){try{this.logger.info(`Analyzing coverage for ${t.length} changed methods with threshold ${n.coverageThreshold}%`);let r=[],i=0,a=0,o=0,s=this.groupChangedMethodsByFile(t);for(let[t,c]of Object.entries(s)){let s=this.findFileCoverage(e,t);if((0,B.isDefined)(s)){let e=this.processFileWithCoverage(t,c,s,n);r.push(...e.testables),i+=e.analyzed,a++}else{let e=this.processFileWithoutCoverage(t,c);r.push(...e.testables),i+=e.analyzed,o++}}let c={testables:r,totalAnalyzed:i,filteredCount:r.length,filesWithCoverage:a,filesWithoutCoverage:o};return this.logger.info(`Changed methods analysis complete: ${c.filteredCount}/${c.totalAnalyzed} methods below threshold across ${a+o} files`),c}catch(e){throw e instanceof Error?(this.logger.error(`Failed to analyze changed methods: ${e.message}`),e):Error(`Unknown error occurred while analyzing changed methods`)}}processFileWithCoverage(e,t,n,r){let i=[],a=0;for(let o of t){if(o.changeType===`deleted`||!o.canCreateTests)continue;let t=this.findTestableInCoverage(n,o);(0,B.isDefined)(t)?(a++,this.shouldIncludeTestable(t,r)&&i.push({name:t.name,percentage:t.percentage,filePath:e,reason:this.getFilterReason(t)})):(a++,i.push({name:o.name??`unknown`,percentage:null,filePath:e,reason:`no-coverage`}))}return{testables:i,analyzed:a}}processFileWithoutCoverage(e,t){let n=t.filter(e=>e.changeType!==`deleted`&&e.canCreateTests),r=n.map(t=>({name:t.name??`unknown`,percentage:null,filePath:e,reason:`no-coverage`}));return this.logger.debug(`No coverage data found for file: ${e}`),{testables:r,analyzed:n.length}}async analyzeChangedFiles(e,t,n){try{this.logger.info(`Analyzing coverage for ${t.length} changed files with threshold ${n.coverageThreshold}%`);let r=[],i=0,a=0,o=0;for(let s of t){let t=this.findFileCoverage(e,s);if((0,B.isDefined)(t)){a++;let e=await this.filterOutClasses(s,t.testables??[]),o=this.filterTestablesForFile(t,s,n),c=await this.filterOutClasses(s,o);r.push(...c),i+=e.length??0,(0,B.isEmpty)(c)||this.logger.debug(`File ${s}: ${c.length}/${e.length??0} testables below threshold`)}else o++,this.logger.debug(`No coverage data found for file: ${s}`)}let s={testables:r,totalAnalyzed:i,filteredCount:r.length,filesWithCoverage:a,filesWithoutCoverage:o};return this.logger.info(`Coverage analysis complete: ${s.filteredCount}/${s.totalAnalyzed} testables below threshold across ${s.filesWithCoverage} files`),s}catch(e){throw e instanceof Error?(this.logger.error(`Failed to analyze coverage: ${e.message}`),e):Error(`Unknown error occurred while analyzing coverage`)}}findFileCoverage(e,t){let n=t.startsWith(`/`)?t:`/${t}`;return(0,B.isDefined)(e[n])?e[n]:null}filterTestablesForFile(e,t,n){let r=[];for(let i of e.testables??[])if(this.shouldIncludeTestable(i,n)){let e=this.getFilterReason(i);r.push({name:i.name,percentage:i.percentage,filePath:t,reason:e})}return r}shouldIncludeTestable(e,t){return!!(e.percentage===null||e.percentage===0||(0,B.isDefined)(e.percentage)&&e.percentage<t.coverageThreshold)}getFilterReason(e){return e.percentage===null?`no-coverage`:e.percentage===0?`zero-coverage`:`below-threshold`}async calculatePRCoverage(e,t){if(!(0,B.isEmpty)(e))try{let n=await this.tsAgent.getCoverageForFiles(e),r=t?`before`:`after`;return this.logger.debug(`PR Coverage (${r}): ${n.percentage}% (${n.coveredStatements}/${n.totalStatements} statements)`),n}catch(e){this.logger.warn(`Failed to calculate PR coverage: ${e instanceof Error?e.message:`Unknown error`}`);return}}async filterOutClasses(e,t){let n=await this.tsAgent.getTestables(e);if((0,B.isEmpty)(n)||!(0,B.isDefined)(n[0]))return this.logger.warn(`getTestables returned empty for ${e}, keeping all testables`),t;let[,r]=n[0],i=r.filter(e=>e.type!==`class`),a=new Set(i.map(e=>e.name));return t.filter(e=>a.has(e.name))}groupChangedMethodsByFile(e){let t={};for(let n of e)(0,B.isDefined)(t[n.filePath])||(t[n.filePath]=[]),t[n.filePath].push(n);return t}findTestableInCoverage(e,t){return(0,B.isDefined)(e.testables)?e.testables.find(e=>{let n=e.name===t.name,r=`parentName`in e?e.parentName===t.parentName:!(0,B.isDefined)(t.parentName);return n&&r})??null:null}};g4=aQ([et(),iQ(0,Ze(lW.TSAgent)),iQ(1,Ze(sQ)),rQ(`design:paramtypes`,[typeof(h4=cW.TSAgent!==void 0&&cW.TSAgent)==`function`?h4:Object,Object])],g4);function _4(e,t){return t2(e,`package.json`,t)??void 0}function v4(e,t){try{return m.default.existsSync(e)?m.default.readFileSync(e,`utf8`):void 0}catch(n){t.warn(`Failed to read file ${e}: ${n instanceof Error?n.message:`Unknown error`}`);return}}async function y4(e,t,n){let r=_4(e,t),i=(await(0,cW.findLintConfigPath)(t)).path??void 0,a=(0,B.isDefined)(r)?v4(r,n):void 0,o=(0,B.isDefined)(i)?v4(i,n):void 0;return(0,B.isDefined)(r)&&n.info(`Found package.json at: ${r}`),(0,B.isDefined)(i)&&n.info(`Found lint config at: ${i}`),{packageJsonPath:r,packageJsonContent:a,lintConfigPath:i,lintConfigContent:o}}const b4={detectProjectConfigs:y4};var x4,S4;let C4=class{constructor(e,t,n){this.apiService=e,this.configService=t,this.logger=n}async detectAndSaveConfigs(e){try{let t=this.configService.getConfigValue(`rootPath`),n=await b4.detectProjectConfigs(t,t,this.logger);if(!(0,B.isDefined)(n.packageJsonContent)&&!(0,B.isDefined)(n.lintConfigContent))return;await this.apiService.patch(`api/v1/github-repos/configs`,{owner:e.owner,repo:e.repository,packageJson:n.packageJsonContent,lintConfig:n.lintConfigContent})}catch(e){this.logger.warn(`Failed to detect and save project configs: ${e instanceof Error?e.message:`Unknown error`}`)}}};C4=aQ([et(),iQ(0,Ze(o4)),iQ(1,Ze(cQ)),iQ(2,Ze(sQ)),rQ(`design:paramtypes`,[typeof(x4=o4!==void 0&&o4)==`function`?x4:Object,typeof(S4=cQ!==void 0&&cQ)==`function`?S4:Object,Object])],C4);var Vte,w4,T4,E4,D4,O4,k4,A4,j4;let M4=class{workflowRunId;initialCoverageTree;resultCommitSha;constructor(e,t,n,r,i,a,o,s,c,l){this.configService=e,this.authService=t,this.gitService=n,this.coverageAnalysisService=r,this.summaryService=i,this.tsAgent=a,this.workflowService=o,this.scmHostService=s,this.repoConfigService=c,this.logger=l}async login(){try{this.logger.info(`Trying login to API...`);let e=await this.authService.login();await this.tsAgent.init(e),this.logger.info(`Successfully authenticated with the API`)}catch(e){throw this.logger.error(`Failed to authenticate:`+(e instanceof Error?e.message:`Unknown error`)),e}}async logStart(){try{let e=await this.gitService.getGitInfo();this.logger.debug(`Git info: `+JSON.stringify(e));try{let t=await this.workflowService.logStartOperation(e);return this.tsAgent.updateContext({git:{...e,workflowRunId:t}}),this.workflowRunId=t,await this.repoConfigService.detectAndSaveConfigs(e),t}catch(e){throw e instanceof G0||e instanceof W0||this.logger.warn(`Failed to log start operation: ${e instanceof Error?e.message:`Unknown error`}`),e}}catch(e){throw e instanceof G0||e instanceof W0||this.logger.error(`Failed to retrieve git info or log start operation:`+(e instanceof Error?e.message:`Unknown error`)),e}}async generateInitialCoverage(){this.logger.verbose(`Try to reuse coverage...`);let e=await this.workflowService.getCoverageFromWorkflowOrUndefined(this.workflowRunId);if((0,B.isDefined)(e))return await this.tsAgent.setCoverage(e),this.initialCoverageTree=e,(0,B.isDefined)(this.workflowRunId)&&await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{}),this.logger.verbose(`Reused coverage: `+(e[`/`]?.percentage??0)+`%`),this.summaryService.setCoverageData(e[`/`]?.percentage??0,e[`/`]?.percentage??0),e;{this.logger.verbose(`Generating initial coverage...`),await this.tsAgent.generateCoverage();let e=await this.tsAgent.getCoverageTree();if(!(0,B.isDefined)(e))throw Error(`Failed to generate initial coverage tree`);return this.initialCoverageTree=e,(0,B.isDefined)(this.workflowRunId)&&await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{coverage:e}),this.logger.verbose(`Initial coverage: `+(e[`/`]?.percentage??0)+`%`),this.summaryService.setCoverageData(e[`/`]?.percentage??0,e[`/`]?.percentage??0),e}}async logEndOperation(e){if((0,B.isDefined)(this.workflowRunId))try{let t=this.summaryService.getWorkflowRunOutput();await this.workflowService.logEndOperation(this.workflowRunId,e,t,this.resultCommitSha),this.logger.info(`Successfully logged workflow end`)}catch(e){this.logger.warn(`Failed to log workflow end: `+(e instanceof Error?e.message:`Unknown error`))}}getWorkflowRunIdOrThrow(){if(!(0,B.isDefined)(this.workflowRunId))throw Error(`Workflow run ID is not set, call logStart() first`);return this.workflowRunId}getInitialCoverageTreeOrThrow(){if(!(0,B.isDefined)(this.initialCoverageTree))throw Error(`Initial coverage tree is not set, call generateInitialCoverage() first`);return this.initialCoverageTree}getInitialCoverageTreeOrUndefined(){return this.initialCoverageTree}async countAllMethodsInFiles(e){let t=(0,B.uniq)(e).map(async e=>{try{return await this.tsAgent.getAllMethodsCount(e)}catch(t){return this.logger.debug(`Failed to count methods in `+e+`: `+(t instanceof Error?t.message:`Unknown error`)),0}});return(await Promise.all(t)).reduce((e,t)=>e+t,0)}};M4=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(u4)),iQ(2,Ze(xQ)),iQ(3,Ze(g4)),iQ(4,Ze(uQ)),iQ(5,Ze(lW.TSAgent)),iQ(6,Ze(m4)),iQ(7,Ze(lW.SCMHostService)),iQ(8,Ze(C4)),iQ(9,Ze(sQ)),rQ(`design:paramtypes`,[typeof(Vte=cQ!==void 0&&cQ)==`function`?Vte:Object,typeof(w4=u4!==void 0&&u4)==`function`?w4:Object,typeof(T4=xQ!==void 0&&xQ)==`function`?T4:Object,typeof(E4=g4!==void 0&&g4)==`function`?E4:Object,typeof(D4=uQ!==void 0&&uQ)==`function`?D4:Object,typeof(O4=cW.TSAgent!==void 0&&cW.TSAgent)==`function`?O4:Object,typeof(k4=m4!==void 0&&m4)==`function`?k4:Object,typeof(A4=hQ!==void 0&&hQ)==`function`?A4:Object,typeof(j4=C4!==void 0&&C4)==`function`?j4:Object,Object])],M4);var N4;let P4=class extends M4{changedFiles=[];prCoverage={before:{percentage:null,totalStatements:0,coveredStatements:0},after:{percentage:null,totalStatements:0,coveredStatements:0}};testableToGenerateService;getWorkflowRunId(){return this.workflowRunId}async runFlow(e){let t=e?.shouldDeferPostGeneration??!1,n,r=!1,i;try{await this.login(),await this.logStart();let e=await this.getRawChangedFiles(),n=this.configService.getConfigValue(`rootPath`),r=this.configService.getConfigValue(`gitTopLevel`)??n;this.logger.info(`Discovering untested functions`);let a=await this.testableToGenerateService.getTestablesToGenerate({changedFiles:e,rootPath:n,gitTopLevel:r,hasDiffContext:this.hasDiffContext(),baseRevision:await this.getBaseRevision(),changedMethodsOnly:this.configService.getConfigValue(`changedMethodsOnly`),coverageReport:{tree:this.initialCoverageTree,threshold:this.configService.getConfigValue(`coverageThreshold`)}});if((0,B.isEmpty)(a.testables)){this.logFilteredOutTestables(a.filteredOut),this.handleNoFilteredTestables();return}if(this.updateRootPath(a.projectRootPath),this.changedFiles=a.testables.map(e=>e.filePath),await this.setSummaryChangedFilesData(e.length,a),a.filteredOut.filter(e=>e.reason===`limit-reached`).length>0){let e=this.configService.getConfigValue(`maxTestables`);this.summaryService.addWarning(`Limited to ${e} functions: test generation was capped due to maximum function limit.`)}this.logFilteredOutTestables(a.filteredOut),this.logTestablesToGenerate([...a.testables]);let o=[...a.testables];if(i=await this.generateTests(o),!t){let e=await this.performAutoCommit();this.summaryService.setTestGenerationData({generated:i.generated,succeeded:i.succeeded,failed:i.failed,successMethodsCount:i.successMethodsCount,committedFilesCount:e,greenTests:i.greenTests,redTests:i.redTests}),this.configService.getConfigValue(`skipCoverageAfter`)?(this.logger.verbose(`Skipping final coverage generation (--skip-coverage-after flag is set)`),this.summaryService.setCoverageSkipped()):await this.generateFinalCoverageAndLog({methodsAffected:o.length,committedFiles:e})}return i}catch(e){if(e instanceof G0){this.logger.warn(`Duplicate SHA execution detected. Skipping.`);return}if(e instanceof W0){this.logger.warn(`Workflow canceled. Skipping.`),r=!0;return}throw n=e instanceof Error?e.message:`Unknown error`,this.logger.error(`Agent flow failed: `+n),e}finally{!t&&(0,B.isDefined)(this.workflowRunId)&&!r&&(this.summaryService.setPRCoverageData(this.prCoverage.before,this.prCoverage.after),await this.scmHostService.safePostSummaryToPr(),await this.logEndOperation(n))}}async setSummaryChangedFilesData(e,t){let n=[...new Set([...t.testables.map(e=>e.filePath),...t.filteredOut.map(e=>e.filePath)])],r=await this.countAllMethodsInFiles(n);this.summaryService.setChangedFilesData({changedFilesCount:e,candidateFilesCount:n.length,functionCount:r,publicMethodCount:t.testables.length,testablesToGenerateCount:t.testables.length,publicMethods:t.testables.map(e=>({name:e.testable.name??`unknown`,filePath:e.filePath})),methodsBelowCoverage:t.testables.map(e=>({name:e.testable.name??`unknown`,filePath:e.filePath}))})}handleNoFilteredTestables(){this.logger.warn(`No filtered untested functions`),this.prCoverage.after=this.prCoverage.before}logFilteredOutTestables(e){if((0,B.isEmpty)(e))return;let t=e.length,n=t===1?`item`:`items`;this.logger.verbose(t+` `+n+` skipped:`);for(let t of e){let e=(0,B.isDefined)(t.testableName)?t.testableName+` in `+t.filePath:t.filePath;this.logger.verbose(` - `+e+`: `+t.reason)}}logTestablesToGenerate(e){this.logger.info(`Found ${e.length} public function${e.length===1?``:`s`} without Early AI tests`);for(let t of e)this.logger.info(` `+t.testable.name+` in `+t.filePath)}async performAutoCommit(){let e=this.configService.getConfigValueOrThrow(`autoCommit`);if(this.summaryService.setAutoCommitStatus(e),e){let e=this.configService.getConfigValue(`refName`),t=await this.gitService.commitFiles(e);return(0,B.isDefined)(t.resultCommitSha)&&(this.resultCommitSha=t.resultCommitSha),t.committedFiles.length}else return this.logger.info(`Auto-commit is disabled - skipping commit step`),0}async _generateInitialCoverageForTestGeneration(){await this.generateInitialCoverage(),await this.savePRCoverageBefore()}async savePRCoverageBefore(){if((0,B.isDefined)(this.workflowRunId))try{let e=await this.coverageAnalysisService.calculatePRCoverage(this.changedFiles,!0);(0,B.isDefined)(e)&&(this.prCoverage.before=e),await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{prCoverage:e}),this.logger.debug(`Successfully saved initial coverage to workflow run`)}catch(e){this.logger.warn(`Failed to save initial coverage: `+(e instanceof Error?e.message:`Unknown error`))}}async generateTests(e){let t=new Set(e),n=0,r=0,i=0,a=0;await this.tsAgent.bulkGenerateTests(e,(o,s)=>{a++;let c=uW.default.basename(o.filePath);(0,B.isDefined)(s)&&s.greenTestsCount>0?(t.delete(o),n+=s.greenTestsCount,r+=s.redTestsCount,i+=s.greyTestsCount,this.logger.info(` [${a}/${e.length}] ✓ ${o.testable.name} (${c}) — ${s.greenTestsCount} passing, ${s.redTestsCount} skipped`)):this.logger.info(` [${a}/${e.length}] ✗ ${o.testable.name} (${c}) — no tests generated`)});let o=e.length-t.size,s=t.size,c=await this.gitService.getEarlyFiles();return this.logger.info(``),this.logger.info(`✅ Test generation complete for ${o} functions`),s>0&&this.logger.info(`❌ ${s} functions were not generated`),this.logger.info(``),this.logger.info(`================`),this.logger.info(`Overall summary:`),this.logger.info(`================`),this.logger.info(``),this.logger.info(`✅ ${n} tests passing`),this.logger.info(`⚠️ ${r} tests skipped`),this.logger.info(`❌ ${i} tests could not be fixed autonomously (yet)`),this.logger.info(``),{generated:e.length,succeeded:o,failed:s,successMethodsCount:c.length,greenTests:n,redTests:r}}async generateFinalCoverageAndLog({methodsAffected:e,committedFiles:t}){let n=this.getWorkflowRunIdOrThrow();this.logger.verbose(`Generating final coverage...`),await this.tsAgent.generateCoverage();let r=await this.tsAgent.getCoverageTree();if(!(0,B.isDefined)(r))throw Error(`Failed to generate final coverage tree`);let i=r[`/`]?.percentage??0,a=this.getInitialCoverageTreeOrUndefined(),o=a?.[`/`]?.percentage??0;(0,B.isDefined)(a)||this.summaryService.setCoverageBeforeSkipped(),this.summaryService.setCoverageData(o,i);let s=(0,B.isDefined)(a)?`${o}% -> ${i}%`:`skipped`;this.logger.verbose(`Final coverage: `+i+`%, Coverage comparison: `+s);try{let i=await this.coverageAnalysisService.calculatePRCoverage(this.changedFiles,!1);(0,B.isDefined)(i)&&(this.prCoverage.after=i),await this.workflowService.saveCoverageToWorkflow(n,`after`,{coverage:r,prCoverage:i,methodsAffected:e,committedFiles:t}),this.logger.debug(`Successfully saved final coverage to workflow run`)}catch(e){this.logger.warn(`Failed to save final coverage: `+(e instanceof Error?e.message:`Unknown error`))}}updateRootPath(e){this.tsAgent.updateRootPath(e),this.configService.updateConfigValue(`rootPath`,e)}};aQ([Ze(S2),rQ(`design:type`,typeof(N4=S2!==void 0&&S2)==`function`?N4:Object)],P4.prototype,`testableToGenerateService`,void 0),P4=aQ([et(),st({extendConstructorArguments:!0,extendProperties:!0})],P4);let F4=class extends P4{async getRawChangedFiles(){return this.gitService.getChangedFilesForCommitWithStatus({absolute:!0})}hasDiffContext(){return!0}async getBaseRevision(){let e=this.configService.getConfigValue(`baseRef`);if((0,B.isDefined)(e))return this.gitService.getBaseRevision({baseBranch:e});let t=this.configService.getConfigValue(`commitHash`);if((0,B.isDefined)(t))return`${t}^`}async logStart(){try{let e=this.configService.getConfigValue(`commitHash`),t=await this.gitService.getCommitMessage(e);t&&this.configService.updateConfigValue(`commitName`,t)}catch(e){this.logger.warn(`Failed to retrieve commit message, continuing without it: `+(e instanceof Error?e.message:`Unknown error`))}try{let e=await this.scmHostService.getContributorAvatarUrl();(0,B.isDefined)(e)&&this.configService.updateConfigValue(`contributorAvatarUrl`,e)}catch(e){this.logger.warn(`Failed to retrieve contributor avatar, continuing without it: `+(e instanceof Error?e.message:`Unknown error`))}return await super.logStart()}};F4=aQ([et(),st({extendConstructorArguments:!0,extendProperties:!0})],F4);function Hte(e){let t=e.command(dW.COMMIT).alias(`generate-commit`).description(`Generate tests for the current project in commit context`);return ce(t,`--commit-hash <hash>`,`Commit hash`,{envName:`COMMIT_HASH`,isRequired:!0}),ce(t,`--ref-name <ref>`,`Head branch name for the commit`,{envName:`REF_NAME`,isRequired:!0}),ce(t,`--base-ref <ref>`,`optional base refrence for comparison`,{envName:`BASE_REF`}),ce(t,`-s, --test-structure <structure>`,`Test file structure`,{envName:`TEST_STRUCTURE`,def:`siblingFolder`}),ce(t,`-f, --test-framework <framework>`,`Test framework to use`,{envName:`TEST_FRAMEWORK`,def:`jest`}),ce(t,`--test-suffix <suffix>`,`Test file suffix`,{envName:`TEST_FILE_SUFFIX`,def:`test`}),ce(t,`--test-file-naming <naming>`,`Test file naming convention`,{envName:`TEST_FILE_NAMING`,def:`camelCase`}),ce(t,`-c, --max-concurrency <number>`,`Number of concurrent workers (1-4)`,{envName:`MAX_CONCURRENCY`,def:`3`}),ce(t,`--auto-commit <boolean>`,`Whether to auto-commit files`,{envName:`AUTO_COMMIT`,def:`true`}),ce(t,`--auto-commit-skip-ci <boolean>`,`Append [skip ci] to auto-commit message`,{envName:`AUTO_COMMIT_SKIP_CI`,def:`true`}),ce(t,`--test-command <command>`,`Custom test command to run`,{envName:`TEST_COMMAND`}),ce(t,`--coverage-command <command>`,`Custom coverage command to run`,{envName:`COVERAGE_COMMAND`}),ce(t,`--lint-command <command>`,`Custom lint command to run`,{envName:`LINT_COMMAND`}),ce(t,`--prettier-command <command>`,`Custom prettier command to run`,{envName:`PRETTIER_COMMAND`}),ce(t,`--disable-lint-rules <boolean>`,`Whether to disable failed lint rules in test files`,{envName:`DISABLE_LINT_RULES`,def:`false`}),ce(t,`--git-org <org>`,`Git organization name`,{envName:`GIT_ORG`}),ce(t,`--git-repo <repo>`,`Git repository name`,{envName:`GIT_REPO`}),ce(t,`--git-user-email <email>`,`Git user email for auto commit`,{envName:`GIT_USER_EMAIL`}),ce(t,`--git-user-name <name>`,`Git user name for auto commit`,{envName:`GIT_USER_NAME`}),ce(t,`--scm-provider <provider>`,`SCM provider (e.g., github, bitbucket)`,{envName:`SCM_PROVIDER`,def:`github`}),ce(t,`--keep-error-tests <boolean>`,`Whether to keep error tests`,{envName:`KEEP_ERROR_TESTS`,def:`false`}),ce(t,`--keep-failed-tests <boolean>`,`Whether to keep failed tests`,{envName:`KEEP_FAILED_TESTS`,def:`false`}),ce(t,`--conditional-keep <boolean>`,`Whether to return the last generated test result even when no green tests were produced`,{envName:`CONDITIONAL_KEEP`,def:`false`}),ce(t,`--continue-on-test-errors <boolean>`,`Whether to continue on test errors`,{envName:`CONTINUE_ON_TEST_ERRORS`,def:`false`}),ce(t,`--changed-methods-only <boolean>`,`Generate tests only for changed methods, not all methods in changed files`,{envName:`CHANGED_METHODS_ONLY`,def:`true`}),ce(t,`--skip-coverage-after <boolean>`,`Skip final coverage generation after test generation`,{envName:`SKIP_COVERAGE_AFTER`,def:`true`}),ce(t,`--max-testables <number>`,`Maximum number of testables to generate`,{envName:`MAX_TESTABLES`}),ce(t,`--per-function-timeout <number>`,`Per function timeout in milliseconds`,{envName:`PER_FUNCTION_TIMEOUT`}),ce(t,`--coverage-threshold <number>`,`Coverage threshold percentage (0-100)`,{envName:`COVERAGE_THRESHOLD`,def:`0`}),ce(t,`--reuse-coverage <boolean>`,`Whether to reuse coverage`,{envName:`REUSE_COVERAGE`,def:`false`}),ce(t,`--reuse-coverage-max-runs <number>`,`Max number of runs to reuse coverage (1-10)`,{envName:`REUSE_COVERAGE_MAX_RUNS`,def:`10`}),ce(t,`--experimental-agent-sdk <boolean>`,`Use experimental Agent SDK for test generation`,{envName:`EXPERIMENTAL_AGENT_SDK`,def:`true`}),t.addHelpText(`after`,`
32412
+ `)}extractMethodText(e,t){return t.slice(e.startIndex,e.endIndex)}createChangedMethod(e,t,n){return{name:t.name,type:t.type,parentName:`parentName`in t?t.parentName:void 0,changeType:n,filePath:e,canCreateTests:t.canCreateTests}}};K0=aQ([et(),iQ(0,Ze(sQ)),rQ(`design:paramtypes`,[Object])],K0);var jte,Mte,Nte;let q0=class{constructor(e,t,n,r){this.gitService=e,this.changedMethodsDetector=t,this.tsAgent=n,this.logger=r}async execute(e,t,n){if(!(0,B.isDefined)(t.baseRevision))return{kept:e};let r=[...new Set(e.map(e=>e.filePath))],i=await this.detectChangedMethods(r,t.baseRevision,t.projectRootPath),a=new Set(i.filter(e=>e.changeType!==`deleted`&&e.canCreateTests).map(e=>`${e.filePath}:${e.name}:${e.parentName??``}`)),o=[],s=[];for(let t of e){let e=`${t.filePath}:${t.testable.name}:${`parentName`in t.testable?t.testable.parentName??``:``}`;a.has(e)?o.push(t):s.push(t)}return{kept:[...o,...s]}}async detectChangedMethods(e,t,n){let r=await this.gitService.getTopLevel(),i=[];for(let a of e){let e=await this.detectChangedMethodsForFile(a,t,n,r);i.push(...e)}return i}async detectChangedMethodsForFile(e,t,n,r){let i=null;try{let a=uW.default.isAbsolute(e)?e:uW.default.join(n,e),o=uW.default.relative(r,a),s=await this.gitService.getFileAtRevision(o,t),c=await this.getBaseMethodsFromContent(s,a,n);(0,B.isDefined)(c.temporaryFilePath)&&(i=c.temporaryFilePath);let l=await this.getCurrentMethods(a),u=await g.readFile(a,`utf8`);return this.changedMethodsDetector.detectChanges(e,c.methods,l,s,u)}catch(t){this.logger.warn(`Failed to detect changed methods for `+e+`: `+(t instanceof Error?t.message:`Unknown error`)+`. Changed-function detection disabled for this file — all its functions will be treated as changed. Fix: add 'fetch-depth: 0' to your checkout step.`);try{let t=uW.default.isAbsolute(e)?e:uW.default.join(n,e);return(await this.getCurrentMethods(t)).map(t=>({filePath:e,name:t.name,type:t.type,parentName:`parentName`in t?t.parentName:void 0,changeType:`modified`,canCreateTests:t.canCreateTests}))}catch{return[]}}finally{await this.cleanupTemporaryFile(i)}}async getBaseMethodsFromContent(e,t,n){if(!(0,B.isDefined)(e)||(0,B.isEmpty)(e))return{methods:[],temporaryFilePath:null};let r=p.default.resolve(n,`.early-temp`);await g.mkdir(r,{recursive:!0});let i=p.default.join(r,`base-${Date.now()}-${p.default.basename(t)}`);await g.writeFile(i,e);let a=i.replaceAll(`\\`,`/`);return{methods:((await this.tsAgent.getTestables(a))[0]?.[1]??[]).filter(e=>e.canCreateTests&&e.type!==`class`),temporaryFilePath:i}}async getCurrentMethods(e){let t=e.replaceAll(`\\`,`/`);return((await this.tsAgent.getTestables(t))[0]?.[1]??[]).filter(e=>e.canCreateTests&&e.type!==`class`)}async cleanupTemporaryFile(e){if((0,B.isDefined)(e))try{await g.unlink(e)}catch{}}};q0=aQ([et(),iQ(0,Ze(xQ)),iQ(1,Ze(K0)),iQ(2,Ze(lW.TSAgent)),iQ(3,Ze(sQ)),rQ(`design:paramtypes`,[typeof(jte=xQ!==void 0&&xQ)==`function`?jte:Object,typeof(Mte=K0!==void 0&&K0)==`function`?Mte:Object,typeof(Nte=cW.TSAgent!==void 0&&cW.TSAgent)==`function`?Nte:Object,Object])],q0);var J0;let Y0=class{constructor(e){this.configService=e}async execute(e,t,n){let r=t.coverageReport?.tree,i=t.coverageReport?.threshold??this.configService.getConfigValue(`coverageThreshold`)??0;if(!(0,B.isDefined)(r))return{kept:e};let a=[];for(let t of e){let e=this.findFileCoverage(r,t.filePath);if(!(0,B.isDefined)(e?.testables)){a.push(t);continue}let o=t.testable.type===`method`?t.testable.parentName:void 0,s=e.testables.find(e=>e.name===t.testable.name&&((0,B.isDefined)(o)?e.parentName===o:!(0,B.isDefined)(e.parentName)));if(!(0,B.isDefined)(s)||!(0,B.isDefined)(s.percentage)){a.push(t);continue}if(s.percentage>i){n.push({filePath:t.filePath,testableName:t.testable.name,reason:`above-coverage-threshold`});continue}a.push(t)}return{kept:a}}findFileCoverage(e,t){return e[t.startsWith(`/`)?t:`/${t}`]??null}};Y0=aQ([et(),iQ(0,Ze(cQ)),rQ(`design:paramtypes`,[typeof(J0=cQ!==void 0&&cQ)==`function`?J0:Object])],Y0);let X0=class{async execute(e,t,n){let r=[];for(let i of e){let e=i.filePath.toLowerCase(),a=dQ.allowedExtensions.some(t=>e.endsWith(t)),o=uW.default.isAbsolute(i.filePath)?uW.default.relative(t.gitTopLevel,i.filePath):i.filePath;if(!a){n.push({filePath:o,reason:`not-code-file`});continue}if(dQ.excludePatterns.some(t=>e.includes(t.toLowerCase()))){n.push({filePath:o,reason:`excluded-pattern`});continue}r.push(i)}return{kept:r}}};X0=aQ([et()],X0);var Z0;let Q0=class{constructor(e){this.configService=e}async execute(e,t,n){let r=this.configService.getConfigValue(`maxTestables`)??1/0;if(e.length<=r)return{kept:e};let i=e.slice(0,r);for(let t=r;t<e.length;t++){let r=e[t];n.push({filePath:r.filePath,testableName:r.testable.name,reason:`limit-reached`})}return{kept:i}}};Q0=aQ([et(),iQ(0,Ze(cQ)),rQ(`design:paramtypes`,[typeof(Z0=cQ!==void 0&&cQ)==`function`?Z0:Object])],Q0);var $0=u(Uz());function e2(e,t){let n=uW.default.relative(e,t);return n===``||!n.startsWith(`..`)&&!uW.default.isAbsolute(n)}function t2(e,t,n){let r=uW.default.isAbsolute(e)&&e2(n,e)?e:uW.default.join(n,e),i=(0,$0.default)(t,{cwd:m.default.existsSync(r)&&m.default.statSync(r).isDirectory()?r:uW.default.dirname(r)});return i!==null&&!e2(n,i)?null:i}function Pte(e,t){let n=[t2(e,`package.json`,t),t2(e,`project.json`,t)].filter(B.isDefined).filter(e=>e2(t,e));if(n.length===0)return t;let r=n.reduce((e,t)=>e.length>t.length?e:t,n[0]);return uW.default.dirname(r)}const n2=[`pyproject.toml`,`setup.py`,`setup.cfg`,`requirements.txt`],r2=[`package.json`,`tsconfig.json`],i2=[`.py`],a2=[`.ts`,`.tsx`,`.js`,`.jsx`];function o2(e,t){return t.some(t=>e.endsWith(t))}function s2(e){if(o2(e,i2))return`python`;if(o2(e,a2))return`typescript`}function c2(e,t){if(e&&t)return`mixed`;if(e)return`python`;if(t)return`typescript`}function l2(e){let t=m.default.readdirSync(e,{recursive:!0});return c2(t.some(e=>o2(e,i2)),t.some(e=>o2(e,a2)))}function u2(e){return c2(n2.some(t=>m.default.existsSync(uW.default.join(e,t))),r2.some(t=>m.default.existsSync(uW.default.join(e,t))))}function d2(e,t){if(t!==void 0&&t!==``){let n=uW.default.isAbsolute(t)?t:uW.default.join(e,t);return m.default.existsSync(n)&&m.default.statSync(n).isFile()?s2(n):m.default.existsSync(n)&&m.default.statSync(n).isDirectory()?l2(n):s2(t)??u2(e)}return u2(e)}const f2={detectProjectRoot(e,t,n){if(t.length===0)return n.verbose(`No changed files provided, using root path`),e;let r=t[0],i=Pte(uW.default.isAbsolute(r)?r:uW.default.join(e,r),e);return i===uW.default.normalize(e)?(n.verbose(`Using workspace root path`),e):(n.info(`Detected nested project root: ${i} (from file: ${r})`),i)}};function p2(e,t){let n=uW.default.relative(e,t);return n!==``&&!n.startsWith(`..`)&&!uW.default.isAbsolute(n)}let m2=class{constructor(e){this.logger=e}async execute(e,t,n){if((0,B.isEmpty)(e))return{kept:[],projectRootPath:t.rootPath};let r=e.map(e=>uW.default.isAbsolute(e.filePath)?e.filePath:uW.default.join(t.rootPath,e.filePath)),i=f2.detectProjectRoot(t.rootPath,r,this.logger),a=[];for(let[t,o]of e.entries()){let e=r[t];if(!p2(i,e)){n.push({filePath:o.filePath,reason:`outside-project`});continue}let s=uW.default.relative(i,e);a.push({filePath:s,status:o.status})}return{kept:a,projectRootPath:i}}};m2=aQ([et(),iQ(0,Ze(sQ)),rQ(`design:paramtypes`,[Object])],m2);let h2=class{constructor(e){this.tsAgent=e}async execute(e,t,n){let r=e.map(e=>e.filePath);if((0,B.isEmpty)(r))return{kept:[]};let i=await this.tsAgent.getTestableFileMap(r),a=[];for(let e of r){let r=this.getEntriesForFile(e,i,t.projectRootPath);if(!(0,B.isDefined)(r)||(0,B.isEmpty)(r)){n.push({filePath:e,reason:`no-testables`});continue}this.processEntriesForFile(e,r,a,n)||n.push({filePath:e,reason:`no-testables`})}return{kept:a}}processEntriesForFile(e,t,n,r){let i=!1;for(let a of t){let{testable:t}=a;if(!t.canCreateTests||t.type===`class`)continue;if(i=!0,(0,B.isDefined)(a.testPath)){r.push({filePath:e,testableName:t.name,reason:`has-test-file`});continue}let o=e.startsWith(`/`)?e.slice(1):e;n.push({filePath:o,testable:t})}return i}getEntriesForFile(e,t,n){if((0,B.isDefined)(t[e]))return t[e];let r=uW.default.resolve(n,e);if((0,B.isDefined)(t[r]))return t[r]}};h2=aQ([et(),iQ(0,Ze(lW.TSAgent)),rQ(`design:paramtypes`,[Object])],h2);var Fte,g2,_2,v2,y2,b2,x2;function Ite(e,t){return{async execute(n,r,i){return e(r)?t.execute(n,r,i):{kept:n}}}}let S2=class{filters;constructor(e,t,n,r,i,a,o,s){this.configService=e,this.tsAgent=t,this.fileNameFilter=n,this.projectRootFilter=r,this.testableMapFilter=i,this.changedMethodsFilter=a,this.coverageFilter=o,this.limitFilter=s,this.filters=[this.fileNameFilter,this.projectRootFilter,this.testableMapFilter,Ite(e=>e.changedMethodsOnly&&e.hasDiffContext,this.changedMethodsFilter),this.coverageFilter,this.limitFilter]}async getTestablesToGenerate(e){let t={rootPath:e.rootPath,projectRootPath:e.rootPath,gitTopLevel:e.gitTopLevel,changedMethodsOnly:e.changedMethodsOnly??!1,hasDiffContext:e.hasDiffContext,baseRevision:e.baseRevision,coverageReport:e.coverageReport};return this.runPipeline([...e.changedFiles],t)}async runPipeline(e,t){let n=[],r=e,i=t.projectRootPath;for(let e of this.filters){let a={...t,projectRootPath:i},o=await e.execute(r,a,n);if((0,B.isDefined)(o.projectRootPath)&&!(0,B.isEmpty)(o.projectRootPath)&&(i=o.projectRootPath,this.tsAgent.updateRootPath(i),this.configService.updateConfigValue(`rootPath`,i)),(0,B.isEmpty)(o.kept))return{testables:[],filteredOut:n,projectRootPath:i};r=o.kept}return{testables:r,filteredOut:n,projectRootPath:i}}};S2=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(lW.TSAgent)),iQ(2,Ze(X0)),iQ(3,Ze(m2)),iQ(4,Ze(h2)),iQ(5,Ze(q0)),iQ(6,Ze(Y0)),iQ(7,Ze(Q0)),rQ(`design:paramtypes`,[typeof(Fte=cQ!==void 0&&cQ)==`function`?Fte:Object,Object,typeof(g2=X0!==void 0&&X0)==`function`?g2:Object,typeof(_2=m2!==void 0&&m2)==`function`?_2:Object,typeof(v2=h2!==void 0&&h2)==`function`?v2:Object,typeof(y2=q0!==void 0&&q0)==`function`?y2:Object,typeof(b2=Y0!==void 0&&Y0)==`function`?b2:Object,typeof(x2=Q0!==void 0&&Q0)==`function`?x2:Object])],S2);var C2=u(lH(),1);const w2=`axios-retry`;function T2(e){return e.response||!e.code||[`ERR_CANCELED`,`ECONNABORTED`].includes(e.code)?!1:(0,C2.default)(e)}const E2=[`get`,`head`,`options`],D2=E2.concat([`put`,`delete`]);function O2(e){return e.code!==`ECONNABORTED`&&(!e.response||e.response.status===429||e.response.status>=500&&e.response.status<=599)}function k2(e){return e.config?.method?O2(e)&&E2.indexOf(e.config.method)!==-1:!1}function A2(e){return e.config?.method?O2(e)&&D2.indexOf(e.config.method)!==-1:!1}function j2(e){return T2(e)||A2(e)}function M2(e=void 0){let t=e?.response?.headers[`retry-after`];if(!t)return 0;let n=(Number(t)||0)*1e3;return n===0&&(n=(new Date(t).valueOf()||0)-Date.now()),Math.max(0,n)}function Lte(e=0,t=void 0){return Math.max(0,M2(t))}function N2(e=0,t=void 0,n=100){let r=2**e*n,i=Math.max(r,M2(t));return i+i*.2*Math.random()}function Rte(e=100){return(t=0,n=void 0)=>{let r=t*e;return Math.max(r,M2(n))}}const zte={retries:3,retryCondition:j2,retryDelay:Lte,shouldResetTimeout:!1,onRetry:()=>{},onMaxRetryTimesExceeded:()=>{},validateResponse:null};function P2(e,t){return{...zte,...t,...e[w2]}}function F2(e,t,n=!1){let r=P2(e,t||{});return r.retryCount=r.retryCount||0,(!r.lastRequestTime||n)&&(r.lastRequestTime=Date.now()),e[w2]=r,r}function I2(e,t){e.defaults.agent===t.agent&&delete t.agent,e.defaults.httpAgent===t.httpAgent&&delete t.httpAgent,e.defaults.httpsAgent===t.httpsAgent&&delete t.httpsAgent}async function L2(e,t){let{retries:n,retryCondition:r}=e,i=(e.retryCount||0)<n&&r(t);if(typeof i==`object`)try{return await i!==!1}catch{return!1}return i}async function R2(e,t,n,r){t.retryCount+=1;let{retryDelay:i,shouldResetTimeout:a,onRetry:o}=t,s=i(t.retryCount,n);if(I2(e,r),!a&&r.timeout&&t.lastRequestTime){let e=Date.now()-t.lastRequestTime,i=r.timeout-e-s;if(i<=0)return Promise.reject(n);r.timeout=i}return r.transformRequest=[e=>e],await o(t.retryCount,n,r),r.signal?.aborted?Promise.resolve(e(r)):new Promise(t=>{let n=()=>{clearTimeout(i),t(e(r))},i=setTimeout(()=>{t(e(r)),r.signal?.removeEventListener&&r.signal.removeEventListener(`abort`,n)},s);r.signal?.addEventListener&&r.signal.addEventListener(`abort`,n,{once:!0})})}async function z2(e,t){e.retryCount>=e.retries&&await e.onMaxRetryTimesExceeded(t,e.retryCount)}const B2=(e,t)=>({requestInterceptorId:e.interceptors.request.use(e=>(F2(e,t,!0),e[w2]?.validateResponse&&(e.validateStatus=()=>!1),e)),responseInterceptorId:e.interceptors.response.use(null,async n=>{let{config:r}=n;if(!r)return Promise.reject(n);let i=F2(r,t);return n.response&&i.validateResponse?.(n.response)?n.response:await L2(i,n)?R2(e,i,n,r):(await z2(i,n),Promise.reject(n))})});B2.isNetworkError=T2,B2.isSafeRequestError=k2,B2.isIdempotentRequestError=A2,B2.isNetworkOrIdempotentRequestError=j2,B2.exponentialDelay=N2,B2.linearDelay=Rte,B2.isRetryableError=O2;const V2=Error(`request for lock canceled`);var H2=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},U2=class{constructor(e,t=V2){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((n,r)=>{let i={resolve:n,reject:r,weight:e,priority:t},a=W2(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return H2(this,arguments,void 0,function*(e,t=1,n=0){let[r,i]=yield this.acquire(t,n);try{return yield e(r)}finally{i()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),Bte(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let n=this._weightedWaiters[t-1];if(!n)continue;let r=n.findIndex(t=>t.priority<=e);(r===-1?n:n.splice(0,r)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function Bte(e,t){let n=W2(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function W2(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var G2=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},K2=class{constructor(e){this._semaphore=new U2(1,e)}acquire(){return G2(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};new TextEncoder;const q2=new TextDecoder;function J2(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function Y2(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:q2.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=q2.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`).replace(/\s/g,``);try{return J2(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}var X2=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},Z2=class extends X2{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`};Symbol.asyncIterator;function Q2(e){return typeof e==`object`&&!!e}var $2=e=>{if(!Q2(e)||Object.prototype.toString.call(e)!==`[object Object]`)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t};function e4(e){if(typeof e!=`string`)throw new Z2(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new Z2(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new Z2(`Invalid JWT`);if(!t)throw new Z2(`JWTs must contain a payload`);let r;try{r=Y2(t)}catch{throw new Z2(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(q2.decode(r))}catch{throw new Z2(`Failed to parse the decoded payload as JSON`)}if(!$2(i))throw new Z2(`Invalid JWT Claims Set`);return i}const t4=e=>{let t=e4(e).exp;return(0,B.isDefined)(t)?t*1e3:null},n4=e=>{if(!(0,B.isDefined)(e))return!0;let t=t4(e);return(0,B.isDefined)(t)?t>Date.now():!0};let r4=class{jwtToken=null;refreshTokenCallback=null;observer=new B.Observer;refreshTokenMutex=new K2;setJWTToken(e){this.jwtToken=e,this.observer.notifyAll(e)}async getJWTToken(){return(0,B.isDefined)(this.jwtToken)?(this.isTokenValid()||await this.refreshTokenMutex.runExclusive(async()=>{if((0,B.isDefined)(this.refreshTokenCallback))return await this.refreshTokenCallback(),this.jwtToken}),this.jwtToken):null}onJWTTokenSave(e){this.observer.addListener(e)}isTokenValid(){return n4(this.jwtToken)}setRefreshTokenCallback(e){this.refreshTokenCallback=e}};r4=aQ([et(`Singleton`)],r4);var i4,a4;let o4=class{axiosInstance;constructor(e,t,n){this.configService=e,this.authStorage=t,this.logger=n,this.configService=e,this.axiosInstance=k0.create({baseURL:this.configService.getConfigValueOrThrow(`backendURL`),headers:{"Content-Type":`application/json`}}),B2(this.axiosInstance,{retries:3,retryDelay:B2.exponentialDelay,retryCondition:e=>k0.isAxiosError(e)&&B2.isNetworkOrIdempotentRequestError(e)||k0.isAxiosError(e)&&e.response?.status!==void 0&&e.response.status>=500||!1})}async getAuthHeaders(){let e={"x-request-source":cW.RequestSource.CLI},t=await this.authStorage.getJWTToken();return(0,B.isDefined)(t)&&(e.authorization=`Bearer ${t}`),e}async apiCall({url:e,method:t,data:n,config:r}){let i=new L0(await this.getAuthHeaders());if(r?.headers)for(let[e,t]of Object.entries(r.headers))i.set(e,t);let a={...r,method:t,url:e,data:n,headers:i};try{return await this.axiosInstance.request(a)}catch(t){this.handleError(e,t)}}async get(e,t){return(await this.apiCall({url:e,method:`GET`,config:t})).data}async post(e,t,n){return(await this.apiCall({url:e,method:`POST`,data:t,config:n})).data}async put(e,t,n){return(await this.apiCall({url:e,method:`PUT`,data:t,config:n})).data}async delete(e,t){return(await this.apiCall({url:e,method:`DELETE`,config:t})).data}async patch(e,t,n){return(await this.apiCall({url:e,method:`PATCH`,data:t,config:n})).data}async head(e,t){return this.apiCall({url:e,method:`HEAD`,config:t})}async options(e,t){return this.apiCall({url:e,method:`OPTIONS`,config:t})}handleCustomErrors(e,t){if(e===R0.Conflict){if(t===`workflow_is_cancelled`)throw this.logger.warn(`Agent flow canceled`),new W0(R0.Conflict,t);if(t===`duplicated_by_sha_workflow`)throw this.logger.warn(`Duplicated SHA workflow`),new G0(R0.Conflict,t)}}handleError(e,t){if(k0.isAxiosError(t))if((0,B.isDefined)(t.response)){let{status:e,statusText:n,data:r}=t.response;throw this.handleCustomErrors(e,r.message),new U0(e,`API request failed: ${e} ${n} - ${JSON.stringify(r)}`)}else if((0,B.isDefined)(t.request))throw Error(`API request failed: No response received from ${e}`);else throw Error(`API request failed: ${t instanceof Error?t.message:`Unknown error`}`);else if(t instanceof Error)throw TypeError(`API request failed: ${t.message}`);else throw TypeError(`API request failed: Unknown error occurred`)}};o4=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(r4)),iQ(2,Ze(sQ)),rQ(`design:paramtypes`,[typeof(i4=cQ!==void 0&&cQ)==`function`?i4:Object,typeof(a4=r4!==void 0&&r4)==`function`?a4:Object,Object])],o4);var s4,c4,l4;let u4=class{constructor(e,t,n){this.configService=e,this.apiService=t,this.authStorage=n,this.authStorage.setRefreshTokenCallback(async()=>{await this.login()})}async login(){let e=this.configService.getConfigValueOrThrow(`secretToken`,`API key is required but not configured`);try{let{idToken:t}=await this.apiService.post(`auth/v2/sign-in-with-secret-token`,{secret:e});return this.authStorage.setJWTToken(t),t}catch{throw Error(`Failed to get JWT token by secret`)}}};u4=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(o4)),iQ(2,Ze(r4)),rQ(`design:paramtypes`,[typeof(s4=cQ!==void 0&&cQ)==`function`?s4:Object,typeof(c4=o4!==void 0&&o4)==`function`?c4:Object,typeof(l4=r4!==void 0&&r4)==`function`?l4:Object])],u4);let d4=function(e){return e.PR=`PR`,e.COMMIT=`COMMIT`,e.PROJECT=`PROJECT`,e.COVERAGE=`COVERAGE`,e}({});var f4,p4;let m4=class{constructor(e,t){this.apiService=e,this.configService=t}mapCommandToType(e){switch(e){case dW.PR:return d4.PR;case dW.COMMIT:return d4.COMMIT;case dW.PROJECT:return d4.PROJECT;case dW.COVERAGE:return d4.COVERAGE}}async logStartOperation(e){let t=this.configService.getConfig(),n={type:this.mapCommandToType(t.command),owner:e.owner,repo:e.repository,sourceRef:e.ref_name,commitSha:e.sha,commitDate:e.commitDate,traceId:this.configService.getConfigValue(`traceId`),config:this.configService.maskedConfig(),operationStartedAt:new Date().toISOString(),version:t.cliVersion};return(await this.apiService.post(`api/v1/workflows/open`,n)).id}async logEndOperation(e,t,n,r){await this.apiService.patch(`api/v1/workflows/close/${e}`,{operationEndedAt:new Date().toISOString(),failureReason:t,runOutput:n,resultCommitSha:r})}async saveCoverageToWorkflow(e,t,{coverage:n,prCoverage:r,methodsAffected:i,committedFiles:a}){await this.apiService.patch(`api/v1/workflows/${e}/coverage`,{type:t,coverage:n,prCoverage:r,methodsAffected:i,committedFiles:a})}async getCoverageFromWorkflowOrUndefined(e){if(!this.configService.getConfigValue(`reuseCoverage`)||!(0,B.isDefined)(e))return;let t=this.configService.getConfigValue(`reuseCoverageMaxRuns`),n=await this.apiService.post(`api/v1/workflows/${e}/reuse-coverage`,{limit:t});if((0,B.isDefined)(n.coverageBefore))return n.coverageBefore}};m4=aQ([et(),iQ(0,Ze(o4)),iQ(1,Ze(cQ)),rQ(`design:paramtypes`,[typeof(f4=o4!==void 0&&o4)==`function`?f4:Object,typeof(p4=cQ!==void 0&&cQ)==`function`?p4:Object])],m4);var h4;let g4=class{constructor(e,t){this.tsAgent=e,this.logger=t}async analyzeChangedMethods(e,t,n){try{this.logger.info(`Analyzing coverage for ${t.length} changed methods with threshold ${n.coverageThreshold}%`);let r=[],i=0,a=0,o=0,s=this.groupChangedMethodsByFile(t);for(let[t,c]of Object.entries(s)){let s=this.findFileCoverage(e,t);if((0,B.isDefined)(s)){let e=this.processFileWithCoverage(t,c,s,n);r.push(...e.testables),i+=e.analyzed,a++}else{let e=this.processFileWithoutCoverage(t,c);r.push(...e.testables),i+=e.analyzed,o++}}let c={testables:r,totalAnalyzed:i,filteredCount:r.length,filesWithCoverage:a,filesWithoutCoverage:o};return this.logger.info(`Changed methods analysis complete: ${c.filteredCount}/${c.totalAnalyzed} methods below threshold across ${a+o} files`),c}catch(e){throw e instanceof Error?(this.logger.error(`Failed to analyze changed methods: ${e.message}`),e):Error(`Unknown error occurred while analyzing changed methods`)}}processFileWithCoverage(e,t,n,r){let i=[],a=0;for(let o of t){if(o.changeType===`deleted`||!o.canCreateTests)continue;let t=this.findTestableInCoverage(n,o);(0,B.isDefined)(t)?(a++,this.shouldIncludeTestable(t,r)&&i.push({name:t.name,percentage:t.percentage,filePath:e,reason:this.getFilterReason(t)})):(a++,i.push({name:o.name??`unknown`,percentage:null,filePath:e,reason:`no-coverage`}))}return{testables:i,analyzed:a}}processFileWithoutCoverage(e,t){let n=t.filter(e=>e.changeType!==`deleted`&&e.canCreateTests),r=n.map(t=>({name:t.name??`unknown`,percentage:null,filePath:e,reason:`no-coverage`}));return this.logger.debug(`No coverage data found for file: ${e}`),{testables:r,analyzed:n.length}}async analyzeChangedFiles(e,t,n){try{this.logger.info(`Analyzing coverage for ${t.length} changed files with threshold ${n.coverageThreshold}%`);let r=[],i=0,a=0,o=0;for(let s of t){let t=this.findFileCoverage(e,s);if((0,B.isDefined)(t)){a++;let e=await this.filterOutClasses(s,t.testables??[]),o=this.filterTestablesForFile(t,s,n),c=await this.filterOutClasses(s,o);r.push(...c),i+=e.length??0,(0,B.isEmpty)(c)||this.logger.debug(`File ${s}: ${c.length}/${e.length??0} testables below threshold`)}else o++,this.logger.debug(`No coverage data found for file: ${s}`)}let s={testables:r,totalAnalyzed:i,filteredCount:r.length,filesWithCoverage:a,filesWithoutCoverage:o};return this.logger.info(`Coverage analysis complete: ${s.filteredCount}/${s.totalAnalyzed} testables below threshold across ${s.filesWithCoverage} files`),s}catch(e){throw e instanceof Error?(this.logger.error(`Failed to analyze coverage: ${e.message}`),e):Error(`Unknown error occurred while analyzing coverage`)}}findFileCoverage(e,t){let n=t.startsWith(`/`)?t:`/${t}`;return(0,B.isDefined)(e[n])?e[n]:null}filterTestablesForFile(e,t,n){let r=[];for(let i of e.testables??[])if(this.shouldIncludeTestable(i,n)){let e=this.getFilterReason(i);r.push({name:i.name,percentage:i.percentage,filePath:t,reason:e})}return r}shouldIncludeTestable(e,t){return!!(e.percentage===null||e.percentage===0||(0,B.isDefined)(e.percentage)&&e.percentage<t.coverageThreshold)}getFilterReason(e){return e.percentage===null?`no-coverage`:e.percentage===0?`zero-coverage`:`below-threshold`}async calculatePRCoverage(e,t){if(!(0,B.isEmpty)(e))try{let n=await this.tsAgent.getCoverageForFiles(e),r=t?`before`:`after`;return this.logger.debug(`PR Coverage (${r}): ${n.percentage}% (${n.coveredStatements}/${n.totalStatements} statements)`),n}catch(e){this.logger.warn(`Failed to calculate PR coverage: ${e instanceof Error?e.message:`Unknown error`}`);return}}async filterOutClasses(e,t){let n=await this.tsAgent.getTestables(e);if((0,B.isEmpty)(n)||!(0,B.isDefined)(n[0]))return this.logger.warn(`getTestables returned empty for ${e}, keeping all testables`),t;let[,r]=n[0],i=r.filter(e=>e.type!==`class`),a=new Set(i.map(e=>e.name));return t.filter(e=>a.has(e.name))}groupChangedMethodsByFile(e){let t={};for(let n of e)(0,B.isDefined)(t[n.filePath])||(t[n.filePath]=[]),t[n.filePath].push(n);return t}findTestableInCoverage(e,t){return(0,B.isDefined)(e.testables)?e.testables.find(e=>{let n=e.name===t.name,r=`parentName`in e?e.parentName===t.parentName:!(0,B.isDefined)(t.parentName);return n&&r})??null:null}};g4=aQ([et(),iQ(0,Ze(lW.TSAgent)),iQ(1,Ze(sQ)),rQ(`design:paramtypes`,[typeof(h4=cW.TSAgent!==void 0&&cW.TSAgent)==`function`?h4:Object,Object])],g4);function _4(e,t){return t2(e,`package.json`,t)??void 0}function v4(e,t){try{return m.default.existsSync(e)?m.default.readFileSync(e,`utf8`):void 0}catch(n){t.warn(`Failed to read file ${e}: ${n instanceof Error?n.message:`Unknown error`}`);return}}async function y4(e,t,n){let r=_4(e,t),i=(await(0,cW.findLintConfigPath)(t)).path??void 0,a=(0,B.isDefined)(r)?v4(r,n):void 0,o=(0,B.isDefined)(i)?v4(i,n):void 0;return(0,B.isDefined)(r)&&n.info(`Found package.json at: ${r}`),(0,B.isDefined)(i)&&n.info(`Found lint config at: ${i}`),{packageJsonPath:r,packageJsonContent:a,lintConfigPath:i,lintConfigContent:o}}const b4={detectProjectConfigs:y4};var x4,S4;let C4=class{constructor(e,t,n){this.apiService=e,this.configService=t,this.logger=n}async detectAndSaveConfigs(e){try{let t=this.configService.getConfigValue(`rootPath`),n=await b4.detectProjectConfigs(t,t,this.logger);if(!(0,B.isDefined)(n.packageJsonContent)&&!(0,B.isDefined)(n.lintConfigContent))return;await this.apiService.patch(`api/v1/github-repos/configs`,{owner:e.owner,repo:e.repository,packageJson:n.packageJsonContent,lintConfig:n.lintConfigContent})}catch(e){this.logger.warn(`Failed to detect and save project configs: ${e instanceof Error?e.message:`Unknown error`}`)}}};C4=aQ([et(),iQ(0,Ze(o4)),iQ(1,Ze(cQ)),iQ(2,Ze(sQ)),rQ(`design:paramtypes`,[typeof(x4=o4!==void 0&&o4)==`function`?x4:Object,typeof(S4=cQ!==void 0&&cQ)==`function`?S4:Object,Object])],C4);var Vte,w4,T4,E4,D4,O4,k4,A4,j4;let M4=class{workflowRunId;initialCoverageTree;resultCommitSha;constructor(e,t,n,r,i,a,o,s,c,l){this.configService=e,this.authService=t,this.gitService=n,this.coverageAnalysisService=r,this.summaryService=i,this.tsAgent=a,this.workflowService=o,this.scmHostService=s,this.repoConfigService=c,this.logger=l}async login(){try{this.logger.info(`Trying login to API...`);let e=await this.authService.login();await this.tsAgent.init(e),this.logger.info(`Successfully authenticated with the API`)}catch(e){throw this.logger.error(`Failed to authenticate:`+(e instanceof Error?e.message:`Unknown error`)),e}}async logStart(){try{let e=await this.gitService.getGitInfo();this.logger.debug(`Git info: `+JSON.stringify(e));try{let t=await this.workflowService.logStartOperation(e);return this.tsAgent.updateContext({git:{...e,workflowRunId:t}}),this.workflowRunId=t,await this.repoConfigService.detectAndSaveConfigs(e),t}catch(e){throw e instanceof G0||e instanceof W0||this.logger.warn(`Failed to log start operation: ${e instanceof Error?e.message:`Unknown error`}`),e}}catch(e){throw e instanceof G0||e instanceof W0||this.logger.error(`Failed to retrieve git info or log start operation:`+(e instanceof Error?e.message:`Unknown error`)),e}}async generateInitialCoverage(){this.logger.verbose(`Try to reuse coverage...`);let e=await this.workflowService.getCoverageFromWorkflowOrUndefined(this.workflowRunId);if((0,B.isDefined)(e))return await this.tsAgent.setCoverage(e),this.initialCoverageTree=e,(0,B.isDefined)(this.workflowRunId)&&await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{}),this.logger.verbose(`Reused coverage: `+(e[`/`]?.percentage??0)+`%`),this.summaryService.setCoverageData(e[`/`]?.percentage??0,e[`/`]?.percentage??0),e;{this.logger.verbose(`Generating initial coverage...`),await this.tsAgent.generateCoverage();let e=await this.tsAgent.getCoverageTree();if(!(0,B.isDefined)(e))throw Error(`Failed to generate initial coverage tree`);return this.initialCoverageTree=e,(0,B.isDefined)(this.workflowRunId)&&await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{coverage:e}),this.logger.verbose(`Initial coverage: `+(e[`/`]?.percentage??0)+`%`),this.summaryService.setCoverageData(e[`/`]?.percentage??0,e[`/`]?.percentage??0),e}}async logEndOperation(e){if((0,B.isDefined)(this.workflowRunId))try{let t=this.summaryService.getWorkflowRunOutput();await this.workflowService.logEndOperation(this.workflowRunId,e,t,this.resultCommitSha),this.logger.info(`Successfully logged workflow end`)}catch(e){this.logger.warn(`Failed to log workflow end: `+(e instanceof Error?e.message:`Unknown error`))}}getWorkflowRunIdOrThrow(){if(!(0,B.isDefined)(this.workflowRunId))throw Error(`Workflow run ID is not set, call logStart() first`);return this.workflowRunId}getInitialCoverageTreeOrThrow(){if(!(0,B.isDefined)(this.initialCoverageTree))throw Error(`Initial coverage tree is not set, call generateInitialCoverage() first`);return this.initialCoverageTree}getInitialCoverageTreeOrUndefined(){return this.initialCoverageTree}async countAllMethodsInFiles(e){let t=(0,B.uniq)(e).map(async e=>{try{return await this.tsAgent.getAllMethodsCount(e)}catch(t){return this.logger.debug(`Failed to count methods in `+e+`: `+(t instanceof Error?t.message:`Unknown error`)),0}});return(await Promise.all(t)).reduce((e,t)=>e+t,0)}};M4=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(u4)),iQ(2,Ze(xQ)),iQ(3,Ze(g4)),iQ(4,Ze(uQ)),iQ(5,Ze(lW.TSAgent)),iQ(6,Ze(m4)),iQ(7,Ze(lW.SCMHostService)),iQ(8,Ze(C4)),iQ(9,Ze(sQ)),rQ(`design:paramtypes`,[typeof(Vte=cQ!==void 0&&cQ)==`function`?Vte:Object,typeof(w4=u4!==void 0&&u4)==`function`?w4:Object,typeof(T4=xQ!==void 0&&xQ)==`function`?T4:Object,typeof(E4=g4!==void 0&&g4)==`function`?E4:Object,typeof(D4=uQ!==void 0&&uQ)==`function`?D4:Object,typeof(O4=cW.TSAgent!==void 0&&cW.TSAgent)==`function`?O4:Object,typeof(k4=m4!==void 0&&m4)==`function`?k4:Object,typeof(A4=hQ!==void 0&&hQ)==`function`?A4:Object,typeof(j4=C4!==void 0&&C4)==`function`?j4:Object,Object])],M4);var N4;let P4=class extends M4{changedFiles=[];prCoverage={before:{percentage:null,totalStatements:0,coveredStatements:0},after:{percentage:null,totalStatements:0,coveredStatements:0}};testableToGenerateService;getWorkflowRunId(){return this.workflowRunId}async runFlow(e){let t=e?.shouldDeferPostGeneration??!1,n,r=!1,i;try{await this.login(),await this.logStart(),await this.validateCommitBranch();let e=await this.getRawChangedFiles(),n=this.configService.getConfigValue(`rootPath`),r=this.configService.getConfigValue(`gitTopLevel`)??n;this.logger.info(`Discovering untested functions`);let a=await this.testableToGenerateService.getTestablesToGenerate({changedFiles:e,rootPath:n,gitTopLevel:r,hasDiffContext:this.hasDiffContext(),baseRevision:await this.getBaseRevision(),changedMethodsOnly:this.configService.getConfigValue(`changedMethodsOnly`),coverageReport:{tree:this.initialCoverageTree,threshold:this.configService.getConfigValue(`coverageThreshold`)}});if((0,B.isEmpty)(a.testables)){this.logFilteredOutTestables(a.filteredOut),this.handleNoFilteredTestables();return}if(this.updateRootPath(a.projectRootPath),this.changedFiles=a.testables.map(e=>e.filePath),await this.setSummaryChangedFilesData(e.length,a),a.filteredOut.filter(e=>e.reason===`limit-reached`).length>0){let e=this.configService.getConfigValue(`maxTestables`);this.summaryService.addWarning(`Limited to ${e} functions: test generation was capped due to maximum function limit.`)}this.logFilteredOutTestables(a.filteredOut),this.logTestablesToGenerate([...a.testables]);let o=[...a.testables];if(i=await this.generateTests(o),!t){let e=await this.performAutoCommit();this.summaryService.setTestGenerationData({generated:i.generated,succeeded:i.succeeded,failed:i.failed,successMethodsCount:i.successMethodsCount,committedFilesCount:e,greenTests:i.greenTests,redTests:i.redTests}),this.configService.getConfigValue(`skipCoverageAfter`)?(this.logger.verbose(`Skipping final coverage generation (--skip-coverage-after flag is set)`),this.summaryService.setCoverageSkipped()):await this.generateFinalCoverageAndLog({methodsAffected:o.length,committedFiles:e})}return i}catch(e){if(e instanceof G0){this.logger.warn(`Duplicate SHA execution detected. Skipping.`);return}if(e instanceof W0){this.logger.warn(`Workflow canceled. Skipping.`),r=!0;return}throw n=e instanceof Error?e.message:`Unknown error`,this.logger.error(`Agent flow failed: `+n),e}finally{!t&&(0,B.isDefined)(this.workflowRunId)&&!r&&(this.summaryService.setPRCoverageData(this.prCoverage.before,this.prCoverage.after),await this.scmHostService.safePostSummaryToPr(),await this.logEndOperation(n))}}async setSummaryChangedFilesData(e,t){let n=[...new Set([...t.testables.map(e=>e.filePath),...t.filteredOut.map(e=>e.filePath)])],r=await this.countAllMethodsInFiles(n);this.summaryService.setChangedFilesData({changedFilesCount:e,candidateFilesCount:n.length,functionCount:r,publicMethodCount:t.testables.length,testablesToGenerateCount:t.testables.length,publicMethods:t.testables.map(e=>({name:e.testable.name??`unknown`,filePath:e.filePath})),methodsBelowCoverage:t.testables.map(e=>({name:e.testable.name??`unknown`,filePath:e.filePath}))})}handleNoFilteredTestables(){this.logger.warn(`No filtered untested functions`),this.prCoverage.after=this.prCoverage.before}logFilteredOutTestables(e){if((0,B.isEmpty)(e))return;let t=e.length,n=t===1?`item`:`items`;this.logger.verbose(t+` `+n+` skipped:`);for(let t of e){let e=(0,B.isDefined)(t.testableName)?t.testableName+` in `+t.filePath:t.filePath;this.logger.verbose(` - `+e+`: `+t.reason)}}logTestablesToGenerate(e){this.logger.info(`Found ${e.length} public function${e.length===1?``:`s`} without Early AI tests`);for(let t of e)this.logger.info(` `+t.testable.name+` in `+t.filePath)}async validateCommitBranch(){if(!this.configService.getConfigValue(`autoCommit`))return;let e=this.configService.getConfigValue(`refName`);if(e&&!await this.gitService.checkRefExists(e))throw Error(`Branch '${e}' does not exist on remote. Create it before running with --auto-commit.`)}async performAutoCommit(){let e=this.configService.getConfigValueOrThrow(`autoCommit`);if(this.summaryService.setAutoCommitStatus(e),e){let e=this.configService.getConfigValue(`refName`),t=await this.gitService.commitFiles(e);return(0,B.isDefined)(t.resultCommitSha)&&(this.resultCommitSha=t.resultCommitSha),t.committedFiles.length}else return this.logger.info(`Auto-commit is disabled - skipping commit step`),0}async _generateInitialCoverageForTestGeneration(){await this.generateInitialCoverage(),await this.savePRCoverageBefore()}async savePRCoverageBefore(){if((0,B.isDefined)(this.workflowRunId))try{let e=await this.coverageAnalysisService.calculatePRCoverage(this.changedFiles,!0);(0,B.isDefined)(e)&&(this.prCoverage.before=e),await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{prCoverage:e}),this.logger.debug(`Successfully saved initial coverage to workflow run`)}catch(e){this.logger.warn(`Failed to save initial coverage: `+(e instanceof Error?e.message:`Unknown error`))}}async generateTests(e){let t=new Set(e),n=0,r=0,i=0,a=0;try{await this.tsAgent.bulkGenerateTests(e,(o,s)=>{a++;let c=uW.default.basename(o.filePath);(0,B.isDefined)(s)&&s.greenTestsCount>0?(t.delete(o),n+=s.greenTestsCount,r+=s.redTestsCount,i+=s.greyTestsCount,this.logger.info(` [${a}/${e.length}] ✓ ${o.testable.name} (${c}) — ${s.greenTestsCount} passing, ${s.redTestsCount} skipped`)):this.logger.info(` [${a}/${e.length}] ✗ ${o.testable.name} (${c}) — no tests generated`)})}catch(e){if(e instanceof Error&&(e.message===`Operation aborted`||e.name===`AbortError`))this.logger.warn(`Test generation was partially aborted due to timeout`);else throw e}let o=e.length-t.size,s=t.size,c=await this.gitService.getEarlyFiles();return this.logger.info(``),this.logger.info(`✅ Test generation complete for ${o} functions`),s>0&&this.logger.info(`❌ ${s} functions were not generated`),this.logger.info(``),this.logger.info(`================`),this.logger.info(`Overall summary:`),this.logger.info(`================`),this.logger.info(``),this.logger.info(`✅ ${n} tests passing`),this.logger.info(`⚠️ ${r} tests skipped`),this.logger.info(`❌ ${i} tests could not be fixed autonomously (yet)`),this.logger.info(``),{generated:e.length,succeeded:o,failed:s,successMethodsCount:c.length,greenTests:n,redTests:r}}async generateFinalCoverageAndLog({methodsAffected:e,committedFiles:t}){let n=this.getWorkflowRunIdOrThrow();this.logger.verbose(`Generating final coverage...`),await this.tsAgent.generateCoverage();let r=await this.tsAgent.getCoverageTree();if(!(0,B.isDefined)(r))throw Error(`Failed to generate final coverage tree`);let i=r[`/`]?.percentage??0,a=this.getInitialCoverageTreeOrUndefined(),o=a?.[`/`]?.percentage??0;(0,B.isDefined)(a)||this.summaryService.setCoverageBeforeSkipped(),this.summaryService.setCoverageData(o,i);let s=(0,B.isDefined)(a)?`${o}% -> ${i}%`:`skipped`;this.logger.verbose(`Final coverage: `+i+`%, Coverage comparison: `+s);try{let i=await this.coverageAnalysisService.calculatePRCoverage(this.changedFiles,!1);(0,B.isDefined)(i)&&(this.prCoverage.after=i),await this.workflowService.saveCoverageToWorkflow(n,`after`,{coverage:r,prCoverage:i,methodsAffected:e,committedFiles:t}),this.logger.debug(`Successfully saved final coverage to workflow run`)}catch(e){this.logger.warn(`Failed to save final coverage: `+(e instanceof Error?e.message:`Unknown error`))}}updateRootPath(e){this.tsAgent.updateRootPath(e),this.configService.updateConfigValue(`rootPath`,e)}};aQ([Ze(S2),rQ(`design:type`,typeof(N4=S2!==void 0&&S2)==`function`?N4:Object)],P4.prototype,`testableToGenerateService`,void 0),P4=aQ([et(),st({extendConstructorArguments:!0,extendProperties:!0})],P4);let F4=class extends P4{async getRawChangedFiles(){return this.gitService.getChangedFilesForCommitWithStatus({absolute:!0})}hasDiffContext(){return!0}async getBaseRevision(){let e=this.configService.getConfigValue(`baseRef`);if((0,B.isDefined)(e))return this.gitService.getBaseRevision({baseBranch:e});let t=this.configService.getConfigValue(`commitHash`);if((0,B.isDefined)(t))return`${t}^`}async logStart(){try{let e=this.configService.getConfigValue(`commitHash`),t=await this.gitService.getCommitMessage(e);t&&this.configService.updateConfigValue(`commitName`,t)}catch(e){this.logger.warn(`Failed to retrieve commit message, continuing without it: `+(e instanceof Error?e.message:`Unknown error`))}try{let e=await this.scmHostService.getContributorAvatarUrl();(0,B.isDefined)(e)&&this.configService.updateConfigValue(`contributorAvatarUrl`,e)}catch(e){this.logger.warn(`Failed to retrieve contributor avatar, continuing without it: `+(e instanceof Error?e.message:`Unknown error`))}return await super.logStart()}};F4=aQ([et(),st({extendConstructorArguments:!0,extendProperties:!0})],F4);function Hte(e){let t=e.command(dW.COMMIT).alias(`generate-commit`).description(`Generate tests for the current project in commit context`);return ce(t,`--commit-hash <hash>`,`Commit hash`,{envName:`COMMIT_HASH`,isRequired:!0}),ce(t,`--ref-name <ref>`,`Head branch name for the commit`,{envName:`REF_NAME`,isRequired:!0}),ce(t,`--base-ref <ref>`,`optional base refrence for comparison`,{envName:`BASE_REF`}),ce(t,`-s, --test-structure <structure>`,`Test file structure`,{envName:`TEST_STRUCTURE`,def:`siblingFolder`}),ce(t,`-f, --test-framework <framework>`,`Test framework to use`,{envName:`TEST_FRAMEWORK`,def:`jest`}),ce(t,`--test-suffix <suffix>`,`Test file suffix`,{envName:`TEST_FILE_SUFFIX`,def:`test`}),ce(t,`--test-file-naming <naming>`,`Test file naming convention`,{envName:`TEST_FILE_NAMING`,def:`camelCase`}),ce(t,`-c, --max-concurrency <number>`,`Number of concurrent workers (1-4)`,{envName:`MAX_CONCURRENCY`,def:`3`}),ce(t,`--auto-commit <boolean>`,`Whether to auto-commit files`,{envName:`AUTO_COMMIT`,def:`true`}),ce(t,`--auto-commit-skip-ci <boolean>`,`Append [skip ci] to auto-commit message`,{envName:`AUTO_COMMIT_SKIP_CI`,def:`true`}),ce(t,`--test-command <command>`,`Custom test command to run`,{envName:`TEST_COMMAND`}),ce(t,`--coverage-command <command>`,`Custom coverage command to run`,{envName:`COVERAGE_COMMAND`}),ce(t,`--lint-command <command>`,`Custom lint command to run`,{envName:`LINT_COMMAND`}),ce(t,`--prettier-command <command>`,`Custom prettier command to run`,{envName:`PRETTIER_COMMAND`}),ce(t,`--disable-lint-rules <boolean>`,`Whether to disable failed lint rules in test files`,{envName:`DISABLE_LINT_RULES`,def:`false`}),ce(t,`--git-org <org>`,`Git organization name`,{envName:`GIT_ORG`}),ce(t,`--git-repo <repo>`,`Git repository name`,{envName:`GIT_REPO`}),ce(t,`--git-user-email <email>`,`Git user email for auto commit`,{envName:`GIT_USER_EMAIL`}),ce(t,`--git-user-name <name>`,`Git user name for auto commit`,{envName:`GIT_USER_NAME`}),ce(t,`--scm-provider <provider>`,`SCM provider (e.g., github, bitbucket)`,{envName:`SCM_PROVIDER`,def:`github`}),ce(t,`--keep-error-tests <boolean>`,`Whether to keep error tests`,{envName:`KEEP_ERROR_TESTS`,def:`false`}),ce(t,`--keep-failed-tests <boolean>`,`Whether to keep failed tests`,{envName:`KEEP_FAILED_TESTS`,def:`false`}),ce(t,`--conditional-keep <boolean>`,`Whether to return the last generated test result even when no green tests were produced`,{envName:`CONDITIONAL_KEEP`,def:`false`}),ce(t,`--continue-on-test-errors <boolean>`,`Whether to continue on test errors`,{envName:`CONTINUE_ON_TEST_ERRORS`,def:`false`}),ce(t,`--changed-methods-only <boolean>`,`Generate tests only for changed methods, not all methods in changed files`,{envName:`CHANGED_METHODS_ONLY`,def:`true`}),ce(t,`--skip-coverage-after <boolean>`,`Skip final coverage generation after test generation`,{envName:`SKIP_COVERAGE_AFTER`,def:`true`}),ce(t,`--max-testables <number>`,`Maximum number of testables to generate`,{envName:`MAX_TESTABLES`}),ce(t,`--per-function-timeout <number>`,`Per function timeout in milliseconds`,{envName:`PER_FUNCTION_TIMEOUT`}),ce(t,`--coverage-threshold <number>`,`Coverage threshold percentage (0-100)`,{envName:`COVERAGE_THRESHOLD`,def:`0`}),ce(t,`--reuse-coverage <boolean>`,`Whether to reuse coverage`,{envName:`REUSE_COVERAGE`,def:`false`}),ce(t,`--reuse-coverage-max-runs <number>`,`Max number of runs to reuse coverage (1-10)`,{envName:`REUSE_COVERAGE_MAX_RUNS`,def:`10`}),ce(t,`--experimental-agent-sdk <boolean>`,`Use experimental Agent SDK for test generation`,{envName:`EXPERIMENTAL_AGENT_SDK`,def:`true`}),t.addHelpText(`after`,`
32412
32413
  Examples:
32413
32414
  $ early generate-commit --api-key your-api-key --token your-token --commit-hash abc123 --ref-name feature/new-feature
32414
32415
  $ early generate-commit -k your-api-key -f jest -s siblingFolder --test-command "npm run test -- $early_filename" --coverage-command "npm run coverage -- --coverageReporters=json --coverageDirectory=$early_coverage_dir"
@@ -32432,7 +32433,7 @@ Need help? → https://docs.startearly.ai
32432
32433
  pip install earlyai-agent
32433
32434
  # or: uv pip install earlyai-agent`);let e;try{await this.authService.login(),await this.gitService.hydrateConfig();let t=await this.gitService.getGitInfo();e=await this.workflowService.logStartOperation(t),this.logger.debug(`Workflow run opened: ${e}`)}catch(e){this.logger.warn(`Failed to open workflow run: ${e instanceof Error?e.message:`Unknown error`}`)}let t=await this.gitService.getChangedFilesForPR();this.logger.debug(`PR changed files (${t.length}): ${t.join(`, `)}`),this._summaryData={total:0,succeeded:0,failed:0},this._totalGreenTests=0,this._skippedMethods=0;let n=this._resolveClaudeCliJs(),r={...process.env,API_KEY:this.configService.getConfigValue(`secretToken`)??``,API_BASE_URL:this.configService.getConfigValue(`backendURL`)??`https://api.startearly.ai`,TEST_FRAMEWORK:`pytest`,TEST_STRUCTURE:this.configService.getConfigValue(`testStructure`)??`siblingFolder`,TEST_FILE_NAMING:this.configService.getConfigValue(`testFileName`)??`camelCase`,MAX_CONCURRENCY:String(this.configService.getConfigValue(`concurrency`)??3),MAX_TESTABLES:String(this.configService.getConfigValue(`maxTestables`)??``),BASE_REF:this.configService.getConfigValue(`baseRef`)??``,CHANGED_FILES:t.join(`
32434
32435
  `),...e===void 0?{}:{WORKFLOW_RUN_ID:e},...n===void 0?{}:{CLAUDE_CLI_PATH:n},LOG_LEVEL:`WARNING`},i=this.configService.getConfigValue(`rootPath`);return await this._runSubprocess(`generate-pr`,r,i),{workflowRunId:e,testResults:{generated:this._summaryData.total,succeeded:this._summaryData.succeeded,failed:this._summaryData.failed,successMethodsCount:this._summaryData.succeeded,greenTests:this._totalGreenTests,redTests:this._summaryData.failed,skippedMethods:this._skippedMethods}}}_runSubprocess(e,t,n){return new Promise((r,i)=>{let a=(0,f.spawn)(`earlyai-agent`,[e],{env:t,cwd:n,stdio:[`ignore`,`pipe`,`pipe`]}),o=``;a.stdout.on(`data`,e=>{o+=e.toString();let t=o.split(`
32435
- `);o=t.pop()??``;for(let e of t)if(e.trim())try{let t=JSON.parse(e);this._handleEvent(t)}catch{this.logger.debug(e)}}),a.stderr?.on(`data`,e=>{let t=e.toString().trim();t&&this.logger.debug(t)}),a.on(`close`,e=>{o.trim()&&this.logger.debug(o),e===0||e===1?r():i(Error(`earlyai-agent exited with code ${e}`))}),a.on(`error`,i)})}_handleEvent(e){switch(e.type){case`scan`:this._handleScan(e);break;case`extract`:this._handleExtract(e);break;case`start`:this._handleStart(e);break;case`skip`:this._handleSkip(e);break;case`progress`:this._handleProgress(e);break;case`done`:this._handleDone(e);break;case`error`:this._handleError(e);break;case`summary`:this._handleSummary(e);break;case`agent_hook`:this._handleAgentHook(e);break;default:this.logger.debug(`${JSON.stringify(e)}`)}}_handleScan(e){let t=e.files===1?``:`s`;this.logger.info(`Found ${e.files} source file${t}`)}_handleExtract(e){let t=e.functions??0,n=e.total_in_file,r=e.skipped??0;if(t===0&&r===0){this.logger.debug(` ${e.file} — 0 functions (skipped)`);return}if(t===0&&r>0){let t=r===1?``:`s`;this.logger.info(` ${e.file} — ${r} function${t} already tested (skipped)`);return}let i=t===1?``:`s`,a=[];e.changed!==void 0&&e.unchanged!==void 0&&a.push(`${e.changed} changed, ${e.unchanged} unchanged`),r>0&&a.push(`${r} already tested`);let o=n===void 0?``:` of ${n} total`,s=a.length>0?` (${a.join(`, `)})`:``;this.logger.info(` ${e.file} — ${t} testable function${i}${o}${s}`)}_handleStart(e){this._summaryData.total=e.total??0;let t=e.total??0,n=t===1?``:`s`,r=``;if(e.files!==void 0&&e.files>0){let t=e.files===1?``:`s`;r=` across ${e.files} file${t}`}this.logger.info(``),this.logger.info(`Generating tests for ${t} function${n}${r}...`)}_handleSkip(e){this._skippedMethods++;let t=e.file?.split(/[\\/]/).pop()??e.file;this.logger.info(` ⊘ ${e.method} (${t}) — already tested`)}_handleProgress(e){this._clearProgressTimer();let t=e.file?.split(/[\\/]/).pop()??e.file,n=` [${e.index}/${e.total}] ${e.method} (${t})`;this.logger.info(n),this._progressStartTime=Date.now(),this._progressTimer=setInterval(()=>{let t=Math.round((Date.now()-this._progressStartTime)/1e3);this.logger.info(` [${e.index}/${e.total}] ${e.method} — generating... (${t}s)`)},15e3)}_clearProgressTimer(){this._progressTimer&&=(clearInterval(this._progressTimer),null)}_handleDone(e){this._clearProgressTimer(),this._totalGreenTests+=e.tests_count??0;let t=``;if(e.tests_count!==void 0){let n=e.tests_count===1?``:`s`;t=` — ${e.tests_count} test${n}`}this.logger.info(` [${e.index}/${e.total}] ✓ ${e.method}${t} → ${e.test_file}`)}_handleError(e){if(this._clearProgressTimer(),e.method===void 0||e.method===``){this.logger.error(`${e.message}`);return}if(e.index===void 0){this.logger.error(`✗ ${e.method}: ${e.message}`);return}this.logger.error(` [${e.index}/${e.total}] ✗ ${e.method} — ${e.message}`)}_handleAgentHook(e){let t=e.passed??0,n=e.failed??0;switch(e.action){case`DONE`:this.logger.info(` ↳ all ${t} tests passed`);break;case`STOPPING`:this.logger.info(` ↳ stopping agent — all tests green`);break;case`BLOCKED`:this.logger.debug(` ↳ blocked tool ${e.tool??`unknown`} — generation complete`);break;case`PRUNE`:this.logger.info(` ↳ ${t} passed, ${n} failed → pruning`);break;case`REPAIR`:this.logger.info(` ↳ ${t} passed, ${n} failed → repairing`);break}}_handleSummary(e){this._clearProgressTimer(),this._summaryData.total=e.total??this._summaryData.total,this._summaryData.succeeded=e.succeeded??0,this._summaryData.failed=e.failed??0,this.logger.info(``),this.logger.info(`Done — ${e.succeeded}/${e.total} succeeded, ${e.failed} failed`)}};W4=U4=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(u4)),iQ(2,Ze(xQ)),iQ(3,Ze(m4)),iQ(4,Ze(sQ)),rQ(`design:paramtypes`,[typeof(z4=cQ!==void 0&&cQ)==`function`?z4:Object,typeof(B4=u4!==void 0&&u4)==`function`?B4:Object,typeof(V4=xQ!==void 0&&xQ)==`function`?V4:Object,typeof(H4=m4!==void 0&&m4)==`function`?H4:Object,Object])],W4);var G4,K4,q4,J4,Y4;let X4=class{constructor(e,t,n,r,i,a){this.gitService=e,this.configService=t,this.summaryService=n,this.scmHostService=r,this.workflowService=i,this.logger=a}async cleanupBlankEarlyFiles(){let e=await this.gitService.getEarlyFiles({absolute:!0}),t=[];for(let n of e)try{(await g.readFile(n,`utf8`)).trim().length===0&&(await g.unlink(n),t.push(n))}catch{this.logger.debug(`Could not read or remove file: ${n}`)}return t}async autoCommit(){if(!this.configService.getConfigValue(`autoCommit`))return this.logger.info(`Auto-commit is disabled — skipping commit step`),{committedFiles:[],error:``};let e=this.configService.getConfigValue(`refName`);return await this.gitService.commitFiles(e)}async finalize(e){if(this.summaryService.setTestGenerationData({generated:e.testResults.generated,succeeded:e.testResults.succeeded,failed:e.testResults.failed,successMethodsCount:e.testResults.successMethodsCount,committedFilesCount:e.committedFilesCount,greenTests:e.testResults.greenTests,redTests:e.testResults.redTests,skippedMethods:e.testResults.skippedMethods}),this.summaryService.setAutoCommitStatus(this.configService.getConfigValue(`autoCommit`)),await this.scmHostService.safePostSummaryToPr(),(0,B.isDefined)(e.workflowRunId))try{let t=this.summaryService.getWorkflowRunOutput();await this.workflowService.logEndOperation(e.workflowRunId,e.failureReason,t,e.resultCommitSha),this.logger.debug(`Successfully logged workflow end`)}catch(e){this.logger.warn(`Failed to log workflow end: ${e instanceof Error?e.message:`Unknown error`}`)}}};X4=aQ([et(),iQ(0,Ze(xQ)),iQ(1,Ze(cQ)),iQ(2,Ze(uQ)),iQ(3,Ze(lW.SCMHostService)),iQ(4,Ze(m4)),iQ(5,Ze(sQ)),rQ(`design:paramtypes`,[typeof(G4=xQ!==void 0&&xQ)==`function`?G4:Object,typeof(K4=cQ!==void 0&&cQ)==`function`?K4:Object,typeof(q4=uQ!==void 0&&uQ)==`function`?q4:Object,typeof(J4=hQ!==void 0&&hQ)==`function`?J4:Object,typeof(Y4=m4!==void 0&&m4)==`function`?Y4:Object,Object])],X4);function Z4(e){let t=e.command(dW.PR).alias(`generate-pr`).description(`Generate tests for the current project in pr context`);return ce(t,`--pr-number <number>`,`PR number`,{envName:`PR_NUMBER`,isRequired:!0}),ce(t,`--ref-name <ref>`,`Head reference for the PR`,{envName:`REF_NAME`,isRequired:!0}),ce(t,`--base-ref <ref>`,`Base reference for the PR`,{envName:`BASE_REF`}),ce(t,`-s, --test-structure <structure>`,`Test file structure`,{envName:`TEST_STRUCTURE`,def:`siblingFolder`}),ce(t,`-f, --test-framework <framework>`,`Test framework to use`,{envName:`TEST_FRAMEWORK`,def:`jest`}),ce(t,`--test-suffix <suffix>`,`Test file suffix`,{envName:`TEST_FILE_SUFFIX`,def:`test`}),ce(t,`--test-file-naming <naming>`,`Test file naming convention`,{envName:`TEST_FILE_NAMING`,def:`camelCase`}),ce(t,`-c, --max-concurrency <number>`,`Number of concurrent workers (1-4)`,{envName:`MAX_CONCURRENCY`,def:`3`}),ce(t,`--auto-commit <boolean>`,`Whether to auto-commit files`,{envName:`AUTO_COMMIT`,def:`true`}),ce(t,`--auto-commit-skip-ci <boolean>`,`Append [skip ci] to auto-commit message`,{envName:`AUTO_COMMIT_SKIP_CI`,def:`true`}),ce(t,`--test-command <command>`,`Custom test command to run`,{envName:`TEST_COMMAND`}),ce(t,`--coverage-command <command>`,`Custom coverage command to run`,{envName:`COVERAGE_COMMAND`}),ce(t,`--lint-command <command>`,`Custom lint command to run`,{envName:`LINT_COMMAND`}),ce(t,`--prettier-command <command>`,`Custom prettier command to run`,{envName:`PRETTIER_COMMAND`}),ce(t,`--disable-lint-rules <boolean>`,`Whether to disable failed lint rules in test files`,{envName:`DISABLE_LINT_RULES`,def:`false`}),ce(t,`--git-org <org>`,`Git organization name`,{envName:`GIT_ORG`}),ce(t,`--git-repo <repo>`,`Git repository name`,{envName:`GIT_REPO`}),ce(t,`--git-user-email <email>`,`Git user email for auto commit`,{envName:`GIT_USER_EMAIL`}),ce(t,`--git-user-name <name>`,`Git user name for auto commit`,{envName:`GIT_USER_NAME`}),ce(t,`--scm-provider <provider>`,`SCM provider (e.g., github, bitbucket)`,{envName:`SCM_PROVIDER`,def:`github`}),ce(t,`--keep-error-tests <boolean>`,`Whether to keep error tests`,{envName:`KEEP_ERROR_TESTS`,def:`false`}),ce(t,`--keep-failed-tests <boolean>`,`Whether to keep failed tests`,{envName:`KEEP_FAILED_TESTS`,def:`false`}),ce(t,`--conditional-keep <boolean>`,`Whether to return the last generated test result even when no green tests were produced`,{envName:`CONDITIONAL_KEEP`,def:`false`}),ce(t,`--continue-on-test-errors <boolean>`,`Whether to continue on test errors`,{envName:`CONTINUE_ON_TEST_ERRORS`,def:`false`}),ce(t,`--changed-methods-only <boolean>`,`Generate tests only for changed methods, not all methods in changed files`,{envName:`CHANGED_METHODS_ONLY`,def:`true`}),ce(t,`--skip-coverage-after <boolean>`,`Skip final coverage generation after test generation`,{envName:`SKIP_COVERAGE_AFTER`,def:`true`}),ce(t,`--max-testables <number>`,`Maximum number of testables to generate`,{envName:`MAX_TESTABLES`}),ce(t,`--per-function-timeout <number>`,`Per function timeout in milliseconds`,{envName:`PER_FUNCTION_TIMEOUT`}),ce(t,`--coverage-threshold <number>`,`Coverage threshold percentage (0-100)`,{envName:`COVERAGE_THRESHOLD`,def:`0`}),ce(t,`--reuse-coverage <boolean>`,`Whether to reuse coverage`,{envName:`REUSE_COVERAGE`,def:`false`}),ce(t,`--reuse-coverage-max-runs <number>`,`Max number of runs to reuse coverage (1-10)`,{envName:`REUSE_COVERAGE_MAX_RUNS`,def:`10`}),ce(t,`--experimental-agent-sdk <boolean>`,`Use experimental Agent SDK for test generation`,{envName:`EXPERIMENTAL_AGENT_SDK`,def:`true`}),t.addHelpText(`after`,`
32436
+ `);o=t.pop()??``;for(let e of t)if(e.trim())try{let t=JSON.parse(e);this._handleEvent(t)}catch{this.logger.debug(e)}}),a.stderr?.on(`data`,e=>{let t=e.toString().trim();t&&this.logger.debug(t)}),a.on(`close`,e=>{o.trim()&&this.logger.debug(o),e===0||e===1?r():i(Error(`earlyai-agent exited with code ${e}`))}),a.on(`error`,i)})}_handleEvent(e){switch(e.type){case`scan`:this._handleScan(e);break;case`extract`:this._handleExtract(e);break;case`start`:this._handleStart(e);break;case`skip`:this._handleSkip(e);break;case`progress`:this._handleProgress(e);break;case`done`:this._handleDone(e);break;case`error`:this._handleError(e);break;case`summary`:this._handleSummary(e);break;case`agent_hook`:this._handleAgentHook(e);break;default:this.logger.debug(`${JSON.stringify(e)}`)}}_handleScan(e){let t=e.files===1?``:`s`;this.logger.info(`Found ${e.files} source file${t}`)}_handleExtract(e){let t=e.functions??0,n=e.skipped??0;if(t===0&&n===0){this.logger.debug(` ${e.file} — 0 functions (skipped)`);return}if(t===0&&n>0){let t=n===1?``:`s`;this.logger.info(` ${e.file} — ${n} function${t} already tested (skipped)`);return}let r=t===1?``:`s`,i=[];e.changed!==void 0&&e.unchanged!==void 0&&i.push(`${e.changed} changed, ${e.unchanged} unchanged`),n>0&&i.push(`${n} already tested`);let a=i.length>0?` (${i.join(`, `)})`:``;this.logger.info(` ${e.file} — ${t} testable function${r}${a}`);let o=this._buildFilteredReasons(e);o.length>0&&this.logger.info(` ${o.join(`, `)}`)}_buildFilteredReasons(e){let t=[],n=e.classes_skipped??0,r=e.private_skipped??0;return n>0&&t.push(`${n} class${n===1?``:`es`} skipped`),r>0&&t.push(`${r} private function${r===1?``:`s`} skipped`),t}_handleStart(e){this._summaryData.total=e.total??0;let t=e.total??0,n=t===1?``:`s`,r=``;if(e.files!==void 0&&e.files>0){let t=e.files===1?``:`s`;r=` across ${e.files} file${t}`}this.logger.info(``),this.logger.info(`Generating tests for ${t} function${n}${r}...`)}_handleSkip(e){this._skippedMethods++;let t=e.file?.split(/[\\/]/).pop()??e.file;this.logger.info(` ⊘ ${e.method} (${t}) — already tested`)}_handleProgress(e){this._clearProgressTimer();let t=e.file?.split(/[\\/]/).pop()??e.file,n=` [${e.index}/${e.total}] ${e.method} (${t})`;this.logger.info(n),this._progressStartTime=Date.now(),this._progressTimer=setInterval(()=>{let t=Math.round((Date.now()-this._progressStartTime)/1e3);this.logger.info(` [${e.index}/${e.total}] ${e.method} — generating... (${t}s)`)},15e3)}_clearProgressTimer(){this._progressTimer&&=(clearInterval(this._progressTimer),null)}_handleDone(e){this._clearProgressTimer(),this._totalGreenTests+=e.tests_count??0;let t=``;if(e.tests_count!==void 0){let n=e.tests_count===1?``:`s`;t=` — ${e.tests_count} test${n}`}this.logger.info(` [${e.index}/${e.total}] ✓ ${e.method}${t} → ${e.test_file}`)}_handleError(e){if(this._clearProgressTimer(),e.method===void 0||e.method===``){this.logger.error(`${e.message}`);return}if(e.index===void 0){this.logger.error(`✗ ${e.method}: ${e.message}`);return}this.logger.error(` [${e.index}/${e.total}] ✗ ${e.method} — ${e.message}`)}_handleAgentHook(e){let t=e.passed??0,n=e.failed??0;switch(e.action){case`DONE`:this.logger.info(` ↳ all ${t} tests passed`);break;case`STOPPING`:this.logger.info(` ↳ stopping agent — all tests green`);break;case`BLOCKED`:this.logger.debug(` ↳ blocked tool ${e.tool??`unknown`} — generation complete`);break;case`PRUNE`:this.logger.info(` ↳ ${t} passed, ${n} failed → pruning`);break;case`REPAIR`:this.logger.info(` ↳ ${t} passed, ${n} failed → repairing`);break}}_handleSummary(e){this._clearProgressTimer(),this._summaryData.total=e.total??this._summaryData.total,this._summaryData.succeeded=e.succeeded??0,this._summaryData.failed=e.failed??0,this.logger.info(``),this.logger.info(`Done — ${e.succeeded}/${e.total} succeeded, ${e.failed} failed`)}};W4=U4=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(u4)),iQ(2,Ze(xQ)),iQ(3,Ze(m4)),iQ(4,Ze(sQ)),rQ(`design:paramtypes`,[typeof(z4=cQ!==void 0&&cQ)==`function`?z4:Object,typeof(B4=u4!==void 0&&u4)==`function`?B4:Object,typeof(V4=xQ!==void 0&&xQ)==`function`?V4:Object,typeof(H4=m4!==void 0&&m4)==`function`?H4:Object,Object])],W4);var G4,K4,q4,J4,Y4;let X4=class{constructor(e,t,n,r,i,a){this.gitService=e,this.configService=t,this.summaryService=n,this.scmHostService=r,this.workflowService=i,this.logger=a}async cleanupBlankEarlyFiles(){let e=await this.gitService.getEarlyFiles({absolute:!0}),t=[];for(let n of e)try{(await g.readFile(n,`utf8`)).trim().length===0&&(await g.unlink(n),t.push(n))}catch{this.logger.debug(`Could not read or remove file: ${n}`)}return t}async autoCommit(){if(!this.configService.getConfigValue(`autoCommit`))return this.logger.info(`Auto-commit is disabled — skipping commit step`),{committedFiles:[],error:``};let e=this.configService.getConfigValue(`refName`);return await this.gitService.commitFiles(e)}async finalize(e){if(this.summaryService.setTestGenerationData({generated:e.testResults.generated,succeeded:e.testResults.succeeded,failed:e.testResults.failed,successMethodsCount:e.testResults.successMethodsCount,committedFilesCount:e.committedFilesCount,greenTests:e.testResults.greenTests,redTests:e.testResults.redTests,skippedMethods:e.testResults.skippedMethods}),this.summaryService.setAutoCommitStatus(this.configService.getConfigValue(`autoCommit`)),await this.scmHostService.safePostSummaryToPr(),(0,B.isDefined)(e.workflowRunId))try{let t=this.summaryService.getWorkflowRunOutput();await this.workflowService.logEndOperation(e.workflowRunId,e.failureReason,t,e.resultCommitSha),this.logger.debug(`Successfully logged workflow end`)}catch(e){this.logger.warn(`Failed to log workflow end: ${e instanceof Error?e.message:`Unknown error`}`)}}};X4=aQ([et(),iQ(0,Ze(xQ)),iQ(1,Ze(cQ)),iQ(2,Ze(uQ)),iQ(3,Ze(lW.SCMHostService)),iQ(4,Ze(m4)),iQ(5,Ze(sQ)),rQ(`design:paramtypes`,[typeof(G4=xQ!==void 0&&xQ)==`function`?G4:Object,typeof(K4=cQ!==void 0&&cQ)==`function`?K4:Object,typeof(q4=uQ!==void 0&&uQ)==`function`?q4:Object,typeof(J4=hQ!==void 0&&hQ)==`function`?J4:Object,typeof(Y4=m4!==void 0&&m4)==`function`?Y4:Object,Object])],X4);function Z4(e){let t=e.command(dW.PR).alias(`generate-pr`).description(`Generate tests for the current project in pr context`);return ce(t,`--pr-number <number>`,`PR number`,{envName:`PR_NUMBER`,isRequired:!0}),ce(t,`--ref-name <ref>`,`Head reference for the PR`,{envName:`REF_NAME`,isRequired:!0}),ce(t,`--base-ref <ref>`,`Base reference for the PR`,{envName:`BASE_REF`}),ce(t,`-s, --test-structure <structure>`,`Test file structure`,{envName:`TEST_STRUCTURE`,def:`siblingFolder`}),ce(t,`-f, --test-framework <framework>`,`Test framework to use`,{envName:`TEST_FRAMEWORK`,def:`jest`}),ce(t,`--test-suffix <suffix>`,`Test file suffix`,{envName:`TEST_FILE_SUFFIX`,def:`test`}),ce(t,`--test-file-naming <naming>`,`Test file naming convention`,{envName:`TEST_FILE_NAMING`,def:`camelCase`}),ce(t,`-c, --max-concurrency <number>`,`Number of concurrent workers (1-4)`,{envName:`MAX_CONCURRENCY`,def:`3`}),ce(t,`--auto-commit <boolean>`,`Whether to auto-commit files`,{envName:`AUTO_COMMIT`,def:`true`}),ce(t,`--auto-commit-skip-ci <boolean>`,`Append [skip ci] to auto-commit message`,{envName:`AUTO_COMMIT_SKIP_CI`,def:`true`}),ce(t,`--test-command <command>`,`Custom test command to run`,{envName:`TEST_COMMAND`}),ce(t,`--coverage-command <command>`,`Custom coverage command to run`,{envName:`COVERAGE_COMMAND`}),ce(t,`--lint-command <command>`,`Custom lint command to run`,{envName:`LINT_COMMAND`}),ce(t,`--prettier-command <command>`,`Custom prettier command to run`,{envName:`PRETTIER_COMMAND`}),ce(t,`--disable-lint-rules <boolean>`,`Whether to disable failed lint rules in test files`,{envName:`DISABLE_LINT_RULES`,def:`false`}),ce(t,`--git-org <org>`,`Git organization name`,{envName:`GIT_ORG`}),ce(t,`--git-repo <repo>`,`Git repository name`,{envName:`GIT_REPO`}),ce(t,`--git-user-email <email>`,`Git user email for auto commit`,{envName:`GIT_USER_EMAIL`}),ce(t,`--git-user-name <name>`,`Git user name for auto commit`,{envName:`GIT_USER_NAME`}),ce(t,`--scm-provider <provider>`,`SCM provider (e.g., github, bitbucket)`,{envName:`SCM_PROVIDER`,def:`github`}),ce(t,`--keep-error-tests <boolean>`,`Whether to keep error tests`,{envName:`KEEP_ERROR_TESTS`,def:`false`}),ce(t,`--keep-failed-tests <boolean>`,`Whether to keep failed tests`,{envName:`KEEP_FAILED_TESTS`,def:`false`}),ce(t,`--conditional-keep <boolean>`,`Whether to return the last generated test result even when no green tests were produced`,{envName:`CONDITIONAL_KEEP`,def:`false`}),ce(t,`--continue-on-test-errors <boolean>`,`Whether to continue on test errors`,{envName:`CONTINUE_ON_TEST_ERRORS`,def:`false`}),ce(t,`--changed-methods-only <boolean>`,`Generate tests only for changed methods, not all methods in changed files`,{envName:`CHANGED_METHODS_ONLY`,def:`true`}),ce(t,`--skip-coverage-after <boolean>`,`Skip final coverage generation after test generation`,{envName:`SKIP_COVERAGE_AFTER`,def:`true`}),ce(t,`--max-testables <number>`,`Maximum number of testables to generate`,{envName:`MAX_TESTABLES`}),ce(t,`--per-function-timeout <number>`,`Per function timeout in milliseconds`,{envName:`PER_FUNCTION_TIMEOUT`}),ce(t,`--coverage-threshold <number>`,`Coverage threshold percentage (0-100)`,{envName:`COVERAGE_THRESHOLD`,def:`0`}),ce(t,`--reuse-coverage <boolean>`,`Whether to reuse coverage`,{envName:`REUSE_COVERAGE`,def:`false`}),ce(t,`--reuse-coverage-max-runs <number>`,`Max number of runs to reuse coverage (1-10)`,{envName:`REUSE_COVERAGE_MAX_RUNS`,def:`10`}),ce(t,`--experimental-agent-sdk <boolean>`,`Use experimental Agent SDK for test generation`,{envName:`EXPERIMENTAL_AGENT_SDK`,def:`true`}),t.addHelpText(`after`,`
32436
32437
  Examples:
32437
32438
  $ early generate-pr --api-key your-api-key --token your-token --pr-number 123 --ref-name feature/new-feature
32438
32439
  $ early generate-pr -k your-api-key -f jest -s siblingFolder --test-command "npm run test -- $early_filename" --coverage-command "npm run coverage -- --coverageReporters=json --coverageDirectory=$early_coverage_dir"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@earlyai/cli",
3
- "version": "2.4.3",
3
+ "version": "2.4.4",
4
4
  "description": "early cli",
5
5
  "main": "dist/index.cjs",
6
6
  "bin": {