@earlyai/cli 2.6.0 → 2.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.cjs +13 -10
  2. package/package.json +2 -2
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:ae,Option:oe,Help:R}=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 se=`2.6.0`,ce=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})),z=ce();function le(e,t,n,{key:r=``,prefix:i=`EARLY`,parser:a,def:o,isRequired:s=!1,envName:c}={}){let l=new oe(t,n);a&&l.argParser(a),s&&l.makeOptionMandatory(!0);let u=c??(()=>{let n=[];for(let t=e;t&&(0,z.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,z.isDefined)(o)&&l.default(o),e.addOption(l),l}function ue(e){return(typeof e==`object`&&!!e||typeof e==`function`)&&typeof e.then==`function`}function de(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 fe=Symbol.for(`@inversifyjs/common/islazyServiceIdentifier`);var pe=class{[fe];#e;constructor(e){this.#e=e,this[fe]=!0}static is(e){return typeof e==`object`&&!!e&&!0===e[fe]}unwrap(){return this.#e()}};function me(e,t,n){return Reflect.getOwnMetadata(t,e,n)}function he(e,t,n,r){Reflect.defineMetadata(t,n,e,r)}function ge(e,t,n,r,i){let a=r(me(e,t,i)??n());Reflect.defineMetadata(t,a,e,i)}function _e(e){return Object.getPrototypeOf(e.prototype)?.constructor}const ve=`@inversifyjs/container/bindingId`;function ye(){let e=me(Object,ve)??0;return e===2**53-1?he(Object,ve,-(2**53-1)):ge(Object,ve,()=>e,e=>e+1),e}const be={Request:`Request`,Singleton:`Singleton`,Transient:`Transient`},xe={ConstantValue:`ConstantValue`,DynamicValue:`DynamicValue`,Factory:`Factory`,Instance:`Instance`,Provider:`Provider`,ResolvedValue:`ResolvedValue`,ServiceRedirection:`ServiceRedirection`};function*Se(...e){for(let t of e)yield*t}var Ce=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)}}},we;(function(e){e.moduleId=`moduleId`,e.serviceId=`serviceId`})(we||={});var Te=class e{#e;#t;constructor(e,t){this.#e=t??new Ce({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(we.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 Se(...t)}removeAllByModuleId(e){this.#e.removeByRelation(we.moduleId,e)}removeAllByServiceId(e){this.#e.removeByRelation(we.serviceId,e)}};const Ee=`@inversifyjs/core/classMetadataReflectKey`;function De(){return{constructorArguments:[],lifecycle:{postConstructMethodNames:new Set,preDestroyMethodNames:new Set},properties:new Map,scope:void 0}}const Oe=`@inversifyjs/core/pendingClassMetadataCountReflectKey`,ke=Symbol.for(`@inversifyjs/core/InversifyCoreError`);var Ae=class e extends Error{[ke];kind;constructor(e,t,n){super(t,n),this[ke]=!0,this.kind=e}static is(e){return typeof e==`object`&&!!e&&!0===e[ke]}static isErrorOfKind(t,n){return e.is(t)&&t.kind===n}},je,Me,Ne,Pe,Fe;function Ie(e){let t=me(e,Ee)??De();if(!function(e){let t=me(e,Oe);return t!==void 0&&t!==0}(e))return function(e,t){let n=[];if(t.length<e.length)throw new Ae(je.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 Ae(je.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!==Me.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===Me.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 Ae(je.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 Ae(je.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:ae,Option:oe,Help:R}=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 se=`2.6.1`,ce=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})),z=ce();function le(e,t,n,{key:r=``,prefix:i=`EARLY`,parser:a,def:o,isRequired:s=!1,envName:c}={}){let l=new oe(t,n);a&&l.argParser(a),s&&l.makeOptionMandatory(!0);let u=c??(()=>{let n=[];for(let t=e;t&&(0,z.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,z.isDefined)(o)&&l.default(o),e.addOption(l),l}function ue(e){return(typeof e==`object`&&!!e||typeof e==`function`)&&typeof e.then==`function`}function de(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 fe=Symbol.for(`@inversifyjs/common/islazyServiceIdentifier`);var pe=class{[fe];#e;constructor(e){this.#e=e,this[fe]=!0}static is(e){return typeof e==`object`&&!!e&&!0===e[fe]}unwrap(){return this.#e()}};function me(e,t,n){return Reflect.getOwnMetadata(t,e,n)}function he(e,t,n,r){Reflect.defineMetadata(t,n,e,r)}function ge(e,t,n,r,i){let a=r(me(e,t,i)??n());Reflect.defineMetadata(t,a,e,i)}function _e(e){return Object.getPrototypeOf(e.prototype)?.constructor}const ve=`@inversifyjs/container/bindingId`;function ye(){let e=me(Object,ve)??0;return e===2**53-1?he(Object,ve,-(2**53-1)):ge(Object,ve,()=>e,e=>e+1),e}const be={Request:`Request`,Singleton:`Singleton`,Transient:`Transient`},xe={ConstantValue:`ConstantValue`,DynamicValue:`DynamicValue`,Factory:`Factory`,Instance:`Instance`,Provider:`Provider`,ResolvedValue:`ResolvedValue`,ServiceRedirection:`ServiceRedirection`};function*Se(...e){for(let t of e)yield*t}var Ce=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)}}},we;(function(e){e.moduleId=`moduleId`,e.serviceId=`serviceId`})(we||={});var Te=class e{#e;#t;constructor(e,t){this.#e=t??new Ce({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(we.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 Se(...t)}removeAllByModuleId(e){this.#e.removeByRelation(we.moduleId,e)}removeAllByServiceId(e){this.#e.removeByRelation(we.serviceId,e)}};const Ee=`@inversifyjs/core/classMetadataReflectKey`;function De(){return{constructorArguments:[],lifecycle:{postConstructMethodNames:new Set,preDestroyMethodNames:new Set},properties:new Map,scope:void 0}}const Oe=`@inversifyjs/core/pendingClassMetadataCountReflectKey`,ke=Symbol.for(`@inversifyjs/core/InversifyCoreError`);var Ae=class e extends Error{[ke];kind;constructor(e,t,n){super(t,n),this[ke]=!0,this.kind=e}static is(e){return typeof e==`object`&&!!e&&!0===e[ke]}static isErrorOfKind(t,n){return e.is(t)&&t.kind===n}},je,Me,Ne,Pe,Fe;function Ie(e){let t=me(e,Ee)??De();if(!function(e){let t=me(e,Oe);return t!==void 0&&t!==0}(e))return function(e,t){let n=[];if(t.length<e.length)throw new Ae(je.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 Ae(je.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!==Me.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===Me.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 Ae(je.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 Ae(je.missingInjectionDecorator,`Invalid class metadata at type ${e.name}:\n\n${n.join(`
21
21
 
22
22
  `)}`)})(e,t)}function Le(e,t){let n=Ie(t).scope??e.scope;return{cache:{isRight:!1,value:void 0},id:ye(),implementationType:t,isSatisfiedBy:()=>!0,moduleId:void 0,onActivation:void 0,onDeactivation:void 0,scope:n,serviceIdentifier:t,type:xe.Instance}}function Re(e){return e.isRight?{isRight:!0,value:e.value}:e}function ze(e){switch(e.type){case xe.ConstantValue:case xe.DynamicValue:return function(e){return{cache:Re(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 xe.Factory:return function(e){return{cache:Re(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 xe.Instance:return function(e){return{cache:Re(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 xe.Provider:return function(e){return{cache:Re(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 xe.ResolvedValue:return function(e){return{cache:Re(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 xe.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`})(je||={}),function(e){e[e.unknown=32]=`unknown`}(Me||={}),function(e){e.id=`id`,e.moduleId=`moduleId`,e.serviceId=`serviceId`}(Ne||={});var Be=class e extends Ce{_buildNewInstance(t){return new e(t)}_cloneModel(e){return ze(e)}},Ve=class e{#e;#t;#n;constructor(e,t,n){this.#t=n??new Be({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(Ne.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(Ne.id,e)??this.#n()?.getById(e)}getByModuleId(e){return this.#t.get(Ne.moduleId,e)??this.#n()?.getByModuleId(e)}getNonParentBindings(e){return this.#t.get(Ne.serviceId,e)}getNonParentBoundServices(){return this.#t.getAllKeys(Ne.serviceId)}removeById(e){this.#t.removeByRelation(Ne.id,e)}removeAllByModuleId(e){this.#t.removeByRelation(Ne.moduleId,e)}removeAllByServiceId(e){this.#t.removeByRelation(Ne.serviceId,e)}set(e){let t={[Ne.id]:e.id,[Ne.serviceId]:e.serviceIdentifier};e.moduleId!==void 0&&(t[Ne.moduleId]=e.moduleId),this.#t.add(e,t)}#r(e){if(this.#e===void 0||typeof e!=`function`)return;let t=Le(this.#e,e);return this.set(t),t}};(function(e){e.moduleId=`moduleId`,e.serviceId=`serviceId`})(Pe||={});var He=class e{#e;#t;constructor(e,t){this.#e=t??new Ce({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(Pe.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 Se(...t)}removeAllByModuleId(e){this.#e.removeByRelation(Pe.moduleId,e)}removeAllByServiceId(e){this.#e.removeByRelation(Pe.serviceId,e)}};function Ue(){return 0}function B(e){return t=>{t!==void 0&&t.kind===Me.unknown&&ge(e,Oe,Ue,e=>e-1)}}function We(e,t){return(...n)=>r=>{if(r===void 0)return e(...n);if(r.kind===Fe.unmanaged)throw new Ae(je.injectionDecoratorConflict,`Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found`);return t(r,...n)}}function Ge(e){if(e.kind!==Me.unknown&&!0!==e.isFromTypescriptParamType)throw new Ae(je.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`})(Fe||={});const Ke=We(function(e,t,n){return e===Fe.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 Ge(e),t===Fe.multipleInjection?{...e,chained:r?.chained??!1,kind:t,value:n}:{...e,kind:t,value:n}});function qe(e,t){return n=>{let r=n.properties.get(t);return n.properties.set(t,e(r)),n}}var Je;function Ye(e,t,n,r){if(Ae.isErrorOfKind(r,je.injectionDecoratorConflict)){let i=function(e,t,n){if(n===void 0){if(t===void 0)throw new Ae(je.unknown,`Unexpected undefined property and index values`);return{kind:Je.property,property:t,targetClass:e.constructor}}return typeof n==`number`?{index:n,kind:Je.parameter,targetClass:e}:{kind:Je.method,method:t,targetClass:e}}(e,t,n);throw new Ae(je.injectionDecoratorConflict,`Unexpected injection error.\n\nCause:\n\n${r.message}\n\nDetails\n\n${function(e){switch(e.kind){case Je.method:return`[class: "${e.targetClass.name}", method: "${e.method.toString()}"]`;case Je.parameter:return`[class: "${e.targetClass.name}", index: "${e.index.toString()}"]`;case Je.property:return`[class: "${e.targetClass.name}", property: "${e.property.toString()}"]`}}(i)}`,{cause:r})}throw r}function Xe(e,t){return(n,r,i)=>{try{i===void 0?function(e,t){let n=Ze(e,t);return(e,t)=>{ge(e.constructor,Ee,De,qe(n(e),t))}}(e,t)(n,r):typeof i==`number`?function(e,t){let n=Ze(e,t);return(e,t,r)=>{if(!function(e,t){return typeof e==`function`&&t===void 0}(e,t))throw new Ae(je.injectionDecoratorConflict,`Found an @inject decorator in a non constructor parameter.\nFound @inject decorator at method "${t?.toString()??``}" at class "${e.constructor.name}"`);ge(e,Ee,De,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=Ze(e,t);return(e,t,r)=>{if(!function(e){return e.set!==void 0}(r))throw new Ae(je.injectionDecoratorConflict,`Found an @inject decorator in a non setter property method.\nFound @inject decorator at method "${t.toString()}" at class "${e.constructor.name}"`);ge(e.constructor,Ee,De,qe(n(e),t))}}(e,t)(n,r,i)}catch(e){Ye(n,r,i,e)}}}function Ze(e,t){return n=>{let r=t(n);return t=>(r(t),e(t))}}function Qe(e){return Xe(Ke(Fe.singleInjection,e),B)}(function(e){e[e.method=0]=`method`,e[e.parameter=1]=`parameter`,e[e.property=2]=`property`})(Je||={});const $e=`@inversifyjs/core/classIsInjectableFlagReflectKey`,et=[Array,BigInt,Boolean,Function,Number,Object,String];function V(e){let t=me(e,`design:paramtypes`);t!==void 0&&ge(e,Ee,De,function(e){return t=>(e.forEach((e,n)=>{var r;t.constructorArguments[n]!==void 0||(r=e,et.includes(r))||(t.constructorArguments[n]=function(e){return{isFromTypescriptParamType:!0,kind:Fe.singleInjection,name:void 0,optional:!1,tags:new Map,value:e}}(e))}),t)}(t))}function tt(e){return t=>{(function(e){if(me(e,$e)!==void 0)throw new Ae(je.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${e.name}"`);he(e,$e,!0)})(t),V(t),e!==void 0&&ge(t,Ee,De,t=>({...t,scope:e}))}}function nt(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 rt(e,t,n){return e?new Set([...t,...n]):n}function it(e,t,n){let r=e.lifecycle?.extendPostConstructMethods??!0,i=rt(e.lifecycle?.extendPreDestroyMethods??!0,t.lifecycle.preDestroyMethodNames,n.lifecycle.preDestroyMethodNames);return{postConstructMethodNames:rt(r,t.lifecycle.postConstructMethodNames,n.lifecycle.postConstructMethodNames),preDestroyMethodNames:i}}function at(e,t,n){let r;return r=e.extendProperties??!0?new Map(Se(t.properties,n.properties)):n.properties,r}function ot(e){return t=>{ge(t,Ee,De,function(e,t){return n=>({constructorArguments:nt(e,t,n),lifecycle:it(e,t,n),properties:at(e,t,n),scope:n.scope})}(e,Ie(e.type)))}}function st(e){return t=>{let n=_e(t);if(n===void 0)throw new Ae(je.injectionDecoratorConflict,`Expected base type for type "${t.name}", none found.`);ot({...e,type:n})(t)}}function ct(e){return t=>{let n=[],r=_e(t);for(;r!==void 0&&r!==Object;){let e=r;n.push(e),r=_e(e)}n.reverse();for(let r of n)ot({...e,type:r})(t)}}function H(e){return t=>{t===void 0&&ge(e,Oe,Ue,e=>e+1)}}function lt(e){return t=>{let n=t??{kind:Me.unknown,name:void 0,optional:!1,tags:new Map};if(n.kind===Fe.unmanaged)throw new Ae(je.injectionDecoratorConflict,`Unexpected injection found. Found @unmanaged injection with additional @named, @optional, @tagged or @targetName injections`);return e(n)}}function ut(e){if(e.optional)throw new Ae(je.injectionDecoratorConflict,`Unexpected duplicated optional decorator`);return e.optional=!0,e}function dt(){return Xe(lt(ut),H)}var ft;function pt(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 mt(e,t){if(pt(t)){let n=function(e){let t=[...e];return t.length===0?`(No dependency trace)`:t.map(de).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 Ae(je.planning,`Circular dependency found: ${n}`,{cause:t})}throw t}(function(e){e[e.multipleInjection=0]=`multipleInjection`,e[e.singleInjection=1]=`singleInjection`})(ft||={});const ht=Symbol.for(`@inversifyjs/core/LazyPlanServiceNode`);var gt=class{[ht];_serviceIdentifier;_serviceNode;constructor(e,t){this[ht]=!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[ht]}invalidate(){this._serviceNode=void 0}isExpanded(){return this._serviceNode!==void 0}_getNode(){return this._serviceNode===void 0&&(this._serviceNode=this._buildPlanServiceNode()),this._serviceNode}},_t=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 vt(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=Le(e.autobindOptions,r);e.operations.setBinding(n),n.isSatisfiedBy(t)&&i.push(n)}return i}var yt=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 bt(e){let t=new Map;return e.rootConstraints.tag!==void 0&&t.set(e.rootConstraints.tag.key,e.rootConstraints.tag.value),new yt({elem:{getAncestorsCalled:!1,name:e.rootConstraints.name,serviceIdentifier:e.rootConstraints.serviceIdentifier,tags:t},previous:void 0})}function xt(e){return e.redirections!==void 0}function St(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: "${de(a[a.length-1]??n)}".${Et(a)}\n\nRegistered bindings:\n\n${e.map(e=>function(e){switch(e.type){case xe.Instance:return`[ type: "${e.type}", serviceIdentifier: "${de(e.serviceIdentifier)}", scope: "${e.scope}", implementationType: "${e.implementationType.name}" ]`;case xe.ServiceRedirection:return`[ type: "${e.type}", serviceIdentifier: "${de(e.serviceIdentifier)}", redirection: "${de(e.targetServiceIdentifier)}" ]`;default:return`[ type: "${e.type}", serviceIdentifier: "${de(e.serviceIdentifier)}", scope: "${e.scope}" ]`}}(e.binding)).join(`
23
23
  `)}\n\nTrying to resolve bindings for "${wt(n,r)}".${Tt(i)}`;throw new Ae(je.planning,t)}t||Ct(n,r,i,a)}(e,t,i,a,n.elem,r):function(e,t,n,r,i,a){e!==void 0||t||Ct(n,r,i,a)}(e,t,i,a,n.elem,r)}function Ct(e,t,n,r){let i=`No bindings found for service: "${de(r[r.length-1]??e)}".\n\nTrying to resolve bindings for "${wt(e,t)}".${Et(r)}${Tt(n)}`;throw new Ae(je.planning,i)}function wt(e,t){return t===void 0?`${de(e)} (Root service)`:de(t)}function Tt(e){let t=e.tags.size===0?``:`\n- tags:\n - ${[...e.tags.keys()].map(e=>e.toString()).join(`
@@ -32002,7 +32002,7 @@ https://www.w3ctech.com/topic/2226`));let i=t(...r);return i.postcssPlugin=e,i.p
32002
32002
  `);let t=new x(`!xml`),n=t,r=``,i=``,a=new S(this.options.processEntities);for(let o=0;o<e.length;o++)if(e[o]===`<`)if(e[o+1]===`/`){let t=L(e,`>`,o,`Closing Tag is not closed.`),a=e.substring(o+2,t).trim();if(this.options.removeNSPrefix){let e=a.indexOf(`:`);e!==-1&&(a=a.substr(e+1))}this.options.transformTagName&&(a=this.options.transformTagName(a)),n&&(r=this.saveTextToParentTag(r,n,i));let s=i.substring(i.lastIndexOf(`.`)+1);if(a&&this.options.unpairedTags.indexOf(a)!==-1)throw Error(`Unpaired tag can not be used as closing tag: </${a}>`);let c=0;s&&this.options.unpairedTags.indexOf(s)!==-1?(c=i.lastIndexOf(`.`,i.lastIndexOf(`.`)-1),this.tagsNodeStack.pop()):c=i.lastIndexOf(`.`),i=i.substring(0,c),n=this.tagsNodeStack.pop(),r=``,o=t}else if(e[o+1]===`?`){let t=ae(e,o,!1,`?>`);if(!t)throw Error(`Pi Tag is not closed.`);if(r=this.saveTextToParentTag(r,n,i),!(this.options.ignoreDeclaration&&t.tagName===`?xml`||this.options.ignorePiTags)){let e=new x(t.tagName);e.add(this.options.textNodeName,``),t.tagName!==t.tagExp&&t.attrExpPresent&&(e[`:@`]=this.buildAttributesMap(t.tagExp,i,t.tagName)),this.addChild(n,e,i,o)}o=t.closeIndex+1}else if(e.substr(o+1,3)===`!--`){let t=L(e,`-->`,o+4,`Comment is not closed.`);if(this.options.commentPropName){let a=e.substring(o+4,t-2);r=this.saveTextToParentTag(r,n,i),n.add(this.options.commentPropName,[{[this.options.textNodeName]:a}])}o=t}else if(e.substr(o+1,2)===`!D`){let t=a.readDocType(e,o);this.docTypeEntities=t.entities,o=t.i}else if(e.substr(o+1,2)===`![`){let t=L(e,`]]>`,o,`CDATA is not closed.`)-2,a=e.substring(o+9,t);r=this.saveTextToParentTag(r,n,i);let s=this.parseTextData(a,n.tagname,i,!0,!1,!0,!0);s??=``,this.options.cdataPropName?n.add(this.options.cdataPropName,[{[this.options.textNodeName]:a}]):n.add(this.options.textNodeName,s),o=t+2}else{let a=ae(e,o,this.options.removeNSPrefix),s=a.tagName,c=a.rawTagName,l=a.tagExp,u=a.attrExpPresent,d=a.closeIndex;this.options.transformTagName&&(s=this.options.transformTagName(s)),n&&r&&n.tagname!==`!xml`&&(r=this.saveTextToParentTag(r,n,i,!1));let f=n;f&&this.options.unpairedTags.indexOf(f.tagname)!==-1&&(n=this.tagsNodeStack.pop(),i=i.substring(0,i.lastIndexOf(`.`))),s!==t.tagname&&(i+=i?`.`+s:s);let p=o;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,i,s)){let t=``;if(l.length>0&&l.lastIndexOf(`/`)===l.length-1)s[s.length-1]===`/`?(s=s.substr(0,s.length-1),i=i.substr(0,i.length-1),l=s):l=l.substr(0,l.length-1),o=a.closeIndex;else if(this.options.unpairedTags.indexOf(s)!==-1)o=a.closeIndex;else{let n=this.readStopNodeData(e,c,d+1);if(!n)throw Error(`Unexpected end of ${c}`);o=n.i,t=n.tagContent}let r=new x(s);s!==l&&u&&(r[`:@`]=this.buildAttributesMap(l,i,s)),t&&=this.parseTextData(t,s,i,!0,u,!0,!0),i=i.substr(0,i.lastIndexOf(`.`)),r.add(this.options.textNodeName,t),this.addChild(n,r,i,p)}else{if(l.length>0&&l.lastIndexOf(`/`)===l.length-1){s[s.length-1]===`/`?(s=s.substr(0,s.length-1),i=i.substr(0,i.length-1),l=s):l=l.substr(0,l.length-1),this.options.transformTagName&&(s=this.options.transformTagName(s));let e=new x(s);s!==l&&u&&(e[`:@`]=this.buildAttributesMap(l,i,s)),this.addChild(n,e,i,p),i=i.substr(0,i.lastIndexOf(`.`))}else{let e=new x(s);this.tagsNodeStack.push(n),s!==l&&u&&(e[`:@`]=this.buildAttributesMap(l,i,s)),this.addChild(n,e,i,p),n=e}r=``,o=d}}else r+=e[o];return t.child};function F(e,t,n,r){this.options.captureMetaData||(r=void 0);let i=this.options.updateTag(t.tagname,n,t[`:@`]);!1===i||(typeof i==`string`&&(t.tagname=i),e.addChild(t,r))}let I=function(e){if(this.options.processEntities){for(let t in this.docTypeEntities){let n=this.docTypeEntities[t];e=e.replace(n.regx,n.val)}for(let t in this.lastEntities){let n=this.lastEntities[t];e=e.replace(n.regex,n.val)}if(this.options.htmlEntities)for(let t in this.htmlEntities){let n=this.htmlEntities[t];e=e.replace(n.regex,n.val)}e=e.replace(this.ampEntity.regex,this.ampEntity.val)}return e};function re(e,t,n,r){return e&&=(r===void 0&&(r=t.child.length===0),(e=this.parseTextData(e,t.tagname,n,!1,!!t[`:@`]&&Object.keys(t[`:@`]).length!==0,r))!==void 0&&e!==``&&t.add(this.options.textNodeName,e),``),e}function ie(e,t,n,r){return!(!t||!t.has(r))||!(!e||!e.has(n))}function L(e,t,n,r){let i=e.indexOf(t,n);if(i===-1)throw Error(r);return i+t.length-1}function ae(e,t,n,r=`>`){let i=function(e,t,n=`>`){let r,i=``;for(let a=t;a<e.length;a++){let t=e[a];if(r)t===r&&(r=``);else if(t===`"`||t===`'`)r=t;else if(t===n[0]){if(!n[1]||e[a+1]===n[1])return{data:i,index:a}}else t===` `&&(t=` `);i+=t}}(e,t+1,r);if(!i)return;let a=i.data,o=i.index,s=a.search(/\s/),c=a,l=!0;s!==-1&&(c=a.substring(0,s),a=a.substring(s+1).trimStart());let u=c;if(n){let e=c.indexOf(`:`);e!==-1&&(c=c.substr(e+1),l=c!==i.data.substr(e+1))}return{tagName:c,tagExp:a,closeIndex:o,attrExpPresent:l,rawTagName:u}}function oe(e,t,n){let r=n,i=1;for(;n<e.length;n++)if(e[n]===`<`)if(e[n+1]===`/`){let a=L(e,`>`,n,`${t} is not closed`);if(e.substring(n+2,a).trim()===t&&(i--,i===0))return{tagContent:e.substring(r,n),i:a};n=a}else if(e[n+1]===`?`)n=L(e,`?>`,n+1,`StopNode is not closed.`);else if(e.substr(n+1,3)===`!--`)n=L(e,`-->`,n+3,`StopNode is not closed.`);else if(e.substr(n+1,2)===`![`)n=L(e,`]]>`,n,`StopNode is not closed.`)-2;else{let r=ae(e,n,`>`);r&&((r&&r.tagName)===t&&r.tagExp[r.tagExp.length-1]!==`/`&&i++,n=r.closeIndex)}}function R(e,t,n){if(t&&typeof e==`string`){let t=e.trim();return t===`true`||t!==`false`&&function(e,t={}){if(t=Object.assign({},O,t),!e||typeof e!=`string`)return e;let n=e.trim();if(t.skipLike!==void 0&&t.skipLike.test(n))return e;if(e===`0`)return 0;if(t.hex&&E.test(n))return function(e){if(parseInt)return parseInt(e,16);if(Number.parseInt)return Number.parseInt(e,16);if(window&&window.parseInt)return window.parseInt(e,16);throw Error(`parseInt, Number.parseInt, window.parseInt are not supported`)}(n);if(n.search(/.+[eE].+/)!==-1)return function(e,t,n){if(!n.eNotation)return e;let r=t.match(k);if(r){let i=r[1]||``,a=r[3].indexOf(`e`)===-1?`E`:`e`,o=r[2],s=i?e[o.length+1]===a:e[o.length]===a;return o.length>1&&s?e:o.length!==1||!r[3].startsWith(`.${a}`)&&r[3][0]!==a?n.leadingZeros&&!s?(t=(r[1]||``)+r[3],Number(t)):e:Number(t)}return e}(e,n,t);{let i=D.exec(n);if(i){let a=i[1]||``,o=i[2],s=((r=i[3])&&r.indexOf(`.`)!==-1&&((r=r.replace(/0+$/,``))===`.`?r=`0`:r[0]===`.`?r=`0`+r:r[r.length-1]===`.`&&(r=r.substring(0,r.length-1))),r),c=a?e[o.length+1]===`.`:e[o.length]===`.`;if(!t.leadingZeros&&(o.length>1||o.length===1&&!c))return e;{let r=Number(n),i=String(r);if(r===0||r===-0)return r;if(i.search(/[eE]/)!==-1)return t.eNotation?r:e;if(n.indexOf(`.`)!==-1)return i===`0`||i===s||i===`${a}${s}`?r:e;let c=o?s:n;return o?c===i||a+c===i?r:e:c===i||c===a+i?r:e}}return e}var r}(e,n)}return e===void 0?``:e}let se=x.getMetaDataSymbol();function ce(e,t){return z(e,t)}function z(e,t,n){let r,i={};for(let a=0;a<e.length;a++){let o=e[a],s=le(o),c=``;if(c=n===void 0?s:n+`.`+s,s===t.textNodeName)r===void 0?r=o[s]:r+=``+o[s];else{if(s===void 0)continue;if(o[s]){let e=z(o[s],t,c),n=de(e,t);o[se]!==void 0&&(e[se]=o[se]),o[`:@`]?ue(e,o[`:@`],c,t):Object.keys(e).length!==1||e[t.textNodeName]===void 0||t.alwaysCreateTextNode?Object.keys(e).length===0&&(t.alwaysCreateTextNode?e[t.textNodeName]=``:e=``):e=e[t.textNodeName],i[s]!==void 0&&i.hasOwnProperty(s)?(Array.isArray(i[s])||(i[s]=[i[s]]),i[s].push(e)):t.isArray(s,c,n)?i[s]=[e]:i[s]=e}}}return typeof r==`string`?r.length>0&&(i[t.textNodeName]=r):r!==void 0&&(i[t.textNodeName]=r),i}function le(e){let t=Object.keys(e);for(let e=0;e<t.length;e++){let n=t[e];if(n!==`:@`)return n}}function ue(e,t,n,r){if(t){let i=Object.keys(t),a=i.length;for(let o=0;o<a;o++){let a=i[o];r.isArray(a,n+`.`+a,!0,!0)?e[a]=[t[a]]:e[a]=t[a]}}}function de(e,t){let{textNodeName:n}=t,r=Object.keys(e).length;return r===0||!(r!==1||!e[n]&&typeof e[n]!=`boolean`&&e[n]!==0)}class fe{constructor(e){this.externalEntities={},this.options=function(e){return Object.assign({},y,e)}(e)}parse(e,t){if(typeof e!=`string`&&e.toString)e=e.toString();else if(typeof e!=`string`)throw Error(`XML data is accepted in String or Bytes[] form.`);if(t){!0===t&&(t={});let n=s(e,t);if(!0!==n)throw Error(`${n.err.msg}:${n.err.line}:${n.err.col}`)}let n=new ee(this.options);n.addExternalEntities(this.externalEntities);let r=n.parseXml(e);return this.options.preserveOrder||r===void 0?r:ce(r,this.options)}addEntity(e,t){if(t.indexOf(`&`)!==-1)throw Error(`Entity value can't have '&'`);if(e.indexOf(`&`)!==-1||e.indexOf(`;`)!==-1)throw Error(`An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'`);if(t===`&`)throw Error(`An entity with value '&' is not permitted`);this.externalEntities[e]=t}static getMetaDataSymbol(){return x.getMetaDataSymbol()}}function pe(e,t){let n=``;return t.format&&t.indentBy.length>0&&(n=`
32003
32003
  `),me(e,t,``,n)}function me(e,t,n,r){let i=``,a=!1;for(let o=0;o<e.length;o++){let s=e[o],c=he(s);if(c===void 0)continue;let l=``;if(l=n.length===0?c:`${n}.${c}`,c===t.textNodeName){let e=s[c];_e(l,t)||(e=t.tagValueProcessor(c,e),e=ve(e,t)),a&&(i+=r),i+=e,a=!1;continue}if(c===t.cdataPropName){a&&(i+=r),i+=`<![CDATA[${s[c][0][t.textNodeName]}]]>`,a=!1;continue}if(c===t.commentPropName){i+=r+`\x3c!--${s[c][0][t.textNodeName]}--\x3e`,a=!0;continue}if(c[0]===`?`){let e=ge(s[`:@`],t),n=c===`?xml`?``:r,o=s[c][0][t.textNodeName];o=o.length===0?``:` `+o,i+=n+`<${c}${o}${e}?>`,a=!0;continue}let u=r;u!==``&&(u+=t.indentBy);let d=r+`<${c}${ge(s[`:@`],t)}`,f=me(s[c],t,l,u);t.unpairedTags.indexOf(c)===-1?f&&f.length!==0||!t.suppressEmptyNode?f&&f.endsWith(`>`)?i+=d+`>${f}${r}</${c}>`:(i+=d+`>`,f&&r!==``&&(f.includes(`/>`)||f.includes(`</`))?i+=r+t.indentBy+f+r:i+=f,i+=`</${c}>`):i+=d+`/>`:t.suppressUnpairedNode?i+=d+`>`:i+=d+`/>`,a=!0}return i}function he(e){let t=Object.keys(e);for(let n=0;n<t.length;n++){let r=t[n];if(e.hasOwnProperty(r)&&r!==`:@`)return r}}function ge(e,t){let n=``;if(e&&!t.ignoreAttributes)for(let r in e){if(!e.hasOwnProperty(r))continue;let i=t.attributeValueProcessor(r,e[r]);i=ve(i,t),!0===i&&t.suppressBooleanAttributes?n+=` ${r.substr(t.attributeNamePrefix.length)}`:n+=` ${r.substr(t.attributeNamePrefix.length)}="${i}"`}return n}function _e(e,t){let n=(e=e.substr(0,e.length-t.textNodeName.length-1)).substr(e.lastIndexOf(`.`)+1);for(let r in t.stopNodes)if(t.stopNodes[r]===e||t.stopNodes[r]===`*.`+n)return!0;return!1}function ve(e,t){if(e&&e.length>0&&t.processEntities)for(let n=0;n<t.entities.length;n++){let r=t.entities[n];e=e.replace(r.regex,r.val)}return e}let ye={attributeNamePrefix:`@_`,attributesGroupName:!1,textNodeName:`#text`,ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:` `,suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:RegExp(`&`,`g`),val:`&amp;`},{regex:RegExp(`>`,`g`),val:`&gt;`},{regex:RegExp(`<`,`g`),val:`&lt;`},{regex:RegExp(`'`,`g`),val:`&apos;`},{regex:RegExp(`"`,`g`),val:`&quot;`}],processEntities:!0,stopNodes:[],oneListGroup:!1};function be(e){this.options=Object.assign({},ye,e),!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=A(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=Ce),this.processTextOrObjNode=xe,this.options.format?(this.indentate=Se,this.tagEndChar=`>
32004
32004
  `,this.newLine=`
32005
- `):(this.indentate=function(){return``},this.tagEndChar=`>`,this.newLine=``)}function xe(e,t,n,r){let i=this.j2x(e,n+1,r.concat(t));return e[this.options.textNodeName]!==void 0&&Object.keys(e).length===1?this.buildTextValNode(e[this.options.textNodeName],t,i.attrStr,n):this.buildObjectNode(i.val,t,i.attrStr,n)}function Se(e){return this.options.indentBy.repeat(e)}function Ce(e){return!(!e.startsWith(this.options.attributeNamePrefix)||e===this.options.textNodeName)&&e.substr(this.attrPrefixLen)}be.prototype.build=function(e){return this.options.preserveOrder?pe(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)},be.prototype.j2x=function(e,t,n){let r=``,i=``,a=n.join(`.`);for(let o in e)if(Object.prototype.hasOwnProperty.call(e,o))if(e[o]===void 0)this.isAttribute(o)&&(i+=``);else if(e[o]===null)this.isAttribute(o)||o===this.options.cdataPropName?i+=``:o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(e[o]instanceof Date)i+=this.buildTextValNode(e[o],o,``,t);else if(typeof e[o]!=`object`){let n=this.isAttribute(o);if(n&&!this.ignoreAttributesFn(n,a))r+=this.buildAttrPairStr(n,``+e[o]);else if(!n)if(o===this.options.textNodeName){let t=this.options.tagValueProcessor(o,``+e[o]);i+=this.replaceEntitiesValue(t)}else i+=this.buildTextValNode(e[o],o,``,t)}else if(Array.isArray(e[o])){let r=e[o].length,a=``,s=``;for(let c=0;c<r;c++){let r=e[o][c];if(r!==void 0)if(r===null)o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(typeof r==`object`)if(this.options.oneListGroup){let e=this.j2x(r,t+1,n.concat(o));a+=e.val,this.options.attributesGroupName&&r.hasOwnProperty(this.options.attributesGroupName)&&(s+=e.attrStr)}else a+=this.processTextOrObjNode(r,o,t,n);else if(this.options.oneListGroup){let e=this.options.tagValueProcessor(o,r);e=this.replaceEntitiesValue(e),a+=e}else a+=this.buildTextValNode(r,o,``,t)}this.options.oneListGroup&&(a=this.buildObjectNode(a,o,s,t)),i+=a}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){let t=Object.keys(e[o]),n=t.length;for(let i=0;i<n;i++)r+=this.buildAttrPairStr(t[i],``+e[o][t[i]])}else i+=this.processTextOrObjNode(e[o],o,t,n);return{attrStr:r,val:i}},be.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,``+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t===`true`?` `+e:` `+e+`="`+t+`"`},be.prototype.buildObjectNode=function(e,t,n,r){if(e===``)return t[0]===`?`?this.indentate(r)+`<`+t+n+`?`+this.tagEndChar:this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar;{let i=`</`+t+this.tagEndChar,a=``;return t[0]===`?`&&(a=`?`,i=``),!n&&n!==``||e.indexOf(`<`)!==-1?!1!==this.options.commentPropName&&t===this.options.commentPropName&&a.length===0?this.indentate(r)+`\x3c!--${e}--\x3e`+this.newLine:this.indentate(r)+`<`+t+n+a+this.tagEndChar+e+this.indentate(r)+i:this.indentate(r)+`<`+t+n+a+`>`+e+i}},be.prototype.closeTag=function(e){let t=``;return this.options.unpairedTags.indexOf(e)===-1?t=this.options.suppressEmptyNode?`/`:`></${e}`:this.options.suppressUnpairedNode||(t=`/`),t},be.prototype.buildTextValNode=function(e,t,n,r){if(!1!==this.options.cdataPropName&&t===this.options.cdataPropName)return this.indentate(r)+`<![CDATA[${e}]]>`+this.newLine;if(!1!==this.options.commentPropName&&t===this.options.commentPropName)return this.indentate(r)+`\x3c!--${e}--\x3e`+this.newLine;if(t[0]===`?`)return this.indentate(r)+`<`+t+n+`?`+this.tagEndChar;{let i=this.options.tagValueProcessor(t,e);return i=this.replaceEntitiesValue(i),i===``?this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar:this.indentate(r)+`<`+t+n+`>`+i+`</`+t+this.tagEndChar}},be.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){let n=this.options.entities[t];e=e.replace(n.regex,n.val)}return e};let we={validate:s};t.exports=n})()})),sW=s((e=>{var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),c=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},l=(e,r,i)=>(i=e==null?{}:t(a(e)),c(r||!e||!e.__esModule?n(i,`default`,{value:e,enumerable:!0}):i,e));let u=l(Oi()),f=l(ki()),p=l(require(`node:fs/promises`)),m=l(require(`node:async_hooks`)),h=l(ce()),g=l(Bi()),_=l(Rc()),v=l((Ol(),d(ll))),y=l(require(`node:crypto`)),b=l(rR()),x=l(pM()),S=l(lz()),C=l((Dj(),d(Ej))),w=l(require(`node:fs`)),T=l(Bz()),E=l(uV()),D=l(require(`node:child_process`)),O=l(require(`node:util`)),k=l(require(`@prisma/internals`)),A=l(oV()),ee=l(require(`node:zlib`)),j=l(aH()),te=l(sH()),M=l(dH()),ne=l(gH()),N=l(require(`node:os`)),P=l(require(`node:events`)),F=l(mU()),I=l(tW()),re=l(Iee()),ie=l(aW()),L=l(oW()),ae=l(hU()),oe=l(require(`node:process`));l(require(`node:readline`)),l(require(`node:tty`));let R=l(require(`node:path`)),se=l(require(`@anthropic-ai/claude-agent-sdk`)),z={DELETE:`delete`,COMMENT_OUT:`comment out`,KEEP:`keep`,SKIP:`skip`},le={GREEN:`Green`,GREY:`Grey`,RED:`Red`,NA:`NA`},ue={GREEN:`Green`,GREY:`Grey`,RUNTIME_ERROR:`RuntimeError`},de=function(e){return e.IDE=`IDE`,e.CLI=`CLI`,e}({}),fe=function(e){return e.SIBLING_FOLDER=`siblingFolder`,e.ROOT_FOLDER=`rootFolder`,e}({}),pe=function(e){return e.JEST=`jest`,e.MOCHA=`mocha`,e.VITEST=`vitest`,e.PYTEST=`pytest`,e}({}),me=function(e){return e.SPEC=`spec`,e.TEST=`test`,e}({}),he=function(e){return e.CAMEL_CASE=`camelCase`,e.KEBAB_CASE=`kebabCase`,e}({}),ge=function(e){return e.NONE=`none`,e.CATEGORIES=`categories`,e}({}),_e=function(e){return e.NEW_CODE_FILE=`newCodeFile`,e.OVERRIDE_CODE_FILE=`overrideCodeFile`,e}({}),ve=function(e){return e.ON=`on`,e.OFF=`off`,e}({}),ye={DEFAULT:0,MIN:0,MAX:100},be={DEFAULT:5,MIN:1,MAX:50};u.z.object({rootPath:u.z.string().default(process.cwd()),testStructure:u.z.enum(fe).optional(),testFramework:u.z.enum(pe).optional(),testSuffix:u.z.enum(me).optional(),testFileName:u.z.enum(he).optional(),calculateCoverage:u.z.enum(ve).optional(),coverageThreshold:u.z.number().min(ye.MIN).max(ye.MAX).default(ye.DEFAULT),requestSource:u.z.enum(de).optional(),concurrency:u.z.number().min(be.MIN).max(be.MAX).default(be.DEFAULT),backendURL:u.z.string().optional(),secretToken:u.z.string().optional(),modelName:u.z.string().optional(),context:u.z.object({git:u.z.object({ref_name:u.z.string(),repository:u.z.string(),owner:u.z.string(),sha:u.z.string(),workflowRunId:u.z.string(),remoteUrl:u.z.string(),topLevel:u.z.string()}).partial().optional()}).optional(),testCommand:u.z.string().optional(),coverageCommand:u.z.string().optional(),lintCommand:u.z.string().optional(),prettierCommand:u.z.string().optional(),disableLintRules:u.z.boolean().optional(),ignoreAsAnyLintErrors:u.z.boolean().optional(),includeEarlyTests:u.z.boolean().optional(),greyTestBehaviour:u.z.enum(z).optional(),redTestBehaviour:u.z.enum(z).optional(),keepErrorTests:u.z.boolean().optional(),keepFailedTests:u.z.boolean().optional(),conditionalKeep:u.z.boolean().optional(),continueOnTestErrors:u.z.boolean().optional(),perFunctionTimeout:u.z.number().positive().optional(),dynamicPromptIterations:u.z.number().min(0).max(10).optional(),removeComments:u.z.boolean().optional(),experimentalAgentSdk:u.z.boolean().optional(),agentSdkModel:u.z.string().optional(),agentSdkBudget:u.z.number().positive().optional(),debug:u.z.boolean().optional(),verbose:u.z.boolean().optional(),progressLogger:u.z.custom().optional()});var xe=`@earlyai/ts-agent`,Se=`0.76.0`;let Ce={VSCODE:`vscode`,GITHUB_ACTION:`github-action`,UNKNOWN:`unknown`},we=`$early_filename`,Te=`$early_coverage_dir`,Ee=`$early_test_files`,De=`npx jest ${we} --no-coverage --silent --json --forceExit --maxWorkers=1`,Oe=`npx --no eslint ${we}`,ke=`npx --no prettier ${we} --write`,Ae={rootPath:process.cwd(),isSiblingFolderStructured:!0,gitURL:`https://github.com/your-owner/your-repo`,testFramework:pe.JEST,greyTestBehaviour:z.DELETE,redTestBehaviour:z.DELETE,keepErrorTests:!1,keepFailedTests:!1,conditionalKeep:!1,continueOnTestErrors:!0,generatedTestStructure:ge.CATEGORIES,isRootFolderStructured:!1,clientSource:Ce.GITHUB_ACTION,backendURL:`https://api.startearly.ai`,requestSource:de.CLI,userPrompt:``,testLocation:`__tests__`,coverageThreshold:ye.DEFAULT,concurrency:5,testFileFormat:`ts`,outputType:_e.NEW_CODE_FILE,shouldRefreshCoverage:!0,kebabCaseFileName:!1,earlyTestFilenameSuffix:`.early.${me.TEST}`,testSuffix:me.TEST,isAppendPrompt:!1,dynamicPromptIterations:3,wsServerEndpoint:`wss://api.startearly.ai`,secretToken:``,loggerConfig:{consoleEnabled:!1,azureEnabled:!0,azureConnectionString:`InstrumentationKey=8b9b0d6a-5400-44a3-ada6-3cd026de6cfe;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/;ApplicationId=d6e130b6-4aaa-4dcc-8d26-c1fa25d4656a`},context:void 0,includeEarlyTests:!1,lintCommand:Oe,prettierCommand:ke,disableLintRules:!1,ignoreAsAnyLintErrors:!0,allowUndefinedLintErrors:!0,perFunctionTimeout:42e4,removeComments:!0,experimentalAgentSdk:!1,agentSdkModel:void 0,agentSdkBudget:void 0,debug:!1,verbose:!1},je=e=>{let t=`testFramework.testSuffix.backendURL.requestSource.secretToken.concurrency.coverageThreshold.context.rootPath.testCommand.coverageCommand.lintCommand.prettierCommand.disableLintRules.greyTestBehaviour.redTestBehaviour.keepErrorTests.keepFailedTests.conditionalKeep.continueOnTestErrors.perFunctionTimeout.dynamicPromptIterations.removeComments.experimentalAgentSdk.agentSdkModel.agentSdkBudget.debug.verbose.progressLogger`.split(`.`).reduce((t,n)=>(0,h.isDefined)(e[n])?{...t,[n]:e[n]}:t,{}),n={...(0,h.isDefined)(e.testStructure)&&{isSiblingFolderStructured:e.testStructure===fe.SIBLING_FOLDER,isRootFolderStructured:e.testStructure===fe.ROOT_FOLDER},...(0,h.isDefined)(e.testFileName)&&{kebabCaseFileName:e.testFileName===he.KEBAB_CASE},...(0,h.isDefined)(e.calculateCoverage)&&{shouldRefreshCoverage:e.calculateCoverage===ve.ON},...(0,h.isDefined)(e.modelName)&&{fixTestsLLMModelName:e.modelName,generateTestsLLMModelName:e.modelName},...(0,h.isDefined)(e.testSuffix)&&{earlyTestFilenameSuffix:`.early.${e.testSuffix}`},...(0,h.isDefined)(e.requestSource)&&{clientSource:e.requestSource===de.IDE?Ce.VSCODE:Ce.GITHUB_ACTION}};return{...t,...n}},Me=new v.Chalk({level:1}),Ne=()=>{},Pe={info:Ne,verbose:Ne,debug:Ne},Fe=[Me.cyan,Me.magenta,Me.green,Me.blue,Me.redBright,Me.cyanBright,Me.magentaBright,Me.greenBright];function Ie(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.codePointAt(n)??0,t=Math.imul(t,16777619);return Fe[Math.abs(t)%Fe.length]}function Le(e,t){let n=(0,h.isDefined)(t.parentName)?`${t.parentName}.${t.methodName}`:t.methodName,r=Ie(n)(`[${n}]`);return{info:(...t)=>e.info(r,...t),verbose:(...t)=>e.verbose(r,...t),debug:(...t)=>e.debug(r,...t)}}var Re=s(((e,t)=>{function n(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports})),ze=s(((e,t)=>{function n(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}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports})),Be=l(Re()),Ve=l(ze()),He,Ue;let B=class{config;constructor(e,t={}){if(!(0,h.isDefined)(e)){this.config=Ae;return}let n=je(e);this.config=(0,h.merge)(Ae,n,t)}getRootPath=()=>this.config.rootPath;isSiblingFolderStructured=()=>this.config.isSiblingFolderStructured;getGitURL=()=>this.config.context?.git?.remoteUrl??this.config.gitURL;getGitTopLevel=()=>this.config.context?.git?.topLevel??this.getRootPath();getTestFramework=()=>this.config.testFramework;getGreyTestBehaviour=()=>this.config.greyTestBehaviour;getRedTestBehaviour=()=>this.config.redTestBehaviour;shouldKeepErrorTests=()=>this.config.keepErrorTests;shouldKeepFailedTests=()=>this.config.keepFailedTests;shouldConditionalKeep=()=>this.config.conditionalKeep;getGeneratedTestStructure=()=>this.config.generatedTestStructure;getGenerateTestsLLMModelName=()=>this.config.generateTestsLLMModelName;isRootFolderStructured=()=>this.config.isRootFolderStructured;getLLMTemperature=()=>this.config.llmTemperature;getLLMTopP=()=>this.config.llmTopP;getClientSource=()=>this.config.clientSource;getBackendURL=()=>this.config.backendURL;getRequestSource=()=>this.config.requestSource;getUserPrompt=()=>this.config.userPrompt;getTestLocation=()=>this.config.testLocation;getCoverageThreshold=()=>this.config.coverageThreshold;getConcurrency=()=>this.config.concurrency;getTestFileFormat=()=>this.config.testFileFormat;getOutputType=()=>this.config.outputType;getShouldRefreshCoverage=()=>this.config.shouldRefreshCoverage;isKebabCaseFileName=()=>this.config.kebabCaseFileName;getEarlyTestFilenameSuffix=()=>this.config.earlyTestFilenameSuffix;getTestSuffix=()=>this.config.testSuffix;getIsAppendPrompt=()=>this.config.isAppendPrompt;getFixTestsLLMModelName=()=>this.config.fixTestsLLMModelName;getDynamicPromptIterations=()=>this.config.dynamicPromptIterations;getWSServerEndpoint=()=>this.config.backendURL.replace(`http://`,`ws://`).replace(`https://`,`wss://`);getAnthropicProxyUrl=()=>new URL(`/anthropic`,this.config.backendURL).href;getSecretToken=()=>this.config.secretToken;getLoggerConfig=()=>this.config.loggerConfig;getContext=()=>this.config.context;getTestCommand=()=>this.config.testCommand;getCoverageCommand=()=>this.config.coverageCommand;getLintCommand=()=>this.config.lintCommand;getPrettierCommand=()=>this.config.prettierCommand;shouldDisableLintRules=()=>this.config.disableLintRules;shouldIgnoreAsAnyLintErrors=()=>this.config.ignoreAsAnyLintErrors;allowUndefinedLintErrors=()=>this.config.allowUndefinedLintErrors;getIncludeEarlyTests=()=>this.config.includeEarlyTests??!1;shouldContinueOnTestErrors=()=>this.config.continueOnTestErrors;getPerFunctionTimeout=()=>this.config.perFunctionTimeout;shouldRemoveComments=()=>this.config.removeComments;getExperimentalAgentSdk=()=>this.config.experimentalAgentSdk;getAgentSdkModel=()=>this.config.agentSdkModel;getAgentSdkBudget=()=>this.config.agentSdkBudget;updateContext=e=>{this.config.context=(0,h.merge)(this.config.context??{},e??{})};updateRootPath=e=>{this.config.rootPath=e};isDebug=()=>this.config.debug??!1;isVerbose=()=>this.config.verbose??!1;getProgressLogger=e=>{let t=this.config.progressLogger??Pe;return(0,h.isDefined)(e)?Le(t,e):t}};B=(0,Ve.default)([(0,_.injectable)(`Singleton`),(0,Be.default)(`design:paramtypes`,[typeof(He=typeof Partial<`u`&&Partial)==`function`?He:Object,typeof(Ue=typeof Partial<`u`&&Partial)==`function`?Ue:Object])],B);var We=new _.Container({autobind:!0,defaultScope:`Singleton`});let Ge=()=>We.get(B);var Ke=class{storage=new m.AsyncLocalStorage;isConsoleEnabled;constructor(e){this.isConsoleEnabled=e}orderedFlush={nextOrder:1,pending:new Map};resetOrder(){this.orderedFlush={nextOrder:1,pending:new Map}}async withBufferedPrinting(e,t){let n=[];try{return await this.storage.run(n,e)}finally{this.flushInOrder(t,n)}}printOrBuffer(e,t){let n=this.storage.getStore();if((0,h.isDefined)(n)){n.push({method:e,message:t});return}this.isConsoleEnabled&&console[e](t)}async flushInOrder(e,t){if(this.orderedFlush.nextOrder===e){this.flushBuffer(t),this.orderedFlush.nextOrder++,this.drainPendingFlushes();return}return new Promise(n=>{this.orderedFlush.pending.set(e,{buffer:t,resolve:n})})}drainPendingFlushes(){let e=this.orderedFlush.pending.get(this.orderedFlush.nextOrder);for(;(0,h.isDefined)(e);)this.orderedFlush.pending.delete(this.orderedFlush.nextOrder),this.flushBuffer(e.buffer),this.orderedFlush.nextOrder++,e.resolve(),e=this.orderedFlush.pending.get(this.orderedFlush.nextOrder)}flushBuffer(e){if(this.isConsoleEnabled)for(let t of e)console[t.method](t.message)}};let qe=function(e){return e.DEFAULT=`default`,e.VERBOSE=`verbose`,e.DEBUG=`debug`,e}({}),Je=function(e){return e.INFO=`info`,e.WARN=`warn`,e}({});function Ye(){return(0,y.randomUUID)()}function Xe(){let e=``;for(let t=0;t<8;t++)e+=`abcdefghijklmnopqrstuvwxyz0123456789`.charAt(Math.floor(Math.random()*36));return e}var Ze=l(Re()),Qe=l(ze()),$e=class{export(e,t){for(let t of e){let e=t.body;if((0,h.isString)(e))console.info(e);else try{console.info(JSON.stringify(e))}catch{console.info(String(e))}}t({code:0})}shutdown(){return Promise.resolve()}};let et=class{loggerProvider;config;constructor(e){this.config=e,this.loggerProvider=new S.LoggerProvider({resource:(0,x.resourceFromAttributes)({[C.ATTR_SERVICE_NAME]:xe,[C.ATTR_SERVICE_VERSION]:Se})}),this.initializeExporters(),this.setGlobalLoggerProvider()}getLogger(e){return this.loggerProvider.getLogger(e)}initializeExporters(){let e=[];if(this.config.consoleEnabled){let t=new $e;e.push(new S.SimpleLogRecordProcessor(t))}if(this.config.azureEnabled&&(0,h.isDefined)(this.config.azureConnectionString)){let t=new b.AzureMonitorLogExporter({connectionString:this.config.azureConnectionString});e.push(new S.BatchLogRecordProcessor(t))}this.loggerProvider=new S.LoggerProvider({processors:e})}setGlobalLoggerProvider(){g.logs.setGlobalLoggerProvider(this.loggerProvider)}};et=(0,Qe.default)([(0,_.injectable)(),(0,Ze.default)(`design:paramtypes`,[Object])],et),l(Re()),l(ze());let V=new class{storage;otelService;otelLogger;isConsoleEnabled;printBuffer;default=this.createLogObject(qe.DEFAULT);verbose=this.createLogObject(qe.VERBOSE);constructor(e){this.storage=new m.AsyncLocalStorage,this.otelService=new et(e),this.otelLogger=this.otelService.getLogger(`ts-agent`),this.isConsoleEnabled=e.consoleEnabled,this.printBuffer=new Ke(e.consoleEnabled)}resetPrintOrder(){this.printBuffer.resetOrder()}async withBufferedPrinting(e,t){return this.printBuffer.withBufferedPrinting(e,t)}info={startLog:(e,...t)=>this.log(g.SeverityNumber.INFO,`Start ${e}`,...t),endLog:(e,...t)=>this.log(g.SeverityNumber.INFO,`End ${e}`,...t),failedLog:(e,...t)=>this.log(g.SeverityNumber.INFO,`Failed ${e}`,...t),defaultLog:(e,...t)=>this.log(g.SeverityNumber.INFO,e,...t)};debug={startLog:(e,...t)=>this.log(g.SeverityNumber.DEBUG,`Start ${e}`,...t),endLog:(e,...t)=>this.log(g.SeverityNumber.DEBUG,`End ${e}`,...t),failedLog:(e,...t)=>this.log(g.SeverityNumber.DEBUG,`Failed ${e}`,...t),defaultLog:(e,...t)=>this.log(g.SeverityNumber.DEBUG,e,...t)};error(e,t,...n){let r=t instanceof Error?`${e} ${t.message} ${t.stack}`:`${e} ${JSON.stringify(t)}`;this.log(g.SeverityNumber.ERROR,r,...n)}getRequestId(){return this.storage.getStore()?.requestId??``}getTraceId(){return this.storage.getStore()?.traceId??``}log(e,t,...n){let r=this.formatMessage(t,...n);this.logToOpenTelemetry(e,r),!(!this.isConsoleEnabled||!this.isLevelEnabled(qe.DEBUG))&&console.info(r)}logToOpenTelemetry(e,t){let n=this.storage.getStore(),r={service:xe,version:Se};(0,h.isDefined)(n)&&((0,h.isDefined)(n.traceId)&&(r.traceId=n.traceId),(0,h.isDefined)(n.requestId)&&(r.requestId=n.requestId),(0,h.isDefined)(n.category)&&(r.category=n.category),(0,h.isDefined)(n.subCategory)&&(r.subCategory=n.subCategory),(0,h.isDefined)(n.testedMethodClass)&&(r.testedMethodClass=n.testedMethodClass),(0,h.isDefined)(n.testedFunction)&&(r.testedFunction=n.testedFunction),(0,h.isDefined)(n.userId)&&(r.userId=n.userId.toString())),this.otelLogger.emit({severityNumber:e,severityText:this.getSeverityText(e),body:t,attributes:r})}getSeverityText(e){switch(e){case g.SeverityNumber.TRACE:return`TRACE`;case g.SeverityNumber.DEBUG:return`DEBUG`;case g.SeverityNumber.INFO:return`INFO`;case g.SeverityNumber.WARN:return`WARN`;case g.SeverityNumber.ERROR:return`ERROR`;case g.SeverityNumber.FATAL:return`FATAL`;default:return`INFO`}}formatMessage(e,...t){let n=this.formatPrefix(),r=(0,h.isDefined)(n)?`${n} ${e}`:e;return this.formatPrint(r,...t)}formatPrint(e,...t){return(0,h.isEmpty)(t)?e:`${e} ${t.map(e=>JSON.stringify(e)).join(` `)}`}withContext=(e,t,n)=>{let r=n.value,i=this.storage;return n.value=function(...e){let t=i.getStore();if(t){let n={...t};return i.run(n,()=>r.apply(this,e))}let n={traceId:Xe(),requestId:Ye()};return i.run(n,()=>r.apply(this,e))},n};addContext(e){let t=this.storage.getStore();(0,h.isDefined)(t)&&(t.category=e.category??t.category,t.subCategory=e.subCategory??t.subCategory,t.testedMethodClass=e.testedMethodClass??t.testedMethodClass,t.testedFunction=e.testedFunction??t.testedFunction,t.userId=e.userId??t.userId)}captureContext({withNewRequestId:e=!1}={}){let t=this.storage.getStore();return t?{...t,...e&&{requestId:Ye()}}:void 0}async runWithContext(e,t){return(0,h.isDefined)(e)?this.storage.run(e,t):t()}isLevelEnabled(e){switch(e){case qe.DEFAULT:return!0;case qe.VERBOSE:return Ge().isVerbose()||Ge().isDebug();case qe.DEBUG:return Ge().isDebug()}}createLogObject(e){return{info:(t,...n)=>{this.isLevelEnabled(e)&&this.printOrBuffer(Je.INFO,this.formatPrint(t,...n))},warn:(t,...n)=>{this.isLevelEnabled(e)&&this.printOrBuffer(Je.WARN,this.formatPrint(t,...n))}}}printOrBuffer(e,t){this.printBuffer.printOrBuffer(e,t)}formatPrefix(){let e=this.storage.getStore();if(!(0,h.isDefined)(e))return``;let t=[];return(0,h.isDefined)(e.traceId)&&t.push(`[${e.traceId}]`),(0,h.isDefined)(e.requestId)&&t.push(`[${e.requestId}]`),(0,h.isDefined)(e.category)&&t.push(`[${e.category}]`),(0,h.isDefined)(e.subCategory)&&t.push(`[${e.subCategory}]`),(0,h.isDefined)(e.testedMethodClass)&&t.push(`[${e.testedMethodClass}]`),(0,h.isDefined)(e.testedFunction)&&t.push(`[${e.testedFunction}]`),t.join(` `)}}({consoleEnabled:!1,azureEnabled:!0,azureConnectionString:`InstrumentationKey=c18a3332-f844-498f-98e0-d818996cf526;IngestionEndpoint=https://eastus2-3.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus2.livediagnostics.monitor.azure.com/;ApplicationId=2150ffe0-cb0f-4b00-9562-d3385b383d74`});function tt(e){return function(t,n,r){return(0,h.isDefined)(e)&&V.addContext(e),V.withContext(t,n,r)}}var nt=class e{rootPath;absolutePath;static EARLY_FILENAME_VAR=`$early_filename`;constructor(e){this.rootPath=f.default.normalizeTrim(Ge().getRootPath());let t=f.default.normalizeTrim(e),n=f.default.normalizeTrim(this.rootPath);if(t===n||t.startsWith(n+f.default.sep))this.absolutePath=t;else{let e=t.replace(/^\//,``);this.absolutePath=f.default.resolve(this.rootPath,e)}}static fromSourceFile(t){let n=f.default.normalizeTrim(t.getFilePath());return new e(f.default.relative(f.default.normalizeTrim(Ge().getRootPath()),n))}static fromAbsolutePath(t){let n=f.default.normalizeTrim(t);return new e(f.default.relative(f.default.normalizeTrim(Ge().getRootPath()),n))}static fromRelativePath(t){return new e(t)}getRelativeFilePath(){return f.default.relative(this.rootPath,this.absolutePath)}getAbsoluteFilePath(){return this.absolutePath}async isFileExists(){try{return(await p.default.stat(this.absolutePath)).isFile()}catch{return!1}}async isDirectoryExists(){try{return(await p.default.stat(this.absolutePath)).isDirectory()}catch{return!1}}async createDirectory(e){await p.default.mkdir(this.absolutePath,{recursive:e?.recursive??!0})}async getText(){try{return await p.default.readFile(this.absolutePath,`utf8`)}catch{return``}}async upsert(e){let t=f.default.dirname(this.absolutePath);await p.default.mkdir(t,{recursive:!0}),await(await this.isFileExists()?p.default.appendFile(this.absolutePath,e):p.default.writeFile(this.absolutePath,e)),V.info.defaultLog(`Upserted file`,{path:this.getRelativeFilePath()})}async replace(e){let t=f.default.dirname(this.absolutePath);await p.default.mkdir(t,{recursive:!0}),await p.default.writeFile(this.absolutePath,e),V.info.defaultLog(`Replaced file`,{path:this.getRelativeFilePath()})}async delete(){try{await p.default.unlink(this.absolutePath),V.info.defaultLog(`Deleted file`,{path:this.getRelativeFilePath()})}catch{}}};let rt={WIN32:`win32`,DARWIN:`darwin`,LINUX:`linux`},it={JAVASCRIPT:`javascript`,TYPESCRIPT:`typescript`,PYTHON:`python`},at=e=>{let t=Ge().getRootPath();return f.default.resolve(t,e)},ot=e=>{let t=Ge().getRootPath(),n=f.default.normalize(e);return f.default.relative(t,n)},st=e=>({".js":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".jsx":`javascript`,".ts":`typescript`,".tsx":`typescript`,".py":`python`})[e.toLowerCase()]??`javascript`;function ct(e){return st((0,f.extname)(e))}function H(e){return st((0,f.extname)(e))===`typescript`}function lt(e){return st((0,f.extname)(e))===it.PYTHON}function ut(e){let t=Ge().getRootPath();if(!(0,h.isDefined)(t))throw Error(`Workspace root path is not defined`);if((0,h.isEmpty)(e))return f.default.normalize(t);let n=f.default.normalize(t),r=f.default.normalize(e);if(process.platform===rt.WIN32){let t=n.split(`:`)[0].toUpperCase(),i=r.split(`:`)[0].toUpperCase();if(t!==i&&!i.startsWith(t))return e}return f.default.relative(n,r)}function dt(e){return e.startsWith(`../`)?`../${e}`:e.startsWith(`./`)?`.${e}`:e}function ft(e){let t=f.default.normalize(at(e)),n=f.default.normalize((0,T.default)([`package.json`,`project.json`],{cwd:t})??``);if(!n)return``;let r=ot((0,f.dirname)(n));return r.startsWith(`/`)?r.slice(1):r}function pt(e,t,n){if(!ht(e))return e;let r=n===``?t:t.replace(n,``),i=n===``?_t(r):gt(r),a=r.split(`/`).slice(0,-1),o=mt(e,`../`),s=o>0?a.slice(0,-o).join(`/`):(0,f.dirname)(r),c=e.replaceAll(`../`,``).replaceAll(`./`,``);return f.default.join(i,s,c)}function mt(e,t){return e.split(t).length-1}function ht(e){return e.startsWith(`../`)||e.startsWith(`./`)}function gt(e){let t=mt(e,`/`);return`../`.repeat(t-1)}function _t(e){let t=mt(e,`/`);return`../`.repeat(t+1)}function vt(e){return e?.includes(`node_modules/`)}let yt=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);function bt(e,t){let n=f.default.isAbsolute(e)?e:at(e);return(0,T.default)(t,{cwd:n})}function xt(e,t){let n=bt(e,t);if(!(0,h.isDefined)(n))return;let r=w.readFileSync(n,`utf8`);return JSON.parse(r)}function St(e){return xt(e,`package.json`)}function Ct(e,t){let{dependencies:n={},devDependencies:r={}}=e;return Object.keys({...r,...n}).includes(t)}let wt=[{path:`eslint.config.js`,isFlat:!0},{path:`eslint.config.cjs`,isFlat:!0},{path:`eslint.config.mjs`,isFlat:!0},{path:`eslint.config.ts`,isFlat:!0},{path:`eslint.config.mts`,isFlat:!0},{path:`eslint.config.cts`,isFlat:!0},{path:`.eslintrc`,isFlat:!1},{path:`.eslintrc.js`,isFlat:!1},{path:`.eslintrc.cjs`,isFlat:!1},{path:`.eslintrc.mjs`,isFlat:!1},{path:`.eslintrc.json`,isFlat:!1},{path:`.eslintrc.yaml`,isFlat:!1},{path:`.eslintrc.yml`,isFlat:!1}],Tt=[`@typescript-eslint/no-undefined`,`unicorn/no-useless-undefined`,`no-undefined`];async function Et(e){for(let{path:t,isFlat:n}of wt){let r=f.default.join(e,t);if(await nt.fromAbsolutePath(r).isFileExists())return{path:r,isFlat:n}}return St(e)?.eslint?{path:bt(e,`package.json`),isFlat:!1}:{path:null,isFlat:!1}}let Dt={GET_TESTABLES:`get-testables`,GET_COVERAGE:`get-coverage`,GENERATE_COVERAGE:`generate-coverage`,SET_COVERAGE:`set-coverage`,GENERATE_TESTS:`generate-tests`,INITIALIZATION:`initialization`,GET_TESTED_CODE_DATA_SOURCE:`get-tested-code-data-source`,DYNAMIC_PROMPT:`dynamic-prompt`,TEST_VALIDATION:`test-validation`},Ot={CODE_EXTRACTOR:`code-extractor`,CODE_REFINEMENT:`code-refinement`,TEST_MANAGEMENT:`test-management`,TEST_VALIDATOR:`test-validator`,CONFIG_FILE:`config-file`,COMMAND_EXECUTION:`command-execution`},kt=[`.jsx`,`.tsx`],At=[`it`,`test`,`it.each`,`test.each`],jt=function(e){return e.Default=`default`,e.ObjectDefault=`object-default`,e.Named=`named`,e.Unknown=`unknown`,e.NotExported=`not-exported`,e}({}),Mt=function(e){return e.PRIVATE=`private`,e.PROTECTED=`protected`,e.PUBLIC=`public`,e}({}),Nt=function(e){return e.REACT=`react`,e.ANGULAR=`angular`,e}({}),Pt=`unknown`,Ft=(0,O.promisify)(D.default.exec);async function It(e,{cwd:t=Ge().getRootPath(),timeout:n=1e4}={}){return(await Ft(e,{cwd:t,maxBuffer:500*1024,timeout:n}))?.stdout?.toString()??``}let Lt=e=>{let t=at(e);return(0,T.default)(`jest.config.+(js|ts|mjs|cjs|json)`,{cwd:t})},Rt=e=>(0,h.isObject)(e)&&(0,h.isString)(e.rootDir),zt=async e=>{let t;if(V.addContext({subCategory:Ot.CONFIG_FILE}),(0,h.isDefined)(e)){let n=Lt(e);n!==null&&(t=(0,f.dirname)(n))}t??=Ge().getRootPath();let n;try{if(n=await It(`npx jest --showConfig`,{cwd:t}),!(0,h.isString)(n))throw V.info.defaultLog(`Jest config return is not a string`,n),Error(`Jest config return is not a string`);let e=JSON.parse(n);if((0,h.isObject)(e)&&(0,h.isArray)(e.configs)&&e.configs.every(e=>Rt(e)))return{projectConfigs:e.configs,globalConfig:e.globalConfig,configs:e.configs}}catch(e){V.info.defaultLog(`Cannot read jest config`,(0,h.getErrorMessage)(e)),V.info.defaultLog(`Failed reading jest config`,e,(0,h.getErrorMessage)(e));return}V.info.defaultLog(`Invalid jest config or config in not supported format`)},Bt=async()=>{let e=[Ge().getRootPath()],t=f.default.join(`node_modules`,`.prisma`,`client`,`index.d.ts`),n=e.map(e=>f.default.join(e,t)).map(e=>nt.fromAbsolutePath(e));return(await(0,h.filterAsync)(n,e=>e.isFileExists())).map(e=>e.getAbsoluteFilePath())},Vt=async()=>{try{let e=Ge().getRootPath();if(!(0,h.isDefined)(e))return[];let t=await(0,k.getSchemaWithPathOptional)(``,``,{cwd:e});if(!(0,h.isDefined)(t))return[];let n=t.schemas.map(e=>e[1]),r=new Set;for(let e of n){let n=(await(0,k.getConfig)({datamodel:e,ignoreEnvVarErrors:!0})).generators;for(let e of n)if((0,h.isDefined)(e.output?.value)){let n=f.default.join(f.default.resolve(t.schemaRootDir,e.output.value),`index.d.ts`);await nt.fromAbsolutePath(n).isFileExists()&&r.add(n)}}return[...r]}catch(e){return V.error(`Failed to get prisma typings paths`,e),[]}},Ht=async()=>(await Promise.all([Bt(),Vt()])).flat(),Ut=async(e,t=!1,n)=>{let r=`!**/node_modules/**`;if(t)return new E.Project({useInMemoryFileSystem:!0,compilerOptions:n});let i=H(e),a=Wt((0,f.dirname)(at(e)),Ge().isSiblingFolderStructured());if(!i&&!(0,h.isDefined)(a)){let t=await Kt(e);if(!(0,h.isDefined)(t)||(0,h.isEmpty)(t))throw Error(`Cannot find source code path in jest config`);let n=new E.Project({compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0},useInMemoryFileSystem:!1});return n.addSourceFilesAtPaths([...t,r]),n}if(!i&&(0,h.isDefined)(a)){let t=new E.Project({tsConfigFilePath:a,compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0}}),n=await Kt(e);return t.addSourceFilesAtPaths([...n,r]),t}let o=new E.Project({tsConfigFilePath:a,compilerOptions:{maxNodeModuleJsDepth:0}}),s=await Ht();for(let e of s)o.addSourceFileAtPath(e);return o},Wt=(e,t)=>{let n;try{n=Gt(e)}catch{t&&(n=Gt((0,f.dirname)(e)))}return n},Gt=e=>{let t=e,n=/^(tsconfig|jsconfig).*\.json$/;for(;t!==(0,f.dirname)(t);){let e=(0,f.join)(t,`tsconfig.json`),r=(0,f.join)(t,`jsconfig.json`);if(!(0,w.existsSync)(t))return Gt((0,f.dirname)(t));if((0,w.existsSync)(e))return e;if((0,w.existsSync)(r))return r;let i=(0,w.readdirSync)(t);for(let e of i)if(n.test(e))return(0,f.join)(t,e);t=(0,f.dirname)(t)}},Kt=async e=>{let t=await zt(e);if((0,h.isDefined)(t)){let e=t?.configs[0].roots.map(e=>f.default.join(e,`**/*.{ts,js,tsx,jsx}`));if(!(0,h.isEmpty)(e))return e}return[at(ft(e))]};var qt=l(Re()),Jt=l(ze());let Yt=`The ts-morph project is not initialized.`,U=new class{storage=new m.AsyncLocalStorage;_project;clear(){this._project=void 0}async init(e,t,n){let r=at(e);if((0,h.isDefined)(this._project))return this._project.addSourceFileAtPathIfExists(r);this._project=await Ut(e,t,n);let i=this.storage.getStore();if((0,h.isDefined)(i))return this._project.addSourceFileAtPathIfExists(r)}add(e,t){let n=at(e),r=this.storage.getStore()?.getProject();if(!(0,h.isDefined)(r))throw Error(Yt);return r.createSourceFile(n,t,{overwrite:!0})}update(e,t){let n=this.get(e);return n.replaceWithText(t),n}addFile(e){(0,h.isDefined)(this._project)&&this._project.addSourceFileAtPathIfExists(e)}removeFile(e){if(!(0,h.isDefined)(this._project))return;let t=this._project.getSourceFile(e);(0,h.isDefined)(t)&&this._project.removeSourceFile(t)}async refreshFromFileSystem(e){if(!(0,h.isDefined)(this._project))return;let t=at(e),n=this._project?.getSourceFile(e)??this._project?.getSourceFile(t);if((0,h.isDefined)(n)){let e=n.getFilePath();this._project.removeSourceFile(n),this._project.addSourceFileAtPath(e)}}get(e){let t=at(e),n=this.storage.getStore()?.getProject();if(!(0,h.isDefined)(n))throw Error(Yt+` store`);let r=n.getSourceFile(t);if(!(0,h.isDefined)(r))throw Error(`The source file is absent. ${e}`);return r}async save(e){await this.get(e).save()}async delete(e){await this.get(e).deleteImmediately()}getOrUndefined(e){let t=at(e);return this._project?.getSourceFile(t)}withContext=(e,t,n)=>{let r=n.value,i=this.storage;if((0,h.isDefined)(i.getStore()))return n;let a=()=>this._project;return n.value=function(...e){let t={getProject:a};return i.run(t,()=>r.apply(this,e))},n}},Xt=U.withContext,Zt=async e=>{class t{async fn(){return e()}}(0,Jt.default)([Xt,(0,qt.default)(`design:type`,Function),(0,qt.default)(`design:paramtypes`,[]),(0,qt.default)(`design:returntype`,Promise)],t.prototype,`fn`,null),await new t().fn()},Qt=e=>{let t=e?.asKind(E.SyntaxKind.ExpressionStatement)?.getExpression();if(!(0,h.isDefined)(t))return;let n=t.asKind(E.SyntaxKind.CallExpression)?.getArguments()?.at(-1),r=n?.asKind(E.SyntaxKind.ArrowFunction)?.getBody(),i=n?.asKind(E.SyntaxKind.FunctionExpression)?.getBody();return r?.asKind(E.SyntaxKind.Block)??i?.asKind(E.SyntaxKind.Block)},$t=e=>E.Node.isExpressionStatement(e)&&e.getFirstChildByKind(E.SyntaxKind.CallExpression)?.getFirstChildByKind(E.SyntaxKind.Identifier)?.getText()===`describe`,en=e=>e.getStatements().filter(e=>$t(e)),tn=e=>{let t=e.getExpression().getFirstChild()?.getText();return!(0,h.isDefined)(t)||(0,h.isEmpty)(t)?!1:At.some(e=>t.startsWith(e))},nn=e=>{let t=Qt(e);return(0,h.isDefined)(t)?t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement).some(e=>tn(e)):!1},rn=e=>{let t=Qt(e);return(0,h.isDefined)(t)?t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement).filter(e=>$t(e)&&nn(e)):[]},an=e=>{let t=Qt(e);if((0,h.isDefined)(t))return t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement).find(e=>$t(e)&&nn(e))},on=e=>{let t=an(e);return(0,h.isDefined)(t)},sn=e=>{let t=Qt(e);if(!(0,h.isDefined)(t))return!0;let n=t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement);if((0,h.isEmpty)(n))return!0;let r=new Set([`beforeEach`,`afterEach`,`beforeAll`,`afterAll`]);return n.every(e=>{let t=e.getExpressionIfKind(E.SyntaxKind.CallExpression)?.getExpressionIfKind(E.SyntaxKind.Identifier);return(0,h.isDefined)(t)?r.has(t.getText()):!1})},cn=e=>{if(e.isNamedExport?.())return jt.Named;if(e.isDefaultExport?.())return jt.Default;let t=e?.getParent();if((0,h.isDefined)(t)){if(t.isNamedExport?.())return jt.Named;if(t.isDefaultExport?.())return jt.Default}return e.isExportDefaultObject?.()??un(e.getSourceFile(),e.getName?.())?jt.ObjectDefault:jt.NotExported},ln=(e,t)=>(0,h.isDefined)(e)?cn(e):(0,h.isDefined)(t)?t.isNamedImport?jt.Named:jt.Default:jt.Unknown;function un(e,t){let[n]=e.getExportAssignments()??[];return n?.getDescendantsOfKind(E.SyntaxKind.Identifier).some(e=>(e.getSymbol()?.getEscapedName()??e.getText())===t)}function dn(e,t){let n=en(U.get(e)),r=n.find(e=>e.getText().includes(t))??n[0],i=rn(r),a=[],o=(0,h.isEmpty)(i)?[r]:i;for(let e of o){let t=Qt(e);(0,h.isDefined)(t)&&a.push(...t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement).filter(e=>tn(e)))}return a}let W=e=>e.getFirstDescendantByKind(E.SyntaxKind.StringLiteral)?.getLiteralValue(),fn=e=>W(e),pn=e=>W(e),mn=(e,t)=>{let n=e.getFullText().slice(0,Math.max(0,t)).split(`
32005
+ `):(this.indentate=function(){return``},this.tagEndChar=`>`,this.newLine=``)}function xe(e,t,n,r){let i=this.j2x(e,n+1,r.concat(t));return e[this.options.textNodeName]!==void 0&&Object.keys(e).length===1?this.buildTextValNode(e[this.options.textNodeName],t,i.attrStr,n):this.buildObjectNode(i.val,t,i.attrStr,n)}function Se(e){return this.options.indentBy.repeat(e)}function Ce(e){return!(!e.startsWith(this.options.attributeNamePrefix)||e===this.options.textNodeName)&&e.substr(this.attrPrefixLen)}be.prototype.build=function(e){return this.options.preserveOrder?pe(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)},be.prototype.j2x=function(e,t,n){let r=``,i=``,a=n.join(`.`);for(let o in e)if(Object.prototype.hasOwnProperty.call(e,o))if(e[o]===void 0)this.isAttribute(o)&&(i+=``);else if(e[o]===null)this.isAttribute(o)||o===this.options.cdataPropName?i+=``:o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(e[o]instanceof Date)i+=this.buildTextValNode(e[o],o,``,t);else if(typeof e[o]!=`object`){let n=this.isAttribute(o);if(n&&!this.ignoreAttributesFn(n,a))r+=this.buildAttrPairStr(n,``+e[o]);else if(!n)if(o===this.options.textNodeName){let t=this.options.tagValueProcessor(o,``+e[o]);i+=this.replaceEntitiesValue(t)}else i+=this.buildTextValNode(e[o],o,``,t)}else if(Array.isArray(e[o])){let r=e[o].length,a=``,s=``;for(let c=0;c<r;c++){let r=e[o][c];if(r!==void 0)if(r===null)o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(typeof r==`object`)if(this.options.oneListGroup){let e=this.j2x(r,t+1,n.concat(o));a+=e.val,this.options.attributesGroupName&&r.hasOwnProperty(this.options.attributesGroupName)&&(s+=e.attrStr)}else a+=this.processTextOrObjNode(r,o,t,n);else if(this.options.oneListGroup){let e=this.options.tagValueProcessor(o,r);e=this.replaceEntitiesValue(e),a+=e}else a+=this.buildTextValNode(r,o,``,t)}this.options.oneListGroup&&(a=this.buildObjectNode(a,o,s,t)),i+=a}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){let t=Object.keys(e[o]),n=t.length;for(let i=0;i<n;i++)r+=this.buildAttrPairStr(t[i],``+e[o][t[i]])}else i+=this.processTextOrObjNode(e[o],o,t,n);return{attrStr:r,val:i}},be.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,``+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t===`true`?` `+e:` `+e+`="`+t+`"`},be.prototype.buildObjectNode=function(e,t,n,r){if(e===``)return t[0]===`?`?this.indentate(r)+`<`+t+n+`?`+this.tagEndChar:this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar;{let i=`</`+t+this.tagEndChar,a=``;return t[0]===`?`&&(a=`?`,i=``),!n&&n!==``||e.indexOf(`<`)!==-1?!1!==this.options.commentPropName&&t===this.options.commentPropName&&a.length===0?this.indentate(r)+`\x3c!--${e}--\x3e`+this.newLine:this.indentate(r)+`<`+t+n+a+this.tagEndChar+e+this.indentate(r)+i:this.indentate(r)+`<`+t+n+a+`>`+e+i}},be.prototype.closeTag=function(e){let t=``;return this.options.unpairedTags.indexOf(e)===-1?t=this.options.suppressEmptyNode?`/`:`></${e}`:this.options.suppressUnpairedNode||(t=`/`),t},be.prototype.buildTextValNode=function(e,t,n,r){if(!1!==this.options.cdataPropName&&t===this.options.cdataPropName)return this.indentate(r)+`<![CDATA[${e}]]>`+this.newLine;if(!1!==this.options.commentPropName&&t===this.options.commentPropName)return this.indentate(r)+`\x3c!--${e}--\x3e`+this.newLine;if(t[0]===`?`)return this.indentate(r)+`<`+t+n+`?`+this.tagEndChar;{let i=this.options.tagValueProcessor(t,e);return i=this.replaceEntitiesValue(i),i===``?this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar:this.indentate(r)+`<`+t+n+`>`+i+`</`+t+this.tagEndChar}},be.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){let n=this.options.entities[t];e=e.replace(n.regex,n.val)}return e};let we={validate:s};t.exports=n})()})),sW=s((e=>{var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),c=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},l=(e,r,i)=>(i=e==null?{}:t(a(e)),c(r||!e||!e.__esModule?n(i,`default`,{value:e,enumerable:!0}):i,e));let u=l(Oi()),f=l(ki()),p=l(require(`node:fs/promises`)),m=l(require(`node:async_hooks`)),h=l(ce()),g=l(Bi()),_=l(Rc()),v=l((Ol(),d(ll))),y=l(require(`node:crypto`)),b=l(rR()),x=l(pM()),S=l(lz()),C=l((Dj(),d(Ej))),w=l(require(`node:fs`)),T=l(Bz()),E=l(uV()),D=l(require(`node:child_process`)),O=l(require(`node:util`)),k=l(require(`@prisma/internals`)),A=l(oV()),ee=l(require(`node:zlib`)),j=l(aH()),te=l(sH()),M=l(dH()),ne=l(gH()),N=l(require(`node:os`)),P=l(require(`node:events`)),F=l(mU()),I=l(tW()),re=l(Iee()),ie=l(aW()),L=l(oW()),ae=l(hU()),oe=l(require(`node:process`));l(require(`node:readline`)),l(require(`node:tty`));let R=l(require(`node:path`)),se=l(require(`@anthropic-ai/claude-agent-sdk`)),z={DELETE:`delete`,COMMENT_OUT:`comment out`,KEEP:`keep`,SKIP:`skip`},le={GREEN:`Green`,GREY:`Grey`,RED:`Red`,NA:`NA`},ue={GREEN:`Green`,GREY:`Grey`,RUNTIME_ERROR:`RuntimeError`},de=function(e){return e.IDE=`IDE`,e.CLI=`CLI`,e}({}),fe=function(e){return e.SIBLING_FOLDER=`siblingFolder`,e.ROOT_FOLDER=`rootFolder`,e}({}),pe=function(e){return e.JEST=`jest`,e.MOCHA=`mocha`,e.VITEST=`vitest`,e.PYTEST=`pytest`,e}({}),me=function(e){return e.SPEC=`spec`,e.TEST=`test`,e}({}),he=function(e){return e.CAMEL_CASE=`camelCase`,e.KEBAB_CASE=`kebabCase`,e}({}),ge=function(e){return e.NONE=`none`,e.CATEGORIES=`categories`,e}({}),_e=function(e){return e.NEW_CODE_FILE=`newCodeFile`,e.OVERRIDE_CODE_FILE=`overrideCodeFile`,e}({}),ve=function(e){return e.ON=`on`,e.OFF=`off`,e}({}),ye={DEFAULT:0,MIN:0,MAX:100},be={DEFAULT:5,MIN:1,MAX:50};u.z.object({rootPath:u.z.string().default(process.cwd()),testStructure:u.z.enum(fe).optional(),testFramework:u.z.enum(pe).optional(),testSuffix:u.z.enum(me).optional(),testFileName:u.z.enum(he).optional(),calculateCoverage:u.z.enum(ve).optional(),coverageThreshold:u.z.number().min(ye.MIN).max(ye.MAX).default(ye.DEFAULT),requestSource:u.z.enum(de).optional(),concurrency:u.z.number().min(be.MIN).max(be.MAX).default(be.DEFAULT),backendURL:u.z.string().optional(),secretToken:u.z.string().optional(),modelName:u.z.string().optional(),context:u.z.object({git:u.z.object({ref_name:u.z.string(),repository:u.z.string(),owner:u.z.string(),sha:u.z.string(),workflowRunId:u.z.string(),remoteUrl:u.z.string(),topLevel:u.z.string()}).partial().optional()}).optional(),testCommand:u.z.string().optional(),coverageCommand:u.z.string().optional(),lintCommand:u.z.string().optional(),prettierCommand:u.z.string().optional(),disableLintRules:u.z.boolean().optional(),ignoreAsAnyLintErrors:u.z.boolean().optional(),includeEarlyTests:u.z.boolean().optional(),greyTestBehaviour:u.z.enum(z).optional(),redTestBehaviour:u.z.enum(z).optional(),keepErrorTests:u.z.boolean().optional(),keepFailedTests:u.z.boolean().optional(),conditionalKeep:u.z.boolean().optional(),continueOnTestErrors:u.z.boolean().optional(),perFunctionTimeout:u.z.number().positive().optional(),dynamicPromptIterations:u.z.number().min(0).max(10).optional(),removeComments:u.z.boolean().optional(),experimentalAgentSdk:u.z.boolean().optional(),agentSdkModel:u.z.string().optional(),agentSdkBudget:u.z.number().positive().optional(),debug:u.z.boolean().optional(),verbose:u.z.boolean().optional(),progressLogger:u.z.custom().optional()});var xe=`@earlyai/ts-agent`,Se=`0.76.1`;let Ce={VSCODE:`vscode`,GITHUB_ACTION:`github-action`,UNKNOWN:`unknown`},we=`$early_filename`,Te=`$early_coverage_dir`,Ee=`$early_test_files`,De=`npx jest ${we} --no-coverage --silent --json --forceExit --maxWorkers=1`,Oe=`npx --no eslint ${we}`,ke=`npx --no prettier ${we} --write`,Ae={rootPath:process.cwd(),isSiblingFolderStructured:!0,gitURL:`https://github.com/your-owner/your-repo`,testFramework:pe.JEST,greyTestBehaviour:z.DELETE,redTestBehaviour:z.DELETE,keepErrorTests:!1,keepFailedTests:!1,conditionalKeep:!1,continueOnTestErrors:!0,generatedTestStructure:ge.CATEGORIES,isRootFolderStructured:!1,clientSource:Ce.GITHUB_ACTION,backendURL:`https://api.startearly.ai`,requestSource:de.CLI,userPrompt:``,testLocation:`__tests__`,coverageThreshold:ye.DEFAULT,concurrency:5,testFileFormat:`ts`,outputType:_e.NEW_CODE_FILE,shouldRefreshCoverage:!0,kebabCaseFileName:!1,earlyTestFilenameSuffix:`.early.${me.TEST}`,testSuffix:me.TEST,isAppendPrompt:!1,dynamicPromptIterations:3,wsServerEndpoint:`wss://api.startearly.ai`,secretToken:``,loggerConfig:{consoleEnabled:!1,azureEnabled:!0,azureConnectionString:`InstrumentationKey=8b9b0d6a-5400-44a3-ada6-3cd026de6cfe;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/;ApplicationId=d6e130b6-4aaa-4dcc-8d26-c1fa25d4656a`},context:void 0,includeEarlyTests:!1,lintCommand:Oe,prettierCommand:ke,disableLintRules:!1,ignoreAsAnyLintErrors:!0,allowUndefinedLintErrors:!0,perFunctionTimeout:42e4,removeComments:!0,experimentalAgentSdk:!1,agentSdkModel:void 0,agentSdkBudget:void 0,debug:!1,verbose:!1},je=e=>{let t=`testFramework.testSuffix.backendURL.requestSource.secretToken.concurrency.coverageThreshold.context.rootPath.testCommand.coverageCommand.lintCommand.prettierCommand.disableLintRules.greyTestBehaviour.redTestBehaviour.keepErrorTests.keepFailedTests.conditionalKeep.continueOnTestErrors.perFunctionTimeout.dynamicPromptIterations.removeComments.experimentalAgentSdk.agentSdkModel.agentSdkBudget.debug.verbose.progressLogger`.split(`.`).reduce((t,n)=>(0,h.isDefined)(e[n])?{...t,[n]:e[n]}:t,{}),n={...(0,h.isDefined)(e.testStructure)&&{isSiblingFolderStructured:e.testStructure===fe.SIBLING_FOLDER,isRootFolderStructured:e.testStructure===fe.ROOT_FOLDER},...(0,h.isDefined)(e.testFileName)&&{kebabCaseFileName:e.testFileName===he.KEBAB_CASE},...(0,h.isDefined)(e.calculateCoverage)&&{shouldRefreshCoverage:e.calculateCoverage===ve.ON},...(0,h.isDefined)(e.modelName)&&{fixTestsLLMModelName:e.modelName,generateTestsLLMModelName:e.modelName},...(0,h.isDefined)(e.testSuffix)&&{earlyTestFilenameSuffix:`.early.${e.testSuffix}`},...(0,h.isDefined)(e.requestSource)&&{clientSource:e.requestSource===de.IDE?Ce.VSCODE:Ce.GITHUB_ACTION}};return{...t,...n}},Me=new v.Chalk({level:1}),Ne=()=>{},Pe={info:Ne,verbose:Ne,debug:Ne},Fe=[Me.cyan,Me.magenta,Me.green,Me.blue,Me.redBright,Me.cyanBright,Me.magentaBright,Me.greenBright];function Ie(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.codePointAt(n)??0,t=Math.imul(t,16777619);return Fe[Math.abs(t)%Fe.length]}function Le(e,t){let n=(0,h.isDefined)(t.parentName)?`${t.parentName}.${t.methodName}`:t.methodName,r=Ie(n)(`[${n}]`);return{info:(...t)=>e.info(r,...t),verbose:(...t)=>e.verbose(r,...t),debug:(...t)=>e.debug(r,...t)}}var Re=s(((e,t)=>{function n(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports})),ze=s(((e,t)=>{function n(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}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports})),Be=l(Re()),Ve=l(ze()),He,Ue;let B=class{config;constructor(e,t={}){if(!(0,h.isDefined)(e)){this.config=Ae;return}let n=je(e);this.config=(0,h.merge)(Ae,n,t)}getRootPath=()=>this.config.rootPath;isSiblingFolderStructured=()=>this.config.isSiblingFolderStructured;getGitURL=()=>this.config.context?.git?.remoteUrl??this.config.gitURL;getGitTopLevel=()=>this.config.context?.git?.topLevel??this.getRootPath();getTestFramework=()=>this.config.testFramework;getGreyTestBehaviour=()=>this.config.greyTestBehaviour;getRedTestBehaviour=()=>this.config.redTestBehaviour;shouldKeepErrorTests=()=>this.config.keepErrorTests;shouldKeepFailedTests=()=>this.config.keepFailedTests;shouldConditionalKeep=()=>this.config.conditionalKeep;getGeneratedTestStructure=()=>this.config.generatedTestStructure;getGenerateTestsLLMModelName=()=>this.config.generateTestsLLMModelName;isRootFolderStructured=()=>this.config.isRootFolderStructured;getLLMTemperature=()=>this.config.llmTemperature;getLLMTopP=()=>this.config.llmTopP;getClientSource=()=>this.config.clientSource;getBackendURL=()=>this.config.backendURL;getRequestSource=()=>this.config.requestSource;getUserPrompt=()=>this.config.userPrompt;getTestLocation=()=>this.config.testLocation;getCoverageThreshold=()=>this.config.coverageThreshold;getConcurrency=()=>this.config.concurrency;getTestFileFormat=()=>this.config.testFileFormat;getOutputType=()=>this.config.outputType;getShouldRefreshCoverage=()=>this.config.shouldRefreshCoverage;isKebabCaseFileName=()=>this.config.kebabCaseFileName;getEarlyTestFilenameSuffix=()=>this.config.earlyTestFilenameSuffix;getTestSuffix=()=>this.config.testSuffix;getIsAppendPrompt=()=>this.config.isAppendPrompt;getFixTestsLLMModelName=()=>this.config.fixTestsLLMModelName;getDynamicPromptIterations=()=>this.config.dynamicPromptIterations;getWSServerEndpoint=()=>this.config.backendURL.replace(`http://`,`ws://`).replace(`https://`,`wss://`);getAnthropicProxyUrl=()=>new URL(`/anthropic`,this.config.backendURL).href;getSecretToken=()=>this.config.secretToken;getLoggerConfig=()=>this.config.loggerConfig;getContext=()=>this.config.context;getTestCommand=()=>this.config.testCommand;getCoverageCommand=()=>this.config.coverageCommand;getLintCommand=()=>this.config.lintCommand;getPrettierCommand=()=>this.config.prettierCommand;shouldDisableLintRules=()=>this.config.disableLintRules;shouldIgnoreAsAnyLintErrors=()=>this.config.ignoreAsAnyLintErrors;allowUndefinedLintErrors=()=>this.config.allowUndefinedLintErrors;getIncludeEarlyTests=()=>this.config.includeEarlyTests??!1;shouldContinueOnTestErrors=()=>this.config.continueOnTestErrors;getPerFunctionTimeout=()=>this.config.perFunctionTimeout;shouldRemoveComments=()=>this.config.removeComments;getExperimentalAgentSdk=()=>this.config.experimentalAgentSdk;getAgentSdkModel=()=>this.config.agentSdkModel;getAgentSdkBudget=()=>this.config.agentSdkBudget;updateContext=e=>{this.config.context=(0,h.merge)(this.config.context??{},e??{})};updateRootPath=e=>{this.config.rootPath=e};isDebug=()=>this.config.debug??!1;isVerbose=()=>this.config.verbose??!1;getProgressLogger=e=>{let t=this.config.progressLogger??Pe;return(0,h.isDefined)(e)?Le(t,e):t}};B=(0,Ve.default)([(0,_.injectable)(`Singleton`),(0,Be.default)(`design:paramtypes`,[typeof(He=typeof Partial<`u`&&Partial)==`function`?He:Object,typeof(Ue=typeof Partial<`u`&&Partial)==`function`?Ue:Object])],B);var We=new _.Container({autobind:!0,defaultScope:`Singleton`});let Ge=()=>We.get(B);var Ke=class{storage=new m.AsyncLocalStorage;isConsoleEnabled;constructor(e){this.isConsoleEnabled=e}orderedFlush={nextOrder:1,pending:new Map};resetOrder(){this.orderedFlush={nextOrder:1,pending:new Map}}async withBufferedPrinting(e,t){let n=[];try{return await this.storage.run(n,e)}finally{this.flushInOrder(t,n)}}printOrBuffer(e,t){let n=this.storage.getStore();if((0,h.isDefined)(n)){n.push({method:e,message:t});return}this.isConsoleEnabled&&console[e](t)}async flushInOrder(e,t){if(this.orderedFlush.nextOrder===e){this.flushBuffer(t),this.orderedFlush.nextOrder++,this.drainPendingFlushes();return}return new Promise(n=>{this.orderedFlush.pending.set(e,{buffer:t,resolve:n})})}drainPendingFlushes(){let e=this.orderedFlush.pending.get(this.orderedFlush.nextOrder);for(;(0,h.isDefined)(e);)this.orderedFlush.pending.delete(this.orderedFlush.nextOrder),this.flushBuffer(e.buffer),this.orderedFlush.nextOrder++,e.resolve(),e=this.orderedFlush.pending.get(this.orderedFlush.nextOrder)}flushBuffer(e){if(this.isConsoleEnabled)for(let t of e)console[t.method](t.message)}};let qe=function(e){return e.DEFAULT=`default`,e.VERBOSE=`verbose`,e.DEBUG=`debug`,e}({}),Je=function(e){return e.INFO=`info`,e.WARN=`warn`,e}({});function Ye(){return(0,y.randomUUID)()}function Xe(){let e=``;for(let t=0;t<8;t++)e+=`abcdefghijklmnopqrstuvwxyz0123456789`.charAt(Math.floor(Math.random()*36));return e}var Ze=l(Re()),Qe=l(ze()),$e=class{export(e,t){for(let t of e){let e=t.body;if((0,h.isString)(e))console.info(e);else try{console.info(JSON.stringify(e))}catch{console.info(String(e))}}t({code:0})}shutdown(){return Promise.resolve()}};let et=class{loggerProvider;config;constructor(e){this.config=e,this.loggerProvider=new S.LoggerProvider({resource:(0,x.resourceFromAttributes)({[C.ATTR_SERVICE_NAME]:xe,[C.ATTR_SERVICE_VERSION]:Se})}),this.initializeExporters(),this.setGlobalLoggerProvider()}getLogger(e){return this.loggerProvider.getLogger(e)}initializeExporters(){let e=[];if(this.config.consoleEnabled){let t=new $e;e.push(new S.SimpleLogRecordProcessor(t))}if(this.config.azureEnabled&&(0,h.isDefined)(this.config.azureConnectionString)){let t=new b.AzureMonitorLogExporter({connectionString:this.config.azureConnectionString});e.push(new S.BatchLogRecordProcessor(t))}this.loggerProvider=new S.LoggerProvider({processors:e})}setGlobalLoggerProvider(){g.logs.setGlobalLoggerProvider(this.loggerProvider)}};et=(0,Qe.default)([(0,_.injectable)(),(0,Ze.default)(`design:paramtypes`,[Object])],et),l(Re()),l(ze());let V=new class{storage;otelService;otelLogger;isConsoleEnabled;printBuffer;default=this.createLogObject(qe.DEFAULT);verbose=this.createLogObject(qe.VERBOSE);constructor(e){this.storage=new m.AsyncLocalStorage,this.otelService=new et(e),this.otelLogger=this.otelService.getLogger(`ts-agent`),this.isConsoleEnabled=e.consoleEnabled,this.printBuffer=new Ke(e.consoleEnabled)}resetPrintOrder(){this.printBuffer.resetOrder()}async withBufferedPrinting(e,t){return this.printBuffer.withBufferedPrinting(e,t)}info={startLog:(e,...t)=>this.log(g.SeverityNumber.INFO,`Start ${e}`,...t),endLog:(e,...t)=>this.log(g.SeverityNumber.INFO,`End ${e}`,...t),failedLog:(e,...t)=>this.log(g.SeverityNumber.INFO,`Failed ${e}`,...t),defaultLog:(e,...t)=>this.log(g.SeverityNumber.INFO,e,...t)};debug={startLog:(e,...t)=>this.log(g.SeverityNumber.DEBUG,`Start ${e}`,...t),endLog:(e,...t)=>this.log(g.SeverityNumber.DEBUG,`End ${e}`,...t),failedLog:(e,...t)=>this.log(g.SeverityNumber.DEBUG,`Failed ${e}`,...t),defaultLog:(e,...t)=>this.log(g.SeverityNumber.DEBUG,e,...t)};error(e,t,...n){let r=t instanceof Error?`${e} ${t.message} ${t.stack}`:`${e} ${JSON.stringify(t)}`;this.log(g.SeverityNumber.ERROR,r,...n)}getRequestId(){return this.storage.getStore()?.requestId??``}getTraceId(){return this.storage.getStore()?.traceId??``}log(e,t,...n){let r=this.formatMessage(t,...n);this.logToOpenTelemetry(e,r),!(!this.isConsoleEnabled||!this.isLevelEnabled(qe.DEBUG))&&console.info(r)}logToOpenTelemetry(e,t){let n=this.storage.getStore(),r={service:xe,version:Se};(0,h.isDefined)(n)&&((0,h.isDefined)(n.traceId)&&(r.traceId=n.traceId),(0,h.isDefined)(n.requestId)&&(r.requestId=n.requestId),(0,h.isDefined)(n.category)&&(r.category=n.category),(0,h.isDefined)(n.subCategory)&&(r.subCategory=n.subCategory),(0,h.isDefined)(n.testedMethodClass)&&(r.testedMethodClass=n.testedMethodClass),(0,h.isDefined)(n.testedFunction)&&(r.testedFunction=n.testedFunction),(0,h.isDefined)(n.userId)&&(r.userId=n.userId.toString())),this.otelLogger.emit({severityNumber:e,severityText:this.getSeverityText(e),body:t,attributes:r})}getSeverityText(e){switch(e){case g.SeverityNumber.TRACE:return`TRACE`;case g.SeverityNumber.DEBUG:return`DEBUG`;case g.SeverityNumber.INFO:return`INFO`;case g.SeverityNumber.WARN:return`WARN`;case g.SeverityNumber.ERROR:return`ERROR`;case g.SeverityNumber.FATAL:return`FATAL`;default:return`INFO`}}formatMessage(e,...t){let n=this.formatPrefix(),r=(0,h.isDefined)(n)?`${n} ${e}`:e;return this.formatPrint(r,...t)}formatPrint(e,...t){return(0,h.isEmpty)(t)?e:`${e} ${t.map(e=>JSON.stringify(e)).join(` `)}`}withContext=(e,t,n)=>{let r=n.value,i=this.storage;return n.value=function(...e){let t=i.getStore();if(t){let n={...t};return i.run(n,()=>r.apply(this,e))}let n={traceId:Xe(),requestId:Ye()};return i.run(n,()=>r.apply(this,e))},n};addContext(e){let t=this.storage.getStore();(0,h.isDefined)(t)&&(t.category=e.category??t.category,t.subCategory=e.subCategory??t.subCategory,t.testedMethodClass=e.testedMethodClass??t.testedMethodClass,t.testedFunction=e.testedFunction??t.testedFunction,t.userId=e.userId??t.userId)}captureContext({withNewRequestId:e=!1}={}){let t=this.storage.getStore();return t?{...t,...e&&{requestId:Ye()}}:void 0}async runWithContext(e,t){return(0,h.isDefined)(e)?this.storage.run(e,t):t()}isLevelEnabled(e){switch(e){case qe.DEFAULT:return!0;case qe.VERBOSE:return Ge().isVerbose()||Ge().isDebug();case qe.DEBUG:return Ge().isDebug()}}createLogObject(e){return{info:(t,...n)=>{this.isLevelEnabled(e)&&this.printOrBuffer(Je.INFO,this.formatPrint(t,...n))},warn:(t,...n)=>{this.isLevelEnabled(e)&&this.printOrBuffer(Je.WARN,this.formatPrint(t,...n))}}}printOrBuffer(e,t){this.printBuffer.printOrBuffer(e,t)}formatPrefix(){let e=this.storage.getStore();if(!(0,h.isDefined)(e))return``;let t=[];return(0,h.isDefined)(e.traceId)&&t.push(`[${e.traceId}]`),(0,h.isDefined)(e.requestId)&&t.push(`[${e.requestId}]`),(0,h.isDefined)(e.category)&&t.push(`[${e.category}]`),(0,h.isDefined)(e.subCategory)&&t.push(`[${e.subCategory}]`),(0,h.isDefined)(e.testedMethodClass)&&t.push(`[${e.testedMethodClass}]`),(0,h.isDefined)(e.testedFunction)&&t.push(`[${e.testedFunction}]`),t.join(` `)}}({consoleEnabled:!1,azureEnabled:!0,azureConnectionString:`InstrumentationKey=c18a3332-f844-498f-98e0-d818996cf526;IngestionEndpoint=https://eastus2-3.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus2.livediagnostics.monitor.azure.com/;ApplicationId=2150ffe0-cb0f-4b00-9562-d3385b383d74`});function tt(e){return function(t,n,r){return(0,h.isDefined)(e)&&V.addContext(e),V.withContext(t,n,r)}}var nt=class e{rootPath;absolutePath;static EARLY_FILENAME_VAR=`$early_filename`;constructor(e){this.rootPath=f.default.normalizeTrim(Ge().getRootPath());let t=f.default.normalizeTrim(e),n=f.default.normalizeTrim(this.rootPath);if(t===n||t.startsWith(n+f.default.sep))this.absolutePath=t;else{let e=t.replace(/^\//,``);this.absolutePath=f.default.resolve(this.rootPath,e)}}static fromSourceFile(t){let n=f.default.normalizeTrim(t.getFilePath());return new e(f.default.relative(f.default.normalizeTrim(Ge().getRootPath()),n))}static fromAbsolutePath(t){let n=f.default.normalizeTrim(t);return new e(f.default.relative(f.default.normalizeTrim(Ge().getRootPath()),n))}static fromRelativePath(t){return new e(t)}getRelativeFilePath(){return f.default.relative(this.rootPath,this.absolutePath)}getAbsoluteFilePath(){return this.absolutePath}async isFileExists(){try{return(await p.default.stat(this.absolutePath)).isFile()}catch{return!1}}async isDirectoryExists(){try{return(await p.default.stat(this.absolutePath)).isDirectory()}catch{return!1}}async createDirectory(e){await p.default.mkdir(this.absolutePath,{recursive:e?.recursive??!0})}async getText(){try{return await p.default.readFile(this.absolutePath,`utf8`)}catch{return``}}async upsert(e){let t=f.default.dirname(this.absolutePath);await p.default.mkdir(t,{recursive:!0}),await(await this.isFileExists()?p.default.appendFile(this.absolutePath,e):p.default.writeFile(this.absolutePath,e)),V.info.defaultLog(`Upserted file`,{path:this.getRelativeFilePath()})}async replace(e){let t=f.default.dirname(this.absolutePath);await p.default.mkdir(t,{recursive:!0}),await p.default.writeFile(this.absolutePath,e),V.info.defaultLog(`Replaced file`,{path:this.getRelativeFilePath()})}async delete(){try{await p.default.unlink(this.absolutePath),V.info.defaultLog(`Deleted file`,{path:this.getRelativeFilePath()})}catch{}}};let rt={WIN32:`win32`,DARWIN:`darwin`,LINUX:`linux`},it={JAVASCRIPT:`javascript`,TYPESCRIPT:`typescript`,PYTHON:`python`},at=e=>{let t=Ge().getRootPath();return f.default.resolve(t,e)},ot=e=>{let t=Ge().getRootPath(),n=f.default.normalize(e);return f.default.relative(t,n)},st=e=>({".js":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".jsx":`javascript`,".ts":`typescript`,".tsx":`typescript`,".py":`python`})[e.toLowerCase()]??`javascript`;function ct(e){return st((0,f.extname)(e))}function H(e){return st((0,f.extname)(e))===`typescript`}function lt(e){return st((0,f.extname)(e))===it.PYTHON}function ut(e){let t=Ge().getRootPath();if(!(0,h.isDefined)(t))throw Error(`Workspace root path is not defined`);if((0,h.isEmpty)(e))return f.default.normalize(t);let n=f.default.normalize(t),r=f.default.normalize(e);if(process.platform===rt.WIN32){let t=n.split(`:`)[0].toUpperCase(),i=r.split(`:`)[0].toUpperCase();if(t!==i&&!i.startsWith(t))return e}return f.default.relative(n,r)}function dt(e){return e.startsWith(`../`)?`../${e}`:e.startsWith(`./`)?`.${e}`:e}function ft(e){let t=f.default.normalize(at(e)),n=f.default.normalize((0,T.default)([`package.json`,`project.json`],{cwd:t})??``);if(!n)return``;let r=ot((0,f.dirname)(n));return r.startsWith(`/`)?r.slice(1):r}function pt(e,t,n){if(!ht(e))return e;let r=n===``?t:t.replace(n,``),i=n===``?_t(r):gt(r),a=r.split(`/`).slice(0,-1),o=mt(e,`../`),s=o>0?a.slice(0,-o).join(`/`):(0,f.dirname)(r),c=e.replaceAll(`../`,``).replaceAll(`./`,``);return f.default.join(i,s,c)}function mt(e,t){return e.split(t).length-1}function ht(e){return e.startsWith(`../`)||e.startsWith(`./`)}function gt(e){let t=mt(e,`/`);return`../`.repeat(t-1)}function _t(e){let t=mt(e,`/`);return`../`.repeat(t+1)}function vt(e){return e?.includes(`node_modules/`)}let yt=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);function bt(e,t){let n=f.default.isAbsolute(e)?e:at(e);return(0,T.default)(t,{cwd:n})}function xt(e,t){let n=bt(e,t);if(!(0,h.isDefined)(n))return;let r=w.readFileSync(n,`utf8`);return JSON.parse(r)}function St(e){return xt(e,`package.json`)}function Ct(e,t){let{dependencies:n={},devDependencies:r={}}=e;return Object.keys({...r,...n}).includes(t)}let wt=[{path:`eslint.config.js`,isFlat:!0},{path:`eslint.config.cjs`,isFlat:!0},{path:`eslint.config.mjs`,isFlat:!0},{path:`eslint.config.ts`,isFlat:!0},{path:`eslint.config.mts`,isFlat:!0},{path:`eslint.config.cts`,isFlat:!0},{path:`.eslintrc`,isFlat:!1},{path:`.eslintrc.js`,isFlat:!1},{path:`.eslintrc.cjs`,isFlat:!1},{path:`.eslintrc.mjs`,isFlat:!1},{path:`.eslintrc.json`,isFlat:!1},{path:`.eslintrc.yaml`,isFlat:!1},{path:`.eslintrc.yml`,isFlat:!1}],Tt=[`@typescript-eslint/no-undefined`,`unicorn/no-useless-undefined`,`no-undefined`];async function Et(e){for(let{path:t,isFlat:n}of wt){let r=f.default.join(e,t);if(await nt.fromAbsolutePath(r).isFileExists())return{path:r,isFlat:n}}return St(e)?.eslint?{path:bt(e,`package.json`),isFlat:!1}:{path:null,isFlat:!1}}let Dt={GET_TESTABLES:`get-testables`,GET_COVERAGE:`get-coverage`,GENERATE_COVERAGE:`generate-coverage`,SET_COVERAGE:`set-coverage`,GENERATE_TESTS:`generate-tests`,INITIALIZATION:`initialization`,GET_TESTED_CODE_DATA_SOURCE:`get-tested-code-data-source`,DYNAMIC_PROMPT:`dynamic-prompt`,TEST_VALIDATION:`test-validation`},Ot={CODE_EXTRACTOR:`code-extractor`,CODE_REFINEMENT:`code-refinement`,TEST_MANAGEMENT:`test-management`,TEST_VALIDATOR:`test-validator`,CONFIG_FILE:`config-file`,COMMAND_EXECUTION:`command-execution`},kt=[`.jsx`,`.tsx`],At=[`it`,`test`,`it.each`,`test.each`],jt=function(e){return e.Default=`default`,e.ObjectDefault=`object-default`,e.Named=`named`,e.Unknown=`unknown`,e.NotExported=`not-exported`,e}({}),Mt=function(e){return e.PRIVATE=`private`,e.PROTECTED=`protected`,e.PUBLIC=`public`,e}({}),Nt=function(e){return e.REACT=`react`,e.ANGULAR=`angular`,e}({}),Pt=`unknown`,Ft=(0,O.promisify)(D.default.exec);async function It(e,{cwd:t=Ge().getRootPath(),timeout:n=1e4}={}){return(await Ft(e,{cwd:t,maxBuffer:500*1024,timeout:n}))?.stdout?.toString()??``}let Lt=e=>{let t=at(e);return(0,T.default)(`jest.config.+(js|ts|mjs|cjs|json)`,{cwd:t})},Rt=e=>(0,h.isObject)(e)&&(0,h.isString)(e.rootDir),zt=async e=>{let t;if(V.addContext({subCategory:Ot.CONFIG_FILE}),(0,h.isDefined)(e)){let n=Lt(e);n!==null&&(t=(0,f.dirname)(n))}t??=Ge().getRootPath();let n;try{if(n=await It(`npx jest --showConfig`,{cwd:t}),!(0,h.isString)(n))throw V.info.defaultLog(`Jest config return is not a string`,n),Error(`Jest config return is not a string`);let e=JSON.parse(n);if((0,h.isObject)(e)&&(0,h.isArray)(e.configs)&&e.configs.every(e=>Rt(e)))return{projectConfigs:e.configs,globalConfig:e.globalConfig,configs:e.configs}}catch(e){V.info.defaultLog(`Cannot read jest config`,(0,h.getErrorMessage)(e)),V.info.defaultLog(`Failed reading jest config`,e,(0,h.getErrorMessage)(e));return}V.info.defaultLog(`Invalid jest config or config in not supported format`)},Bt=async()=>{let e=[Ge().getRootPath()],t=f.default.join(`node_modules`,`.prisma`,`client`,`index.d.ts`),n=e.map(e=>f.default.join(e,t)).map(e=>nt.fromAbsolutePath(e));return(await(0,h.filterAsync)(n,e=>e.isFileExists())).map(e=>e.getAbsoluteFilePath())},Vt=async()=>{try{let e=Ge().getRootPath();if(!(0,h.isDefined)(e))return[];let t=await(0,k.getSchemaWithPathOptional)(``,``,{cwd:e});if(!(0,h.isDefined)(t))return[];let n=t.schemas.map(e=>e[1]),r=new Set;for(let e of n){let n=(await(0,k.getConfig)({datamodel:e,ignoreEnvVarErrors:!0})).generators;for(let e of n)if((0,h.isDefined)(e.output?.value)){let n=f.default.join(f.default.resolve(t.schemaRootDir,e.output.value),`index.d.ts`);await nt.fromAbsolutePath(n).isFileExists()&&r.add(n)}}return[...r]}catch(e){return V.error(`Failed to get prisma typings paths`,e),[]}},Ht=async()=>(await Promise.all([Bt(),Vt()])).flat(),Ut=async(e,t=!1,n)=>{let r=`!**/node_modules/**`;if(t)return new E.Project({useInMemoryFileSystem:!0,compilerOptions:n});let i=H(e),a=Wt((0,f.dirname)(at(e)),Ge().isSiblingFolderStructured());if(!i&&!(0,h.isDefined)(a)){let t=await Kt(e);if(!(0,h.isDefined)(t)||(0,h.isEmpty)(t))throw Error(`Cannot find source code path in jest config`);let n=new E.Project({compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0},useInMemoryFileSystem:!1});return n.addSourceFilesAtPaths([...t,r]),n}if(!i&&(0,h.isDefined)(a)){let t=new E.Project({tsConfigFilePath:a,compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0}}),n=await Kt(e);return t.addSourceFilesAtPaths([...n,r]),t}let o=new E.Project({tsConfigFilePath:a,compilerOptions:{maxNodeModuleJsDepth:0}}),s=await Ht();for(let e of s)o.addSourceFileAtPath(e);return o},Wt=(e,t)=>{let n;try{n=Gt(e)}catch{t&&(n=Gt((0,f.dirname)(e)))}return n},Gt=e=>{let t=e,n=/^(tsconfig|jsconfig).*\.json$/;for(;t!==(0,f.dirname)(t);){let e=(0,f.join)(t,`tsconfig.json`),r=(0,f.join)(t,`jsconfig.json`);if(!(0,w.existsSync)(t))return Gt((0,f.dirname)(t));if((0,w.existsSync)(e))return e;if((0,w.existsSync)(r))return r;let i=(0,w.readdirSync)(t);for(let e of i)if(n.test(e))return(0,f.join)(t,e);t=(0,f.dirname)(t)}},Kt=async e=>{let t=await zt(e);if((0,h.isDefined)(t)){let e=t?.configs[0].roots.map(e=>f.default.join(e,`**/*.{ts,js,tsx,jsx}`));if(!(0,h.isEmpty)(e))return e}return[at(ft(e))]};var qt=l(Re()),Jt=l(ze());let Yt=`The ts-morph project is not initialized.`,U=new class{storage=new m.AsyncLocalStorage;_project;clear(){this._project=void 0}async init(e,t,n){let r=at(e);if((0,h.isDefined)(this._project))return this._project.addSourceFileAtPathIfExists(r);this._project=await Ut(e,t,n);let i=this.storage.getStore();if((0,h.isDefined)(i))return this._project.addSourceFileAtPathIfExists(r)}add(e,t){let n=at(e),r=this.storage.getStore()?.getProject();if(!(0,h.isDefined)(r))throw Error(Yt);return r.createSourceFile(n,t,{overwrite:!0})}update(e,t){let n=this.get(e);return n.replaceWithText(t),n}addFile(e){(0,h.isDefined)(this._project)&&this._project.addSourceFileAtPathIfExists(e)}removeFile(e){if(!(0,h.isDefined)(this._project))return;let t=this._project.getSourceFile(e);(0,h.isDefined)(t)&&this._project.removeSourceFile(t)}async refreshFromFileSystem(e){if(!(0,h.isDefined)(this._project))return;let t=at(e),n=this._project?.getSourceFile(e)??this._project?.getSourceFile(t);if((0,h.isDefined)(n)){let e=n.getFilePath();this._project.removeSourceFile(n),this._project.addSourceFileAtPath(e)}}get(e){let t=at(e),n=this.storage.getStore()?.getProject();if(!(0,h.isDefined)(n))throw Error(Yt+` store`);let r=n.getSourceFile(t);if(!(0,h.isDefined)(r))throw Error(`The source file is absent. ${e}`);return r}async save(e){await this.get(e).save()}async delete(e){await this.get(e).deleteImmediately()}getOrUndefined(e){let t=at(e);return this._project?.getSourceFile(t)}withContext=(e,t,n)=>{let r=n.value,i=this.storage;if((0,h.isDefined)(i.getStore()))return n;let a=()=>this._project;return n.value=function(...e){let t={getProject:a};return i.run(t,()=>r.apply(this,e))},n}},Xt=U.withContext,Zt=async e=>{class t{async fn(){return e()}}(0,Jt.default)([Xt,(0,qt.default)(`design:type`,Function),(0,qt.default)(`design:paramtypes`,[]),(0,qt.default)(`design:returntype`,Promise)],t.prototype,`fn`,null),await new t().fn()},Qt=e=>{let t=e?.asKind(E.SyntaxKind.ExpressionStatement)?.getExpression();if(!(0,h.isDefined)(t))return;let n=t.asKind(E.SyntaxKind.CallExpression)?.getArguments()?.at(-1),r=n?.asKind(E.SyntaxKind.ArrowFunction)?.getBody(),i=n?.asKind(E.SyntaxKind.FunctionExpression)?.getBody();return r?.asKind(E.SyntaxKind.Block)??i?.asKind(E.SyntaxKind.Block)},$t=e=>E.Node.isExpressionStatement(e)&&e.getFirstChildByKind(E.SyntaxKind.CallExpression)?.getFirstChildByKind(E.SyntaxKind.Identifier)?.getText()===`describe`,en=e=>e.getStatements().filter(e=>$t(e)),tn=e=>{let t=e.getExpression().getFirstChild()?.getText();return!(0,h.isDefined)(t)||(0,h.isEmpty)(t)?!1:At.some(e=>t.startsWith(e))},nn=e=>{let t=Qt(e);return(0,h.isDefined)(t)?t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement).some(e=>tn(e)):!1},rn=e=>{let t=Qt(e);return(0,h.isDefined)(t)?t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement).filter(e=>$t(e)&&nn(e)):[]},an=e=>{let t=Qt(e);if((0,h.isDefined)(t))return t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement).find(e=>$t(e)&&nn(e))},on=e=>{let t=an(e);return(0,h.isDefined)(t)},sn=e=>{let t=Qt(e);if(!(0,h.isDefined)(t))return!0;let n=t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement);if((0,h.isEmpty)(n))return!0;let r=new Set([`beforeEach`,`afterEach`,`beforeAll`,`afterAll`]);return n.every(e=>{let t=e.getExpressionIfKind(E.SyntaxKind.CallExpression)?.getExpressionIfKind(E.SyntaxKind.Identifier);return(0,h.isDefined)(t)?r.has(t.getText()):!1})},cn=e=>{if(e.isNamedExport?.())return jt.Named;if(e.isDefaultExport?.())return jt.Default;let t=e?.getParent();if((0,h.isDefined)(t)){if(t.isNamedExport?.())return jt.Named;if(t.isDefaultExport?.())return jt.Default}return e.isExportDefaultObject?.()??un(e.getSourceFile(),e.getName?.())?jt.ObjectDefault:jt.NotExported},ln=(e,t)=>(0,h.isDefined)(e)?cn(e):(0,h.isDefined)(t)?t.isNamedImport?jt.Named:jt.Default:jt.Unknown;function un(e,t){let[n]=e.getExportAssignments()??[];return n?.getDescendantsOfKind(E.SyntaxKind.Identifier).some(e=>(e.getSymbol()?.getEscapedName()??e.getText())===t)}function dn(e,t){let n=en(U.get(e)),r=n.find(e=>e.getText().includes(t))??n[0],i=rn(r),a=[],o=(0,h.isEmpty)(i)?[r]:i;for(let e of o){let t=Qt(e);(0,h.isDefined)(t)&&a.push(...t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement).filter(e=>tn(e)))}return a}let W=e=>e.getFirstDescendantByKind(E.SyntaxKind.StringLiteral)?.getLiteralValue(),fn=e=>W(e),pn=e=>W(e),mn=(e,t)=>{let n=e.getFullText().slice(0,Math.max(0,t)).split(`
32006
32006
  `);return{line:n.length,column:(n.at(-1)?.length??0)+1}},hn=(e,t)=>{let n=t.getStart(),r=t.getEnd(),{line:i,column:a}=mn(e,n),{line:o,column:s}=mn(e,r);return{startLine:i,startColumn:a,startIndex:n,endLine:o,endColumn:s,endIndex:r}},gn=e=>e.getDescendantsOfKind(E.SyntaxKind.ExpressionStatement).filter(e=>tn(e)),_n=(e,t,n,r)=>{let i=r?`.tsx`:`.ts`,a=t+Date.now()+(0,y.randomUUID)()+i;return e.createSourceFile(a,n)},vn=e=>e.getDescendantsOfKind(E.SyntaxKind.CallExpression).reduce((e,t)=>{let n=t.getExpression(),r=n.getParentIfKind(E.SyntaxKind.VariableDeclaration);return(0,h.isDefined)(r)&&n.getText()===`require`&&e.push(r),e},[]),yn=e=>{let t=e.getFirstChildByKind(E.SyntaxKind.CallExpression);if(!(0,h.isDefined)(t))return;let[n]=t.getArguments();if(!(!(0,h.isDefined)(n)||n.getKind()!==E.SyntaxKind.StringLiteral))return n.getText().slice(1,-1)},bn=e=>{let t=[`${Ge().getEarlyTestFilenameSuffix()}.ts`,`.test.ts`,`.spec.ts`,`.test.tsx`,`.spec.tsx`,`.test.js`,`.spec.js`,`.test.jsx`,`.spec.jsx`],n=e.getFilePath(),r=`_`+(0,y.randomUUID)()+`_temp`;for(let e of t)if(n.endsWith(e))return n.slice(0,-e.length)+r+e;let i=n.split(`.`);return i[i.length-2]+=r,i.join(`.`)},xn=(e,t=e.getFullText())=>{let n=bn(e);return e.getProject().createSourceFile(n,t)},Sn=e=>e.getSymbol()?.getDeclarations()?.[0]?.getSourceFile()??e.getAliasSymbol()?.getDeclarations()?.[0]?.getSourceFile(),Cn=(e,t)=>{let n=e.getRelativePathTo(t.getFilePath());n=n.replaceAll(`\\`,`/`);let r=f.default.extname(n);return n=n.replaceAll(r,``),n.startsWith(`.`)||(n=`./`+n),n},wn=[E.SyntaxKind.JsxElement,E.SyntaxKind.JsxOpeningElement,E.SyntaxKind.JsxClosingElement,E.SyntaxKind.JsxExpression,E.SyntaxKind.JsxSelfClosingElement,E.SyntaxKind.JsxAttributes,E.SyntaxKind.JsxAttribute,E.SyntaxKind.JsxFragment,E.SyntaxKind.JsxOpeningFragment,E.SyntaxKind.JsxClosingFragment,E.SyntaxKind.JsxNamespacedName,E.SyntaxKind.JsxSpreadAttribute,E.SyntaxKind.JsxText,E.SyntaxKind.JsxTextAllWhiteSpaces],G=e=>wn.some(t=>(0,h.isDefined)(e.getFirstDescendantByKind(t))),Tn=e=>wn.some(t=>(0,h.isDefined)(e.getParentIfKind(t))),En=e=>{let t=e.compilerType;if(`id`in t&&(0,h.isNumber)(t.id)){let e=t.id;return e===0?null:e}return null},Dn=new Set(`withRouter.connect.withAuth.withStyles.withTheme.forwardRef.styled.withErrorBoundary.withSuspense.withProps.withState.withHandlers.withContext.withApollo.withRedux.withIntl.withTranslation.withFormik.withViewport.withLogger.withMemo.withDefaults.withReduxForm.withPermissions.withData.withTracker.withServices.withFirebase.withNavigation.withHeader.withFooter`.split(`.`)),On=`anonymousFunction`;var kn=class{exportedDeclarations;constructor(e,t){this.sourceFile=e,this.moduleInfo=t;let n=this.moduleInfo.getExports();this.exportedDeclarations=[n.defaultExport,...n.namedExports].filter(Boolean)}getAllTestables(){return[...this.getClassesWithMethods(),...this.getFunctionsDeclarations(),...this.getFunctionsExpressions(),...this.getArrowFunctionsExpressions(),...this.getHOCs(),...this.getObjectMethods()]}getAllSerializedTestables(){return this.getAllTestables().map(e=>(0,h.removeNestedField)(e,[`node`,`parent`]))}getAllMethodsCount(){return this.getAllTestables().filter(e=>e.type!==`class`).length}getHOCs(){return this.sourceFile.getVariableStatements().filter(e=>{let t=e.getFirstDescendantByKind(E.SyntaxKind.CallExpression),n=t?.getFirstDescendantByKind(E.SyntaxKind.PropertyAccessExpression),r=t?.getFirstDescendantByKind(E.SyntaxKind.Identifier);return[n?.getText(),r?.getText()].some(e=>(0,h.isDefined)(e)?[...Dn.values()].some(t=>e.includes(t)):!1)}).map(e=>{let t=e.getFirstDescendantByKind(E.SyntaxKind.VariableDeclaration)?.getFirstChildByKind(E.SyntaxKind.Identifier)?.getText(),n=this.isEntityExported(t)||e.isExported();return{...this.getLocationPivot(e),name:t,type:`function`,node:e,canCreateTests:n}})}getFunctionsDeclarations(){return this.sourceFile.getFunctions().map(e=>{let t=e.getName()??On,n=this.isEntityExported(t)||e.isExported();return{...this.getLocationPivot(e),name:t,type:`function`,node:e,canCreateTests:n}})}getFunctionsExpressions(){return this.sourceFile.getDescendantsOfKind(E.SyntaxKind.FunctionExpression).filter(e=>e.getParentIfKind(E.SyntaxKind.ExportAssignment)?.isExportEquals()??!(this.isCallbackFunction(e)||this.isInnerFunction(e)||this.isJSXFunction(e))).map(e=>{let t=e.getName()??this.getArrowFunctionName(e)??On,n=this.isEntityExported(t);return{...this.getLocationPivot(e),name:t,type:`function`,node:e,canCreateTests:n}})}getArrowFunctionsExpressions(){return this.sourceFile.getDescendantsOfKind(E.SyntaxKind.ArrowFunction).filter(e=>e.getParentIfKind(E.SyntaxKind.ExportAssignment)?.isExportEquals()??!(this.isCallbackFunction(e)||this.isInnerFunction(e)||this.isJSXFunction(e))).map(e=>{let t=this.getArrowFunctionName(e)??On,n=this.isEntityExported(t)||this.isEntityExportedWithThis(e);return{...this.getLocationPivot(e),name:t,type:`function`,node:e,canCreateTests:n}})}isCallbackFunction(e){return e.getParent()?.getKind()===E.SyntaxKind.CallExpression}isJSXFunction(e){return Tn(e)}isInnerFunction(e){let t=e.getParent(),n=0;for(;(0,h.isDefined)(t)&&t.getKind()!==E.SyntaxKind.SourceFile&&n<20;){if(t.getKind()===E.SyntaxKind.ArrowFunction)return!0;t=t.getParent(),n++}return!1}getArrowFunctionName(e){let t=e.getParent();if(t?.getKind()===E.SyntaxKind.BinaryExpression&&t?.getFirstChild()?.getKind()===E.SyntaxKind.PropertyAccessExpression)return e.getParent()?.getFirstChildByKind(E.SyntaxKind.PropertyAccessExpression)?.getName();let n=e.getFirstAncestorByKind(E.SyntaxKind.VariableDeclaration);if((0,h.isDefined)(n))return n.getName();let r=e.getFirstAncestorByKind(E.SyntaxKind.PropertyAssignment);if((0,h.isDefined)(r))return r.getName()}getClasses(){return this.sourceFile.getClasses().map(e=>{let t=e.getName(),n=this.isEntityExported(t)||e.isDefaultExport(),r=n?this.getClassMethods(e,n).some(e=>e.canCreateTests):!1;return{...this.getLocationPivot(e),name:t,type:`class`,node:e,canCreateTests:r}})}getClassesWithMethods(){return this.getClasses().flatMap(e=>[e,...this.getClassMethods(e.node,e.canCreateTests)])}getClassMethods(e,t){return e.getMethods().map(n=>{let r=n.hasModifier(E.SyntaxKind.PrivateKeyword),i=n.getName().startsWith(`#`),a=r||i;return{...this.getLocationPivot(n),parent:e,parentName:e.getName()??``,type:`method`,node:n,name:n.getName(),canCreateTests:t&&!a}})}getObjectMethods(){let e=this.sourceFile.getDescendantsOfKind(E.SyntaxKind.BinaryExpression).map(e=>e.getRight()).filter(e=>E.Node.isObjectLiteralExpression(e)),t=this.sourceFile.getExportAssignments().map(e=>e.getExpression()).filter(e=>E.Node.isObjectLiteralExpression(e));return[...e,...t].flatMap(e=>e.getProperties()).filter(e=>E.Node.isMethodDeclaration(e)).map(e=>({...this.getLocationPivot(e),type:`object-method`,node:e,name:e.getName(),canCreateTests:!0}))}getLocationPivot(e){return hn(this.sourceFile,e)}isEntityExported(e){return(0,h.isDefined)(e)&&!(0,h.isEmpty)(e)?this.exportedDeclarations.includes(e):!1}isEntityExportedWithThis(e){let t=e.getParent()?.getChildren()??[];return t[0]?.getFirstChild()?.getKind()===E.SyntaxKind.ThisKeyword&&t[1]?.getKind()===E.SyntaxKind.EqualsToken&&t[2]===e}findTestable(e,t,n){return this.getAllTestables().find(r=>r.name===t&&r.type===e?r.type===`method`?r.parentName===n:!0:!1)}};let An=`default`;var jn=class{constructor(e,t){this.sourceFile=e,this.isUsingJSX=t}getImports(){return[...this.getESMImportsNodes(),...this.getCJSImportsNodes()].map(e=>({name:`Import`,location:hn(this.sourceFile,e),node:e,type:`import`,sourceValue:(E.Node.isImportDeclaration(e)?e.getModuleSpecifierValue():e.getFirstDescendantByKind(E.SyntaxKind.StringLiteral)?.getLiteralValue())??``}))}getCJSImportsNodes(){return this.sourceFile.getVariableStatements().filter(e=>(e.getFirstDescendantByKind(E.SyntaxKind.CallExpression)?.getExpression())?.getText()===`require`)}getESMImportsNodes(){return this.sourceFile.getImportDeclarations()}isESM(){let e=this.sourceFile.getImportDeclarations().length>0,t=this.sourceFile.getExportDeclarations().length>0||this.sourceFile.getExportedDeclarations().size>0,n=this.sourceFile.getDescendantsOfKind(E.SyntaxKind.ExportAssignment).length>0;return e||t||n}getCJSExports(){let e=[],t=``,n=`module.exports`,r=`exports`;for(let i of this.sourceFile.getDescendantsOfKind(E.SyntaxKind.ExpressionStatement)){let a=i.getExpression(),o=a.getText().trim(),s=a.asKind(E.SyntaxKind.BinaryExpression);if(!o.startsWith(n)&&!o.startsWith(r)||!(0,h.isDefined)(s))continue;let c=s.getLeft(),l=c.getText(),u=c.asKind(E.SyntaxKind.PropertyAccessExpression),d=u?.getName()??``,f=c.getKind()===E.SyntaxKind.PropertyAccessExpression,p=s.getRight(),m=f&&u?.getExpression().getText()===n,g=f&&u?.getExpression().getText()===r;if(m&&d===An){t=p.getText();continue}if(m||g){e.push(d);continue}if(l!==n)continue;let _=t=>{let n=t.asKind(E.SyntaxKind.ObjectLiteralExpression);if((0,h.isDefined)(n))for(let t of n.getProperties()){if(t.getKind()===E.SyntaxKind.PropertyAssignment||t.getKind()===E.SyntaxKind.ShorthandPropertyAssignment||t.getKind()===E.SyntaxKind.MethodDeclaration){let n=t.getName();e.push(n)}if(t.getKind()===E.SyntaxKind.PropertyAssignment){let e=t.getInitializer();(0,h.isDefined)(e)&&_(e)}}},v=t=>{let n=t.asKind(E.SyntaxKind.FunctionDeclaration)?.getBody()?.asKind(E.SyntaxKind.Block);if((0,h.isDefined)(n))for(let t of n.getStatements()){let n=((t.asKind(E.SyntaxKind.ExpressionStatement)?.getExpression())?.asKind(E.SyntaxKind.BinaryExpression)?.getLeft())?.asKind(E.SyntaxKind.PropertyAccessExpression);n?.getExpression().getKind()===E.SyntaxKind.ThisKeyword&&e.push(n.getName())}},y=t=>{let n=t.asKind(E.SyntaxKind.FunctionDeclaration)?.getName();if((0,h.isDefined)(n))for(let t of this.sourceFile.getStatements()){let r=((t.asKind(E.SyntaxKind.ExpressionStatement)?.getExpression())?.asKind(E.SyntaxKind.BinaryExpression)?.getLeft())?.asKind(E.SyntaxKind.PropertyAccessExpression);r?.getExpression().getText()===`${n}.prototype`&&e.push(r.getName())}};if(p.getKind()===E.SyntaxKind.ObjectLiteralExpression){_(p);continue}if(p.getKind()===E.SyntaxKind.Identifier){let t=p.asKind(E.SyntaxKind.Identifier),n=t?.findReferences().map(e=>e.getDefinition().getNode().getParent()).filter(e=>(0,h.isDefined)(e)).filter(e=>e.getKind()===E.SyntaxKind.VariableDeclaration);if(!(0,h.isDefined)(n))continue;for(let t of n){let n=t.getInitializer()?.asKind(E.SyntaxKind.ObjectLiteralExpression);if((0,h.isDefined)(n)){for(let t of n.getProperties())if(t.getKind()===E.SyntaxKind.PropertyAssignment||t.getKind()===E.SyntaxKind.ShorthandPropertyAssignment){let n=t.getName();e.push(n)}}}let r=t?.findReferences().map(e=>e.getDefinition().getNode().getParent()).filter(e=>e?.getKind()===E.SyntaxKind.FunctionDeclaration);if(!(0,h.isDefined)(r))continue;for(let e of r)v(e),y(e)}if(p.isKind(E.SyntaxKind.NewExpression)){let e=p.asKind(E.SyntaxKind.NewExpression);(0,h.isDefined)(e)&&(t=e.getExpression().getText());continue}t=p.getText()}return{namedExports:e,defaultExport:t}}getESMExports(){let e=``,t=[],n=!1;for(let r of this.sourceFile.getExportAssignments()){r.isExportEquals()||(n=!0);let i=r.getExpression();if(i.getKind()===E.SyntaxKind.Identifier){e=i.getText();continue}let a=r.getFirstChildByKind(E.SyntaxKind.ObjectLiteralExpression);if((0,h.isDefined)(a)){for(let e of a.getProperties())if(e.getKind()===E.SyntaxKind.PropertyAssignment||e.getKind()===E.SyntaxKind.ShorthandPropertyAssignment||e.getKind()===E.SyntaxKind.MethodDeclaration){let n=e.getName();t.push(n)}}}let r=this.sourceFile.getExportedDeclarations();if(!(n&&r.size===1&&[...r.keys()][0]===An))for(let[n,i]of r)if(n===An){let t=(i[0]?.getFirstChildByKind(E.SyntaxKind.Identifier))?.getText()?.trim()??On;(0,h.isDefined)(t)&&(e=t)}else t.push(n);return{defaultExport:e,namedExports:t}}hasRequire(){return this.sourceFile.getDescendantsOfKind(E.SyntaxKind.CallExpression).some(e=>e.getExpression().getText()===`require`)}transformRequiresToImports(){let e=_n(this.sourceFile.getProject(),`transformRequiresToImports`,this.sourceFile.getFullText(),this.isUsingJSX),t;try{let n=e.getVariableStatements();for(let e of n){let t=e.getFirstDescendantByKind(E.SyntaxKind.CallExpression),n=t?.getExpression();if(!(0,h.isDefined)(t)||!(0,h.isDefined)(n)||n.getText()!==`require`)continue;let r=t.getFirstDescendantByKind(E.SyntaxKind.StringLiteral)?.getLiteralValue();if(!(0,h.isDefined)(r))continue;let i=e.getDeclarations()?.[0]?.getNameNode()?.getText();if(!(0,h.isDefined)(i))continue;let a=`import ${i} from "${r}";`;e.replaceWithText(a)}t=e.getFullText()}finally{e.getProject().removeSourceFile(e)}return t}getExports(){return this.isESM()?this.getESMExports():this.getCJSExports()}},Mn=class{tests;constructor(e){this.sourceFile=e}getDescribes(){return en(this.sourceFile).map(e=>{let t=fn(e);return(0,h.isDefined)(t)?{node:e,name:t,location:hn(this.sourceFile,e),type:`describe`}:null}).filter(e=>(0,h.isDefined)(e))}getTests(){return(0,h.isDefined)(this.tests)||(this.tests=gn(this.sourceFile).map(e=>{let t=hn(this.sourceFile,e),n=pn(e);return(0,h.isDefined)(n)?{node:e,name:n,location:t,type:`test`}:null}).filter(e=>(0,h.isDefined)(e))),this.tests}getDescribeTests(e){return gn(e.node).map(e=>{let t=pn(e);return(0,h.isDefined)(t)?{node:e,name:t,location:hn(this.sourceFile,e),type:`test`}:null}).filter(e=>(0,h.isDefined)(e))}},Nn=class{sourceFile;tests;testables;moduleInfo;constructor(e,t){this.filePath=t;let n=!0;try{let t=new E.Project({useInMemoryFileSystem:!0,skipAddingFilesFromTsConfig:!0,skipFileDependencyResolution:!0,skipLoadingLibFiles:!0}),r=_n(t,`ast`,e,!0);G(r)?this.sourceFile=r:(t.removeSourceFile(r),this.sourceFile=_n(t,`ast`,e,!1),n=!1)}catch{throw Error(`Cannot parse file content`)}this.moduleInfo=new jn(this.sourceFile,n),this.testables=new kn(this.sourceFile,this.moduleInfo),this.tests=new Mn(this.sourceFile)}isReactFile(){let e=(0,f.extname)(this.filePath??this.sourceFile.getFilePath());return kt.includes(e)||this.isFileContainsImport(`react`)}isFileContainsImport(e){return this.moduleInfo.getImports().some(t=>t.sourceValue.includes(e))}checkIsJSDoc(e,t,n){return t===E.SyntaxKind.MultiLineCommentTrivia?e.slice(n,n+3)===`/**`&&e.slice(n,n+5)!==`/***/`:!1}getLineRange(e,t){let n=this.sourceFile.compilerNode,r=n.getLineStarts(),{line:i}=n.getLineAndCharacterOfPosition(e),{line:a}=n.getLineAndCharacterOfPosition(t);return{start:r[i]??0,end:r[a+1]??this.sourceFile.getEnd()}}stripComments(e=()=>!0){let t=new Set,n=[],r=this.sourceFile.getFullText(),i=(e,r)=>{for(let i of[...e.getLeadingCommentRanges(),...e.getTrailingCommentRanges()]){let e=i.getPos(),a=i.getEnd(),o=e+`,`+a;if(t.has(o))continue;t.add(o);let s=i.getText(),c=this.checkIsJSDoc(r,i.getKind(),e);n.push({start:e,end:a,text:s,width:i.getWidth(),isJSDoc:c})}};i(this.sourceFile,r),this.sourceFile.forEachDescendant(e=>i(e,r));let a=n.filter(e).map(e=>{let{start:t,end:n}=this.getLineRange(e.start,e.end);return(0,h.isEmpty)(r.slice(t,e.start).trim())&&(0,h.isEmpty)(r.slice(e.end,n).trim())?{start:t,end:n}:{start:e.start,end:e.end}}).toSorted((e,t)=>t.start-e.start);for(let e of a)this.sourceFile.removeText(e.start,e.end);return this.sourceFile.getFullText()}};let Pn=e=>{let{node:t,parent:n,...r}=e;return r};var Fn=class{GITIGNORE_FILE_NAME=`.gitignore`;gitignorePath;constructor(e){this.gitignorePath=(0,f.join)(e,this.GITIGNORE_FILE_NAME)}async add(e){try{let t=await p.default.readFile(this.gitignorePath,`utf8`);t.includes(e)||await p.default.writeFile(this.gitignorePath,`${t}\n${e}`)}catch(e){let t=e instanceof Error?e.message:`Unknown error`;V.info.defaultLog(`Error reading gitignore file`,{message:t})}}};let In=`.early.coverage`;var Ln=class{getCoverageDirectoryPath(){let e=Ge().getRootPath();return f.default.join(e,In,`v8`)}getCoverageDirectoryForCommand(){return this.getCoverageDirectoryPath()}getExecutionCwd(){return Ge().getRootPath()}},Rn=class extends Ln{getCoverageDirectoryForCommand(){let e=Ge().getGitTopLevel(),t=Ge().getRootPath(),n=f.default.relative(e,t);return f.default.join(n,In,`v8`)}};function zn(){let e=Ge().getCoverageCommand()?.split(/\s+/).includes(`nx`)??!1;return V.info.defaultLog(`Coverage path strategy: `+(e?`nx`:`standard`)),e?new Rn:new Ln}var Bn=class{report={};constructor(e,t){for(let[n,r]of Object.entries(e)){let e=f.default.normalize(n);if(e.toLowerCase().startsWith(t.toLowerCase())){let n=e.slice(t.length);this.report[n]=r}}}getEntries(){return Object.entries(this.report)}getStatsForTestable(e,t,n){let r=this.report[e];if(!(0,h.isDefined)(r))return null;let i=this.findFunctionDefinition(t,r.fnMap,n);if(!(0,h.isDefined)(i))return null;let a=0,o=0;for(let[e,t]of Object.entries(r.statementMap))if(this.isStatementInFunction(t,i)||this.isFunctionInStatement(t,i)){o++;let t=r.s[e];(0,h.isDefined)(t)&&t>0&&a++}return{percentage:this.toPercentage(a,o),totalStatements:o,coveredStatements:a}}getStatsForFile(e){let t=this.report[e];if(!(0,h.isDefined)(t))return{percentage:null,totalStatements:0,coveredStatements:0};let n=0,r=0;for(let[e]of Object.entries(t.statementMap)){r++;let i=t.s[e];(0,h.isDefined)(i)&&i>0&&n++}return{percentage:this.toPercentage(n,r),totalStatements:r,coveredStatements:n}}getStatsForDirectory(e){let t=0,n=0;for(let[r,i]of Object.entries(this.report))if(this.isSubdirectory(e,r)){n+=Object.keys(i.statementMap).length;for(let[e]of Object.entries(i.statementMap)){let n=i.s[e];(0,h.isDefined)(n)&&n>0&&t++}}return{percentage:this.toPercentage(t,n),totalStatements:n,coveredStatements:t}}calculateCoverageForFiles(e){let t=0,n=0,r=new Set(e.map(e=>this.normalizeFilePath(e)));for(let[e,i]of Object.entries(this.report)){let a=this.normalizeFilePath(e);if(r.has(a)){let e=Object.keys(i.statementMap).length;t+=e;for(let[e]of Object.entries(i.statementMap)){let t=i.s[e];(0,h.isDefined)(t)&&t>0&&n++}}}return{percentage:this.toPercentage(n,t),totalStatements:t,coveredStatements:n}}normalizeFilePath(e){return e.startsWith(`/`)?e.slice(1):e}isSubdirectory(e,t){let n=f.default.relative(e,t);return(0,h.isDefined)(n)?!n.startsWith(`..`)&&!f.default.isAbsolute(n):!1}isStatementInFunction(e,t){return!(e.start.line<t.loc.start.line||e.end.line>t.loc.end.line||e.start.line===t.loc.start.line&&e.start.column<t.loc.start.column||e.end.line===t.loc.end.line&&e.end.column>t.loc.end.column)}isFunctionInStatement(e,t){return!(t.loc.start.line<e.start.line||t.loc.end.line>e.end.line||t.loc.start.line===e.start.line&&t.loc.start.column<e.start.column||t.loc.end.line===e.end.line&&t.loc.end.column>e.end.column)}findFunctionDefinition(e,t,n){for(let[,n]of Object.entries(t))if(n.name===e)return n;return null}toPercentage(e,t,n=0){if(t===0)return null;let r=e/t;return Number(Math.round(r*100).toFixed(n))}};async function Vn(e){let t=Ge().getRootPath(),n=[];try{let e=new nt(`.gitignore`);await e.isFileExists()&&(n=(await e.getText()).split(`
32007
32007
  `).map(e=>e.trim()).filter(e=>(0,h.isDefined)(e)&&!e.startsWith(`#`)))}catch{}let r=[`node_modules`,`*.config.ts`,`**/*.mock.ts`,`**/*.mocks.ts`,`**/*.test.ts`,`**/*.spec.ts`,...n];return(await(0,A.default)(e,{cwd:t,absolute:!0,ignore:r})).map(e=>`/${f.default.relative(t,e)}`)}var Hn=class{nextSource=null;setNext(e){return this.nextSource=e,e}async getFromNext(e){return this.nextSource?this.nextSource.getFiles(e):[]}},Un=class extends Hn{async getFiles(e){return Vn(`**/*.{js,ts,jsx,tsx}`)}};let Wn=/\.[jt]sx?$/;var Gn=class extends Hn{async getFiles(e){let t=Object.keys(e).filter(e=>Wn.test(e));return t.length>0?t:this.getFromNext(e)}};function Kn(){let e=new Gn,t=new Un;return e.setNext(t),e}let qn=String.raw`.*\.early\.(spec|test)\.[tj]sx?$`;var Jn=class{EXEC_TIMEOUT_IN_MS=24e5;MAX_BUFFER_SIZE=2e4*1024;DEFAULT_ROOT_PATH=`/`;COVERAGE_ROOT_DIRECTORY_NAME=`.early.coverage`;COVERAGE_REPORT_FILE_NAME=`coverage-final.json`;pathStrategy=null;async init(){this.pathStrategy=zn()}getCoverageDirectoryPath(){if(!(0,h.isDefined)(this.pathStrategy))throw Error(`Provider not initialized. Call init() first.`);return this.pathStrategy.getCoverageDirectoryPath()}getCoverageDirectoryForCommand(){if(!(0,h.isDefined)(this.pathStrategy))throw Error(`Provider not initialized. Call init() first.`);return this.pathStrategy.getCoverageDirectoryForCommand()}getExecutionCwd(){if(!(0,h.isDefined)(this.pathStrategy))throw Error(`Provider not initialized. Call init() first.`);return this.pathStrategy.getExecutionCwd()}getCoverageReportPath(){return f.default.join(this.getCoverageDirectoryPath(),this.COVERAGE_REPORT_FILE_NAME)}async getCommand(e){let t=Ge().getCoverageCommand(),n=(0,h.isDefined)(e)&&e.length>0?this.formatTestFiles(e):``;if((0,h.isDefined)(t)){let e=t.replaceAll(Te,this.getCoverageDirectoryForCommand()).replaceAll(Ee,n);return!t.includes(Ee)&&n&&(e=`${e} ${n}`),e}return(await this.buildJestCoverageCommand(e)).replaceAll(Te,this.getCoverageDirectoryForCommand())}async isReportExists(){try{return await p.default.access(this.getCoverageReportPath(),p.constants.R_OK),!0}catch{return!1}}async removeReport(){try{let e=nt.fromAbsolutePath(this.getCoverageReportPath());await e.isFileExists()&&await e.delete()}catch(e){V.error(`Error removing coverage report`,e)}}async getReport(){try{let e=await nt.fromAbsolutePath(this.getCoverageReportPath()).getText(),t=JSON.parse(e);return this.calculateCoverage(t)}catch{throw Error(`Coverage report file could not be read: ${this.getCoverageReportPath()}`)}}async generateReport(e){V.info.defaultLog(`Coverage: generation started`),await this.removeReport();let t=await this.getCommand(e);V.info.defaultLog(`Coverage command: ${t}`);try{await Ft(t,{cwd:this.getExecutionCwd(),timeout:this.EXEC_TIMEOUT_IN_MS,maxBuffer:this.MAX_BUFFER_SIZE}),V.info.defaultLog(`Coverage command generation success`)}catch(e){let n=e instanceof Error&&`code`in e?{code:e.code,signal:e.signal,killed:e.killed}:{code:`UNKNOWN_ERROR`};throw V.info.defaultLog(`Coverage generation exited with error: "${t}".`,n),Error(`Failed to generate coverage report: ${e.message}`)}finally{await new Fn(Ge().getGitTopLevel()).add(this.COVERAGE_ROOT_DIRECTORY_NAME)}}calculateCoverage(e){let t=new Bn(e,f.default.normalize(Ge().getRootPath()).toLowerCase()),n=new Map;for(let[e,r]of t.getEntries()){let i=t.getStatsForFile(e),a=e.split(`/`).slice(0,-1);for(;a.length>0;){let e=a.join(`/`)||this.DEFAULT_ROOT_PATH;if(!n.has(e)){let r=t.getStatsForDirectory(e);n.set(e,{percentage:r.percentage,totalStatements:r.totalStatements,coveredStatements:r.coveredStatements})}a.pop()}let o=[];for(let{name:n}of Object.values(r.fnMap)){let r=t.getStatsForTestable(e,n);o.push({name:n,percentage:r?.percentage??null,totalStatements:r?.totalStatements??null,coveredStatements:r?.coveredStatements??null})}n.set(e,{percentage:i.percentage,totalStatements:i.totalStatements,coveredStatements:i.coveredStatements,testables:o})}return Object.fromEntries(n.entries())}async hasJestConfig(){let e=Lt(Ge().getRootPath());return(0,h.isDefined)(e)}async buildJestCoverageCommand(e){let t=[`node_modules`,`dist`];Ge().getIncludeEarlyTests()||t.push(qn);let n=t.map(e=>`"${e}"`).join(` `),r=Ge().getRootPath(),i=await this.hasJestConfig(),a=(0,h.isDefined)(e)&&e.length>0?` ${this.formatTestFiles(e)}`:``;return i?`npx jest --coverage --coverageProvider=v8 --coveragePathIgnorePatterns ${n} --coverageReporters=json --coverageDirectory=${Te} --silent --passWithNoTests --maxWorkers=2 ${a}`:`npx jest --coverage --coverageProvider=v8 --coveragePathIgnorePatterns ${n} --coverageReporters=json --coverageDirectory=${Te} --rootDir="${r}" --silent --passWithNoTests --maxWorkers=2 ${a}`}async getCoverageTree(e){let t=await Kn().getFiles(e),n=new Map;for(let r of t){let t=new Nn(await new nt(r).getText(),`getCoverageTree`).testables.getAllTestables(),i=r.split(`/`).slice(0,-1);for(;!(0,h.isEmpty)(i);){let t=i.join(`/`)||this.DEFAULT_ROOT_PATH,r=e[t];n.has(t)||n.set(t,{percentage:r?.percentage??null,totalStatements:r?.totalStatements??null,coveredStatements:r?.coveredStatements??null}),i.pop()}let a=[],o=t.map(e=>Pn(e)),s=e[r];for(let e of o){let{name:t}=e;if(!(0,h.isDefined)(t))continue;let n=e.type===`method`?e.parentName:void 0,r=s?.testables?.find(e=>e.name===t),i={name:t,...(0,h.isDefined)(n)&&{parentName:n},percentage:r?.percentage??null,totalStatements:r?.totalStatements??null,coveredStatements:r?.coveredStatements??null};a.push(i)}n.set(r,{percentage:s?.percentage??null,totalStatements:s?.totalStatements??null,coveredStatements:s?.coveredStatements??null,testables:a})}return Object.fromEntries(n.entries())}getCoverageForFiles(e,t){let n=0,r=0,i=new Set(e.map(e=>this.normalizeFilePath(e)));for(let[e,a]of Object.entries(t)){let t=this.normalizeFilePath(e);i.has(t)&&(n+=a.totalStatements??0,r+=a.coveredStatements??0)}return{percentage:this.toPercentage(r,n),totalStatements:n,coveredStatements:r}}normalizeFilePath(e){return e.startsWith(`/`)?e.slice(1):e}formatTestFiles(e){return e.map(e=>`"${e}"`).join(` `)}toPercentage(e,t,n=0){if(t===0)return null;let r=e/t;return Number(Math.round(r*100).toFixed(n))}},Yn=class extends Bn{constructor(e,t){super(e,t)}findFunctionDefinition(e,t,n){for(let r of Object.values(t))if(r.name===e||(0,h.isDefined)(n)&&r.name.startsWith(`(anonymous`)&&r.loc.start.line===n)return r;return null}};let Xn=`npx vitest run --coverage.enabled --coverage.exclude="${qn}" --coverage.reportsDirectory=${Te} --coverage.reportOnFailure=true --coverage.reporter=json --maxWorkers=2 --passWithNoTests`;var Zn=class extends Jn{async init(){await super.init()}async getCommand(e){let t=Ge().getCoverageCommand(),n=(0,h.isDefined)(e)&&e.length>0?this.formatTestFiles(e):``;if((0,h.isDefined)(t)){let e=t.replaceAll(Te,this.getCoverageDirectoryForCommand()).replaceAll(Ee,n);return!t.includes(Ee)&&n&&(e=`${e} ${n}`),e}let r=Xn.replaceAll(Te,this.getCoverageDirectoryForCommand());return n?`${r} ${n}`:r}async getReport(){try{let e=await nt.fromAbsolutePath(this.getCoverageReportPath()).getText(),t=JSON.parse(e);return await this.calculateCoverageWithVitest(t)}catch{throw Error(`Coverage report file could not be read: ${this.getCoverageReportPath()}`)}}async calculateCoverageWithVitest(e){let t=f.default.normalize(Ge().getRootPath()).toLowerCase(),n=new Yn(e,t),r=this.buildAbsolutePathMap(e,t),i=[...n.getEntries()];return this.processEntries(i,n,r)}buildAbsolutePathMap(e,t){let n=new Map;for(let r of Object.keys(e)){let e=f.default.normalize(r);if(e.toLowerCase().startsWith(t.toLowerCase())){let i=e.slice(t.length);n.set(i,r)}}return n}async processEntries(e,t,n){let r=new Map;for(let[i]of e)this.addDirectoryCoverage(i,t,r),await this.addFileCoverage(i,t,n,r);return Object.fromEntries(r.entries())}addDirectoryCoverage(e,t,n){let r=e.split(`/`).slice(0,-1);for(;r.length>0;){let e=r.join(`/`)||`/`;if(!n.has(e)){let r=t.getStatsForDirectory(e);n.set(e,{percentage:r.percentage,totalStatements:r.totalStatements,coveredStatements:r.coveredStatements})}r.pop()}}async addFileCoverage(e,t,n,r){let i=t.getStatsForFile(e),a=n.get(e);if(!(0,h.isDefined)(a))return;let o=await this.readFileText(a);if(!(0,h.isDefined)(o)){r.set(e,{percentage:i.percentage,totalStatements:i.totalStatements,coveredStatements:i.coveredStatements,testables:[]});return}let s=this.extractTestables(o,e,t);r.set(e,{percentage:i.percentage,totalStatements:i.totalStatements,coveredStatements:i.coveredStatements,testables:s})}async readFileText(e){try{return await nt.fromAbsolutePath(e).getText()}catch{return null}}extractTestables(e,t,n){let r=new Nn(e,`getReport`).testables.getAllTestables(),i=[];for(let e of r){let r=e.name??``,a=e.type===`method`?e.parentName:void 0,o=n.getStatsForTestable(t,r,e.startLine);i.push({name:r,...(0,h.isDefined)(a)&&{parentName:a},percentage:o?.percentage??null,totalStatements:o?.totalStatements??null,coveredStatements:o?.coveredStatements??null})}return i}},Qn=function(e){return e.JEST=`jest`,e.VITEST=`vitest`,e}(Qn||{}),$n=class{provider=null;async create(){let e=await this.detectProjectType();return V.info.defaultLog(`Coverage: project type`,e),e===Qn.JEST?this.provider=new Jn:e===Qn.VITEST&&(this.provider=new Zn),this.provider&&await this.provider.init(),V.info.defaultLog(`Coverage Provider: `+(e??`null`)),this.provider}async detectProjectType(){return await this.checkFileExists([`vitest.config.ts`,`vitest.config.js`])?Qn.VITEST:await this.checkFileExists([`package.json`,`jest.config.js`,`jest.config.ts`,`tsconfig.json`])?Qn.JEST:null}async checkFileExists(e){V.info.defaultLog(`Coverage: checking files`,e);for(let t of e)if(await new nt(t).isFileExists())return!0;return!1}};let er={};var tr=class{provider=null;coverage=null;async init(){(0,h.isDefined)(this.provider)||(this.provider=await new $n().create())}async consumeReport(){if((0,h.isDefined)(this.provider))try{this.coverage=await this.provider.getReport(),await this.provider.removeReport()}catch(e){V.info.defaultLog(`Error reading coverage report`,{error:e})}}async generateCoverage(e){if(!(0,h.isDefined)(this.provider))return er;try{await this.provider.generateReport(e)}catch(e){let t=await this.provider.isReportExists();if(!Ge().shouldContinueOnTestErrors()||!t)throw e;V.info.defaultLog(`Coverage: report exists but test command failed, continuing...`)}let t=null;try{await this.consumeReport()}catch(e){t=e instanceof Error?e:Error(String(e))}if(!(0,h.isDefined)(this.coverage))throw(0,h.isDefined)(t)?Error(`Coverage report is not available. Reason: ${t.message}`):Error(`Coverage report is not available`);return this.coverage}getCoverage(){return this.coverage}async getCoverageTree(){return!(0,h.isDefined)(this.provider)||!(0,h.isDefined)(this.coverage)?er:this.provider.getCoverageTree(this.coverage)}setCoverage(e){this.coverage=e}getCoverageForFiles(e){if(!(0,h.isDefined)(this.provider))throw Error(`Coverage provider not initialized`);if(!(0,h.isDefined)(this.coverage))throw Error(`Coverage report not available`);return this.provider.getCoverageForFiles(e,this.coverage)}},nr=l(Re()),rr=l(ze());let ir=class{coverageService=new tr;async generateCoverage(e){try{await this.coverageService.init(),await this.coverageService.generateCoverage(e)}catch(e){throw V.info.failedLog(`Failed to generate coverage`,e),e}}async setCoverage(e){try{await this.coverageService.init(),await this.coverageService.setCoverage(e)}catch(e){throw V.info.failedLog(`Failed to set coverage`,e),e}}async getCoverageTree(){try{await this.coverageService.init(),V.info.startLog(`Getting coverage tree`);let e=await this.coverageService.getCoverageTree();return V.info.endLog(`Getting coverage tree`),e??null}catch(e){throw V.info.failedLog(`Failed to get coverage tree`,e),e}}async getCoverageForFiles(e){try{return await this.coverageService.init(),this.coverageService.getCoverageForFiles(e)}catch(e){throw V.info.failedLog(`Failed to get coverage for files`,e),e}}};(0,rr.default)([tt({category:Dt.GENERATE_COVERAGE}),(0,nr.default)(`design:type`,Function),(0,nr.default)(`design:paramtypes`,[Array]),(0,nr.default)(`design:returntype`,Promise)],ir.prototype,`generateCoverage`,null),(0,rr.default)([tt({category:Dt.SET_COVERAGE}),(0,nr.default)(`design:type`,Function),(0,nr.default)(`design:paramtypes`,[Object]),(0,nr.default)(`design:returntype`,Promise)],ir.prototype,`setCoverage`,null),(0,rr.default)([tt({category:Dt.GET_COVERAGE}),(0,nr.default)(`design:type`,Function),(0,nr.default)(`design:paramtypes`,[]),(0,nr.default)(`design:returntype`,Promise)],ir.prototype,`getCoverageTree`,null),(0,rr.default)([tt({category:Dt.GET_COVERAGE}),(0,nr.default)(`design:type`,Function),(0,nr.default)(`design:paramtypes`,[Array]),(0,nr.default)(`design:returntype`,Promise)],ir.prototype,`getCoverageForFiles`,null),ir=(0,rr.default)([(0,_.injectable)()],ir);let ar=new class{safeTrackEvent(e,t){}},or={EMPTY_TEST:`0000`,DESCRIBE_NOT_FOUND:`0001`,TESTED_CODE_DATA_SOURCE_ERROR:`0002`,GENERATING_TESTS_REQUEST_ERROR:`0003`,GET_VERSION_REQUEST_ERROR:`0004`,GENERATING_HELPER_REQUEST_ERROR:`0005`,PREPARATIONS_FOR_GENERATING_TEST_DTO_ERROR:`0006`,ENHANCE_TESTS_REQUEST_ERROR:`0011`,EMPTY_FIXED_TESTS:`1000`,TESTABLE_NOT_FOUND:`1001`,TESTED_CODE_FILE_PATH_NOT_FOUND:`1002`,PREEN_TESTS_ERROR:`2001`,ORGANIZE_IMPORTS_ERROR:`2002`,NOT_ENOUGH_BALANCE_ERROR:`3000`,UNSUPPORTED_MODEL_ERROR:`4000`,TOO_MANY_USERS_ERROR:`4001`,PAYLOAD_TOO_LARGE_ERROR:`4002`,TEST_SUMMARY_DB_REQUEST_ERROR:`5000`,TEST_SUMMARY_INVALID_CREATED_BY_ERROR:`5001`,TEST_SUMMARY_INVALID_GIT_REMOTE_ERROR:`5002`,TEST_SUMMARY_INVALID_GIT_BRANCH_ERROR:`5003`,WS_DYNAMIC_PROMPT_GENERAL_ERROR:`6000`,WS_DYNAMIC_PROMPT_AUTH_ERROR:`6001`,PREPARATIONS_FOR_DYNAMIC_PROMPT_ERROR:`6002`,WS_DYNAMIC_PROMPT_VALIDATION_FAILED_ERROR:`6003`,WS_DYNAMIC_PROMPT_TIMEOUT_ERROR:`6004`,GITHUB_ACTION_TEST_SUMMARY_DB_REQUEST_ERROR:`7000`,GITHUB_ACTION_TEST_SUMMARY_READ_CONF_FILE:`7001`,GITHUB_ACTION_TEST_SUMMARY_INVALID_GIT_REMOTE_ERROR:`7002`,GITHUB_ACTION_TEST_SUMMARY_INVALID_GIT_BRANCH_ERROR:`7003`,GITHUB_ACTION_TEST_SUMMARY_READ_CONF_FILE_EMPTY_OPTIONS:`7004`,GITHUB_ACTION_TEST_SUMMARY_NO_COVERAGE_FOUND:`7005`},sr={[or.EMPTY_TEST]:`Oops! No tests were generated for "{{methodName}}". Code:{{code}} - We're on it!`,[or.DESCRIBE_NOT_FOUND]:`Oops! Test suite not found for "{{methodName}}". Code:{{code}} - We're on it!`,[or.TESTED_CODE_DATA_SOURCE_ERROR]:`Cannot get testable data for "{{methodName}}". Code:{{code}} - We're on it!`,[or.GENERATING_TESTS_REQUEST_ERROR]:`Generating tests for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[or.PREPARATIONS_FOR_GENERATING_TEST_DTO_ERROR]:`Generating tests for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[or.GET_VERSION_REQUEST_ERROR]:`Failed to make request. Code:{{code}} - We're on it!`,[or.GENERATING_HELPER_REQUEST_ERROR]:`Generating helpers for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[or.ENHANCE_TESTS_REQUEST_ERROR]:`Enhance tests for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[or.EMPTY_FIXED_TESTS]:`Oops! We got an empty API response for "{{methodName}}" test fixes. Code:{{code}} - We're on it!`,[or.TESTABLE_NOT_FOUND]:`Oops! Testable code not found for "{{methodName}}". Code:{{code}} - We're on it!`,[or.TESTED_CODE_FILE_PATH_NOT_FOUND]:`Oops! Testable code file path not found for "{{methodName}}". Code:{{code}}`,[or.PREEN_TESTS_ERROR]:`Encountered a problem while processing "{{methodName}}". Code:{{code}} - We're on it!`,[or.ORGANIZE_IMPORTS_ERROR]:`There was an issue with the processing "{{methodName}}". Code:{{code}} - We're on it!`,[or.NOT_ENOUGH_BALANCE_ERROR]:`Usage test generation limit reached.`,[or.UNSUPPORTED_MODEL_ERROR]:`We do not support this model at the moment.`,[or.TOO_MANY_USERS_ERROR]:`Users limit reached. Please contact support.`,[or.PAYLOAD_TOO_LARGE_ERROR]:`We could not generate tests due to code size.`,[or.TEST_SUMMARY_DB_REQUEST_ERROR]:`We could not save test summary to database.`,[or.TEST_SUMMARY_INVALID_CREATED_BY_ERROR]:`Invalid created by field.`,[or.TEST_SUMMARY_INVALID_GIT_REMOTE_ERROR]:`Invalid git remote.`,[or.TEST_SUMMARY_INVALID_GIT_BRANCH_ERROR]:`Invalid git branch.`,[or.GITHUB_ACTION_TEST_SUMMARY_DB_REQUEST_ERROR]:`We could not save test summary to database.`,[or.GITHUB_ACTION_TEST_SUMMARY_READ_CONF_FILE]:`Failed to read github action config file.`,[or.GITHUB_ACTION_TEST_SUMMARY_INVALID_GIT_REMOTE_ERROR]:`Invalid git remote.`,[or.GITHUB_ACTION_TEST_SUMMARY_INVALID_GIT_BRANCH_ERROR]:`Invalid git branch.`,[or.GITHUB_ACTION_TEST_SUMMARY_READ_CONF_FILE_EMPTY_OPTIONS]:`Failed to parse options from github action conf file.`,[or.GITHUB_ACTION_TEST_SUMMARY_NO_COVERAGE_FOUND]:`No coverage found. Please run coverage first.`,[or.WS_DYNAMIC_PROMPT_GENERAL_ERROR]:`Failed initializing dynamic prompt.`,[or.WS_DYNAMIC_PROMPT_AUTH_ERROR]:`Failed authorizing dynamic prompt.`,[or.PREPARATIONS_FOR_DYNAMIC_PROMPT_ERROR]:`Failed preparing init dynamic prompt.`,[or.WS_DYNAMIC_PROMPT_VALIDATION_FAILED_ERROR]:`Failed validating dynamic prompt dto.`,[or.WS_DYNAMIC_PROMPT_TIMEOUT_ERROR]:`Dynamic prompt operation timed out.`};var cr=class extends Error{constructor(e,t){let n=lr(e,t);super(n),this.code=e}};let lr=(e,t)=>{let n=sr[e];for(let[r,i]of Object.entries({...t,code:e}))n=n.replace(`{{${r}}}`,i);return n},ur=`x-request-id`;var dr=class extends Error{constructor(){super(`Not authorized`)}};new TextEncoder;let fr=new TextDecoder;function pr(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 mr(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:fr.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=fr.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return pr(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}var hr=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)}},gr=class extends hr{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`};let _r=e=>typeof e==`object`&&!!e;function vr(e){if(!_r(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 yr(e){if(typeof e!=`string`)throw new gr(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new gr(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new gr(`Invalid JWT`);if(!t)throw new gr(`JWTs must contain a payload`);let r;try{r=mr(t)}catch{throw new gr(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(fr.decode(r))}catch{throw new gr(`Failed to parse the decoded payload as JSON`)}if(!vr(i))throw new gr(`Invalid JWT Claims Set`);return i}let br=e=>{let t=yr(e).exp;return(0,h.isDefined)(t)?t*1e3:null},xr=e=>{if(!(0,h.isDefined)(e))return!0;let t=br(e);return(0,h.isDefined)(t)?t<Date.now():!0};var Sr=l(ze());let Cr=class{jwtToken=null;refreshTokenCallback=null;observer=new h.Observer;refreshTokenMutex=new M.Mutex;setJWTToken(e){this.jwtToken=e,this.observer.notifyAll(e)}async getJWTToken(){return(0,h.isDefined)(this.jwtToken)?(this.isTokenValid()||await this.refreshTokenMutex.runExclusive(async()=>{if((0,h.isDefined)(this.refreshTokenCallback))return await this.refreshTokenCallback(),this.jwtToken}),this.jwtToken):null}async getJWTTokenOrThrow(){let e=await this.getJWTToken();if(!(0,h.isDefined)(e))throw new dr;return e}onJWTTokenSave(e){this.observer.addListener(e)}isTokenValid(){return!xr(this.jwtToken)}setRefreshTokenCallback(e){this.refreshTokenCallback=e}};Cr=(0,Sr.default)([(0,_.injectable)(`Singleton`)],Cr);var wr=s(((e,t)=>{function n(e,t){return function(n,r){t(n,r,e)}}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports})),Tr=l(Re()),Er=l(wr()),Dr=l(ze()),Or,kr;let Ar=class{axiosInstance;constructor(e,t){this.authStorage=e,this.globalConfigService=t,this.axiosInstance=j.default.create({baseURL:this.globalConfigService.getBackendURL(),headers:{"x-client-name":`ts-agent`,"x-client-version":Se,"Content-Type":`application/json`,"Content-Encoding":`gzip`},transformRequest:[e=>{if((0,h.isDefined)(e)){let t=ee.default.createGzip();return t.write(JSON.stringify(e)),t.end(),t}else return e}]}),(0,te.default)(this.axiosInstance)}async apiCall({url:e,method:t,data:n,config:r}){let i=new j.AxiosHeaders({"x-request-source":this.globalConfigService.getRequestSource(),...r?.headers});if(!r?.ignoreAuth){let e=await this.authStorage.getJWTToken();(0,h.isDefined)(e)&&!(0,h.isEmpty)(e)&&(i.authorization=`Bearer ${e}`)}let a={...r,method:t,url:e,data:n,headers:i};try{return await this.axiosInstance.request(a)}catch(t){this.handleError(e,t,n)}}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})}handleError(e,t,n){if(j.default.isAxiosError(t))if((0,h.isDefined)(t.response)){let{status:e,statusText:n,data:r}=t.response;throw e===j.HttpStatusCode.PaymentRequired?new cr(or.NOT_ENOUGH_BALANCE_ERROR):Error(`API request failed: ${e} ${n} - ${JSON.stringify(r)}`)}else if((0,h.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`)}onLogin(e){this.authStorage.onJWTTokenSave(t=>{(0,h.isDefined)(t)&&e()})}};Ar=(0,Dr.default)([(0,_.injectable)(),(0,Er.default)(0,(0,_.inject)(Cr)),(0,Er.default)(1,(0,_.inject)(B)),(0,Tr.default)(`design:paramtypes`,[typeof(Or=Cr!==void 0&&Cr)==`function`?Or:Object,typeof(kr=B!==void 0&&B)==`function`?kr:Object])],Ar);let jr={SUPER_ADMIN:1,ADMIN:2,USER:3},Mr=[jr.ADMIN,jr.SUPER_ADMIN];var Nr=l(Re()),Pr=l(wr()),Fr=l(ze()),Ir;let Lr=class{mutex=new M.Mutex;user=null;constructor(e){this.apiService=e}async fetchUser(){let e=await this.apiService.get(`/api/v1/user/me`);return this.setUser(e),e}setUser(e){this.user=e,V.addContext({userId:e.id})}async getUser(){return(0,h.isDefined)(this.user)?this.user:await this.mutex.runExclusive(async()=>await this.fetchUser())}async isAdminUser(){let e=await this.getUser();return(0,h.isDefined)(e)?Mr.includes(e?.role):!1}async isInOrganization(){let e=await this.getUser();return(0,h.isDefined)(e?.organization)}};Lr=(0,Fr.default)([(0,_.injectable)(),(0,Pr.default)(0,(0,_.inject)(Ar)),(0,Nr.default)(`design:paramtypes`,[typeof(Ir=Ar!==void 0&&Ar)==`function`?Ir:Object])],Lr);let Rr=e=>(0,y.createHash)(`md5`).update(String(e)).digest(`hex`),zr=e=>({...Br(e),testFrameworkReceived:(0,h.isDefined)(e.testFrameworkReceived)?Rr(e.testFrameworkReceived):void 0,testFrameworkExpected:(0,h.isDefined)(e.testFrameworkExpected)?Rr(e.testFrameworkExpected):void 0}),Br=e=>({errorCode:e.errorCode,shortDescription:Rr(e.shortDescription),fullDescription:Rr(e.fullDescription)}),Vr=e=>({name:Rr(e.name),code:Rr(e.code),status:e.status,errors:e.errors?.map(e=>zr(e)),lintErrors:e.lintErrors?.map(e=>Hr(e))??null}),Hr=e=>({errorCode:e.errorCode,fullDescription:Rr(e.fullDescription),shortDescription:Rr(e.shortDescription),severity:e.severity,exactCode:Rr(e.exactCode)}),Ur=({describe:e,stdout:t})=>({describe:{path:e.path,code:Rr(e.code),fullCode:Rr(e.fullCode),status:e.status,errors:e.errors?.map(e=>Br(e)),tests:e.tests.map(e=>Vr(e)),lintErrors:e.lintErrors?.map(e=>Hr(e))??null},stdout:t});var Wr=l(Re()),Gr=l(wr()),Kr=l(ze()),qr,Jr,Yr;let Xr=class{constructor(e,t,n){this.apiService=e,this.userService=t,this.globalConfigService=n}async saveTestMetrics({requestId:e,timeElapsed:t,validationReport:n,...r}){try{let i={timeElapsed:t,...n,...r};await this.userService.isInOrganization()&&(V.debug.defaultLog(`Filtering private data for B2B user`),i.testResult=(0,h.isDefined)(n?.testResult)?Ur(n.testResult):void 0),V.debug.startLog(`Sending metrics with request id ${e}`),await this.apiService.post(`/api/v1/tests/update-operation-metrics`,i,{headers:{[ur]:e}}),V.debug.defaultLog(`Test metrics have been saved`)}catch(e){V.error(`Test metrics cannot be saved`,e)}V.debug.endLog(`Sending metrics with request id ${e}`)}registerStartTime(e){let t=Date.now();return async({...n})=>{let r=Date.now()-t;return await this.saveTestMetrics({...n,requestId:e,timeElapsed:r}),r}}async logPackageDependencies(e){try{if(await this.userService.isInOrganization())return;let t=St(e);if(!(0,h.isDefined)(t))return;await this.updateRepositoryPackageJson(t)}catch(e){V.info.defaultLog(`Failed to log package dependencies.`,e);return}}async saveOperationMetricsTrace(e){let{parentRequestId:t,llmModel:n,testResultIteration:r=0,toolsOutput:i,testFileContent:a}=e;try{V.debug.startLog(`Sending operation metrics trace for testResultIteration ${r}`),await this.apiService.post(`/api/v1/tests/operation-metrics-trace`,{parentRequestId:t,iteration:r,llmModel:n,toolsOutput:i,testFileContent:a}),V.debug.defaultLog(`Operation metrics trace saved for testResultIteration ${r}`)}catch(e){V.error(`Failed to save operation metrics trace for testResultIteration ${r}`,e)}V.debug.endLog(`Sending operation metrics trace for testResultIteration ${r}`)}async updateRepositoryPackageJson(e){try{let t=this.globalConfigService.getContext();if(!(0,h.isDefined)(t?.git?.owner)||!(0,h.isDefined)(t?.git?.repository)){V.debug.defaultLog(`No git context available, skipping package.json update`);return}let n={owner:t.git.owner,repo:t.git.repository,packageJson:JSON.stringify(e)};await this.apiService.patch(`/api/v1/github-repos/package-json`,n),V.debug.defaultLog(`Successfully updated repository package.json`)}catch(e){V.info.defaultLog(`Failed to update repository package.json`,e)}}};Xr=(0,Kr.default)([(0,_.injectable)(),(0,Gr.default)(0,(0,_.inject)(Ar)),(0,Gr.default)(1,(0,_.inject)(Lr)),(0,Gr.default)(2,(0,_.inject)(B)),(0,Wr.default)(`design:paramtypes`,[typeof(qr=Ar!==void 0&&Ar)==`function`?qr:Object,typeof(Jr=Lr!==void 0&&Lr)==`function`?Jr:Object,typeof(Yr=B!==void 0&&B)==`function`?Yr:Object])],Xr);var Zr=class{queue;activeProcesses=[];itemAddedObserver=new h.Observer;itemExecutedObserver=new h.Observer;itemAbortedObserver=new h.Observer;abortControllers=new Map;getItemKey;constructor({concurrency:e,getItemKey:t}){this.queue=new ne.default({concurrency:e}),this.getItemKey=t}async add(e,t){let n=this.getItemKey(e);if(this.activeProcesses.includes(n))return;let r=new AbortController,i=V.captureContext({withNewRequestId:!0});return this.abortControllers.set(n,r),this.activeProcesses.push(n),this.itemAddedObserver.notifyAll(n),this.queue.add(async()=>{await V.runWithContext(i,async()=>{await t(r.signal)})},{signal:r.signal}).then(()=>{this.itemExecutedObserver.notifyAll(n)}).finally(()=>{this.activeProcesses=this.activeProcesses.filter(e=>e!==n),this.abortControllers.delete(n)})}shouldQueue(){return this.queue.pending>=this.queue.concurrency}onIdleEmit(e){this.queue.on(`idle`,()=>{e()})}has(e){let t=this.getItemKey(e);return this.activeProcesses.includes(t)}getActiveProcesses(){return this.activeProcesses}getProcessing(){return this.activeProcesses.slice(0,this.queue.concurrency)}getQueued(){return this.activeProcesses.slice(this.queue.concurrency)}onDone(e){this.itemExecutedObserver.addListener(e)}onAdded(e){this.itemAddedObserver.addListener(e)}onAborted(e){this.itemAbortedObserver.addListener(e)}abortAll(){this.queue.clear();for(let[,e]of this.abortControllers)e.abort();this.abortControllers.clear();for(let e of this.activeProcesses)this.itemAbortedObserver.notifyAll(e);this.activeProcesses=[]}abort(e){let t=this.getItemKey(e);this.activeProcesses=this.activeProcesses.filter(e=>e!==t),this.itemAbortedObserver.notifyAll(t);let n=this.abortControllers.get(t);(0,h.isDefined)(n)&&(n.abort(),this.abortControllers.delete(t))}clearQueued(){this.queue.clear();let e=this.getQueued();for(let t of e){let e=this.abortControllers.get(t);(0,h.isDefined)(e)&&(e.abort(),this.abortControllers.delete(t)),this.itemAbortedObserver.notifyAll(t)}this.activeProcesses=this.getProcessing()}getIdlePromise(){return this.queue.onIdle()}};let Qr=`npx jest ${we} --coverage=false --verbose=false --watchAll=false --silent --json --forceExit --testPathIgnorePatterns=// --maxWorkers=1`;var $r=class{fulfill(e){if(Ge().getTestFramework()!==pe.JEST)return!1;let t=e,n=null,r=0;for(;r<25;){r++;let e=bt(t,`package.json`);if(!(0,h.isDefined)(e)||e===n)return!1;let i=St(t);if((0,h.isDefined)(i)&&Ct(i,`jest`))return!0;n=e,t=f.default.dirname(f.default.dirname(e))}return!1}getTestCommand(){return{command:Ge().getTestCommand()??Qr,framework:pe.JEST}}};let ei=`npx vitest run ${we} --reporter=junit --silent --pool=threads --maxWorkers=1 --coverage.enabled=false`,ti=new class{constructor(e){this.providers=e}getTestCommand(e){let t=this.getProvider(e);if(!(0,h.isDefined)(t))throw Error(`No CmdProvider found for file: ${e}`);return t.getTestCommand()}getProvider(e){return this.providers.find(t=>t.fulfill(e))}}([new class{fulfill(e){if(Ge().getTestFramework()!==pe.VITEST)return!1;let t=e,n=null,r=0;for(;r<25;){r++;let e=bt(t,`package.json`);if(!(0,h.isDefined)(e)||e===n)return!1;let i=St(t);if((0,h.isDefined)(i)&&Ct(i,`vitest`))return!0;n=e,t=f.default.dirname(f.default.dirname(e))}return!1}getTestCommand(){return{command:Ge().getTestCommand()??ei,framework:pe.VITEST}}},new $r]);var ni=class e{static of(...t){return new e(...t)}static all=e.of();static success=e.of(0);static suppress_1=e.of(0,1);allow(e){return this.allowed.length===0||this.allowed.includes(e)}allowed;constructor(...e){this.allowed=e}};let ri=`validate-tests`,ii=e=>e instanceof Error&&`code`in e&&typeof e.code==`number`;var ai=class e{constructor(e){this.relativePath=e}async runCommandOnFile(e,t=ni.success,n=!1){let r=n?yt(f.default.normalize(this.relativePath)):f.default.normalize(this.relativePath),i=e.replaceAll(we,`"${r}"`);try{V.debug.startLog(`Command been executed on test-file ${this.relativePath} ${e}`),V.info.defaultLog(`Running command on file ${this.relativePath}`,{renderedCommand:i});let{stdout:t,stderr:n}=await Ft(i,{cwd:Ge().getRootPath(),timeout:3e5}),r=t||n;return V.debug.endLog(`Command been executed on test-file ${this.relativePath} ${e}: ${r}`),r}catch(n){if(!(ii(n)&&(0,h.isDefined)(n.code)&&t.allow(n.code))){let t=`Failed run command "${e}" on file ${this.relativePath}`;throw V.error(t,n),n}let r=n.stdout||n.stderr;return V.debug.endLog(`Command been executed on test-file ${this.relativePath} ${e}: ${r}`),r}}getTempFileName(e,t,n){if(t){let t=f.default.join(N.default.tmpdir(),`early`),n=`${e}-${(0,y.randomUUID)()}`;return f.default.join(t,n)}let r=(0,h.isDefined)(n)&&!(0,h.isEmpty)(n),i=r&&f.default.isAbsolute(n)?f.default.dirname(n):f.default.join(Ge().getRootPath(),f.default.dirname(n??``));if(!(0,h.isDefined)(i))throw Error(`Workspace root path is not defined`);let a=`.${e}-${(0,y.randomUUID)()}-${r?f.default.basename(n):`.ts`}`;return f.default.join(i,a)}async runCommandWithContent(t,n,r,i=!1){V.addContext({subCategory:Ot.COMMAND_EXECUTION});let a={filePrefix:`generated-content`,useTemporaryOSFolder:!(0,h.isDefined)(r?.predefinedPath),validExitCodes:ni.success,...r},o=this.getTempFileName(a.filePrefix,a.useTemporaryOSFolder,a.predefinedPath);try{V.info.defaultLog(`Creating temp file ${o}`),await p.default.mkdir(f.default.dirname(o),{recursive:!0}),await p.default.writeFile(o,t);let r=new e(o);return V.info.defaultLog(`Running command "${n}" on temp file`),await r.runCommandOnFile(n,a.validExitCodes,i)}catch(e){return V.error(`Failed running command "${n}" on temp file`,e),``}finally{try{await p.default.unlink(o)}catch(e){V.info.defaultLog(`Failed removing temp file`,e)}}}async runTestCommand(){V.addContext({subCategory:Ot.COMMAND_EXECUTION});let e;try{e=ti.getTestCommand(this.relativePath)}catch(e){return e instanceof Error?e.message:`Framework is not supported yet`}return await this.runCommandOnFile(e.command,ni.suppress_1,!0)}async runTestCommandOnTempFile(e){V.addContext({subCategory:Ot.COMMAND_EXECUTION});let t;try{t=ti.getTestCommand(this.relativePath)}catch(e){return e instanceof Error?e.message:`Framework is not supported yet`}return await this.runCommandWithContent(e,t.command,{validExitCodes:ni.suppress_1,filePrefix:ri,predefinedPath:this.relativePath},!0)}async runFormatCommand(){V.addContext({subCategory:Ot.COMMAND_EXECUTION});let e=Ge().getPrettierCommand();V.debug.startLog(`format command: ${e}`);let t=await this.runCommandOnFile(e,ni.all);return V.debug.endLog(`format command: ${e}`),t}async runLintCommand(e=[]){V.addContext({subCategory:Ot.COMMAND_EXECUTION});let t=Ge().getLintCommand(),n=e.length>0?t+` `+e.join(` `):t;V.debug.startLog(`lint command: ${n}`);let r=await this.runCommandOnFile(n,ni.all);return V.debug.endLog(`lint command: ${n}`),r}};let oi=e=>{let t=e.name??``,n=e.type;return{methodType:n,methodName:t,parentName:n===`method`?e.parentName:void 0}};async function si(e,{methodType:t,methodName:n,parentName:r}){let i=new Nn(await new nt(e).getText()).testables.findTestable(t,n,r);if(!(0,h.isDefined)(i))throw new cr(or.TESTABLE_NOT_FOUND,{methodName:n});return i}function ci(e,t){return(0,h.isDefined)(t)&&!(0,h.isEmpty)(t)?`${t}.${e}`:e}function li(e){if(!e||e.trim()===``)return[];let t=e.indexOf(`[`),n=e.lastIndexOf(`]`),r=t!==-1&&n!==-1&&n>t?e.slice(t,n+1):e;try{return JSON.parse(r)}catch(e){return V.error(`Failed to parse eslint JSON output`,e),null}}var ui=l(ze());let di=class{contentCache=new Map;filePathIndex=new Map;computeContentHash(e){return Rr(e)}getContentCacheKey(e,t){return`${e}:${t?`fix`:`nofix`}`}evictOldest(){let e=this.contentCache.keys().next().value;(0,h.isDefined)(e)&&(this.contentCache.delete(e),V.debug.defaultLog(`Lint cache evicted oldest entry (FIFO)`))}get(e,t,n){let r=this.computeContentHash(t),i=this.getContentCacheKey(r,n),a=this.contentCache.get(i);return(0,h.isDefined)(a)?(V.debug.defaultLog(`Lint cache hit for ${e}`),a.results):null}set(e,t,n,r){let i=this.computeContentHash(t),a=Date.now(),o=this.getContentCacheKey(i,n);if(!this.contentCache.has(o)&&this.contentCache.size>=100&&this.evictOldest(),this.contentCache.set(o,{results:r,contentHash:i,withFix:n,timestamp:a}),n){let e=this.getContentCacheKey(i,!1);!this.contentCache.has(e)&&this.contentCache.size>=100&&this.evictOldest(),this.contentCache.set(e,{results:r,contentHash:i,withFix:!1,timestamp:a})}this.filePathIndex.set(e,i)}invalidate(e){let t=this.filePathIndex.get(e);if(!(0,h.isDefined)(t))return;let n=this.getContentCacheKey(t,!0),r=this.getContentCacheKey(t,!1),i=this.contentCache.delete(n),a=this.contentCache.delete(r);this.filePathIndex.delete(e),(i||a)&&V.debug.defaultLog(`Lint cache invalidated for ${e}`)}invalidateAll(){let e=this.contentCache.size;this.contentCache.clear(),this.filePathIndex.clear(),e>0&&V.debug.defaultLog(`Lint cache cleared: ${e} entries removed`)}};di=(0,ui.default)([(0,_.injectable)()],di);let fi=function(e){return e[e.ERROR=2]=`ERROR`,e[e.WARN=1]=`WARN`,e[e.OFF=0]=`OFF`,e}({});var pi=l(Re()),mi=l(wr()),hi=l(ze()),gi,_i;let vi=class{constructor(e,t){this.globalConfigService=e,this.lintCacheService=t}async disableRules(e){let t=[this.globalConfigService.shouldIgnoreAsAnyLintErrors()?`@typescript-eslint/no-explicit-any`:void 0,...this.globalConfigService.allowUndefinedLintErrors()?Tt:[]].filter(h.isDefined);this.globalConfigService.shouldDisableLintRules()?await this.disableAllLintRules(e):(0,h.isEmpty)(t)||await this.disableLintRules(e,t),await U.refreshFromFileSystem(e)}async disableAllLintRules(e){let t=await this.getRulesToDisable(e);if((0,h.isDefined)(t)){if((0,h.isEmpty)(t)){V.info.defaultLog(`No lint rules needed to be disabled`);return}await this.addDisableComment(e,t),V.info.defaultLog(`Added eslint-disable comment for rules: ${t.join(`, `)}`)}}async lintFiles(e,t){let n=nt.fromRelativePath(e),r=await n.getText(),i=this.lintCacheService.get(e,r,t);if((0,h.isDefined)(i))return i;let a=t?[`--format`,`json`,`--fix`]:[`--format`,`json`],o=li(await new ai(e).runLintCommand(a));if(!(0,h.isDefined)(o))return null;if(t){await U.refreshFromFileSystem(e);let r=await n.getText();this.lintCacheService.set(e,r,t,o)}else this.lintCacheService.set(e,r,t,o);return o}async lint(e,t){try{return await this.lintFiles(e,t)}catch(e){return V.error(`Failed to get lint results:`,e),null}}async fixLint(e){try{return await this.lint(e,!0)}catch(e){return V.error(`Failed to fix lint:`,e),null}}async getLintResults(e){try{return await this.lint(e,!1)}catch(e){return V.error(`Failed to get lint results:`,e),null}}async getRulesToDisable(e){let t=await this.getLintResults(e);if(!(0,h.isDefined)(t))return null;let n=(t[0]?.messages??[]).filter(e=>e.severity===fi.ERROR);return[...new Set(n.map(e=>e.ruleId).filter(h.isDefined))]}async addDisableComment(e,t){let n=nt.fromRelativePath(e),r=await n.getText(),i=`/* eslint-disable ${t.join(`, `)} */\n\n`;await n.replace(i+r),this.lintCacheService.invalidate(e)}hasDisableCommentForRules(e,t){let n=e.split(`
32008
32008
  `);for(let e of n){let n=e.indexOf(`/*`),r=e.indexOf(`*/`);if(n===-1||r===-1)continue;let i=e.slice(n+2,r).trim();if(i.startsWith(`eslint-disable`)&&i.replace(`eslint-disable`,``).trim().split(`,`).map(e=>e.trim()).every(e=>t.includes(e)))return!0}return!1}async disableLintRules(e,t){if(!this.globalConfigService.shouldIgnoreAsAnyLintErrors())return;let n=nt.fromRelativePath(e),r=await n.getText();if(this.hasDisableCommentForRules(r,t))return;let i=await this.getLintResults(e);if(!(0,h.isDefined)(i)){V.info.defaultLog(`No lint results returned`);return}let a=i[0]?.messages??[],o=t.filter(e=>a.some(t=>t.severity===fi.ERROR&&t.ruleId===e));if((0,h.isEmpty)(o))return;let s=`/* eslint-disable ${o.join(`, `)} */\n\n`;await n.replace(s+r),this.lintCacheService.invalidate(e),V.info.defaultLog(`Added eslint-disable comment for ${o.join(`, `)} in ${e}`)}};vi=(0,hi.default)([(0,_.injectable)(),(0,mi.default)(0,(0,_.inject)(B)),(0,mi.default)(1,(0,_.inject)(di)),(0,pi.default)(`design:paramtypes`,[typeof(gi=B!==void 0&&B)==`function`?gi:Object,typeof(_i=di!==void 0&&di)==`function`?_i:Object])],vi);let yi="${methodName}";`${yi}`,`${yi}`;function bi(e,t,n){let r=e.split(`
@@ -32077,11 +32077,11 @@ ${Jd}${t.trimStart()}`),n=3+(0,O.stripVTControlCharacters)(t.trimStart()).length
32077
32077
  it("placeholder", () => {
32078
32078
  assert.ok(true);
32079
32079
  });
32080
- `;default:return rp}}function ap(e){return(0,h.isDefined)(e)?{status:$f.RESOLVED,command:e}:{status:$f.UNRESOLVED}}function op(e){return{testCommand:ap(e.testCommand),buildCommand:ap(e.typecheckCommand),lintCommand:ap(e.lintCommand),prettierCommand:ap(e.prettierCommand),packageManager:e.packageManager}}var sp=l(ze());let cp=(0,O.promisify)(D.exec),lp=new Map,up=[/Oops! Something went wrong/i,/ESLint couldn't find a?n? ?configuration/i,/Cannot find module/i,/MODULE_NOT_FOUND/,/ENOENT/,/command not found/i,/ERR_MODULE_NOT_FOUND/,/Cannot read config file/i,/No ESLint configuration found/i,/Error: No files matching/i];function dp(e){return up.some(t=>t.test(e))}function fp(e,t){let n=f.default.basename(t);return e.includes(n)}let pp=class{async verify(e){let{setup:t,workingDirectory:n}=e,[r,i,a,o]=await Promise.all([this.runGate(t.testCommand,n),this.runGate(t.buildCommand,n),this.runGate(t.lintCommand,n),this.runGate(t.prettierCommand,n)]);return{testCommand:r,buildCommand:i,lintCommand:a,prettierCommand:o,passed:r.status!==ep.FAILED&&i.status!==ep.FAILED&&a.status!==ep.FAILED&&o.status!==ep.FAILED}}async runGate(e,t){if(e.status===$f.UNRESOLVED)return{status:ep.SKIPPED,reason:`unresolved`};let n=`${e.command}::${t}`,r=lp.get(n);if(r)return V.default.info(`[test-verification] Reusing in-flight gate: ${e.command}`),r;let i=this.executeGate(e,t);lp.set(n,i);try{return await i}finally{lp.delete(n)}}async executeGate(e,t){try{return await cp(e.command,{cwd:t,encoding:`utf8`,timeout:3e5,maxBuffer:10485760}),{status:ep.PASSED,command:e.command}}catch(t){let n=t,r=((n.stdout??``)+(n.stderr??``)).trim();return V.default.warn(`[test-verification] Gate failed: ${e.command}\n${r}`),{status:ep.FAILED,command:e.command,output:r}}}};pp=(0,sp.default)([(0,_.injectable)()],pp);function mp(e,t,n){let r=(e,t)=>e.status===$f.UNRESOLVED?e:t.status===ep.PASSED?{status:$f.VERIFIED,command:e.command}:{status:$f.UNRESOLVED},i=(e,t,r)=>e.status===$f.UNRESOLVED?e:t.status===ep.PASSED?{status:$f.VERIFIED,command:e.command}:t.status===ep.FAILED&&!dp(t.output)?(fp(t.output,n)||V.default.warn(`[test-verification] ${r} failed on unrelated files — promoting anyway`),{status:$f.VERIFIED,command:e.command}):{status:$f.UNRESOLVED};return{testCommand:r(e.testCommand,t.testCommand),buildCommand:i(e.buildCommand,t.buildCommand,`build`),lintCommand:i(e.lintCommand,t.lintCommand,`lint`),prettierCommand:i(e.prettierCommand,t.prettierCommand,`prettier`),packageManager:e.packageManager}}let hp=[`jest.config.ts`,`jest.config.js`,`jest.config.mjs`,`jest.config.cjs`,`vitest.config.ts`,`vitest.config.js`,`vitest.config.mjs`],gp=[`tsconfig.json`],_p=[`.eslintrc`,`.eslintrc.js`,`.eslintrc.cjs`,`.eslintrc.json`,`.eslintrc.yml`,`.eslintrc.yaml`,`eslint.config.js`,`eslint.config.mjs`,`eslint.config.cjs`,`eslint.config.ts`],vp=[`.prettierrc`,`.prettierrc.js`,`.prettierrc.cjs`,`.prettierrc.mjs`,`.prettierrc.json`,`.prettierrc.yaml`,`.prettierrc.yml`,`prettier.config.js`,`prettier.config.cjs`,`prettier.config.mjs`,`prettier.config.ts`],yp=new Set([`build`,`compile`,`dist`,`prepublish`,`prepublishOnly`,`prepare`]),bp=[`test:unit`,`test:ci`,`test:run`],xp=[`check:ts`,`typecheck`,`type-check`,`tsc`],Sp=[`check:lint`,`lint`],Cp=[`check:prettier`,`format`,`prettier`];function wp(e){let t=[],n=e,r=f.default.parse(n).root;for(;n!==r&&(t.push(n),!(0,w.existsSync)(f.default.join(n,`.git`)));)n=f.default.dirname(n);return t}function Tp(e){let t=[];for(let n of wp(e)){let e=f.default.join(n,`package.json`);if((0,w.existsSync)(e))try{let r=JSON.parse((0,w.readFileSync)(e,`utf8`));t.push({dir:n,pkg:r})}catch{}}return t}function Ep(e,t){for(let n of e)for(let e of t)if((0,w.existsSync)(f.default.join(n,e)))return!0;return!1}function Dp(e){for(let t of e)for(let e of hp)if((0,w.existsSync)(f.default.join(t,e)))return e.startsWith(`vitest`)?`vitest`:`jest`;return null}function Op(e,t){let n=Dp(t);if((0,h.isDefined)(n))return n;for(let{pkg:t}of e){let e=Bp(t);if((0,h.isDefined)(e.vitest))return`vitest`;if((0,h.isDefined)(e.jest))return`jest`;if((0,h.isDefined)(e.mocha))return`mocha`}return kp(t,`vitest`)?`vitest`:kp(t,`jest`)?`jest`:null}function kp(e,t){for(let n of e)if((0,w.existsSync)(f.default.join(n,`node_modules`,`.bin`,t)))return!0;return!1}function Ap(e){for(let t of wp(e)){if((0,w.existsSync)(f.default.join(t,`pnpm-lock.yaml`))||(0,w.existsSync)(f.default.join(t,`pnpm-workspace.yaml`)))return`pnpm`;if((0,w.existsSync)(f.default.join(t,`yarn.lock`)))return`yarn`;if((0,w.existsSync)(f.default.join(t,`bun.lockb`))||(0,w.existsSync)(f.default.join(t,`bun.lock`)))return`bun`}return`npm`}function jp(e,t){return e===`yarn`?`yarn ${t}`:`${e} run ${t}`}function Mp(e,t){return e.startsWith(`npx `)||e.startsWith(`yarn `)?`${e} ${t}`:`${e} -- ${t}`}let Np=/(?:^echo\b)|(?:no test specified)|(?:placeholder)/i;function Pp(e,t){let n=e.scripts??{},r=Bp(e),i=n.test;if((0,h.isDefined)(i)&&!Np.test(i))return jp(t,`test`);for(let e of bp)if((0,h.isDefined)(n[e]))return jp(t,e);for(let[e,r]of Object.entries(n))if(/\bjest\b/.test(r)||/\bvitest\b/.test(r))return jp(t,e);return(0,h.isDefined)(r.jest)?`npx jest`:(0,h.isDefined)(r.vitest)?`npx vitest`:null}function Fp(e,t,n){for(let{pkg:t}of e){let e=Pp(t,n);if((0,h.isDefined)(e))return e}let r=Dp(t);return(0,h.isDefined)(r)?(V.info.defaultLog(`[project-setup] test: found config file for ${r}`),`npx ${r}`):kp(t,`jest`)?(V.info.defaultLog(`[project-setup] test: found jest in node_modules`),`npx jest`):kp(t,`vitest`)?(V.info.defaultLog(`[project-setup] test: found vitest in node_modules`),`npx vitest`):null}function Ip(e,t){let n=e.scripts??{},r=Bp(e);for(let e of xp)if((0,h.isDefined)(n[e]))return jp(t,e);for(let[e,r]of Object.entries(n))if(/\btsc\b/.test(r)&&!yp.has(e))return jp(t,e);return(0,h.isDefined)(r.typescript)?`npx tsc --noEmit`:null}function Lp(e,t,n){for(let{pkg:t}of e){let e=Ip(t,n);if((0,h.isDefined)(e))return e}return Ep(t,gp)?(V.info.defaultLog(`[project-setup] typecheck: found tsconfig.json`),`npx tsc --noEmit`):kp(t,`tsc`)?(V.info.defaultLog(`[project-setup] typecheck: found tsc in node_modules`),`npx tsc --noEmit`):null}function Rp(e,t,n){for(let{pkg:t}of e){let e=t.scripts??{},r=Bp(t);for(let t of Sp)if((0,h.isDefined)(e[t]))return jp(n,t);for(let[t,r]of Object.entries(e))if(/\beslint\b/.test(r))return jp(n,t);if((0,h.isDefined)(r.eslint))return`npx eslint`}return Ep(t,_p)?(V.info.defaultLog(`[project-setup] lint: found eslint config file`),`npx eslint`):kp(t,`eslint`)?(V.info.defaultLog(`[project-setup] lint: found eslint in node_modules`),`npx eslint`):null}function zp(e,t,n){for(let{pkg:t}of e){let e=t.scripts??{},r=Bp(t);for(let t of Cp)if((0,h.isDefined)(e[t]))return jp(n,t);for(let[t,r]of Object.entries(e))if(/\bprettier\b/.test(r))return jp(n,t);if((0,h.isDefined)(r.prettier))return`npx prettier`}return Ep(t,vp)?(V.info.defaultLog(`[project-setup] prettier: found prettier config file`),`npx prettier`):kp(t,`prettier`)?(V.info.defaultLog(`[project-setup] prettier: found prettier in node_modules`),`npx prettier`):null}function Bp(e){return{...e.dependencies,...e.devDependencies}}function Vp(e,t){let n=wp(e),r=Tp(e),i=Ap(e),a=(0,h.isDefined)(t)?f.default.relative(e,t):null,o=Fp(r,n,i),s=(0,h.isDefined)(o)&&(0,h.isDefined)(a)?Mp(o,a):null,c=Op(r,n),l=Lp(r,n,i),u=Rp(r,n,i),d=(0,h.isDefined)(u)&&(0,h.isDefined)(a)?`npx eslint ${a}`:null,p=zp(r,n,i),m=(0,h.isDefined)(p)&&(0,h.isDefined)(a)?`npx prettier ${a} --write`:null,g=[];return(0,h.isDefined)(s)||g.push(`testCommand`),(0,h.isDefined)(l)||g.push(`typecheckCommand`),(0,h.isDefined)(d)||g.push(`lintCommand`),(0,h.isDefined)(m)||g.push(`prettierCommand`),{testCommand:s,testRunner:c,typecheckCommand:l,lintCommand:d,prettierCommand:m,packageManager:i,missing:g}}let Hp=(0,O.promisify)(D.exec),Up={testCommand:`test`,buildCommand:`build`,lintCommand:`lint`,prettierCommand:`format`},Wp=function(e){return e.TEST=`testCommand`,e.BUILD=`buildCommand`,e.LINT=`lintCommand`,e.FORMAT=`prettierCommand`,e}({});var Gp=class{setup;testFilePath;workingDirectory;lastCheckAllResult=null;mcpServer;progressLogger;constructor(e){this.setup=e.setup,this.testFilePath=e.testFilePath,this.workingDirectory=e.workingDirectory,this.progressLogger=e.progressLogger??Pe,this.mcpServer=this.buildServer()}getLastCheckAllResult(){return this.lastCheckAllResult}getServer(){return this.mcpServer}buildValidationSummary(){if(!(0,h.isDefined)(this.lastCheckAllResult))return;let e=this.lastCheckAllResult.gates.find(e=>e.gate===Wp.TEST),t=this.lastCheckAllResult.gates.find(e=>e.gate===Wp.LINT),n=(0,h.isDefined)(e?.output)?bf(e.output):void 0,r=(0,h.isDefined)(t?.output)?Sf(t.output):0;return{greenTestsCount:n?.passed??0,redTestsCount:n?.failed??0,greyTestsCount:0,whiteTestsCount:0,naTestsCount:0,errorSuitsCount:n?.suitesFailed??0,lintErrorsCount:r}}async runGate(e){let t=this.setup[e];if(t.status===$f.UNRESOLVED)return{gate:e,passed:!0,skipped:!0};try{let{stdout:n,stderr:r}=await Hp(t.command,{cwd:this.workingDirectory,encoding:`utf8`,timeout:3e5,maxBuffer:10485760});return{gate:e,passed:!0,skipped:!1,output:of((n+r).trim())}}catch(t){let n=sf(t);if(e===Wp.BUILD||e===Wp.LINT){let t=f.default.basename(this.testFilePath);if(!n.includes(t))return{gate:e,passed:!0,skipped:!1,output:`[warning] ${Up[e]??e} failed on unrelated files — not blocking.\n${n}`}}return{gate:e,passed:!1,skipped:!1,output:n}}}async checkAll(){let e=this.setup.lintCommand.status!==$f.UNRESOLVED,t=this.setup.prettierCommand.status!==$f.UNRESOLVED,n=await this.runStabilityLoop(e,t);if(n.stabilityConflict===!0)return this.lastCheckAllResult=n,n;this.progressLogger.verbose(`validating...`);let[r,i]=await Promise.all([this.runGate(Wp.TEST),this.runGate(Wp.BUILD)]),a=!1;if(!r.passed&&(0,h.isDefined)(r.output)){let e=bf(r.output);(0,h.isDefined)(e)&&e.passed>=6&&(a=!0,r.passed=!0)}let o=[...n.gates,r,i],s={passed:o.every(e=>e.passed),gates:o},c=s.gates.find(e=>e.gate===Wp.TEST),l=(0,h.isDefined)(c?.output)?bf(c.output):void 0,u=s.gates.filter(e=>!e.skipped).map(e=>`${Up[e.gate]??e.gate} ${e.passed?`✓`:`✗`}`).join(` `),d=[];(0,h.isDefined)(l)&&(d.push(`${l.passed} green, ${l.failed} red`),l.suitesFailed>0&&d.push(`${l.suitesFailed} suite errors`));let f=d.length>0?` — ${d.join(`, `)}`:``;return this.progressLogger.verbose(`Validation ${s.passed?`passed`:`failed`}:`,u+f),a&&(0,h.isDefined)(l)&&this.progressLogger.verbose(`Pruning tests — ${l.passed} passing, ${l.failed} failing`),this.lastCheckAllResult=s,s}async runStabilityLoop(e,t){let n={gate:Wp.LINT,passed:!0,skipped:!0},r={gate:Wp.FORMAT,passed:!0,skipped:!0};if(!e&&!t)return{passed:!0,gates:[n,r]};let i=await(0,p.readFile)(this.testFilePath,`utf8`);for(let a=0;a<2;a++){let o=await Promise.all([e?this.runGate(Wp.LINT):Promise.resolve(n),t?this.runGate(Wp.FORMAT):Promise.resolve(r)]);if(n=o[0],r=o[1],!n.passed||!r.passed)break;let s=await(0,p.readFile)(this.testFilePath,`utf8`);if(s===i)break;if(a===1)return{passed:!1,stabilityConflict:!0,gates:[n,r]};i=s}return{passed:n.passed&&r.passed,gates:[n,r]}}buildServer(){let e=(0,se.tool)(`check_lint`,`Runs the lint command against the test file and returns pass/fail with output. Use during iteration to check lint status.`,{},async()=>{let e=await this.runGate(Wp.LINT);return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),t=(0,se.tool)(`check_format`,`Runs the format/prettier command against the test file and returns pass/fail with output. Use during iteration to check formatting status.`,{},async()=>{let e=await this.runGate(Wp.FORMAT);return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),n=(0,se.tool)(`check_test`,`Runs the test command and returns pass/fail with output. Use during iteration to check test status.`,{},async()=>{let e=await this.runGate(Wp.TEST),t=(0,h.isDefined)(e.output)?bf(e.output):void 0;return!e.passed&&(0,h.isDefined)(t)&&t.passed>=6&&(this.progressLogger.verbose(`Pruning tests — ${t.passed} passing, ${t.failed} failing`),e.passed=!0),e.testReport=t,{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),r=(0,se.tool)(`check_build`,`Runs the build command and returns pass/fail with output. Use during iteration to check build status.`,{},async()=>{let e=await this.runGate(Wp.BUILD);return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),i=(0,se.tool)(`check_all`,[`Runs ALL verification gates with a lint/format stability check.`,`First runs lint+format in a loop (max 2 iterations) to ensure they stabilize.`,`Then runs test+build once. Returns combined pass/fail.`,`You MUST call this tool and get all-green before completing your task.`,`If it reports a stability conflict, inform the user — do not retry.`].join(` `),{},async()=>{let e=await this.checkAll(),t=e.gates.find(e=>e.gate===Wp.TEST);return e.testReport=(0,h.isDefined)(t?.output)?bf(t.output):void 0,{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),a=(0,se.tool)(`get_status`,`Returns the current verification state: last check_all result and whether you are cleared to finish.`,{},async()=>{let e=this.getLastCheckAllResult(),t={lastCheckAllResult:e,clearedToFinish:e?.passed===!0};return{content:[{type:`text`,text:JSON.stringify(t,null,2)}]}});return(0,se.createSdkMcpServer)({name:`verification_gates`,version:`1.0.0`,tools:[e,t,n,r,i,a]})}},Kp=l(Re()),qp=l(wr()),Jp=l(ze()),Yp,Xp,Zp,Qp;function $p(e){return(0,h.isEmpty)(e)||!(0,w.existsSync)(e)?``:(0,w.readFileSync)(e,`utf8`)}function em(e){return(e.duration_ms/1e3).toFixed(1),``}function tm(e,t){return e+[``,`---`,`IMPORTANT: A test file has been pre-created at: ${t}`,`Use the Edit tool to add your test cases to this file. Do NOT create a new file with the Write tool.`].join(`
32080
+ `;default:return rp}}function ap(e){return(0,h.isDefined)(e)?{status:$f.RESOLVED,command:e}:{status:$f.UNRESOLVED}}function op(e){return{testCommand:ap(e.testCommand),buildCommand:ap(e.typecheckCommand),lintCommand:ap(e.lintCommand),prettierCommand:ap(e.prettierCommand),packageManager:e.packageManager}}var sp=l(ze());let cp=(0,O.promisify)(D.exec),lp=new Map,up=[/Oops! Something went wrong/i,/ESLint couldn't find a?n? ?configuration/i,/Cannot find module/i,/MODULE_NOT_FOUND/,/ENOENT/,/command not found/i,/ERR_MODULE_NOT_FOUND/,/Cannot read config file/i,/No ESLint configuration found/i,/Error: No files matching/i];function dp(e){return up.some(t=>t.test(e))}function fp(e,t){let n=f.default.basename(t);return e.includes(n)}let pp=class{async verify(e){let{setup:t,workingDirectory:n}=e,[r,i,a,o]=await Promise.all([this.runGate(t.testCommand,n),this.runGate(t.buildCommand,n),this.runGate(t.lintCommand,n),this.runGate(t.prettierCommand,n)]),s=t=>t.status===ep.FAILED?fp(t.output,e.testFilePath):!1;return{testCommand:r,buildCommand:i,lintCommand:a,prettierCommand:o,passed:r.status!==ep.FAILED&&!s(i)&&!s(a)&&!s(o)}}async runGate(e,t){if(e.status===$f.UNRESOLVED)return{status:ep.SKIPPED,reason:`unresolved`};let n=`${e.command}::${t}`,r=lp.get(n);if(r)return V.default.info(`[test-verification] Reusing in-flight gate: ${e.command}`),r;let i=this.executeGate(e,t);lp.set(n,i);try{return await i}finally{lp.delete(n)}}async executeGate(e,t){try{return await cp(e.command,{cwd:t,encoding:`utf8`,timeout:3e5,maxBuffer:10485760}),{status:ep.PASSED,command:e.command}}catch(t){let n=t,r=((n.stdout??``)+(n.stderr??``)).trim();return V.default.warn(`[test-verification] Gate failed: ${e.command}\n${r}`),{status:ep.FAILED,command:e.command,output:r}}}};pp=(0,sp.default)([(0,_.injectable)()],pp);function mp(e,t,n){let r=(e,t)=>e.status===$f.UNRESOLVED?e:t.status===ep.PASSED?{status:$f.VERIFIED,command:e.command}:{status:$f.UNRESOLVED},i=(e,t,r)=>e.status===$f.UNRESOLVED?e:t.status===ep.PASSED?{status:$f.VERIFIED,command:e.command}:t.status===ep.FAILED&&!dp(t.output)?(fp(t.output,n)||V.default.warn(`[test-verification] ${r} failed on unrelated files — promoting anyway`),{status:$f.VERIFIED,command:e.command}):{status:$f.UNRESOLVED};return{testCommand:r(e.testCommand,t.testCommand),buildCommand:i(e.buildCommand,t.buildCommand,`build`),lintCommand:i(e.lintCommand,t.lintCommand,`lint`),prettierCommand:i(e.prettierCommand,t.prettierCommand,`prettier`),packageManager:e.packageManager}}let hp=[`jest.config.ts`,`jest.config.js`,`jest.config.mjs`,`jest.config.cjs`,`vitest.config.ts`,`vitest.config.js`,`vitest.config.mjs`],gp=[`tsconfig.json`],_p=[`.eslintrc`,`.eslintrc.js`,`.eslintrc.cjs`,`.eslintrc.json`,`.eslintrc.yml`,`.eslintrc.yaml`,`eslint.config.js`,`eslint.config.mjs`,`eslint.config.cjs`,`eslint.config.ts`],vp=[`.prettierrc`,`.prettierrc.js`,`.prettierrc.cjs`,`.prettierrc.mjs`,`.prettierrc.json`,`.prettierrc.yaml`,`.prettierrc.yml`,`prettier.config.js`,`prettier.config.cjs`,`prettier.config.mjs`,`prettier.config.ts`],yp=new Set([`build`,`compile`,`dist`,`prepublish`,`prepublishOnly`,`prepare`]),bp=[`test:unit`,`test:ci`,`test:run`],xp=[`check:ts`,`typecheck`,`type-check`,`tsc`],Sp=[`check:lint`,`lint`],Cp=[`check:prettier`,`format`,`prettier`];function wp(e){let t=[],n=e,r=f.default.parse(n).root;for(;n!==r&&(t.push(n),!(0,w.existsSync)(f.default.join(n,`.git`)));)n=f.default.dirname(n);return t}function Tp(e){let t=[];for(let n of wp(e)){let e=f.default.join(n,`package.json`);if((0,w.existsSync)(e))try{let r=JSON.parse((0,w.readFileSync)(e,`utf8`));t.push({dir:n,pkg:r})}catch{}}return t}function Ep(e,t){for(let n of e)for(let e of t)if((0,w.existsSync)(f.default.join(n,e)))return!0;return!1}function Dp(e){for(let t of e)for(let e of hp)if((0,w.existsSync)(f.default.join(t,e)))return e.startsWith(`vitest`)?`vitest`:`jest`;return null}function Op(e,t){let n=Dp(t);if((0,h.isDefined)(n))return n;for(let{pkg:t}of e){let e=Bp(t);if((0,h.isDefined)(e.vitest))return`vitest`;if((0,h.isDefined)(e.jest))return`jest`;if((0,h.isDefined)(e.mocha))return`mocha`}return kp(t,`vitest`)?`vitest`:kp(t,`jest`)?`jest`:null}function kp(e,t){for(let n of e)if((0,w.existsSync)(f.default.join(n,`node_modules`,`.bin`,t)))return!0;return!1}function Ap(e){for(let t of wp(e)){if((0,w.existsSync)(f.default.join(t,`pnpm-lock.yaml`))||(0,w.existsSync)(f.default.join(t,`pnpm-workspace.yaml`)))return`pnpm`;if((0,w.existsSync)(f.default.join(t,`yarn.lock`)))return`yarn`;if((0,w.existsSync)(f.default.join(t,`bun.lockb`))||(0,w.existsSync)(f.default.join(t,`bun.lock`)))return`bun`}return`npm`}function jp(e,t){return e===`yarn`?`yarn ${t}`:`${e} run ${t}`}function Mp(e,t){return e.startsWith(`npx `)||e.startsWith(`yarn `)?`${e} ${t}`:`${e} -- ${t}`}let Np=/(?:^echo\b)|(?:no test specified)|(?:placeholder)/i;function Pp(e,t){let n=e.scripts??{},r=Bp(e),i=n.test;if((0,h.isDefined)(i)&&!Np.test(i))return jp(t,`test`);for(let e of bp)if((0,h.isDefined)(n[e]))return jp(t,e);for(let[e,r]of Object.entries(n))if(/\bjest\b/.test(r)||/\bvitest\b/.test(r))return jp(t,e);return(0,h.isDefined)(r.jest)?`npx jest`:(0,h.isDefined)(r.vitest)?`npx vitest`:null}function Fp(e,t,n){for(let{pkg:t}of e){let e=Pp(t,n);if((0,h.isDefined)(e))return e}let r=Dp(t);return(0,h.isDefined)(r)?(V.info.defaultLog(`[project-setup] test: found config file for ${r}`),`npx ${r}`):kp(t,`jest`)?(V.info.defaultLog(`[project-setup] test: found jest in node_modules`),`npx jest`):kp(t,`vitest`)?(V.info.defaultLog(`[project-setup] test: found vitest in node_modules`),`npx vitest`):null}function Ip(e,t){let n=e.scripts??{},r=Bp(e);for(let e of xp)if((0,h.isDefined)(n[e]))return jp(t,e);for(let[e,r]of Object.entries(n))if(/\btsc\b/.test(r)&&!yp.has(e))return jp(t,e);return(0,h.isDefined)(r.typescript)?`npx tsc --noEmit`:null}function Lp(e,t,n){for(let{pkg:t}of e){let e=Ip(t,n);if((0,h.isDefined)(e))return e}return Ep(t,gp)?(V.info.defaultLog(`[project-setup] typecheck: found tsconfig.json`),`npx tsc --noEmit`):kp(t,`tsc`)?(V.info.defaultLog(`[project-setup] typecheck: found tsc in node_modules`),`npx tsc --noEmit`):null}function Rp(e,t,n){for(let{pkg:t}of e){let e=t.scripts??{},r=Bp(t);for(let t of Sp)if((0,h.isDefined)(e[t]))return jp(n,t);for(let[t,r]of Object.entries(e))if(/\beslint\b/.test(r))return jp(n,t);if((0,h.isDefined)(r.eslint))return`npx eslint`}return Ep(t,_p)?(V.info.defaultLog(`[project-setup] lint: found eslint config file`),`npx eslint`):kp(t,`eslint`)?(V.info.defaultLog(`[project-setup] lint: found eslint in node_modules`),`npx eslint`):null}function zp(e,t,n){for(let{pkg:t}of e){let e=t.scripts??{},r=Bp(t);for(let t of Cp)if((0,h.isDefined)(e[t]))return jp(n,t);for(let[t,r]of Object.entries(e))if(/\bprettier\b/.test(r))return jp(n,t);if((0,h.isDefined)(r.prettier))return`npx prettier`}return Ep(t,vp)?(V.info.defaultLog(`[project-setup] prettier: found prettier config file`),`npx prettier`):kp(t,`prettier`)?(V.info.defaultLog(`[project-setup] prettier: found prettier in node_modules`),`npx prettier`):null}function Bp(e){return{...e.dependencies,...e.devDependencies}}function Vp(e,t){let n=wp(e),r=Tp(e),i=Ap(e),a=(0,h.isDefined)(t)?f.default.relative(e,t):null,o=Fp(r,n,i),s=(0,h.isDefined)(o)&&(0,h.isDefined)(a)?Mp(o,a):null,c=Op(r,n),l=Lp(r,n,i),u=Rp(r,n,i),d=(0,h.isDefined)(u)&&(0,h.isDefined)(a)?`npx eslint ${a}`:null,p=zp(r,n,i),m=(0,h.isDefined)(p)&&(0,h.isDefined)(a)?`npx prettier ${a} --write`:null,g=[];return(0,h.isDefined)(s)||g.push(`testCommand`),(0,h.isDefined)(l)||g.push(`typecheckCommand`),(0,h.isDefined)(d)||g.push(`lintCommand`),(0,h.isDefined)(m)||g.push(`prettierCommand`),{testCommand:s,testRunner:c,typecheckCommand:l,lintCommand:d,prettierCommand:m,packageManager:i,missing:g}}let Hp=(0,O.promisify)(D.exec),Up={testCommand:`test`,buildCommand:`build`,lintCommand:`lint`,prettierCommand:`format`},Wp=function(e){return e.TEST=`testCommand`,e.BUILD=`buildCommand`,e.LINT=`lintCommand`,e.FORMAT=`prettierCommand`,e}({});var Gp=class{setup;testFilePath;workingDirectory;lastCheckAllResult=null;mcpServer;progressLogger;constructor(e){this.setup=e.setup,this.testFilePath=e.testFilePath,this.workingDirectory=e.workingDirectory,this.progressLogger=e.progressLogger??Pe,this.mcpServer=this.buildServer()}getLastCheckAllResult(){return this.lastCheckAllResult}getServer(){return this.mcpServer}buildValidationSummary(){if(!(0,h.isDefined)(this.lastCheckAllResult))return;let e=this.lastCheckAllResult.gates.find(e=>e.gate===Wp.TEST),t=this.lastCheckAllResult.gates.find(e=>e.gate===Wp.LINT),n=(0,h.isDefined)(e?.output)?bf(e.output):void 0,r=(0,h.isDefined)(t?.output)?Sf(t.output):0;return{greenTestsCount:n?.passed??0,redTestsCount:n?.failed??0,greyTestsCount:0,whiteTestsCount:0,naTestsCount:0,errorSuitsCount:n?.suitesFailed??0,lintErrorsCount:r}}async runGate(e){let t=this.setup[e];if(t.status===$f.UNRESOLVED)return{gate:e,passed:!0,skipped:!0};try{let{stdout:n,stderr:r}=await Hp(t.command,{cwd:this.workingDirectory,encoding:`utf8`,timeout:3e5,maxBuffer:10485760});return{gate:e,passed:!0,skipped:!1,output:of((n+r).trim())}}catch(t){let n=sf(t);if(e===Wp.BUILD||e===Wp.LINT){let t=f.default.basename(this.testFilePath);if(!n.includes(t))return{gate:e,passed:!0,skipped:!1,output:`[warning] ${Up[e]??e} failed on unrelated files — not blocking.\n${n}`}}return{gate:e,passed:!1,skipped:!1,output:n}}}async checkAll(){let e=this.setup.lintCommand.status!==$f.UNRESOLVED,t=this.setup.prettierCommand.status!==$f.UNRESOLVED,n=await this.runStabilityLoop(e,t);if(n.stabilityConflict===!0)return this.lastCheckAllResult=n,n;this.progressLogger.verbose(`validating...`);let[r,i]=await Promise.all([this.runGate(Wp.TEST),this.runGate(Wp.BUILD)]),a=!1;if(!r.passed&&(0,h.isDefined)(r.output)){let e=bf(r.output);(0,h.isDefined)(e)&&e.passed>=6&&(a=!0,r.passed=!0)}let o=[...n.gates,r,i],s={passed:o.every(e=>e.passed),gates:o},c=s.gates.find(e=>e.gate===Wp.TEST),l=(0,h.isDefined)(c?.output)?bf(c.output):void 0,u=s.gates.filter(e=>!e.skipped).map(e=>`${Up[e.gate]??e.gate} ${e.passed?`✓`:`✗`}`).join(` `),d=[];(0,h.isDefined)(l)&&(d.push(`${l.passed} green, ${l.failed} red`),l.suitesFailed>0&&d.push(`${l.suitesFailed} suite errors`));let f=d.length>0?` — ${d.join(`, `)}`:``;return this.progressLogger.verbose(`Validation ${s.passed?`passed`:`failed`}:`,u+f),a&&(0,h.isDefined)(l)&&this.progressLogger.verbose(`Pruning tests — ${l.passed} passing, ${l.failed} failing`),this.lastCheckAllResult=s,s}async runStabilityLoop(e,t){let n={gate:Wp.LINT,passed:!0,skipped:!0},r={gate:Wp.FORMAT,passed:!0,skipped:!0};if(!e&&!t)return{passed:!0,gates:[n,r]};let i=await(0,p.readFile)(this.testFilePath,`utf8`);for(let a=0;a<2;a++){let o=await Promise.all([e?this.runGate(Wp.LINT):Promise.resolve(n),t?this.runGate(Wp.FORMAT):Promise.resolve(r)]);if(n=o[0],r=o[1],!n.passed||!r.passed)break;let s=await(0,p.readFile)(this.testFilePath,`utf8`);if(s===i)break;if(a===1)return{passed:!1,stabilityConflict:!0,gates:[n,r]};i=s}return{passed:n.passed&&r.passed,gates:[n,r]}}buildServer(){let e=(0,se.tool)(`check_lint`,`Runs the lint command against the test file and returns pass/fail with output. Use during iteration to check lint status.`,{},async()=>{let e=await this.runGate(Wp.LINT);return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),t=(0,se.tool)(`check_format`,`Runs the format/prettier command against the test file and returns pass/fail with output. Use during iteration to check formatting status.`,{},async()=>{let e=await this.runGate(Wp.FORMAT);return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),n=(0,se.tool)(`check_test`,`Runs the test command and returns pass/fail with output. Use during iteration to check test status.`,{},async()=>{let e=await this.runGate(Wp.TEST),t=(0,h.isDefined)(e.output)?bf(e.output):void 0;return!e.passed&&(0,h.isDefined)(t)&&t.passed>=6&&(this.progressLogger.verbose(`Pruning tests — ${t.passed} passing, ${t.failed} failing`),e.passed=!0),e.testReport=t,{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),r=(0,se.tool)(`check_build`,`Runs the build command and returns pass/fail with output. Use during iteration to check build status.`,{},async()=>{let e=await this.runGate(Wp.BUILD);return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),i=(0,se.tool)(`check_all`,[`Runs ALL verification gates with a lint/format stability check.`,`First runs lint+format in a loop (max 2 iterations) to ensure they stabilize.`,`Then runs test+build once. Returns combined pass/fail.`,`You MUST call this tool and get all-green before completing your task.`,`If it reports a stability conflict, inform the user — do not retry.`].join(` `),{},async()=>{let e=await this.checkAll(),t=e.gates.find(e=>e.gate===Wp.TEST);return e.testReport=(0,h.isDefined)(t?.output)?bf(t.output):void 0,{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),a=(0,se.tool)(`get_status`,`Returns the current verification state: last check_all result and whether you are cleared to finish.`,{},async()=>{let e=this.getLastCheckAllResult(),t={lastCheckAllResult:e,clearedToFinish:e?.passed===!0};return{content:[{type:`text`,text:JSON.stringify(t,null,2)}]}});return(0,se.createSdkMcpServer)({name:`verification_gates`,version:`1.0.0`,tools:[e,t,n,r,i,a]})}},Kp=l(Re()),qp=l(wr()),Jp=l(ze()),Yp,Xp,Zp,Qp;function $p(e){return(0,h.isEmpty)(e)||!(0,w.existsSync)(e)?``:(0,w.readFileSync)(e,`utf8`)}function em(e){return(e.duration_ms/1e3).toFixed(1),``}function tm(e,t){return e+[``,`---`,`IMPORTANT: A test file has been pre-created at: ${t}`,`Use the Edit tool to add your test cases to this file. Do NOT create a new file with the Write tool.`].join(`
32081
32081
  `)}function nm(e){return[``,`<environment>`,`Your working directory is: \`${e}\``,`All tools (Bash, Read, Glob, Grep, Edit) operate relative to this directory automatically.`,"- Do NOT use `cd` to change directories before running commands. Commands like `npm run test` already run from the project root.","- Prefer using relative paths (e.g. `src/services/foo.ts`) instead of absolute paths.",`</environment>`].join(`
32082
32082
  `)}function rm(e){let t=[``,`<project-setup>`,`The following project tooling was verified. Use these commands directly.`,``];e.testCommand.status!==$f.UNRESOLVED&&t.push(`- **Test command**: \`${e.testCommand.command}\``),e.buildCommand.status!==$f.UNRESOLVED&&t.push(`- **Build command**: \`${e.buildCommand.command}\``),e.lintCommand.status!==$f.UNRESOLVED&&t.push(`- **Lint command**: \`${e.lintCommand.command}\``),e.prettierCommand.status!==$f.UNRESOLVED&&t.push(`- **Prettier command**: \`${e.prettierCommand.command}\``),t.push(`- **Package manager**: ${e.packageManager}`);let n=[];return e.testCommand.status===$f.UNRESOLVED&&n.push(`testCommand`),e.buildCommand.status===$f.UNRESOLVED&&n.push(`buildCommand`),e.lintCommand.status===$f.UNRESOLVED&&n.push(`lintCommand`),e.prettierCommand.status===$f.UNRESOLVED&&n.push(`prettierCommand`),(0,h.isEmpty)(n)||t.push(``,`The following commands could not be auto-discovered: ${n.join(`, `)}.`,`Search package.json and project config files to find these manually. Do NOT search for commands already listed above.`),t.push(`</project-setup>`),t.join(`
32083
32083
  `)}function im(e){let t=[[`testCommand`,e.testCommand],[`buildCommand`,e.buildCommand],[`lintCommand`,e.lintCommand],[`prettierCommand`,e.prettierCommand]],n=[``,`<verification-results>`];for(let[e,r]of t)r.status===ep.FAILED?n.push(`${e}: FAILED`,`Output:\n${r.output.trim()}`,``):r.status===ep.PASSED?n.push(`${e}: PASSED`):n.push(`${e}: SKIPPED (command not configured)`);return n.push(`</verification-results>`),n.join(`
32084
- `)}let am=[`testCommand`,`buildCommand`,`lintCommand`,`prettierCommand`],om={testCommand:`test`,buildCommand:`build`,lintCommand:`lint`,prettierCommand:`format`};function sm(e){return e===ep.PASSED?`✓`:e===ep.FAILED?`✗`:`-`}function cm(e){return am.map(t=>`${om[t]} ${sm(e[t].status)}`).join(` `)}function lm(e){return(0,h.isDefined)(e)?` — ${e.greenTestsCount} green, ${e.redTestsCount} red`:``}function um(e,t){for(let n of am){let r=t[n];r.status===ep.FAILED&&e.debug(` ${om[n]} output: ${r.output}`)}}function dm(e,t,n){let r=f.default.relative(t,n),i=e.getTestCommand(),a=e.getLintCommand(),o=e.getPrettierCommand(),s=Vp(t,n);return(0,h.isDefined)(i)&&i!==De&&(s.testCommand=i.replaceAll(we,r),s.missing=s.missing.filter(e=>e!==`testCommand`)),a!==Oe&&(s.lintCommand=a.replaceAll(we,r),s.missing=s.missing.filter(e=>e!==`lintCommand`)),o!==ke&&(s.prettierCommand=o.replaceAll(we,r),s.missing=s.missing.filter(e=>e!==`prettierCommand`)),s}let fm=class{constructor(e,t,n,r,i){this.globalConfigService=e,this.authStorage=t,this.llmModelService=n,this.metricReportService=r,this.verificationService=i}registerAbortGuard(){process.on(`unhandledRejection`,e=>{if(e instanceof se.AbortError){V.info.defaultLog(`[generation] Suppressed SDK AbortError during abort teardown`);return}throw e})}async run(e){let t=new AbortController,n=this.globalConfigService.getProgressLogger((0,h.isDefined)(e.methodName)?{parentName:e.parentName,methodName:e.methodName}:void 0);e.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>t.abort());let{modelName:r,capPrice:i}=await this.llmModelService.getAgentSdkConfig(),a=dm(this.globalConfigService,e.workingDirectory,e.testFilePath);V.info.defaultLog(`[precalc] Project setup resolved:\n${JSON.stringify(a,null,2)}`);let o=[[`test`,a.testCommand],[`build`,a.typecheckCommand],[`lint`,a.lintCommand],[`format`,a.prettierCommand]];n.verbose(`Discovered commands:`);for(let[e,t]of o)n.verbose(` ${(0,h.isDefined)(t)?`✓`:`✗`} ${e}: ${t??`not found`}`);let s=V.getRequestId(),c=new tp(this.metricReportService,s,r,e.testFilePath),l=this.globalConfigService.getPerFunctionTimeout(),u=setTimeout(()=>{let e=(l/6e4).toFixed(1);n.info(`Testable reached timeout after ${e} minutes, aborting`),c.logSyntheticTool(`timeout-abort`,{timeoutMs:l},{reason:`timeout`}),c.flush(),t.abort()},l);try{let o=op(a),s=ip(a.testRunner);await(0,p.mkdir)(f.default.dirname(e.testFilePath),{recursive:!0}),await(0,p.writeFile)(e.testFilePath,s,`utf8`);let l=await this.verificationService.verify({setup:o,testFilePath:e.testFilePath,workingDirectory:e.workingDirectory});V.info.defaultLog(`[verification] Pre-generation: ${JSON.stringify(l,null,2)}`),n.verbose(`Pre-verification:`,cm(l)),um(n,l);let u=o;o=mp(o,l,e.testFilePath),c.addPreVerification(u,l,o),l.testCommand.status===ep.FAILED&&await this.handlePreVerificationFailure(l.testCommand.output,n,c,e.testFilePath),V.info.defaultLog(`[verification] Promoted setup: ${JSON.stringify(o,null,2)}`);let d=am.filter(e=>o[e].status!==$f.UNRESOLVED).map(e=>om[e]),m=am.filter(e=>o[e].status===$f.UNRESOLVED).map(e=>om[e]);n.verbose(`Verified:`,d.join(`, `)+((0,h.isEmpty)(m)?``:` (${m.join(`, `)} dropped)`));let g=await this.runGenerationQuery({...e,model:r,budget:i,verifiedSetup:o,abortController:t,metricsTracer:c,progressLogger:n}),_=await this.verificationService.verify({setup:o,testFilePath:e.testFilePath,workingDirectory:e.workingDirectory});if(V.info.defaultLog(`[verification] Post-generation: ${JSON.stringify(_,null,2)}`),n.verbose(`Post-verification ${_.passed?`passed`:`failed`}:`,cm(_)+lm(g.validationSummary)),_.passed)return g;V.default.warn(`[verification] Gates failed — running cleanup agent to salvage passing tests`),await this.runCleanupQuery({workingDirectory:e.workingDirectory,testFilePath:e.testFilePath,model:r,budget:i,verifiedSetup:o,abortController:t,postVerification:_});let v=await this.verificationService.verify({setup:o,testFilePath:e.testFilePath,workingDirectory:e.workingDirectory});return V.info.defaultLog(`[verification] Post-cleanup: ${JSON.stringify(v,null,2)}`),n.verbose(`Post-cleanup ${v.passed?`passed`:`failed`}:`,cm(v)),v.passed?{code:$p(e.testFilePath),costUsd:g.costUsd,validationSummary:g.validationSummary}:(V.default.warn(`[verification] Cleanup failed — deleting test file: ${e.testFilePath}`),await(0,p.unlink)(e.testFilePath),{code:``,costUsd:g.costUsd,validationSummary:g.validationSummary})}catch(e){if(!t.signal.aborted)throw e;return V.info.defaultLog(`[generation] Aborted — returning partial result`),{code:``}}finally{clearTimeout(u)}}async handlePreVerificationFailure(e,t,n,r){throw t.verbose(`Test command failed on dummy test — aborting`),V.default.warn(`[verification] Test command failed on dummy test — aborting.\n${e}`),await n.flush(),await(0,p.unlink)(r),new np(`test_command_failed`,[`Test command failed: ${e.length>200?e.slice(0,200)+`...(truncated ${e.length-200} chars)`:e}`],0)}async handleGenerationResult(e,t,n,r,i){if(await t.flush(),n.logResult(e),V.info.defaultLog(`SDK model usage: `,e.modelUsage),tf(e))throw new np(e.subtype,e.errors,e.total_cost_usd);let a=$p(i),o=r?.buildValidationSummary()??n.buildValidationSummary();if(V.info.defaultLog(`Validation summary: `,o),!(0,h.isEmpty)(a)){let t=em(e)+a;return(0,w.writeFileSync)(i,t,`utf8`),{code:t,costUsd:e.total_cost_usd,validationSummary:o}}return{code:a,costUsd:e.total_cost_usd,validationSummary:o}}async runCleanupQuery(e){let t=pf(e.testFilePath,e.workingDirectory),n=await this.authStorage.getJWTToken()??``,r=Math.max(e.budget*.25,.25),i=[...bd],a=new Qf(!1),o=V.getRequestId(),s=new tp(this.metricReportService,o,e.model,e.testFilePath);a.logStart({model:e.model,budget:r,cwd:e.workingDirectory,testFile:e.testFilePath,tools:i,hooks:{pre:[`file-restriction`,`env-protection`,`dangerous-command`,`bash-exit-code`],post:[]},maxTurns:15});let c=[`You are a test cleanup agent.`,`The generated test file has failed quality checks (lint, typecheck, prettier, or test failures).`,`Your ONLY goal is to salvage passing tests by removing test cases that fail any check.`,`DO NOT generate new tests. DO NOT fix or modify the logic of any existing test.`,`DO NOT add new imports or describe blocks.`,`Run the available checks, identify failing test cases, and remove them from the file.`,`Keep all tests that pass every check. Leave the file with only clean, passing tests.`].join(` `),l=`The test file at ${e.testFilePath} has failed quality verification.\nThe verification results below were already collected — use them directly to identify failing tests.\nRemove only the failing test cases from the file. Do not generate new tests and do not fix any test.\nAfter removing failing tests, re-run all configured checks (all non-skipped commands) to confirm they all pass.`+im(e.postVerification)+nm(e.workingDirectory)+rm(e.verifiedSetup),u=(0,se.query)({prompt:l,options:{model:e.model,systemPrompt:c,allowedTools:[...bd],permissionMode:yd,allowDangerouslySkipPermissions:!0,maxBudgetUsd:r,maxTurns:15,cwd:e.workingDirectory,abortController:e.abortController,sessionId:(0,y.randomUUID)(),env:{...process.env,ANTHROPIC_BASE_URL:this.globalConfigService.getAnthropicProxyUrl(),ANTHROPIC_AUTH_TOKEN:n,ANTHROPIC_CUSTOM_HEADERS:[`x-request-id: `+V.getRequestId()].join(`
32084
+ `)}let am=[`testCommand`,`buildCommand`,`lintCommand`,`prettierCommand`],om={testCommand:`test`,buildCommand:`build`,lintCommand:`lint`,prettierCommand:`format`};function sm(e){return e===ep.PASSED?`✓`:e===ep.FAILED?`✗`:`-`}function cm(e){return am.map(t=>`${om[t]} ${sm(e[t].status)}`).join(` `)}function lm(e){return(0,h.isDefined)(e)?` — ${e.greenTestsCount} green, ${e.redTestsCount} red`:``}function um(e,t){for(let n of am){let r=t[n];r.status===ep.FAILED&&e.debug(` ${om[n]} output: ${r.output}`)}}function dm(e,t,n){let r=f.default.relative(t,n),i=e.getTestCommand(),a=e.getLintCommand(),o=e.getPrettierCommand(),s=Vp(t,n);return(0,h.isDefined)(i)&&i!==De&&(s.testCommand=i.replaceAll(we,r),s.missing=s.missing.filter(e=>e!==`testCommand`)),a!==Oe&&(s.lintCommand=a.replaceAll(we,r),s.missing=s.missing.filter(e=>e!==`lintCommand`)),o!==ke&&(s.prettierCommand=o.replaceAll(we,r),s.missing=s.missing.filter(e=>e!==`prettierCommand`)),s}let fm=class{constructor(e,t,n,r,i){this.globalConfigService=e,this.authStorage=t,this.llmModelService=n,this.metricReportService=r,this.verificationService=i}registerAbortGuard(){process.on(`unhandledRejection`,e=>{if(e instanceof se.AbortError){V.info.defaultLog(`[generation] Suppressed SDK AbortError during abort teardown`);return}V.error(`unhandledRejection:`,e)})}async run(e){let t=new AbortController,n=this.globalConfigService.getProgressLogger((0,h.isDefined)(e.methodName)?{parentName:e.parentName,methodName:e.methodName}:void 0);e.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>t.abort());let{modelName:r,capPrice:i}=await this.llmModelService.getAgentSdkConfig(),a=dm(this.globalConfigService,e.workingDirectory,e.testFilePath);V.info.defaultLog(`[precalc] Project setup resolved:\n${JSON.stringify(a,null,2)}`);let o=[[`test`,a.testCommand],[`build`,a.typecheckCommand],[`lint`,a.lintCommand],[`format`,a.prettierCommand]];n.verbose(`Discovered commands:`);for(let[e,t]of o)n.verbose(` ${(0,h.isDefined)(t)?`✓`:`✗`} ${e}: ${t??`not found`}`);let s=V.getRequestId(),c=new tp(this.metricReportService,s,r,e.testFilePath),l=this.globalConfigService.getPerFunctionTimeout(),u;try{let o=op(a),s=ip(a.testRunner);await(0,p.mkdir)(f.default.dirname(e.testFilePath),{recursive:!0}),await(0,p.writeFile)(e.testFilePath,s,`utf8`);let d=await this.verificationService.verify({setup:o,testFilePath:e.testFilePath,workingDirectory:e.workingDirectory});V.info.defaultLog(`[verification] Pre-generation: ${JSON.stringify(d,null,2)}`),n.verbose(`Pre-verification:`,cm(d)),um(n,d);let m=o;o=mp(o,d,e.testFilePath),c.addPreVerification(m,d,o),d.testCommand.status===ep.FAILED&&await this.handlePreVerificationFailure(d.testCommand.output,n,c,e.testFilePath),V.info.defaultLog(`[verification] Promoted setup: ${JSON.stringify(o,null,2)}`);let g=am.filter(e=>o[e].status!==$f.UNRESOLVED).map(e=>om[e]),_=am.filter(e=>o[e].status===$f.UNRESOLVED).map(e=>om[e]);n.verbose(`Verified:`,g.join(`, `)+((0,h.isEmpty)(_)?``:` (${_.join(`, `)} dropped)`)),u=setTimeout(()=>{let e=(l/6e4).toFixed(1);n.info(`Testable reached timeout after ${e} minutes, aborting`),c.logSyntheticTool(`timeout-abort`,{timeoutMs:l},{reason:`timeout`}),c.flush(),t.abort()},l);let v=await this.runGenerationQuery({...e,model:r,budget:i,verifiedSetup:o,abortController:t,metricsTracer:c,progressLogger:n});clearTimeout(u),u=void 0;let y=await this.verificationService.verify({setup:o,testFilePath:e.testFilePath,workingDirectory:e.workingDirectory});if(V.info.defaultLog(`[verification] Post-generation: ${JSON.stringify(y,null,2)}`),n.verbose(`Post-verification ${y.passed?`passed`:`failed`}:`,cm(y)+lm(v.validationSummary)),y.passed)return v;V.default.warn(`[verification] Gates failed — running cleanup agent to salvage passing tests`),await this.runCleanupQuery({workingDirectory:e.workingDirectory,testFilePath:e.testFilePath,model:r,budget:i,verifiedSetup:o,abortController:t,postVerification:y});let b=await this.verificationService.verify({setup:o,testFilePath:e.testFilePath,workingDirectory:e.workingDirectory});return V.info.defaultLog(`[verification] Post-cleanup: ${JSON.stringify(b,null,2)}`),n.verbose(`Post-cleanup ${b.passed?`passed`:`failed`}:`,cm(b)),b.passed?{code:$p(e.testFilePath),costUsd:v.costUsd,validationSummary:v.validationSummary}:(V.default.warn(`[verification] Cleanup failed — deleting test file: ${e.testFilePath}`),await(0,p.unlink)(e.testFilePath),{code:``,costUsd:v.costUsd,validationSummary:v.validationSummary})}catch(e){if(!t.signal.aborted)throw e;return V.info.defaultLog(`[generation] Aborted — returning partial result`),{code:``}}finally{clearTimeout(u)}}async handlePreVerificationFailure(e,t,n,r){throw t.verbose(`Test command failed on dummy test — aborting`),V.default.warn(`[verification] Test command failed on dummy test — aborting.\n${e}`),await n.flush(),await(0,p.unlink)(r),new np(`test_command_failed`,[`Test command failed: ${e.length>200?e.slice(0,200)+`...(truncated ${e.length-200} chars)`:e}`],0)}async handleGenerationResult(e,t,n,r,i){if(await t.flush(),n.logResult(e),V.info.defaultLog(`SDK model usage: `,e.modelUsage),tf(e))throw new np(e.subtype,e.errors,e.total_cost_usd);let a=$p(i),o=r?.buildValidationSummary()??n.buildValidationSummary();if(V.info.defaultLog(`Validation summary: `,o),!(0,h.isEmpty)(a)){let t=em(e)+a;return(0,w.writeFileSync)(i,t,`utf8`),{code:t,costUsd:e.total_cost_usd,validationSummary:o}}return{code:a,costUsd:e.total_cost_usd,validationSummary:o}}async runCleanupQuery(e){let t=pf(e.testFilePath,e.workingDirectory),n=await this.authStorage.getJWTToken()??``,r=Math.max(e.budget*.25,.25),i=[...bd],a=new Qf(!1),o=V.getRequestId(),s=new tp(this.metricReportService,o,e.model,e.testFilePath);a.logStart({model:e.model,budget:r,cwd:e.workingDirectory,testFile:e.testFilePath,tools:i,hooks:{pre:[`file-restriction`,`env-protection`,`dangerous-command`,`bash-exit-code`],post:[]},maxTurns:15});let c=[`You are a test cleanup agent.`,`The generated test file has failed quality checks (lint, typecheck, prettier, or test failures).`,`Your ONLY goal is to salvage passing tests by removing test cases that fail any check.`,`DO NOT generate new tests. DO NOT fix or modify the logic of any existing test.`,`DO NOT add new imports or describe blocks.`,`Run the available checks, identify failing test cases, and remove them from the file.`,`Keep all tests that pass every check. Leave the file with only clean, passing tests.`].join(` `),l=`The test file at ${e.testFilePath} has failed quality verification.\nThe verification results below were already collected — use them directly to identify failing tests.\nRemove only the failing test cases from the file. Do not generate new tests and do not fix any test.\nAfter removing failing tests, re-run all configured checks (all non-skipped commands) to confirm they all pass.`+im(e.postVerification)+nm(e.workingDirectory)+rm(e.verifiedSetup),u=(0,se.query)({prompt:l,options:{model:e.model,systemPrompt:c,allowedTools:[...bd],permissionMode:yd,allowDangerouslySkipPermissions:!0,maxBudgetUsd:r,maxTurns:15,cwd:e.workingDirectory,abortController:e.abortController,sessionId:(0,y.randomUUID)(),env:{...process.env,ANTHROPIC_BASE_URL:this.globalConfigService.getAnthropicProxyUrl(),ANTHROPIC_AUTH_TOKEN:n,ANTHROPIC_CUSTOM_HEADERS:[`x-request-id: `+V.getRequestId()].join(`
32085
32085
  `)},hooks:{PreToolUse:[{matcher:`Write|Edit`,hooks:[t]},{matcher:`Read`,hooks:[ff]},{matcher:`Bash`,hooks:[df,uf]}]}}});for await(let e of u)if(a.logMessage(e),await s.processMessage(e),ef(e)){await s.flush(),a.logResult(e),V.info.defaultLog(`[cleanup] SDK model usage: `,e.modelUsage),tf(e)&&V.default.warn(`[cleanup] Agent finished with error: ${e.subtype}`);break}}async runGenerationQuery(e){let t=pf(e.testFilePath,e.workingDirectory),n=xd?new Gp({setup:e.verifiedSetup,testFilePath:e.testFilePath,workingDirectory:e.workingDirectory,progressLogger:e.progressLogger}):void 0,r=n?Nf(n):void 0,i=new Qf(!1),a=[...bd];i.logStart({model:e.model,budget:e.budget,cwd:e.workingDirectory,testFile:e.testFilePath,tools:a,hooks:{pre:[`file-restriction`,`env-protection`,`dangerous-command`,`bash-exit-code`],post:[`test-prune`],...xd&&{stop:[`verification-gates`]}}});let o=tm(e.userPrompt,e.testFilePath)+nm(e.workingDirectory)+rm(e.verifiedSetup),s=await this.authStorage.getJWTToken()??``,{metricsTracer:c}=e,l=(0,se.query)({prompt:o,options:{model:e.model,systemPrompt:e.systemPrompt,allowedTools:a,permissionMode:yd,allowDangerouslySkipPermissions:!0,maxBudgetUsd:e.budget,cwd:e.workingDirectory,abortController:e.abortController,sessionId:(0,y.randomUUID)(),env:{...process.env,ANTHROPIC_BASE_URL:this.globalConfigService.getAnthropicProxyUrl(),ANTHROPIC_AUTH_TOKEN:s,ANTHROPIC_CUSTOM_HEADERS:[`x-request-id: `+V.getRequestId()].join(`
32086
32086
  `)},...n&&{mcpServers:{verification_gates:n.getServer()}},hooks:{PreToolUse:[{matcher:`Write|Edit`,hooks:[t]},{matcher:`Read`,hooks:[ff]},{matcher:`Bash`,hooks:[df,uf]}],PostToolUse:[{matcher:`Bash`,hooks:[jf]},{matcher:`${Cd}|${Sd}`,hooks:[jf]}],...r&&{Stop:[{hooks:[r]}]}}}});for await(let t of l)if(i.logMessage(t),await c.processMessage(t),ef(t))return this.handleGenerationResult(t,c,i,n,e.testFilePath);return{code:$p(e.testFilePath)}}};(0,Jp.default)([(0,_.postConstruct)(),(0,Kp.default)(`design:type`,Function),(0,Kp.default)(`design:paramtypes`,[]),(0,Kp.default)(`design:returntype`,void 0)],fm.prototype,`registerAbortGuard`,null),fm=(0,Jp.default)([(0,_.injectable)(),(0,qp.default)(0,(0,_.inject)(B)),(0,qp.default)(1,(0,_.inject)(Cr)),(0,qp.default)(2,(0,_.inject)(Bf)),(0,qp.default)(3,(0,_.inject)(Xr)),(0,qp.default)(4,(0,_.inject)(pp)),(0,Kp.default)(`design:paramtypes`,[Object,typeof(Yp=Cr!==void 0&&Cr)==`function`?Yp:Object,typeof(Xp=Bf!==void 0&&Bf)==`function`?Xp:Object,typeof(Zp=Xr!==void 0&&Xr)==`function`?Zp:Object,typeof(Qp=pp!==void 0&&pp)==`function`?Qp:Object])],fm);var pm=class{execute(e){let t=!1,n=new Set(e.getKnownDependenciesSnapshot().flatMap(t=>e.getParentParameterRelations(t).filter(e=>e.depthLevelInParent>0).map(e=>e.parameterParentId)));for(let r of e.getKnownDependenciesSnapshot())e.getParentParameterRelations(r).every(e=>n.has(e.parameterParentId))&&(t||=e.moveKnownDependencyToMissing(r.name));let r=e.getDataSource().testedCodeDataSource.codeDependencies.length;return e.getDataSource().testedCodeDataSource.codeDependencies=e.getDataSource().testedCodeDataSource.codeDependencies.filter(t=>!e.getParentParameterRelations(t).every(e=>e.depthLevelInParent>0)),e.getDataSource().testedCodeDataSource.codeDependencies.length!==r&&(t=!0),t}},mm=class{kindsToRemove;constructor(...e){this.kindsToRemove=new Set(e)}execute(e){let t=!1;for(let n of e.getKnownDependenciesSnapshot())this.kindsToRemove.has(n.kind)&&(t||=e.moveKnownDependencyToMissing(n.name));return t}},hm=class{execute(e){let t=e.getDataSource().testedCodeDataSource.testedMethodClass,n=t?.constructorMetadata?.parameters??[],r=t?.properties??[],i=[...n,...r];return e.moveKnownDependencyToMissingByParameters(i)}},gm=class{kinds;constructor(...e){this.kinds=new Set(e)}execute(e){let t=!1,n=e.getMissingDependenciesSnapshot();for(let[r,i]of n.entries())this.kinds.has(i.kind)&&(t||=e.removeCodeInMissingDependencyByIndex(r));return t}},_m=class{execute(e){let t=e.getDataSource().testedCodeDataSource.testedMethod.parameters??[];return e.moveKnownDependencyToMissingByParameters(t)}},vm=class{execute(e){let t=e.getDataSourceSnapshot(),n=this.getParameters(t),r=!1;for(let i=0;i<t.testedCodeDataSource.missingDependencies.length;i++){let a=t.testedCodeDataSource.missingDependencies[i];(0,h.isDefined)(a.dependencyMetadata)&&(this.isMockDependencyKept(a.dependencyMetadata,n)||(r||=e.removeMockDependencyByIndex(i)))}return r}isMockDependencyKept(e,t){if((0,h.isEmpty)(t))return!1;let n=this.getParametersIdsFromMockDependency(e),r=(0,h.intersection)([...t],[...n]);return!(0,h.isEmpty)(r)}getParametersIdsFromMockDependency(e){let t=new h.SafeSet;if(!(0,h.isDefined)(e))return t.toSet();for(let n of e?.methodsMetadata??[]){for(let e of n.parameters)t.safeAdd(e.id);t.safeAdd(n?.returnParam?.id)}for(let n of e?.classMetadata?.properties??[])t.safeAdd(n?.id);for(let n of e?.classMetadata?.constructorMetadata?.parameters??[])t.safeAdd(n?.id);return t.toSet()}getParameters(e){let t=e.testedCodeDataSource.testedMethod.parameters.map(e=>e.id),n=e.testedCodeDataSource.testedMethod.returnParam?.id,r=e.testedCodeDataSource.testedMethodClass?.constructorMetadata?.parameters.map(e=>e.id)??[],i=e.testedCodeDataSource.testedMethodClass?.properties.map(e=>e.id)??[];return new h.SafeSet([...t,n,...r,...i]).toSet()}},ym=class{execute(e){let t=e.getDataSourceSnapshot(),n=t.testedCodeDataSource.testedMethod.parameters.map(e=>e.id),r=t.testedCodeDataSource.testedMethod.returnParam?.id,i=t.testedCodeDataSource.testedMethodClass?.constructorMetadata?.parameters.map(e=>e.id)??[],a=new Set([...n,r,...i].filter(e=>(0,h.isDefined)(e))),o=!1;for(let t of e.getKnownDependenciesSnapshot())this.isDependencyKept(t,a)||(o||=e.moveKnownDependencyToMissing(t.name));return o}isDependencyKept(e,t){return e.kind===`file`||e.kind===`enum`?!0:e.parentParameterRelations.some(e=>e.depthLevelInParent===0&&t.has(e.parameterParentId))}},bm=class{execute(e){let t=e.getDataSource().testedCodeDataSource.testedMethod.returnParam?.id;return(0,h.isDefined)(t)?e.moveKnowDependencyToMissingByParameterId(t):!1}},xm=class{dataSource;getKnownDependenciesSnapshot(){return this.getDataSourceSnapshot().testedCodeDataSource.codeDependencies}getMissingDependenciesSnapshot(){return this.getDataSourceSnapshot().testedCodeDataSource.missingDependencies}constructor(e){this.dataSource=e}getDataSourceSnapshot(){return structuredClone(this.dataSource)}getDataSource(){return this.dataSource}getParentParameterRelations(e){return e.kind===`file`?[]:e.parentParameterRelations}moveKnownDependencyToMissingByParameters(e){let t=e.map(e=>e.id).filter(e=>(0,h.isString)(e)),n=!1;for(let e of t)n||=this.moveKnowDependencyToMissingByParameterId(e);return n}moveKnownDependencyToMissing(e){let t=this.dataSource.testedCodeDataSource.codeDependencies.findIndex(t=>t.name===e);if(t===-1)return!1;let n=this.dataSource.testedCodeDataSource.codeDependencies[t],r=`parentParameterRelations`in n?n.parentParameterRelations:[];if(r.length>1)return!1;let i=r[0]?.parameterParentId;return(0,h.isDefined)(i)?this.moveKnowDependencyToMissingByParameterId(i):this.moveKnowDependencyToMissingByIndex(t)}moveKnowDependencyToMissingByParameterId(e){let t=this.dataSource.testedCodeDataSource.codeDependencies.filter(t=>{let n=this.getParentParameterRelations(t);return n.length===1&&n[0].parameterParentId===e}),n=!1;for(let e of t){this.getParentParameterRelations(e)[0].depthLevelInParent===0&&(this.dataSource.testedCodeDataSource.missingDependencies.push(this.convertCodeDependencyToMissingDependency(e)),n=!0);let t=this.dataSource.testedCodeDataSource.codeDependencies.length;this.dataSource.testedCodeDataSource.codeDependencies=this.dataSource.testedCodeDataSource.codeDependencies.filter(t=>t.name!==e.name),this.dataSource.testedCodeDataSource.codeDependencies.length!==t&&(n=!0)}return n}moveKnowDependencyToMissingByIndex(e){if(e<0||this.dataSource.testedCodeDataSource.codeDependencies.length<=e)return!1;let t=this.dataSource.testedCodeDataSource.codeDependencies[e],n=this.convertCodeDependencyToMissingDependency(t);return this.dataSource.testedCodeDataSource.codeDependencies.splice(e,1),this.dataSource.testedCodeDataSource.missingDependencies.push(n),!0}convertCodeDependencyToMissingDependency(e){let t=(e.kind===`file`?!1:e.containedInTestedFile)??!1;return{name:e.name,kind:e.kind,importPath:e.importPath,code:e.code,isCoreModule:!1,exportType:jt.Unknown,containedInTestedFile:t,isDataObject:e.isDataObject??!1,parentParameterRelations:e.kind===`file`?[]:e.parentParameterRelations,isGenerated:e.isGenerated,baseTypeNames:e.kind===`file`?[]:e.baseTypeNames,ancestorDepthFromTestedClass:e.kind===`file`?void 0:e.ancestorDepthFromTestedClass,importUsageMetadata:e.kind===`file`?void 0:e.importUsageMetadata}}removeMockDependencyByIndex(e){let t=this.dataSource.testedCodeDataSource.missingDependencies?.[e];if(!(0,h.isDefined)(t))return!1;let n=t.dependencyMetadata;return(0,h.isDefined)(n)?(t.dependencyMetadata=void 0,!0):!1}removeCodeInMissingDependencyByIndex(e){let t=this.dataSource.testedCodeDataSource.missingDependencies?.[e];return(0,h.isEmpty)(t?.code)?!1:(t.code=``,!0)}},Sm=class{modifierHandlers=[];modifierCount;constructor(){let e=new gm(`react-class-component`,`react-hook`,`react-forward-ref-component`,`react-function-component`,`react-css-in-js`),t=new mm(`class`),n=new ym,r=new hm,i=new _m,a=new bm,o=new pm,s=new vm;this.modifierHandlers.push(e,t,n,r,i,a,o,s),this.modifierCount=this.modifierHandlers.length}refine(e){let t=new xm(e);for(let e of this.modifierHandlers)if(e.execute(t))return!0;return!1}},Cm=class e{testCodeDatasourceRefiner=new Sm;sizeLimit=0;constructor(e){this.sizeLimit=e??this.sizeLimit}static async init(t){return new e(await t.getDataSourceOptimizerSizeLimit())}async optimize(e){if(this.sizeLimit===0)return e;try{let t=structuredClone(e);return await this.iterateOptimize(t,1)}catch{return e}}getSizeInKilobytes(e){let t=JSON.stringify(e);return Buffer.byteLength(t)/1024}async iterateOptimize(e,t){if(this.testCodeDatasourceRefiner.modifierCount<t||!this.testCodeDatasourceRefiner.refine(e))return e;let n=await this.iterateOptimize(e,t+1);return this.getSizeInKilobytes(n)<=this.sizeLimit?n:await this.iterateOptimize(e,t+1)}};let wm=()=>Ge().getRequestSource()===de.IDE;var Tm=l(Re()),Em=l(ze()),Dm=class{sourceFileCache=new Map;constructor(e,t){this.testable=e,this.filePath=t}async getReferences(e=2){let t=U.get(this.filePath),n=this.findTargetNode(t);if(!n)return[];let r=n.findReferences(),i=[];for(let e of r)for(let t of e.getReferences()){if(t.isDefinition()??!1)continue;let e=t.getSourceFile().getFilePath();if(!/\.spec|\.test/g.test(e)){let e=await this.getReferencedTestables(t);i.push(...e)}}return(0,h.uniqWith)(i,(e,t)=>e.node===t.node).slice(0,e).map(e=>e.node.getText())}findTargetNode(e){return e.getDescendantsOfKind(E.SyntaxKind.Identifier).find(e=>e.getText()===this.testable.name)}async getTestables(e){let t=e.getSourceFile(),n=t.getFilePath(),r=this.sourceFileCache.get(n);if((0,h.isDefined)(r))return r;let i=new Nn(await nt.fromSourceFile(t).getText()).testables.getAllTestables();return this.sourceFileCache.set(n,i),i}async getReferencedTestables(e){try{let t=e.getNode(),[n,r]=[t.getStart(),t.getEnd()];return(await this.getTestables(e)).filter(({type:e,node:t})=>e===`class`||e===`object-method`?!1:t.containsRange(n,r))}catch(e){return V.error(`Error while getting js usage reference code`,e),[]}}};(0,Em.default)([Xt,(0,Tm.default)(`design:type`,Function),(0,Tm.default)(`design:paramtypes`,[Object]),(0,Tm.default)(`design:returntype`,Promise)],Dm.prototype,`getReferences`,null);var Om=l(Re()),km=l(wr()),Am=l(ze()),jm;let Mm=class{constructor(e){this.dependenciesService=e}async getTestedCodeDataSource(e,t,n){await U.init(e);let{methodType:r,methodName:i,parentName:a}=oi(t);V.addContext({subCategory:Ot.CODE_EXTRACTOR}),V.debug.defaultLog(`Get testable context for ${r} ${i}() in ${e}.`);try{let o=await new nt(e).getText(),s=st((0,f.extname)(e)),c=Bl(s),l=c.extract({methodName:i,methodType:r,parentName:a,filePath:e}),u=wm(),d=await this.dependenciesService.getTestCodeDataSourceCore(l,e,u);if(s===`javascript`)return Ga(await this.getJsCodeDataSource(e,t,o,d,l,n));let p,m,g,_,v={name:`NA`,kind:`file`,code:o,importPath:e,dependencyType:`file`,isGenerated:!1},b=[];(0,h.isDefined)(d)?(p=d.codeDependencies,m=d.missingDependencies,g=d.testedMethod,_=d.testedMethodClass,v=d.fileCodeDependency,b=d.libraries):(V.info.defaultLog(`No data source for ${i} - ${r}`),m=[],p=[],g={name:i,isAsync:!1,isStatic:!1,parameters:[],decorators:[],code:o.slice(t.startIndex,t.endIndex),callExpressions:[],imports:[],accessModifierType:Mt.PUBLIC,extendedProperties:{},signature:``,parameterId:(0,y.randomUUID)(),kind:`any`,exportType:jt.Unknown});let x=await new Dm(t,e).getReferences();return m=await this.reevaluateMissingDependencies(m,d,c),Ga({gitUrl:Ge().getGitURL(),filePath:e,relativePathToTestFile:this.getRelativePathToTestFile(e,n),testFramework:Ge().getTestFramework(),language:s,testedMethod:g,testedMethodClass:_,missingDependencies:m,codeDependencies:[v,...p],usages:x,libraries:b})}catch(e){throw V.error(`Error occurred during getTestedCodeDataSource ${i}`,e,i),new cr(or.TESTED_CODE_DATA_SOURCE_ERROR,{methodName:i})}}async getJsCodeDataSource(e,t,n,r,i,a){let{methodName:o}=oi(t),s={name:o,isAsync:!1,isStatic:!1,parameters:[],decorators:[],code:n.slice(t.startIndex,t.endIndex),callExpressions:[],imports:r?.testedMethod.imports??[],exportType:r?.testedMethod.exportType??jt.Named,accessModifierType:r?.testedMethod.accessModifierType??Mt.PUBLIC,extendedProperties:r?.testedMethod.extendedProperties,signature:``,parameterId:(0,y.randomUUID)(),kind:`any`},c={name:`NA`,kind:`file`,code:n,importPath:e,dependencyType:`file`,isGenerated:!1},l=await new Dm(t,e).getReferences(),u=[];if((0,h.isDefined)(i)){let t=await new cc(i,e).extract(),n=i.testedMethod.nestedReactComponents?.hooks??[],r=i.testedMethod.nestedReactComponents?.jsxElements??[],a=[...n,...r].map(t=>({name:t.name,kind:t.kind,importPath:t.importPath,isCoreModule:t.isCoreModule,code:t.code,containedInTestedFile:Qa(e,t),exportType:t.exportType,isDataObject:!1,parentParameterIds:[],parentParameterRelations:[],dependenciesMetadata:[],isGenerated:t.isGenerated,baseTypeNames:[]})),o=t.filter(e=>[`function`,`react-function-component`].includes(e.kind)).map(e=>({name:e.name,kind:e.kind,importPath:e.importPath,isCoreModule:e.isCoreModule,code:e.code,containedInTestedFile:e.containedInTestedFile,exportType:e.exportType,isDataObject:!1,parentParameterIds:[],parentParameterRelations:[],dependenciesMetadata:[],isGenerated:e.isGenerated,baseTypeNames:[]}));u=(0,h.uniqWith)([...o,...a],(e,t)=>e.name===t.name)}return{gitUrl:Ge().getGitURL(),filePath:e,relativePathToTestFile:this.getRelativePathToTestFile(e,a),testFramework:Ge().getTestFramework(),language:`javascript`,testedMethod:s,testedMethodClass:void 0,missingDependencies:u,codeDependencies:[c],usages:l,libraries:r?.libraries??[]}}async getSecondLevelReactMissingDependencies(e,t){if(!(0,h.isDefined)(e))return[];let n=wm(),r=e.missingDependencies.filter(e=>e.kind===`react-function-component`);return(await Promise.all(r.map(async e=>{let r=e.sourceFile;if(!(0,h.isDefined)(r))return null;let i=nt.fromAbsolutePath(r.getFilePath()).getRelativeFilePath(),a=t.extract({methodName:e.name,methodType:`function`,filePath:i});return await this.dependenciesService.getTestCodeDataSourceCore(a,i,n)}))).filter(e=>(0,h.isDefined)(e))}async reevaluateMissingDependencies(e,t,n){if(!(0,h.isDefined)(t))return e;let r=t.testedMethod.parameterId,i=(e,t)=>({...e,parentParameterIds:[r,...e.parentParameterIds],parentParameterRelations:[{parameterParentId:r,depthLevelInParent:t},...e.parentParameterRelations]}),a=t.missingDependencies.map(e=>i(e,1)),o=(await this.getSecondLevelReactMissingDependencies(t,n)).flatMap(e=>e.missingDependencies.map(e=>i(e,2)));return(0,h.uniqWith)([...a,...o],(e,t)=>e.name===t.name&&e.kind===t.kind)}getRelativePathToTestFile(e,t){let n=U.get(e);return U.get(t).getRelativePathTo(n)}};(0,Am.default)([Xt,(0,Om.default)(`design:type`,Function),(0,Om.default)(`design:paramtypes`,[String,Object,String]),(0,Om.default)(`design:returntype`,Promise)],Mm.prototype,`getTestedCodeDataSource`,null),Mm=(0,Am.default)([(0,_.injectable)(),(0,km.default)(0,(0,_.inject)(Fc)),(0,Om.default)(`design:paramtypes`,[typeof(jm=Fc!==void 0&&Fc)==`function`?jm:Object])],Mm);var Nm=l(Re()),Pm=l(wr()),Fm=l(ze()),Im,Lm;let Rm=class{constructor(e,t,n){this.globalConfigService=e,this.featureFlagsService=t,this.testableContextService=n}async gatherDataSource(e){let t=await this.testableContextService.getTestedCodeDataSource(e.path,e.testable,e.testFilePath),n={...(0,h.isDefined)(this.globalConfigService.getGenerateTestsLLMModelName())&&{modelName:this.globalConfigService.getGenerateTestsLLMModelName()},...(0,h.isDefined)(this.globalConfigService.getLLMTemperature())&&{temperature:this.globalConfigService.getLLMTemperature()},...(0,h.isDefined)(this.globalConfigService.getLLMTopP())&&{topP:this.globalConfigService.getLLMTopP()}},r=V.getRequestId();return await this.prepareDTO({dataSource:t,llmConfig:n,userPrompt:(0,h.isDefined)(e.userPrompt)&&!(0,h.isEmpty)(e.userPrompt)?e.userPrompt:this.globalConfigService.getUserPrompt(),generatedTestStructure:this.globalConfigService.getGeneratedTestStructure()},r)}async prepareDTO(e,t){let n=e.dataSource.testedMethod.name;V.debug.defaultLog(`Preparing dto for method ${n}`);try{let t=Xl(e,await this.featureFlagsService.isRemovingDuplicatedCodeInDependencyMetadataEnabled());return(await Cm.init(this.featureFlagsService)).optimize(t)}catch(e){throw V.info.defaultLog(`Failed making preparations for generate test dto`,e,t),new cr(or.PREPARATIONS_FOR_GENERATING_TEST_DTO_ERROR,{methodName:n,errorMessage:`Failed making preparations for generate test dto`})}}};Rm=(0,Fm.default)([(0,_.injectable)(),(0,Pm.default)(0,(0,_.inject)(B)),(0,Pm.default)(1,(0,_.inject)(Ac)),(0,Pm.default)(2,(0,_.inject)(Mm)),(0,Nm.default)(`design:paramtypes`,[typeof(Im=B!==void 0&&B)==`function`?Im:Object,Object,typeof(Lm=Mm!==void 0&&Mm)==`function`?Lm:Object])],Rm);var zm=l(Re()),Bm=l(wr()),Vm=l(ze()),Hm,Um;let Wm=class{constructor(e,t,n){this.apiService=e,this.globalConfigService=t,this.agentSdkRunner=n}async generate(e,t,n,r,i,a){let o={...e,testedCodeDataSource:{...e.testedCodeDataSource,metadataCollectionTime:n}};if(this.globalConfigService.getExperimentalAgentSdk()){V.info.defaultLog(`[experimental] Using generate-prompt endpoint`);let e;try{e=await this.generatePrompt(o,t,r)}catch(e){throw this.globalConfigService.getProgressLogger(a).verbose(`Failed to analyze function — skipping`),e}return this.generateTestViaClaudeAgentSdk(e,i,r,a)}return this.generateViaBackend(o,t,r)}async generateViaBackend(e,t,n){return this.apiService.post(`/api/v1/tests/generate-tests`,e,{headers:{[ur]:t},signal:n})}async generatePrompt(e,t,n){return await this.apiService.post(`/api/v1/tests/generate-prompt`,e,{headers:{[ur]:t},signal:n})}async generateTestViaClaudeAgentSdk(e,t,n,r){if(!(0,h.isDefined)(t)||(0,h.isEmpty)(t))throw Error(`[agent-sdk] testFilePath is required for experimental SDK flow`);V.info.defaultLog(`[agent-sdk] Running Claude Agent SDK locally...`);let i=this.globalConfigService.getRootPath(),a=(xd?`You are an expert unit test generation agent. Your goal is to produce 7-12 high-quality, passing, type-safe, lint-clean unit tests for a given function or method.
32087
32087
 
@@ -32388,8 +32388,11 @@ var n=require(`buffer`),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.fr
32388
32388
  `),stack:e&&e.stack,exception:!0,date:new Date().toString(),process:this.getProcessInfo(),os:this.getOsInfo(),trace:this.getTrace(e)}}getProcessInfo(){return{pid:process.pid,uid:process.getuid?process.getuid():null,gid:process.getgid?process.getgid():null,cwd:process.cwd(),execPath:process.execPath,version:process.version,argv:process.argv,memoryUsage:process.memoryUsage()}}getOsInfo(){return{loadavg:n.loadavg(),uptime:n.uptime()}}getTrace(e){return(e?o.parse(e):o.get()).map(e=>({column:e.getColumnNumber(),file:e.getFileName(),function:e.getFunctionName(),line:e.getLineNumber(),method:e.getMethodName(),native:e.isNative()}))}_addHandler(e){if(!this.handlers.has(e)){e.handleExceptions=!0;let t=new s(e);this.handlers.set(e,t),this.logger.pipe(t)}}_uncaughtException(e){let t=this.getAllInfo(e),n=this._getExceptionHandlers(),o=typeof this.logger.exitOnError==`function`?this.logger.exitOnError(e):this.logger.exitOnError,s;!n.length&&o&&(console.warn(`winston: exitOnError cannot be true with no exception handlers.`),console.warn(`winston: not exiting process.`),o=!1);function c(){i(`doExit`,o),i(`process._exiting`,process._exiting),o&&!process._exiting&&(s&&clearTimeout(s),process.exit(1))}if(!n||n.length===0)return process.nextTick(c);r(n,(e,t)=>{let n=a(t),r=e.transport||e;function o(e){return()=>{i(e),n()}}r._ending=!0,r.once(`finish`,o(`finished`)),r.once(`error`,o(`error`))},()=>o&&c()),this.logger.log(t),o&&(s=setTimeout(c,3e3))}_getExceptionHandlers(){return this.logger.transports.filter(e=>(e.transport||e).handleExceptions)}}})),JZ=s(((e,t)=>{let{Writable:n}=kZ();t.exports=class extends n{constructor(e){if(super({objectMode:!0}),!e)throw Error(`RejectionStream requires a TransportStream instance.`);this.handleRejections=!0,this.transport=e}_write(e,t,n){return e.rejection?this.transport.log(e,n):(n(),!0)}}})),YZ=s(((e,t)=>{let n=require(`os`),r=HZ(),i=MZ()(`winston:rejection`),a=WZ(),o=GZ(),s=JZ();t.exports=class{constructor(e){if(!e)throw Error(`Logger is required to handle rejections`);this.logger=e,this.handlers=new Map}handle(...e){e.forEach(e=>{if(Array.isArray(e))return e.forEach(e=>this._addHandler(e));this._addHandler(e)}),this.catcher||(this.catcher=this._unhandledRejection.bind(this),process.on(`unhandledRejection`,this.catcher))}unhandle(){this.catcher&&(process.removeListener(`unhandledRejection`,this.catcher),this.catcher=!1,Array.from(this.handlers.values()).forEach(e=>this.logger.unpipe(e)))}getAllInfo(e){let t=null;return e&&(t=typeof e==`string`?e:e.message),{error:e,level:`error`,message:[`unhandledRejection: ${t||`(no error message)`}`,e&&e.stack||` No stack trace`].join(`
32389
32389
  `),stack:e&&e.stack,rejection:!0,date:new Date().toString(),process:this.getProcessInfo(),os:this.getOsInfo(),trace:this.getTrace(e)}}getProcessInfo(){return{pid:process.pid,uid:process.getuid?process.getuid():null,gid:process.getgid?process.getgid():null,cwd:process.cwd(),execPath:process.execPath,version:process.version,argv:process.argv,memoryUsage:process.memoryUsage()}}getOsInfo(){return{loadavg:n.loadavg(),uptime:n.uptime()}}getTrace(e){return(e?o.parse(e):o.get()).map(e=>({column:e.getColumnNumber(),file:e.getFileName(),function:e.getFunctionName(),line:e.getLineNumber(),method:e.getMethodName(),native:e.isNative()}))}_addHandler(e){if(!this.handlers.has(e)){e.handleRejections=!0;let t=new s(e);this.handlers.set(e,t),this.logger.pipe(t)}}_unhandledRejection(e){let t=this.getAllInfo(e),n=this._getRejectionHandlers(),o=typeof this.logger.exitOnError==`function`?this.logger.exitOnError(e):this.logger.exitOnError,s;!n.length&&o&&(console.warn(`winston: exitOnError cannot be true with no rejection handlers.`),console.warn(`winston: not exiting process.`),o=!1);function c(){i(`doExit`,o),i(`process._exiting`,process._exiting),o&&!process._exiting&&(s&&clearTimeout(s),process.exit(1))}if(!n||n.length===0)return process.nextTick(c);r(n,(e,t)=>{let n=a(t),r=e.transport||e;function o(e){return()=>{i(e),n()}}r._ending=!0,r.once(`finish`,o(`finished`)),r.once(`error`,o(`error`))},()=>o&&c()),this.logger.log(t),o&&(s=setTimeout(c,3e3))}_getRejectionHandlers(){return this.logger.transports.filter(e=>(e.transport||e).handleRejections)}}})),ite=s(((e,t)=>{t.exports=class{constructor(e){let t=XZ();if(typeof e!=`object`||Array.isArray(e)||!(e instanceof t))throw Error(`Logger is required for profiling`);this.logger=e,this.start=Date.now()}done(...e){typeof e[e.length-1]==`function`&&(console.warn(`Callback function no longer supported as of winston@3.0.0`),e.pop());let t=typeof e[e.length-1]==`object`?e.pop():{};return t.level=t.level||`info`,t.durationMs=Date.now()-this.start,this.logger.write(t)}}})),XZ=s(((e,t)=>{let{Stream:n,Transform:r}=kZ(),i=HZ(),{LEVEL:a,SPLAT:o}=mX(),s=IZ(),c=qZ(),l=YZ(),u=XX(),d=ite(),{warn:f}=PX(),p=zZ(),m=/%[scdjifoO%]/g;var h=class extends r{constructor(e){super({objectMode:!0}),this.configure(e)}child(e){let t=this;return Object.create(t,{write:{value:function(n){let r=Object.assign({},e,n);n instanceof Error&&(r.stack=n.stack,r.message=n.message,r.cause=n.cause),t.write(r)}}})}configure({silent:e,format:t,defaultMeta:n,levels:r,level:i=`info`,exitOnError:a=!0,transports:o,colors:s,emitErrs:u,formatters:d,padLevels:f,rewriters:m,stripColors:h,exceptionHandlers:g,rejectionHandlers:_}={}){if(this.transports.length&&this.clear(),this.silent=e,this.format=t||this.format||CX()(),this.defaultMeta=n||null,this.levels=r||this.levels||p.npm.levels,this.level=i,this.exceptions&&this.exceptions.unhandle(),this.rejections&&this.rejections.unhandle(),this.exceptions=new c(this),this.rejections=new l(this),this.profilers={},this.exitOnError=a,o&&(o=Array.isArray(o)?o:[o],o.forEach(e=>this.add(e))),s||u||d||f||m||h)throw Error([`{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.`,`Use a custom winston.format(function) instead.`,`See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md`].join(`
32390
32390
  `));g&&this.exceptions.handle(g),_&&this.rejections.handle(_)}getHighestLogLevel(){let e=g(this.levels,this.level);return!this.transports||this.transports.length===0?e:this.transports.reduce((e,t)=>{let n=g(this.levels,t.level);return n!==null&&n>e?n:e},e)}isLevelEnabled(e){let t=g(this.levels,e);if(t===null)return!1;let n=g(this.levels,this.level);return n===null?!1:!this.transports||this.transports.length===0?n>=t:this.transports.findIndex(e=>{let r=g(this.levels,e.level);return r===null&&(r=n),r>=t})!==-1}log(e,t,...n){if(arguments.length===1)return e[a]=e.level,this._addDefaultMeta(e),this.write(e),this;if(arguments.length===2)return t&&typeof t==`object`?(t[a]=t.level=e,this._addDefaultMeta(t),this.write(t),this):(t={[a]:e,level:e,message:t},this._addDefaultMeta(t),this.write(t),this);let[r]=n;if(typeof r==`object`&&r&&!(t&&t.match&&t.match(m))){let i=Object.assign({},this.defaultMeta,r,{[a]:e,[o]:n,level:e,message:t});return r.message&&(i.message=`${i.message} ${r.message}`),r.stack&&(i.stack=r.stack),r.cause&&(i.cause=r.cause),this.write(i),this}return this.write(Object.assign({},this.defaultMeta,{[a]:e,[o]:n,level:e,message:t})),this}_transform(e,t,n){if(this.silent)return n();e[a]||(e[a]=e.level),!this.levels[e[a]]&&this.levels[e[a]]!==0&&console.error(`[winston] Unknown logger level: %s`,e[a]),this._readableState.pipes||console.error(`[winston] Attempt to write logs with no transports, which can increase memory usage: %j`,e);try{this.push(this.format.transform(e,this.format.options))}finally{this._writableState.sync=!1,n()}}_final(e){i(this.transports.slice(),(e,t)=>{if(!e||e.finished)return setImmediate(t);e.once(`finish`,t),e.end()},e)}add(e){let t=!s(e)||e.log.length>2?new u({transport:e}):e;if(!t._writableState||!t._writableState.objectMode)throw Error(`Transports must WritableStreams in objectMode. Set { objectMode: true }.`);return this._onEvent(`error`,t),this._onEvent(`warn`,t),this.pipe(t),e.handleExceptions&&this.exceptions.handle(),e.handleRejections&&this.rejections.handle(),this}remove(e){if(!e)return this;let t=e;return(!s(e)||e.log.length>2)&&(t=this.transports.filter(t=>t.transport===e)[0]),t&&this.unpipe(t),this}clear(){return this.unpipe(),this}close(){return this.exceptions.unhandle(),this.rejections.unhandle(),this.clear(),this.emit(`close`),this}setLevels(){f.deprecated(`setLevels`)}query(e,t){typeof e==`function`&&(t=e,e={}),e||={};let n={},r=Object.assign({},e.query||{});function a(t,n){e.query&&typeof t.formatQuery==`function`&&(e.query=t.formatQuery(r)),t.query(e,(r,i)=>{if(r)return n(r);typeof t.formatResults==`function`&&(i=t.formatResults(i,e.format)),n(null,i)})}function o(e,t){a(e,(r,i)=>{t&&(i=r||i,i&&(n[e.name]=i),t()),t=null})}i(this.transports.filter(e=>!!e.query),o,()=>t(null,n))}stream(e={}){let t=new n,r=[];return t._streams=r,t.destroy=()=>{let e=r.length;for(;e--;)r[e].destroy()},this.transports.filter(e=>!!e.stream).forEach(n=>{let i=n.stream(e);i&&(r.push(i),i.on(`log`,e=>{e.transport=e.transport||[],e.transport.push(n.name),t.emit(`log`,e)}),i.on(`error`,e=>{e.transport=e.transport||[],e.transport.push(n.name),t.emit(`error`,e)}))}),t}startTimer(){return new d(this)}profile(e,...t){let n=Date.now();if(this.profilers[e]){let r=this.profilers[e];delete this.profilers[e],typeof t[t.length-2]==`function`&&(console.warn(`Callback function no longer supported as of winston@3.0.0`),t.pop());let i=typeof t[t.length-1]==`object`?t.pop():{};return i.level=i.level||`info`,i.durationMs=n-r,i.message=i.message||e,this.write(i)}return this.profilers[e]=n,this}handleExceptions(...e){console.warn(`Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()`),this.exceptions.handle(...e)}unhandleExceptions(...e){console.warn(`Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()`),this.exceptions.unhandle(...e)}cli(){throw Error([`Logger.cli() was removed in winston@3.0.0`,`Use a custom winston.formats.cli() instead.`,`See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md`].join(`
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})),ZZ=s(((e,t)=>{let{LEVEL:n}=mX(),r=zZ(),i=XZ(),a=MZ()(`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}})),QZ=s(((e,t)=>{let n=ZZ();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)}}})),$Z=u(s((e=>{let t=NX(),{warn:n}=PX();e.version=FX().version,e.transports=RZ(),e.config=zZ(),e.addColors=t.levels,e.format=t.format,e.createLogger=ZZ(),e.Logger=XZ(),e.ExceptionHandler=qZ(),e.RejectionHandler=YZ(),e.Container=QZ(),e.Transport=ZX(),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 eQ=function(e){return e.ERROR=`error`,e.WARN=`warn`,e.INFO=`info`,e.VERBOSE=`verbose`,e.DEBUG=`debug`,e}({});const tQ=eQ.INFO,nQ=eQ.VERBOSE,rQ=eQ.DEBUG;eQ.ERROR,eQ.WARN,eQ.INFO,eQ.VERBOSE,eQ.DEBUG;function iQ(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function aQ(e,t){return function(n,r){t(n,r,e)}}function oQ(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 sQ(...e){return e.map(e=>typeof e==`object`&&e?(0,S.inspect)(e,{depth:4,breakLength:80}):String(e)).join(` `)}let cQ=class{logger;isDebugMode;constructor(e){this.isDebugMode=String(e?.debug)===`true`,this.logger=$Z.createLogger({level:this.getLogLevel(e),transports:[new $Z.transports.Console({format:$Z.format.printf(({message:e})=>String(e??``))})]})}error(...e){this.logger.error(sQ(...e))}warn(...e){this.logger.warn(sQ(...e))}info(...e){this.logger.info(sQ(...e))}verbose(...e){this.logger.verbose(sQ(...e))}debug(...e){this.logger.debug(sQ(...e))}getLogLevel(e){return String(e?.debug)===`true`?rQ:String(e?.verbose)===`true`?nQ:tQ}};cQ=oQ([tt(),aQ(0,Qe(cW.CliOptions)),aQ(0,dt()),iQ(`design:paramtypes`,[Object])],cQ);let lQ=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===uW.PROJECT?{...this.config,secretToken:`xxxx`,token:`xxxx`,...(0,z.isDefined)(e)&&{rootPath:lW.default.relative(e,this.config.rootPath)},...(0,z.isDefined)(this.config.targetDirectory)&&{targetDirectory:lW.default.normalize(this.config.targetDirectory)}}:{...this.config,secretToken:`xxxx`,token:`xxxx`,...(0,z.isDefined)(e)&&{rootPath:lW.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,z.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=QY.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===uW.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:sW.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,z.isEmpty)(e)))}};lQ=oQ([tt(`Singleton`),aQ(0,Qe(cW.CliOptions)),aQ(1,Qe(cQ)),iQ(`design:paramtypes`,[Object,Object])],lQ);let uQ=function(e){return e.Success=`success`,e.Failed=`failed`,e.Skipped=`skipped`,e.NoGeneration=`no_generation`,e}({});var dQ;let fQ=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}setCoverageState(e,t){this.data.coverageState=e,this.data.coverageFailureReason=t}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,z.isDefined)(i)&&i>0?[`- Skipped ${i} methods (already tested)`]:[],`**Action Taken**`,``,`✅ Unit tests automatically generated for ${t} public functions below threshold.`)}if((0,z.isDefined)(this.data.autoCommit)&&this.data.autoCommit.enabled&&e.push(`📦 Test files have been auto-committed to this branch.`),(0,z.isDefined)(this.data.coverageState))switch(this.data.coverageState){case uQ.Failed:e.push(``,`**📊 No coverage data**`),(0,z.isDefined)(this.data.coverageFailureReason)&&e.push(`reason: ${this.data.coverageFailureReason}`);break;case uQ.Skipped:e.push(``,`**📊 Coverage skipped**`);break;case uQ.NoGeneration:e.push(``,`**📊 No tests were generated**`);break;case uQ.Success:this.appendCoverageLine(e,this.data.prCoverage);break}else if((0,z.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}%`;this.appendCoverageLine(e,void 0,r,i)}return e.push(``,`Early Agent is now guarding your coverage.`,"Early Trace ID: `"+this.configService.getConfigValue(`traceId`)+"`"),e.join(`
32392
- `)}appendCoverageLine(e,t,n,r){let i=n??`${t?.before.percentage??0}%`,a=r??`${t?.after.percentage??0}%`;if(!(0,z.isDefined)(t)&&!(0,z.isDefined)(n))return;let o=this.configService.getConfigValue(`command`),s={[uW.PR]:`PR`,[uW.COMMIT]:`Commit`,[uW.PROJECT]:`Project`}[o];(0,z.isDefined)(s)&&e.push(``,`**📊 ${s} coverage before: ${i}. ${s} coverage after: ${a}.**`)}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:[]}}};fQ=oQ([tt(),aQ(0,Qe(lQ)),aQ(1,Qe(cQ)),iQ(`design:paramtypes`,[typeof(dQ=lQ!==void 0&&lQ)==`function`?dQ:Object,Object])],fQ);const pQ={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 mQ=function(e){return e.Added=`added`,e.Modified=`modified`,e}({});var hQ,gQ;let _Q=class{constructor(e,t,n){this.configService=e,this.summaryService=t,this.logger=n}async safePostSummaryToPr(){try{if((0,z.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:mQ.Modified}))}async getContributorAvatarUrl(){}};_Q=oQ([tt(),aQ(0,Qe(lQ)),aQ(1,Qe(fQ)),aQ(2,Qe(cQ)),iQ(`design:paramtypes`,[typeof(hQ=lQ!==void 0&&lQ)==`function`?hQ:Object,typeof(gQ=fQ!==void 0&&fQ)==`function`?gQ:Object,Object])],_Q);const vQ=()=>J0.get(lQ),yQ=(0,S.promisify)(f.exec),bQ=async(e,t={})=>await yQ(e,{cwd:vQ().getConfig().rootPath,...t});var xQ,SQ;let CQ=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 bQ(`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 bQ(`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 bQ(`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 bQ(`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 bQ(`git ls-files --others --exclude-standard`),{stdout:n}=await bQ(`git diff --name-only --diff-filter=M`),r=[...new Set([...t.trim().split(`
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})),ZZ=s(((e,t)=>{let{LEVEL:n}=mX(),r=zZ(),i=XZ(),a=MZ()(`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}})),QZ=s(((e,t)=>{let n=ZZ();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)}}})),$Z=u(s((e=>{let t=NX(),{warn:n}=PX();e.version=FX().version,e.transports=RZ(),e.config=zZ(),e.addColors=t.levels,e.format=t.format,e.createLogger=ZZ(),e.Logger=XZ(),e.ExceptionHandler=qZ(),e.RejectionHandler=YZ(),e.Container=QZ(),e.Transport=ZX(),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 eQ=function(e){return e.ERROR=`error`,e.WARN=`warn`,e.INFO=`info`,e.VERBOSE=`verbose`,e.DEBUG=`debug`,e}({});const tQ=eQ.INFO,nQ=eQ.VERBOSE,rQ=eQ.DEBUG;eQ.ERROR,eQ.WARN,eQ.INFO,eQ.VERBOSE,eQ.DEBUG;function iQ(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function aQ(e,t){return function(n,r){t(n,r,e)}}function oQ(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 sQ(...e){return e.map(e=>typeof e==`object`&&e?(0,S.inspect)(e,{depth:4,breakLength:80}):String(e)).join(` `)}let cQ=class{logger;isDebugMode;constructor(e){this.isDebugMode=String(e?.debug)===`true`,this.logger=$Z.createLogger({level:this.getLogLevel(e),transports:[new $Z.transports.Console({format:$Z.format.printf(({message:e})=>String(e??``))})]})}error(...e){this.logger.error(sQ(...e))}warn(...e){this.logger.warn(sQ(...e))}info(...e){this.logger.info(sQ(...e))}verbose(...e){this.logger.verbose(sQ(...e))}debug(...e){this.logger.debug(sQ(...e))}getLogLevel(e){return String(e?.debug)===`true`?rQ:String(e?.verbose)===`true`?nQ:tQ}};cQ=oQ([tt(),aQ(0,Qe(cW.CliOptions)),aQ(0,dt()),iQ(`design:paramtypes`,[Object])],cQ);let lQ=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===uW.PROJECT?{...this.config,secretToken:`xxxx`,token:`xxxx`,...(0,z.isDefined)(e)&&{rootPath:lW.default.relative(e,this.config.rootPath)},...(0,z.isDefined)(this.config.targetDirectory)&&{targetDirectory:lW.default.normalize(this.config.targetDirectory)}}:{...this.config,secretToken:`xxxx`,token:`xxxx`,...(0,z.isDefined)(e)&&{rootPath:lW.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,z.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=QY.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===uW.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:sW.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,z.isEmpty)(e)))}};lQ=oQ([tt(`Singleton`),aQ(0,Qe(cW.CliOptions)),aQ(1,Qe(cQ)),iQ(`design:paramtypes`,[Object,Object])],lQ);let uQ=function(e){return e.Success=`success`,e.Failed=`failed`,e.Skipped=`skipped`,e.NoGeneration=`no_generation`,e}({});var dQ;let fQ=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}setCoverageState(e,t){this.data.coverageState=e,this.data.coverageFailureReason=t}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,z.isDefined)(i)&&i>0?[`- Skipped ${i} methods (already tested)`]:[],`**Action Taken**`,``,`✅ Unit tests automatically generated for ${t} public functions below threshold.`)}if((0,z.isDefined)(this.data.autoCommit)&&this.data.autoCommit.enabled&&e.push(`📦 Test files have been auto-committed to this branch.`),(0,z.isDefined)(this.data.coverageState))switch(this.data.coverageState){case uQ.Failed:e.push(``,`**📊 No coverage data**`),(0,z.isDefined)(this.data.coverageFailureReason)&&e.push(`reason: ${this.truncateReason(this.data.coverageFailureReason)}`);break;case uQ.Skipped:e.push(``,`**📊 Coverage skipped**`);break;case uQ.NoGeneration:e.push(``,`**📊 No tests were generated**`);break;case uQ.Success:this.appendCoverageLine(e,this.data.prCoverage);break}else if((0,z.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}%`;this.appendCoverageLine(e,void 0,r,i)}return e.push(``,`Early Agent is now guarding your coverage.`,"Early Trace ID: `"+this.configService.getConfigValue(`traceId`)+"`"),e.join(`
32392
+ `)}truncateReason(e,t=5){let n=e.split(`
32393
+ `),r=n.length>t;return`${(r?n.slice(0,t):n).join(`
32394
+ `)}${r?`
32395
+ ...(truncated)`:``}`}appendCoverageLine(e,t,n,r){let i=n??`${t?.before.percentage??0}%`,a=r??`${t?.after.percentage??0}%`;if(!(0,z.isDefined)(t)&&!(0,z.isDefined)(n))return;let o=this.configService.getConfigValue(`command`),s={[uW.PR]:`PR`,[uW.COMMIT]:`Commit`,[uW.PROJECT]:`Project`}[o];(0,z.isDefined)(s)&&e.push(``,`**📊 ${s} coverage before: ${i}. ${s} coverage after: ${a}.**`)}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:[]}}};fQ=oQ([tt(),aQ(0,Qe(lQ)),aQ(1,Qe(cQ)),iQ(`design:paramtypes`,[typeof(dQ=lQ!==void 0&&lQ)==`function`?dQ:Object,Object])],fQ);const pQ={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 mQ=function(e){return e.Added=`added`,e.Modified=`modified`,e}({});var hQ,gQ;let _Q=class{constructor(e,t,n){this.configService=e,this.summaryService=t,this.logger=n}async safePostSummaryToPr(){try{if((0,z.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:mQ.Modified}))}async getContributorAvatarUrl(){}};_Q=oQ([tt(),aQ(0,Qe(lQ)),aQ(1,Qe(fQ)),aQ(2,Qe(cQ)),iQ(`design:paramtypes`,[typeof(hQ=lQ!==void 0&&lQ)==`function`?hQ:Object,typeof(gQ=fQ!==void 0&&fQ)==`function`?gQ:Object,Object])],_Q);const vQ=()=>J0.get(lQ),yQ=(0,S.promisify)(f.exec),bQ=async(e,t={})=>await yQ(e,{cwd:vQ().getConfig().rootPath,...t});var xQ,SQ;let CQ=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 bQ(`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 bQ(`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 bQ(`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 bQ(`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 bQ(`git ls-files --others --exclude-standard`),{stdout:n}=await bQ(`git diff --name-only --diff-filter=M`),r=[...new Set([...t.trim().split(`
32393
32396
  `),...n.trim().split(`
32394
32397
  `)])].filter(Boolean).filter(e=>e.includes(`.early.`)||lW.default.basename(e).startsWith(`test_early_`));return(0,z.isDefined)(e)&&e.absolute?r.map(e=>lW.default.resolve(this.configService.getConfigValue(`gitTopLevel`),e)):r}async commitFiles(e){try{await this.scmHostService.setupGit(),await bQ(`git fetch`),(0,z.isDefined)(e)&&(await bQ(`git checkout ${e}`),await bQ(`git branch --set-upstream-to=origin/${e}`),await bQ(`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 bQ(`git ls-files --others --exclude-standard`),r=n.trim().split(`
32395
32398
  `).filter(Boolean),i=new Set(t.map(e=>lW.default.dirname(e))),a=new Set;for(let e of i){let t=e;for(;t&&t!==`.`;)a.add(t),t=lW.default.dirname(t)}let o=r.filter(e=>{let t=lW.default.basename(e);return t!==`__init__.py`&&t!==`conftest.py`?!1:a.has(lW.default.dirname(e))}),s=[...new Set([...t,...o])];for(let e of s)await bQ(`git add "${e}"`);let{name:c,email:l}=this.scmHostService.getGitCommiterInfo();await bQ(`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 bQ(`git push --no-verify`);let{stdout:u}=await bQ(`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 bQ(`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,z.isDefined)(e.absolute)&&e.absolute){let e=await this.getTopLevel();return t.map(t=>({filePath:lW.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,z.isDefined)(t))throw Error(`commitHash config is required for commit file retrieval`);try{let n=this.configService.getConfigValue(`baseRef`),r;r=(0,z.isDefined)(n)?(await bQ(`git diff --name-status --diff-filter=AM "${await this.getBaseRevision({baseBranch:n})}...${t}"`)).stdout:(await bQ(`git diff-tree --no-commit-id --name-status -r --diff-filter=AM "${t}"`)).stdout;let i=r.trim().split(`
@@ -32405,11 +32408,11 @@ var n=require(`buffer`),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.fr
32405
32408
  `),c=s.byteLength,l=Array.from(e.entries()).map(([e,t])=>{let n=new T1(e,t);return c+=n.size,n});c+=o.byteLength*l.length,c=S$.toFiniteNumber(c);let u={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(c)&&(u[`Content-Length`]=c),t&&t(u),D.Readable.from((async function*(){for(let e of l)yield o,yield*e.encode();yield s})())};var D1=class extends D.default.Transform{__transform(e,t,n){this.push(e),n()}_transform(e,t,n){if(e.length!==0&&(this._transform=this.__transform,e[0]!==120)){let e=Buffer.alloc(2);e[0]=120,e[1]=156,this.push(e,t)}this.__transform(e,t,n)}};const O1=(e,t)=>S$.isAsyncFn(e)?function(...n){let r=n.pop();e.apply(this,n).then(e=>{try{t?r(null,...t(e)):r(null,e)}catch(e){r(e)}},r)}:e;function k1(e,t){e||=10;let n=Array(e),r=Array(e),i=0,a=0,o;return t=t===void 0?1e3:t,function(s){let c=Date.now(),l=r[a];o||=c,n[i]=s,r[i]=c;let u=a,d=0;for(;u!==i;)d+=n[u++],u%=e;if(i=(i+1)%e,i===a&&(a=(a+1)%e),c-o<t)return;let f=l&&c-l;return f?Math.round(d*1e3/f):void 0}}function A1(e,t){let n=0,r=1e3/t,i,a,o=(t,r=Date.now())=>{n=r,i=null,a&&=(clearTimeout(a),null),e(...t)};return[(...e)=>{let t=Date.now(),s=t-n;s>=r?o(e,t):(i=e,a||=setTimeout(()=>{a=null,o(i)},r-s))},()=>i&&o(i)]}const j1=(e,t,n=3)=>{let r=0,i=k1(50,250);return A1(n=>{let a=n.loaded,o=n.lengthComputable?n.total:void 0,s=a-r,c=i(s),l=a<=o;r=a,e({loaded:a,total:o,progress:o?a/o:void 0,bytes:s,rate:c||void 0,estimated:c&&o&&l?(o-a)/c:void 0,event:n,lengthComputable:o!=null,[t?`download`:`upload`]:!0})},n)},M1=(e,t)=>{let n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},N1=e=>(...t)=>S$.asap(()=>e(...t));function P1(e){if(!e||typeof e!=`string`||!e.startsWith(`data:`))return 0;let t=e.indexOf(`,`);if(t<0)return 0;let n=e.slice(5,t),r=e.slice(t+1);if(/;base64/i.test(n)){let e=r.length,t=r.length;for(let n=0;n<t;n++)if(r.charCodeAt(n)===37&&n+2<t){let t=r.charCodeAt(n+1),i=r.charCodeAt(n+2);(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102)&&(i>=48&&i<=57||i>=65&&i<=70||i>=97&&i<=102)&&(e-=2,n+=2)}let n=0,i=t-1,a=e=>e>=2&&r.charCodeAt(e-2)===37&&r.charCodeAt(e-1)===51&&(r.charCodeAt(e)===68||r.charCodeAt(e)===100);i>=0&&(r.charCodeAt(i)===61?(n++,i--):a(i)&&(n++,i-=3)),n===1&&i>=0&&(r.charCodeAt(i)===61||a(i))&&n++;let o=Math.floor(e/4)*3-(n||0);return o>0?o:0}return Buffer.byteLength(r,`utf8`)}const F1={flush:O.default.constants.Z_SYNC_FLUSH,finishFlush:O.default.constants.Z_SYNC_FLUSH},I1={flush:O.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:O.default.constants.BROTLI_OPERATION_FLUSH},L1=S$.isFunction(O.default.createBrotliDecompress),{http:R1,https:z1}=p1.default,B1=/https:?/,V1=X$.protocols.map(e=>e+`:`),H1=(e,[t,n])=>(e.on(`end`,n).on(`error`,n),t);function Ste(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function U1(e,t,n){let r=t;if(!r&&r!==!1){let e=m1.getProxyForUrl(n);e&&(r=new URL(e))}if(r){if(r.username&&(r.auth=(r.username||``)+`:`+(r.password||``)),r.auth){(r.auth.username||r.auth.password)&&(r.auth=(r.auth.username||``)+`:`+(r.auth.password||``));let t=Buffer.from(r.auth,`utf8`).toString(`base64`);e.headers[`Proxy-Authorization`]=`Basic `+t}e.headers.host=e.hostname+(e.port?`:`+e.port:``);let t=r.hostname||r.host;e.hostname=t,e.host=t,e.port=r.port,e.path=n,r.protocol&&(e.protocol=r.protocol.includes(`:`)?r.protocol:`${r.protocol}:`)}e.beforeRedirects.proxy=function(e){U1(e,t,e.href)}}const W1=typeof process<`u`&&S$.kindOf(process)===`process`,G1=e=>new Promise((t,n)=>{let r,i,a=(e,t)=>{i||(i=!0,r&&r(e,t))},o=e=>{a(e),t(e)},s=e=>{a(e,!0),n(e)};e(o,s,e=>r=e).catch(s)}),K1=({address:e,family:t})=>{if(!S$.isString(e))throw TypeError(`address must be a string`);return{address:e,family:t||(e.indexOf(`.`)<0?6:4)}},q1=(e,t)=>K1(S$.isObject(e)?e:{address:e,family:t});var J1=W1&&function(e){return G1(async function(t,n,r){let{data:i,lookup:a,family:o}=e,{responseType:s,responseEncoding:c}=e,l=e.method.toUpperCase(),u,d=!1,f;if(a){let e=O1(a,e=>S$.isArray(e)?e:[e]);a=(t,n,r)=>{e(t,n,(e,t,i)=>{if(e)return r(e);let a=S$.isArray(t)?t.map(e=>q1(e)):[q1(t,i)];n.all?r(e,a):r(e,a[0].address,a[0].family)})}}let p=new E.EventEmitter,m=()=>{e.cancelToken&&e.cancelToken.unsubscribe(h),e.signal&&e.signal.removeEventListener(`abort`,h),p.removeAllListeners()};r((e,t)=>{u=!0,t&&(d=!0,m())});function h(t){p.emit(`abort`,!t||t.type?new c1(null,e,f):t)}p.once(`abort`,n),(e.cancelToken||e.signal)&&(e.cancelToken&&e.cancelToken.subscribe(h),e.signal&&(e.signal.aborted?h():e.signal.addEventListener(`abort`,h)));let g=f1(e.baseURL,e.url,e.allowAbsoluteUrls),_=new URL(g,X$.hasBrowserEnv?X$.origin:void 0),v=_.protocol||V1[0];if(v===`data:`){if(e.maxContentLength>-1&&P1(String(e.url||g||``))>e.maxContentLength)return n(new C$(`maxContentLength size of `+e.maxContentLength+` exceeded`,C$.ERR_BAD_RESPONSE,e));let r;if(l!==`GET`)return l1(t,n,{status:405,statusText:`method not allowed`,headers:{},config:e});try{r=v1(e.url,s===`blob`,{Blob:e.env&&e.env.Blob})}catch(t){throw C$.from(t,C$.ERR_BAD_REQUEST,e)}return s===`text`?(r=r.toString(c),(!c||c===`utf8`)&&(r=S$.stripBOM(r))):s===`stream`&&(r=D.default.Readable.from(r)),l1(t,n,{data:r,status:200,statusText:`OK`,headers:new a1,config:e})}if(V1.indexOf(v)===-1)return n(new C$(`Unsupported protocol `+v,C$.ERR_BAD_REQUEST,e));let y=a1.from(e.headers).normalize();y.set(`User-Agent`,`axios/`+h1,!1);let{onUploadProgress:x,onDownloadProgress:S}=e,T=e.maxRate,k,A;if(S$.isSpecCompliantForm(i)){let e=y.getContentType(/boundary=([-_\w\d]{10,70})/i);i=E1(i,e=>{y.set(e)},{tag:`axios-${h1}-boundary`,boundary:e&&e[1]||void 0})}else if(S$.isFormData(i)&&S$.isFunction(i.getHeaders)){if(y.set(i.getHeaders()),!y.hasContentLength())try{let e=await b.default.promisify(i.getLength).call(i);Number.isFinite(e)&&e>=0&&y.setContentLength(e)}catch{}}else if(S$.isBlob(i)||S$.isFile(i))i.size&&y.setContentType(i.type||`application/octet-stream`),y.setContentLength(i.size||0),i=D.default.Readable.from(S1(i));else if(i&&!S$.isStream(i)){if(!Buffer.isBuffer(i))if(S$.isArrayBuffer(i))i=Buffer.from(new Uint8Array(i));else if(S$.isString(i))i=Buffer.from(i,`utf-8`);else return n(new C$(`Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream`,C$.ERR_BAD_REQUEST,e));if(y.setContentLength(i.length,!1),e.maxBodyLength>-1&&i.length>e.maxBodyLength)return n(new C$(`Request body larger than maxBodyLength limit`,C$.ERR_BAD_REQUEST,e))}let ee=S$.toFiniteNumber(y.getContentLength());S$.isArray(T)?(k=T[0],A=T[1]):k=A=T,i&&(x||k)&&(S$.isStream(i)||(i=D.default.Readable.from(i,{objectMode:!1})),i=D.default.pipeline([i,new b1({maxRate:S$.toFiniteNumber(k)})],S$.noop),x&&i.on(`progress`,H1(i,M1(ee,j1(N1(x),!1,3)))));let j;if(e.auth){let t=e.auth.username||``,n=e.auth.password||``;j=t+`:`+n}if(!j&&_.username){let e=_.username,t=_.password;j=e+`:`+t}j&&y.delete(`authorization`);let te;try{te=L$(_.pathname+_.search,e.params,e.paramsSerializer).replace(/^\?/,``)}catch(t){let r=Error(t.message);return r.config=e,r.url=e.url,r.exists=!0,n(r)}y.set(`Accept-Encoding`,`gzip, compress, deflate`+(L1?`, br`:``),!1);let M={path:te,method:l,headers:y.toJSON(),agents:{http:e.httpAgent,https:e.httpsAgent},auth:j,protocol:v,family:o,beforeRedirect:Ste,beforeRedirects:{}};!S$.isUndefined(a)&&(M.lookup=a),e.socketPath?M.socketPath=e.socketPath:(M.hostname=_.hostname.startsWith(`[`)?_.hostname.slice(1,-1):_.hostname,M.port=_.port,U1(M,e.proxy,v+`//`+_.hostname+(_.port?`:`+_.port:``)+M.path));let ne,N=B1.test(M.protocol);if(M.agent=N?e.httpsAgent:e.httpAgent,e.transport?ne=e.transport:e.maxRedirects===0?ne=N?w.default:C.default:(e.maxRedirects&&(M.maxRedirects=e.maxRedirects),e.beforeRedirect&&(M.beforeRedirects.config=e.beforeRedirect),ne=N?z1:R1),e.maxBodyLength>-1?M.maxBodyLength=e.maxBodyLength:M.maxBodyLength=1/0,e.insecureHTTPParser&&(M.insecureHTTPParser=e.insecureHTTPParser),f=ne.request(M,function(r){if(f.destroyed)return;let i=[r],a=+r.headers[`content-length`];if(S||A){let e=new b1({maxRate:S$.toFiniteNumber(A)});S&&e.on(`progress`,H1(e,M1(a,j1(N1(S),!0,3)))),i.push(e)}let o=r,u=r.req||f;if(e.decompress!==!1&&r.headers[`content-encoding`])switch((l===`HEAD`||r.statusCode===204)&&delete r.headers[`content-encoding`],(r.headers[`content-encoding`]||``).toLowerCase()){case`gzip`:case`x-gzip`:case`compress`:case`x-compress`:i.push(O.default.createUnzip(F1)),delete r.headers[`content-encoding`];break;case`deflate`:i.push(new D1),i.push(O.default.createUnzip(F1)),delete r.headers[`content-encoding`];break;case`br`:L1&&(i.push(O.default.createBrotliDecompress(I1)),delete r.headers[`content-encoding`])}o=i.length>1?D.default.pipeline(i,S$.noop):i[0];let h=D.default.finished(o,()=>{h(),m()}),g={status:r.statusCode,statusText:r.statusMessage,headers:new a1(r.headers),config:e,request:u};if(s===`stream`)g.data=o,l1(t,n,g);else{let r=[],i=0;o.on(`data`,function(t){r.push(t),i+=t.length,e.maxContentLength>-1&&i>e.maxContentLength&&(d=!0,o.destroy(),n(new C$(`maxContentLength size of `+e.maxContentLength+` exceeded`,C$.ERR_BAD_RESPONSE,e,u)))}),o.on(`aborted`,function(){if(d)return;let t=new C$(`stream has been aborted`,C$.ERR_BAD_RESPONSE,e,u);o.destroy(t),n(t)}),o.on(`error`,function(t){f.destroyed||n(C$.from(t,null,e,u))}),o.on(`end`,function(){try{let e=r.length===1?r[0]:Buffer.concat(r);s!==`arraybuffer`&&(e=e.toString(c),(!c||c===`utf8`)&&(e=S$.stripBOM(e))),g.data=e}catch(t){return n(C$.from(t,null,e,g.request,g))}l1(t,n,g)})}p.once(`abort`,e=>{o.destroyed||(o.emit(`error`,e),o.destroy())})}),p.once(`abort`,e=>{n(e),f.destroy(e)}),f.on(`error`,function(t){n(C$.from(t,null,e,f))}),f.on(`socket`,function(e){e.setKeepAlive(!0,1e3*60)}),e.timeout){let t=parseInt(e.timeout,10);if(Number.isNaN(t)){n(new C$("error trying to parse `config.timeout` to int",C$.ERR_BAD_OPTION_VALUE,e,f));return}f.setTimeout(t,function(){if(u)return;let t=e.timeout?`timeout of `+e.timeout+`ms exceeded`:`timeout exceeded`,r=e.transitional||z$;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),n(new C$(t,r.clarifyTimeoutError?C$.ETIMEDOUT:C$.ECONNABORTED,e,f)),h()})}if(S$.isStream(i)){let t=!1,n=!1;i.on(`end`,()=>{t=!0}),i.once(`error`,e=>{n=!0,f.destroy(e)}),i.on(`close`,()=>{!t&&!n&&h(new c1(`Request stream has been aborted`,e,f))}),i.pipe(f)}else f.end(i)})},Y1=X$.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,X$.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(X$.origin),X$.navigator&&/(msie|trident)/i.test(X$.navigator.userAgent)):()=>!0,X1=X$.hasStandardBrowserEnv?{write(e,t,n,r,i,a){let o=[e+`=`+encodeURIComponent(t)];S$.isNumber(n)&&o.push(`expires=`+new Date(n).toGMTString()),S$.isString(r)&&o.push(`path=`+r),S$.isString(i)&&o.push(`domain=`+i),a===!0&&o.push(`secure`),document.cookie=o.join(`; `)},read(e){let t=document.cookie.match(RegExp(`(^|;\\s*)(`+e+`)=([^;]*)`));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,``,Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};const Z1=e=>e instanceof a1?{...e}:e;function Q1(e,t){t||={};let n={};function r(e,t,n,r){return S$.isPlainObject(e)&&S$.isPlainObject(t)?S$.merge.call({caseless:r},e,t):S$.isPlainObject(t)?S$.merge({},t):S$.isArray(t)?t.slice():t}function i(e,t,n,i){if(!S$.isUndefined(t))return r(e,t,n,i);if(!S$.isUndefined(e))return r(void 0,e,n,i)}function a(e,t){if(!S$.isUndefined(t))return r(void 0,t)}function o(e,t){if(!S$.isUndefined(t))return r(void 0,t);if(!S$.isUndefined(e))return r(void 0,e)}function s(n,i,a){if(a in t)return r(n,i);if(a in e)return r(void 0,n)}let c={url:a,method:a,data:a,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:s,headers:(e,t,n)=>i(Z1(e),Z1(t),n,!0)};return S$.forEach(Object.keys({...e,...t}),function(r){let a=c[r]||i,o=a(e[r],t[r],r);S$.isUndefined(o)&&a!==s||(n[r]=o)}),n}var $1=e=>{let t=Q1({},e),{data:n,withXSRFToken:r,xsrfHeaderName:i,xsrfCookieName:a,headers:o,auth:s}=t;if(t.headers=o=a1.from(o),t.url=L$(f1(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),s&&o.set(`Authorization`,`Basic `+btoa((s.username||``)+`:`+(s.password?unescape(encodeURIComponent(s.password)):``))),S$.isFormData(n)){if(X$.hasStandardBrowserEnv||X$.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(S$.isFunction(n.getHeaders)){let e=n.getHeaders(),t=[`content-type`,`content-length`];Object.entries(e).forEach(([e,n])=>{t.includes(e.toLowerCase())&&o.set(e,n)})}}if(X$.hasStandardBrowserEnv&&(r&&S$.isFunction(r)&&(r=r(t)),r||r!==!1&&Y1(t.url))){let e=i&&a&&X1.read(a);e&&o.set(i,e)}return t},e0=typeof XMLHttpRequest<`u`&&function(e){return new Promise(function(t,n){let r=$1(e),i=r.data,a=a1.from(r.headers).normalize(),{responseType:o,onUploadProgress:s,onDownloadProgress:c}=r,l,u,d,f,p;function m(){f&&f(),p&&p(),r.cancelToken&&r.cancelToken.unsubscribe(l),r.signal&&r.signal.removeEventListener(`abort`,l)}let h=new XMLHttpRequest;h.open(r.method.toUpperCase(),r.url,!0),h.timeout=r.timeout;function g(){if(!h)return;let r=a1.from(`getAllResponseHeaders`in h&&h.getAllResponseHeaders());l1(function(e){t(e),m()},function(e){n(e),m()},{data:!o||o===`text`||o===`json`?h.responseText:h.response,status:h.status,statusText:h.statusText,headers:r,config:e,request:h}),h=null}`onloadend`in h?h.onloadend=g:h.onreadystatechange=function(){!h||h.readyState!==4||h.status===0&&!(h.responseURL&&h.responseURL.indexOf(`file:`)===0)||setTimeout(g)},h.onabort=function(){h&&=(n(new C$(`Request aborted`,C$.ECONNABORTED,e,h)),null)},h.onerror=function(t){let r=new C$(t&&t.message?t.message:`Network Error`,C$.ERR_NETWORK,e,h);r.event=t||null,n(r),h=null},h.ontimeout=function(){let t=r.timeout?`timeout of `+r.timeout+`ms exceeded`:`timeout exceeded`,i=r.transitional||z$;r.timeoutErrorMessage&&(t=r.timeoutErrorMessage),n(new C$(t,i.clarifyTimeoutError?C$.ETIMEDOUT:C$.ECONNABORTED,e,h)),h=null},i===void 0&&a.setContentType(null),`setRequestHeader`in h&&S$.forEach(a.toJSON(),function(e,t){h.setRequestHeader(t,e)}),S$.isUndefined(r.withCredentials)||(h.withCredentials=!!r.withCredentials),o&&o!==`json`&&(h.responseType=r.responseType),c&&([d,p]=j1(c,!0),h.addEventListener(`progress`,d)),s&&h.upload&&([u,f]=j1(s),h.upload.addEventListener(`progress`,u),h.upload.addEventListener(`loadend`,f)),(r.cancelToken||r.signal)&&(l=t=>{h&&=(n(!t||t.type?new c1(null,e,h):t),h.abort(),null)},r.cancelToken&&r.cancelToken.subscribe(l),r.signal&&(r.signal.aborted?l():r.signal.addEventListener(`abort`,l)));let _=g1(r.url);if(_&&X$.protocols.indexOf(_)===-1){n(new C$(`Unsupported protocol `+_+`:`,C$.ERR_BAD_REQUEST,e));return}h.send(i||null)})};const t0=(e,t)=>{let{length:n}=e=e?e.filter(Boolean):[];if(t||n){let n=new AbortController,r,i=function(e){if(!r){r=!0,o();let t=e instanceof Error?e:this.reason;n.abort(t instanceof C$?t:new c1(t instanceof Error?t.message:t))}},a=t&&setTimeout(()=>{a=null,i(new C$(`timeout ${t} of ms exceeded`,C$.ETIMEDOUT))},t),o=()=>{e&&=(a&&clearTimeout(a),a=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(i):e.removeEventListener(`abort`,i)}),null)};e.forEach(e=>e.addEventListener(`abort`,i));let{signal:s}=n;return s.unsubscribe=()=>S$.asap(o),s}},n0=function*(e,t){let n=e.byteLength;if(!t||n<t){yield e;return}let r=0,i;for(;r<n;)i=r+t,yield e.slice(r,i),r=i},r0=async function*(e,t){for await(let n of i0(e))yield*n0(n,t)},i0=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:e,value:n}=await t.read();if(e)break;yield n}}finally{await t.cancel()}},a0=(e,t,n,r)=>{let i=r0(e,t),a=0,o,s=e=>{o||(o=!0,r&&r(e))};return new ReadableStream({async pull(e){try{let{done:t,value:r}=await i.next();if(t){s(),e.close();return}let o=r.byteLength;n&&n(a+=o),e.enqueue(new Uint8Array(r))}catch(e){throw s(e),e}},cancel(e){return s(e),i.return()}},{highWaterMark:2})},o0=64*1024,{isFunction:s0}=S$,c0=(({Request:e,Response:t})=>({Request:e,Response:t}))(S$.global),{ReadableStream:l0,TextEncoder:u0}=S$.global,d0=(e,...t)=>{try{return!!e(...t)}catch{return!1}},f0=e=>{e=S$.merge.call({skipUndefined:!0},c0,e);let{fetch:t,Request:n,Response:r}=e,i=t?s0(t):typeof fetch==`function`,a=s0(n),o=s0(r);if(!i)return!1;let s=i&&s0(l0),c=i&&(typeof u0==`function`?(e=>t=>e.encode(t))(new u0):async e=>new Uint8Array(await new n(e).arrayBuffer())),l=a&&s&&d0(()=>{let e=!1,t=new n(X$.origin,{body:new l0,method:`POST`,get duplex(){return e=!0,`half`}}).headers.has(`Content-Type`);return e&&!t}),u=o&&s&&d0(()=>S$.isReadableStream(new r(``).body)),d={stream:u&&(e=>e.body)};i&&[`text`,`arrayBuffer`,`blob`,`formData`,`stream`].forEach(e=>{!d[e]&&(d[e]=(t,n)=>{let r=t&&t[e];if(r)return r.call(t);throw new C$(`Response type '${e}' is not supported`,C$.ERR_NOT_SUPPORT,n)})});let f=async e=>{if(e==null)return 0;if(S$.isBlob(e))return e.size;if(S$.isSpecCompliantForm(e))return(await new n(X$.origin,{method:`POST`,body:e}).arrayBuffer()).byteLength;if(S$.isArrayBufferView(e)||S$.isArrayBuffer(e))return e.byteLength;if(S$.isURLSearchParams(e)&&(e+=``),S$.isString(e))return(await c(e)).byteLength},p=async(e,t)=>S$.toFiniteNumber(e.getContentLength())??f(t);return async e=>{let{url:i,method:o,data:s,signal:c,cancelToken:f,timeout:m,onDownloadProgress:h,onUploadProgress:g,responseType:_,headers:v,withCredentials:y=`same-origin`,fetchOptions:b}=$1(e),x=t||fetch;_=_?(_+``).toLowerCase():`text`;let S=t0([c,f&&f.toAbortSignal()],m),C=null,w=S&&S.unsubscribe&&(()=>{S.unsubscribe()}),T;try{if(g&&l&&o!==`get`&&o!==`head`&&(T=await p(v,s))!==0){let e=new n(i,{method:`POST`,body:s,duplex:`half`}),t;if(S$.isFormData(s)&&(t=e.headers.get(`content-type`))&&v.setContentType(t),e.body){let[t,n]=M1(T,j1(N1(g)));s=a0(e.body,o0,t,n)}}S$.isString(y)||(y=y?`include`:`omit`);let t=a&&`credentials`in n.prototype,c={...b,signal:S,method:o.toUpperCase(),headers:v.normalize().toJSON(),body:s,duplex:`half`,credentials:t?y:void 0};C=a&&new n(i,c);let f=await(a?x(C,b):x(i,c)),m=u&&(_===`stream`||_===`response`);if(u&&(h||m&&w)){let e={};[`status`,`statusText`,`headers`].forEach(t=>{e[t]=f[t]});let t=S$.toFiniteNumber(f.headers.get(`content-length`)),[n,i]=h&&M1(t,j1(N1(h),!0))||[];f=new r(a0(f.body,o0,n,()=>{i&&i(),w&&w()}),e)}_||=`text`;let E=await d[S$.findKey(d,_)||`text`](f,e);return!m&&w&&w(),await new Promise((t,n)=>{l1(t,n,{data:E,headers:a1.from(f.headers),status:f.status,statusText:f.statusText,config:e,request:C})})}catch(t){throw w&&w(),t&&t.name===`TypeError`&&/Load failed|fetch/i.test(t.message)?Object.assign(new C$(`Network Error`,C$.ERR_NETWORK,e,C),{cause:t.cause||t}):C$.from(t,t&&t.code,e,C)}}},p0=new Map,m0=e=>{let t=e?e.env:{},{fetch:n,Request:r,Response:i}=t,a=[r,i,n],o=a.length,s,c,l=p0;for(;o--;)s=a[o],c=l.get(s),c===void 0&&l.set(s,c=o?new Map:f0(t)),l=c;return c};m0();const h0={http:J1,xhr:e0,fetch:{get:m0}};S$.forEach(h0,(e,t)=>{if(e){try{Object.defineProperty(e,`name`,{value:t})}catch{}Object.defineProperty(e,`adapterName`,{value:t})}});const g0=e=>`- ${e}`,_0=e=>S$.isFunction(e)||e===null||e===!1;var v0={getAdapter:(e,t)=>{e=S$.isArray(e)?e:[e];let{length:n}=e,r,i,a={};for(let o=0;o<n;o++){r=e[o];let n;if(i=r,!_0(r)&&(i=h0[(n=String(r)).toLowerCase()],i===void 0))throw new C$(`Unknown adapter '${n}'`);if(i&&(S$.isFunction(i)||(i=i.get(t))))break;a[n||`#`+o]=i}if(!i){let e=Object.entries(a).map(([e,t])=>`adapter ${e} `+(t===!1?`is not supported by the environment`:`is not available in the build`));throw new C$(`There is no suitable adapter to dispatch the request `+(n?e.length>1?`since :
32406
32409
  `+e.map(g0).join(`
32407
32410
  `):` `+g0(e[0]):`as no adapter specified`),`ERR_NOT_SUPPORT`)}return i},adapters:h0};function y0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new c1(null,e)}function b0(e){return y0(e),e.headers=a1.from(e.headers),e.data=o1.call(e,e.transformRequest),[`post`,`put`,`patch`].indexOf(e.method)!==-1&&e.headers.setContentType(`application/x-www-form-urlencoded`,!1),v0.getAdapter(e.adapter||t1.adapter,e)(e).then(function(t){return y0(e),t.data=o1.call(e,e.transformResponse,t),t.headers=a1.from(t.headers),t},function(t){return s1(t)||(y0(e),t&&t.response&&(t.response.data=o1.call(e,e.transformResponse,t.response),t.response.headers=a1.from(t.response.headers))),Promise.reject(t)})}const x0={};[`object`,`boolean`,`number`,`function`,`string`,`symbol`].forEach((e,t)=>{x0[e]=function(n){return typeof n===e||`a`+(t<1?`n `:` `)+e}});const S0={};x0.transitional=function(e,t,n){function r(e,t){return`[Axios v`+h1+`] Transitional option '`+e+`'`+t+(n?`. `+n:``)}return(n,i,a)=>{if(e===!1)throw new C$(r(i,` has been removed`+(t?` in `+t:``)),C$.ERR_DEPRECATED);return t&&!S0[i]&&(S0[i]=!0,console.warn(r(i,` has been deprecated since v`+t+` and will be removed in the near future`))),e?e(n,i,a):!0}},x0.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};function C0(e,t,n){if(typeof e!=`object`)throw new C$(`options must be an object`,C$.ERR_BAD_OPTION_VALUE);let r=Object.keys(e),i=r.length;for(;i-- >0;){let a=r[i],o=t[a];if(o){let t=e[a],n=t===void 0||o(t,a,e);if(n!==!0)throw new C$(`option `+a+` must be `+n,C$.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new C$(`Unknown option `+a,C$.ERR_BAD_OPTION)}}var w0={assertOptions:C0,validators:x0};const T0=w0.validators;var E0=class{constructor(e){this.defaults=e||{},this.interceptors={request:new R$,response:new R$}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=Error();let n=t.stack?t.stack.replace(/^.+\n/,``):``;try{e.stack?n&&!String(e.stack).endsWith(n.replace(/^.+\n.+\n/,``))&&(e.stack+=`
32408
- `+n):e.stack=n}catch{}}throw e}}_request(e,t){typeof e==`string`?(t||={},t.url=e):t=e||{},t=Q1(this.defaults,t);let{transitional:n,paramsSerializer:r,headers:i}=t;n!==void 0&&w0.assertOptions(n,{silentJSONParsing:T0.transitional(T0.boolean),forcedJSONParsing:T0.transitional(T0.boolean),clarifyTimeoutError:T0.transitional(T0.boolean)},!1),r!=null&&(S$.isFunction(r)?t.paramsSerializer={serialize:r}:w0.assertOptions(r,{encode:T0.function,serialize:T0.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls===void 0?t.allowAbsoluteUrls=!0:t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls),w0.assertOptions(t,{baseUrl:T0.spelling(`baseURL`),withXsrfToken:T0.spelling(`withXSRFToken`)},!0),t.method=(t.method||this.defaults.method||`get`).toLowerCase();let a=i&&S$.merge(i.common,i[t.method]);i&&S$.forEach([`delete`,`get`,`head`,`post`,`put`,`patch`,`common`],e=>{delete i[e]}),t.headers=a1.concat(a,i);let o=[],s=!0;this.interceptors.request.forEach(function(e){typeof e.runWhen==`function`&&e.runWhen(t)===!1||(s&&=e.synchronous,o.unshift(e.fulfilled,e.rejected))});let c=[];this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let l,u=0,d;if(!s){let e=[b0.bind(this),void 0];for(e.unshift(...o),e.push(...c),d=e.length,l=Promise.resolve(t);u<d;)l=l.then(e[u++],e[u++]);return l}d=o.length;let f=t;for(;u<d;){let e=o[u++],t=o[u++];try{f=e(f)}catch(e){t.call(this,e);break}}try{l=b0.call(this,f)}catch(e){return Promise.reject(e)}for(u=0,d=c.length;u<d;)l=l.then(c[u++],c[u++]);return l}getUri(e){return e=Q1(this.defaults,e),L$(f1(e.baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};S$.forEach([`delete`,`get`,`head`,`options`],function(e){E0.prototype[e]=function(t,n){return this.request(Q1(n||{},{method:e,url:t,data:(n||{}).data}))}}),S$.forEach([`post`,`put`,`patch`],function(e){function t(t){return function(n,r,i){return this.request(Q1(i||{},{method:e,headers:t?{"Content-Type":`multipart/form-data`}:{},url:n,data:r}))}}E0.prototype[e]=t(),E0.prototype[e+`Form`]=t(!0)});var D0=class e{constructor(e){if(typeof e!=`function`)throw TypeError(`executor must be a function.`);let t;this.promise=new Promise(function(e){t=e});let n=this;this.promise.then(e=>{if(!n._listeners)return;let t=n._listeners.length;for(;t-- >0;)n._listeners[t](e);n._listeners=null}),this.promise.then=e=>{let t,r=new Promise(e=>{n.subscribe(e),t=e}).then(e);return r.cancel=function(){n.unsubscribe(t)},r},e(function(e,r,i){n.reason||(n.reason=new c1(e,r,i),t(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){let e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e(function(e){t=e}),cancel:t}}};function O0(e){return function(t){return e.apply(null,t)}}function k0(e){return S$.isObject(e)&&e.isAxiosError===!0}const A0={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(A0).forEach(([e,t])=>{A0[t]=e});function j0(e){let t=new E0(e),n=wQ(E0.prototype.request,t);return S$.extend(n,E0.prototype,t,{allOwnKeys:!0}),S$.extend(n,t,null,{allOwnKeys:!0}),n.create=function(t){return j0(Q1(e,t))},n}const M0=j0(t1);M0.Axios=E0,M0.CanceledError=c1,M0.CancelToken=D0,M0.isCancel=s1,M0.VERSION=h1,M0.toFormData=M$,M0.AxiosError=C$,M0.Cancel=M0.CanceledError,M0.all=function(e){return Promise.all(e)},M0.spread=O0,M0.isAxiosError=k0,M0.mergeConfig=Q1,M0.AxiosHeaders=a1,M0.formToJSON=e=>e1(S$.isHTMLForm(e)?new FormData(e):e),M0.getAdapter=v0.getAdapter,M0.HttpStatusCode=A0,M0.default=M0;const{Axios:N0,AxiosError:P0,CanceledError:F0,isCancel:I0,CancelToken:L0,VERSION:Cte,all:wte,Cancel:R0,isAxiosError:z0,spread:B0,toFormData:V0,AxiosHeaders:H0,HttpStatusCode:U0,formToJSON:Tte,getAdapter:W0,mergeConfig:G0}=M0;let K0=class extends _Q{async postSummaryToPr(){let e=this.summaryService.generateMarkdownSummary();await M0.post(`https://api.bitbucket.org/2.0/repositories/${this.configService.getConfigValue(`gitOrg`)}/${this.configService.getConfigValue(`gitRepo`)}/pullrequests/${this.configService.getConfigValue(`prNumber`)}/comments`,{content:{raw:e}},{headers:{Authorization:`Bearer ${this.configService.getConfigValue(`token`)}`}})}async getPullRequestInfo(){let e=this.configService.getConfigValue(`gitOrg`),t=this.configService.getConfigValue(`gitRepo`),n=this.configService.getConfigValue(`prNumber`),r=`https://api.bitbucket.org/2.0/repositories/${e}/${t}/pullrequests/${n}`,i=`https://api.bitbucket.org/2.0/repositories/${e}/${t}/pullrequests/${n}/diffstat`,a={Authorization:`Bearer ${this.configService.getConfigValue(`token`)}`},[o,s]=await Promise.all([M0.get(r,{headers:a}),M0.get(i,{headers:a})]);return{number:o.data.id,title:o.data.title,url:o.data.links.html.href,changedFiles:s.data.size,baseRef:o.data.destination.branch.name,headRef:o.data.source.branch.name,contributorAvatarUrl:o.data.author?.links?.avatar?.href}}getGitOrigin(){return this.logger.info(`BitbucketHostService: Getting Git origin`),{origin:`origin`}}async getChangedFilesPR(){return(await this.getChangedFilesWithStatus()).map(e=>e.filePath)}async getChangedFilesWithStatus(){return(await M0.get(`https://api.bitbucket.org/2.0/repositories/${this.configService.getConfigValue(`gitOrg`)}/${this.configService.getConfigValue(`gitRepo`)}/pullrequests/${this.configService.getConfigValue(`prNumber`)}/diffstat`,{headers:{Authorization:`Bearer ${this.configService.getConfigValue(`token`)}`}})).data.values.filter(e=>[`commit_file`,`modified`].includes(e.status)).map(e=>({filePath:e.new?.path??e.old?.path??``,status:e.status===`commit_file`?mQ.Added:mQ.Modified})).filter(e=>e.filePath.length>0)}async getContributorAvatarUrl(){let e=this.configService.getConfigValue(`commitHash`),t=this.configService.getConfigValue(`gitOrg`),n=this.configService.getConfigValue(`gitRepo`);if(!(!(0,z.isDefined)(e)||!(0,z.isDefined)(t)||!(0,z.isDefined)(n)))try{let r=`https://api.bitbucket.org/2.0/repositories/${t}/${n}/commit/${e}`;return(await M0.get(r,{headers:{Authorization:`Bearer ${this.configService.getConfigValue(`token`)}`}})).data.author?.user?.links?.avatar?.href}catch(e){this.logger.warn(`BitbucketHostService: Failed to get contributor avatar: ${e instanceof Error?e.message:`Unknown error`}`);return}}getGitCommiterInfo(){return{name:this.configService.getConfigValue(`gitUserName`)??`early-agent[bot]`,email:this.configService.getConfigValue(`gitUserEmail`)??`early-agent[bot]@startearly.ai`}}async setupGit(){let e=this.configService.getConfigValueOrThrow(`token`),t=Buffer.from(`x-token-auth:${e}`).toString(`base64`);try{await bQ(`git remote set-url origin https://x-token-auth@bitbucket.org/${this.configService.getConfigValue(`gitOrg`)}/${this.configService.getConfigValue(`gitRepo`)}.git`),await bQ(`git config --local http.https://bitbucket.org/.extraheader "AUTHORIZATION: basic ${t}"`)}catch{this.logger.error(`Failed to setup Git for Bitbucket`)}}async teardownGit(){try{await bQ(`git config --local --unset http.https://bitbucket.org/.extraheader`)}catch{this.logger.warn(`Failed to tear down Git configuration for Bitbucket`)}}};K0=oQ([tt(),st({extendConstructorArguments:!0,extendProperties:!0})],K0);let q0=class extends _Q{async setupGit(){let e=Buffer.from(`oauth2:${this.configService.getConfigValue(`token`)}`).toString(`base64`);try{await bQ(`git config --local http.https://github.com/.extraheader "AUTHORIZATION: basic ${e}"`)}catch{this.logger.error(`Failed to setup Git`)}try{await bQ(`git fetch --unshallow`)}catch{}}async getPullRequestInfo(){let e=`https://api.github.com/repos/${this.configService.getConfigValue(`gitOrg`)}/${this.configService.getConfigValue(`gitRepo`)}/pulls/${this.configService.getConfigValue(`prNumber`)}`,t=await M0.get(e,{headers:{Authorization:`Bearer ${this.configService.getConfigValue(`token`)}`}});return{title:t.data.title,number:t.data.number,url:t.data.html_url,changedFiles:t.data.changed_files,baseRef:t.data.base.ref,headRef:t.data.head.ref,contributorAvatarUrl:t.data.user?.avatar_url}}async teardownGit(){await bQ(`git config --local --unset http.https://github.com/.extraheader`)}async postSummaryToPr(){let e=this.summaryService.generateMarkdownSummary();await M0.post(`https://api.github.com/repos/${this.configService.getConfigValue(`gitOrg`)}/${this.configService.getConfigValue(`gitRepo`)}/issues/${this.configService.getConfigValue(`prNumber`)}/comments`,{body:e},{headers:{Authorization:`Bearer ${this.configService.getConfigValue(`token`)}`}})}async getChangedFilesPR(){return(await this.getChangedFilesWithStatus()).map(e=>e.filePath)}async getChangedFilesWithStatus(){let e=`https://api.github.com/repos/${this.configService.getConfigValue(`gitOrg`)}/${this.configService.getConfigValue(`gitRepo`)}/pulls/${this.configService.getConfigValue(`prNumber`)}/files`,t=[];for(let n=1;n<=3;n+=1){let r=await M0.get(e,{headers:{Authorization:`Bearer ${this.configService.getConfigValue(`token`)}`},params:{per_page:100,page:n}});if(t.push(...r.data),r.data.length<100)break}return t.filter(e=>[`added`,`modified`].includes(e.status)).map(e=>({filePath:e.filename,status:e.status===`added`?mQ.Added:mQ.Modified})).filter(e=>e.filePath.length>0)}async getContributorAvatarUrl(){let e=this.configService.getConfigValue(`gitOrg`),t=this.configService.getConfigValue(`gitRepo`),n=this.configService.getConfigValue(`commitHash`);if(!(!(0,z.isDefined)(e)||!(0,z.isDefined)(t)||!(0,z.isDefined)(n)))try{let r=`https://api.github.com/repos/${e}/${t}/commits/${n}`;return(await M0.get(r,{headers:{Authorization:`Bearer ${this.configService.getConfigValue(`token`)}`}})).data.author?.avatar_url}catch(e){this.logger.warn(`GithubHostService: Failed to get contributor avatar: ${e instanceof Error?e.message:`Unknown error`}`);return}}getGitOrigin(){return{origin:`origin`}}getGitCommiterInfo(){return{name:this.configService.getConfigValue(`gitUserName`)??`early-agent[bot]`,email:this.configService.getConfigValue(`gitUserEmail`)??`217573370+Early-Agent[bot]@users.noreply.github.com`}}};q0=oQ([tt(),st({extendConstructorArguments:!0,extendProperties:!0})],q0);const J0=new fr({defaultScope:`Singleton`,autobind:!0});J0.bind(cQ).toSelf().inSingletonScope(),J0.bind(lQ).toDynamicValue(e=>new lQ(J0.get(cW.CliOptions),e.get(cQ))).inSingletonScope(),J0.bind(q0).toSelf().inSingletonScope(),J0.bind(K0).toSelf().inSingletonScope(),J0.bind(cW.SCMHostService).toDynamicValue(e=>{let t=e.get(lQ),n=e.get(cQ),r=t.getConfigValue(`SCMProvider`);n.info(`SCMHostService: Selecting provider based on config: ${r}`);let i;switch(r.toLowerCase()){case`github`:i=e.get(q0);break;case`bitbucket`:i=e.get(K0);break;default:n.warn(`Unknown SCM provider: `+r+`, defaulting to github`),i=e.get(q0);break}return i}).inSingletonScope(),J0.bind(cW.TSAgent).toDynamicValue(async e=>{let t=e.get(lQ),n=await e.getAsync(CQ),r=e.get(cW.SCMHostService);await n.hydrateConfig();let i=await n.getGitInfo();await r.setupGit();let a=J0.get(cQ);return(0,sW.createTSAgent)({...t.getConfig(),includeEarlyTests:!0,context:{git:i},progressLogger:a})}).inSingletonScope();var Y0=class extends Error{constructor(e,t){super(t),this.statusCode=e}},X0=class extends Y0{},Z0=class extends Y0{},Ete,Dte,Ote;let Q0=class{constructor(e,t,n,r){this.tsAgent=e,this.gitService=t,this.configService=n,this.logger=r}async calculateCoverage(e){let{resultCommitSha:t,successSourceFiles:n,successTestFiles:r}=e,i=this.configService.getConfigValue(`refName`);try{this.logger.verbose(`Coverage: checking out pre-commit state...`),await this.gitService.checkout(`${t}^`);let e=this.configService.getConfigValue(`rootPath`),i=r.map(t=>lW.default.isAbsolute(t)?t:lW.default.resolve(e,t)),a=new Set(i.map(e=>lW.default.normalize(e))),o=await this.tsAgent.getTestableFileMap(n),s=this.extractTestPaths(o).filter(e=>!a.has(lW.default.normalize(e)));this.logger.verbose(`Coverage (before): running with ${s.length} existing test files`);for(let e of s)this.logger.debug(` [before] test file: ${e}`);await this.tsAgent.generateCoverage(s);let c=await this.tsAgent.getCoverageForFiles(n),l=await this.tsAgent.getCoverageTree();this.logger.verbose(`Coverage: checking out post-commit state...`),await this.gitService.checkout(t);let u=[...s,...i];this.logger.verbose(`Coverage (after): running with ${u.length} test files`);for(let e of u)this.logger.debug(` [after] test file: ${e}`);await this.tsAgent.generateCoverage(u);let d=await this.tsAgent.getCoverageForFiles(n),f=await this.tsAgent.getCoverageTree();return this.logger.debug(`Coverage complete: before=${c.percentage??`null`}%, after=${d.percentage??`null`}%`),{success:!0,before:{prCoverage:c,coverageTree:l},after:{prCoverage:d,coverageTree:f}}}catch(e){let t=e instanceof Error?e.message:`Unknown error`;return this.logger.warn(`Post-commit coverage failed: `+t),{success:!1,reason:t}}finally{try{(0,z.isDefined)(i)&&await this.gitService.checkout(i)}catch(e){let t=e instanceof Error?e.message:`Unknown error`;this.logger.warn(`Failed to restore HEAD to `+i+`: `+t)}}}extractTestPaths(e){let t=[];for(let n of Object.values(e))for(let e of n)(0,z.isDefined)(e.testPath)&&t.push(e.testPath);return[...new Set(t)]}};Q0=oQ([tt(),aQ(0,Qe(cW.TSAgent)),aQ(1,Qe(CQ)),aQ(2,Qe(lQ)),aQ(3,Qe(cQ)),iQ(`design:paramtypes`,[typeof(Ete=sW.TSAgent!==void 0&&sW.TSAgent)==`function`?Ete:Object,typeof(Dte=CQ!==void 0&&CQ)==`function`?Dte:Object,typeof(Ote=lQ!==void 0&&lQ)==`function`?Ote:Object,Object])],Q0);var $0=u(oH(),1);const e2=`axios-retry`;function t2(e){return e.response||!e.code||[`ERR_CANCELED`,`ECONNABORTED`].includes(e.code)?!1:(0,$0.default)(e)}const n2=[`get`,`head`,`options`],r2=n2.concat([`put`,`delete`]);function i2(e){return e.code!==`ECONNABORTED`&&(!e.response||e.response.status===429||e.response.status>=500&&e.response.status<=599)}function a2(e){return e.config?.method?i2(e)&&n2.indexOf(e.config.method)!==-1:!1}function o2(e){return e.config?.method?i2(e)&&r2.indexOf(e.config.method)!==-1:!1}function kte(e){return t2(e)||o2(e)}function s2(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 c2(e=0,t=void 0){return Math.max(0,s2(t))}function l2(e=0,t=void 0,n=100){let r=2**e*n,i=Math.max(r,s2(t));return i+i*.2*Math.random()}function u2(e=100){return(t=0,n=void 0)=>{let r=t*e;return Math.max(r,s2(n))}}const d2={retries:3,retryCondition:kte,retryDelay:c2,shouldResetTimeout:!1,onRetry:()=>{},onMaxRetryTimesExceeded:()=>{},validateResponse:null};function Ate(e,t){return{...d2,...t,...e[e2]}}function f2(e,t,n=!1){let r=Ate(e,t||{});return r.retryCount=r.retryCount||0,(!r.lastRequestTime||n)&&(r.lastRequestTime=Date.now()),e[e2]=r,r}function p2(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 m2(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 h2(e,t,n,r){t.retryCount+=1;let{retryDelay:i,shouldResetTimeout:a,onRetry:o}=t,s=i(t.retryCount,n);if(p2(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 g2(e,t){e.retryCount>=e.retries&&await e.onMaxRetryTimesExceeded(t,e.retryCount)}const _2=(e,t)=>({requestInterceptorId:e.interceptors.request.use(e=>(f2(e,t,!0),e[e2]?.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 m2(i,n)?h2(e,i,n,r):(await g2(i,n),Promise.reject(n))})});_2.isNetworkError=t2,_2.isSafeRequestError=a2,_2.isIdempotentRequestError=o2,_2.isNetworkOrIdempotentRequestError=kte,_2.exponentialDelay=l2,_2.linearDelay=u2,_2.isRetryableError=i2;const jte=Error(`request for lock canceled`);var v2=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())})},Mte=class{constructor(e,t=jte){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=b2(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return v2(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]=[]),y2(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 y2(e,t){let n=b2(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function b2(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var x2=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())})},S2=class{constructor(e){this._semaphore=new Mte(1,e)}acquire(){return x2(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 C2=new TextDecoder;function w2(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 Nte(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:C2.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=C2.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`).replace(/\s/g,``);try{return w2(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}var T2=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)}},E2=class extends T2{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`};Symbol.asyncIterator;function D2(e){return typeof e==`object`&&!!e}var O2=e=>{if(!D2(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 k2(e){if(typeof e!=`string`)throw new E2(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new E2(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new E2(`Invalid JWT`);if(!t)throw new E2(`JWTs must contain a payload`);let r;try{r=Nte(t)}catch{throw new E2(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(C2.decode(r))}catch{throw new E2(`Failed to parse the decoded payload as JSON`)}if(!O2(i))throw new E2(`Invalid JWT Claims Set`);return i}const A2=e=>{let t=k2(e).exp;return(0,z.isDefined)(t)?t*1e3:null},j2=e=>{if(!(0,z.isDefined)(e))return!0;let t=A2(e);return(0,z.isDefined)(t)?t>Date.now():!0};let M2=class{jwtToken=null;refreshTokenCallback=null;observer=new z.Observer;refreshTokenMutex=new S2;setJWTToken(e){this.jwtToken=e,this.observer.notifyAll(e)}async getJWTToken(){return(0,z.isDefined)(this.jwtToken)?(this.isTokenValid()||await this.refreshTokenMutex.runExclusive(async()=>{if((0,z.isDefined)(this.refreshTokenCallback))return await this.refreshTokenCallback(),this.jwtToken}),this.jwtToken):null}onJWTTokenSave(e){this.observer.addListener(e)}isTokenValid(){return j2(this.jwtToken)}setRefreshTokenCallback(e){this.refreshTokenCallback=e}};M2=oQ([tt(`Singleton`)],M2);var N2,P2;let F2=class{axiosInstance;constructor(e,t,n){this.configService=e,this.authStorage=t,this.logger=n,this.configService=e,this.axiosInstance=M0.create({baseURL:this.configService.getConfigValueOrThrow(`backendURL`),headers:{"Content-Type":`application/json`}}),_2(this.axiosInstance,{retries:3,retryDelay:_2.exponentialDelay,retryCondition:e=>M0.isAxiosError(e)&&_2.isNetworkOrIdempotentRequestError(e)||M0.isAxiosError(e)&&e.response?.status!==void 0&&e.response.status>=500||!1})}async getAuthHeaders(){let e={"x-request-source":sW.RequestSource.CLI},t=await this.authStorage.getJWTToken();return(0,z.isDefined)(t)&&(e.authorization=`Bearer ${t}`),e}async apiCall({url:e,method:t,data:n,config:r}){let i=new H0(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===U0.Conflict){if(t===`workflow_is_cancelled`)throw this.logger.warn(`Agent flow canceled`),new X0(U0.Conflict,t);if(t===`duplicated_by_sha_workflow`)throw this.logger.warn(`Duplicated SHA workflow`),new Z0(U0.Conflict,t)}}handleError(e,t){if(M0.isAxiosError(t))if((0,z.isDefined)(t.response)){let{status:e,statusText:n,data:r}=t.response;throw this.handleCustomErrors(e,r.message),new Y0(e,`API request failed: ${e} ${n} - ${JSON.stringify(r)}`)}else if((0,z.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`)}};F2=oQ([tt(),aQ(0,Qe(lQ)),aQ(1,Qe(M2)),aQ(2,Qe(cQ)),iQ(`design:paramtypes`,[typeof(N2=lQ!==void 0&&lQ)==`function`?N2:Object,typeof(P2=M2!==void 0&&M2)==`function`?P2:Object,Object])],F2);let I2=function(e){return e.PR=`PR`,e.COMMIT=`COMMIT`,e.PROJECT=`PROJECT`,e.COVERAGE=`COVERAGE`,e}({});var L2,Pte;let R2=class{constructor(e,t){this.apiService=e,this.configService=t}mapCommandToType(e){switch(e){case uW.PR:return I2.PR;case uW.COMMIT:return I2.COMMIT;case uW.PROJECT:return I2.PROJECT;case uW.COVERAGE:return I2.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,z.isDefined)(e))return;let t=this.configService.getConfigValue(`reuseCoverageMaxRuns`),n=await this.apiService.post(`api/v1/workflows/${e}/reuse-coverage`,{limit:t});if((0,z.isDefined)(n.coverageBefore))return n.coverageBefore}};R2=oQ([tt(),aQ(0,Qe(F2)),aQ(1,Qe(lQ)),iQ(`design:paramtypes`,[typeof(L2=F2!==void 0&&F2)==`function`?L2:Object,typeof(Pte=lQ!==void 0&&lQ)==`function`?Pte:Object])],R2);var z2,B2,V2,H2,U2;let W2=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,z.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`}`)}}};W2=oQ([tt(),aQ(0,Qe(CQ)),aQ(1,Qe(lQ)),aQ(2,Qe(fQ)),aQ(3,Qe(cW.SCMHostService)),aQ(4,Qe(R2)),aQ(5,Qe(cQ)),iQ(`design:paramtypes`,[typeof(z2=CQ!==void 0&&CQ)==`function`?z2:Object,typeof(B2=lQ!==void 0&&lQ)==`function`?B2:Object,typeof(V2=fQ!==void 0&&fQ)==`function`?V2:Object,typeof(H2=_Q!==void 0&&_Q)==`function`?H2:Object,typeof(U2=R2!==void 0&&R2)==`function`?U2:Object,Object])],W2);let G2=class{constructor(e){this.logger=e}detectChanges(e,t,n,r,i){try{return!(0,z.isDefined)(r)||(0,z.isEmpty)(r)?this.handleNewFile(e,n):this.compareMethodLists(e,t,n,r,i)}catch(t){return this.logger.warn(`Failed to detect changes in file ${e}: ${t instanceof Error?t.message:`Unknown error`}`),[]}}handleNewFile(e,t){return t.map(t=>({name:t.name,type:t.type,parentName:`parentName`in t?t.parentName:void 0,changeType:`added`,filePath:e,canCreateTests:t.canCreateTests}))}compareMethodLists(e,t,n,r,i){let a=[];for(let o of n){let n=this.findMatchingMethod(t,o);(0,z.isDefined)(n)?this.hasMethodChanged(n,o,r,i)&&a.push(this.createChangedMethod(e,o,`modified`)):a.push(this.createChangedMethod(e,o,`added`))}for(let r of t)this.findMatchingMethod(n,r)||a.push(this.createChangedMethod(e,r,`deleted`));return a}findMatchingMethod(e,t){return e.find(e=>{let n=e.name===t.name,r=e.type===t.type,i=(`parentName`in e?e.parentName:void 0)===(`parentName`in t?t.parentName:void 0);return n&&r&&i})}hasMethodChanged(e,t,n,r){let i=this.extractMethodText(e,n),a=this.extractMethodText(t,r);return i.replaceAll(`\r
32411
+ `+n):e.stack=n}catch{}}throw e}}_request(e,t){typeof e==`string`?(t||={},t.url=e):t=e||{},t=Q1(this.defaults,t);let{transitional:n,paramsSerializer:r,headers:i}=t;n!==void 0&&w0.assertOptions(n,{silentJSONParsing:T0.transitional(T0.boolean),forcedJSONParsing:T0.transitional(T0.boolean),clarifyTimeoutError:T0.transitional(T0.boolean)},!1),r!=null&&(S$.isFunction(r)?t.paramsSerializer={serialize:r}:w0.assertOptions(r,{encode:T0.function,serialize:T0.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls===void 0?t.allowAbsoluteUrls=!0:t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls),w0.assertOptions(t,{baseUrl:T0.spelling(`baseURL`),withXsrfToken:T0.spelling(`withXSRFToken`)},!0),t.method=(t.method||this.defaults.method||`get`).toLowerCase();let a=i&&S$.merge(i.common,i[t.method]);i&&S$.forEach([`delete`,`get`,`head`,`post`,`put`,`patch`,`common`],e=>{delete i[e]}),t.headers=a1.concat(a,i);let o=[],s=!0;this.interceptors.request.forEach(function(e){typeof e.runWhen==`function`&&e.runWhen(t)===!1||(s&&=e.synchronous,o.unshift(e.fulfilled,e.rejected))});let c=[];this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let l,u=0,d;if(!s){let e=[b0.bind(this),void 0];for(e.unshift(...o),e.push(...c),d=e.length,l=Promise.resolve(t);u<d;)l=l.then(e[u++],e[u++]);return l}d=o.length;let f=t;for(;u<d;){let e=o[u++],t=o[u++];try{f=e(f)}catch(e){t.call(this,e);break}}try{l=b0.call(this,f)}catch(e){return Promise.reject(e)}for(u=0,d=c.length;u<d;)l=l.then(c[u++],c[u++]);return l}getUri(e){return e=Q1(this.defaults,e),L$(f1(e.baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};S$.forEach([`delete`,`get`,`head`,`options`],function(e){E0.prototype[e]=function(t,n){return this.request(Q1(n||{},{method:e,url:t,data:(n||{}).data}))}}),S$.forEach([`post`,`put`,`patch`],function(e){function t(t){return function(n,r,i){return this.request(Q1(i||{},{method:e,headers:t?{"Content-Type":`multipart/form-data`}:{},url:n,data:r}))}}E0.prototype[e]=t(),E0.prototype[e+`Form`]=t(!0)});var D0=class e{constructor(e){if(typeof e!=`function`)throw TypeError(`executor must be a function.`);let t;this.promise=new Promise(function(e){t=e});let n=this;this.promise.then(e=>{if(!n._listeners)return;let t=n._listeners.length;for(;t-- >0;)n._listeners[t](e);n._listeners=null}),this.promise.then=e=>{let t,r=new Promise(e=>{n.subscribe(e),t=e}).then(e);return r.cancel=function(){n.unsubscribe(t)},r},e(function(e,r,i){n.reason||(n.reason=new c1(e,r,i),t(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){let e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e(function(e){t=e}),cancel:t}}};function O0(e){return function(t){return e.apply(null,t)}}function k0(e){return S$.isObject(e)&&e.isAxiosError===!0}const A0={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(A0).forEach(([e,t])=>{A0[t]=e});function j0(e){let t=new E0(e),n=wQ(E0.prototype.request,t);return S$.extend(n,E0.prototype,t,{allOwnKeys:!0}),S$.extend(n,t,null,{allOwnKeys:!0}),n.create=function(t){return j0(Q1(e,t))},n}const M0=j0(t1);M0.Axios=E0,M0.CanceledError=c1,M0.CancelToken=D0,M0.isCancel=s1,M0.VERSION=h1,M0.toFormData=M$,M0.AxiosError=C$,M0.Cancel=M0.CanceledError,M0.all=function(e){return Promise.all(e)},M0.spread=O0,M0.isAxiosError=k0,M0.mergeConfig=Q1,M0.AxiosHeaders=a1,M0.formToJSON=e=>e1(S$.isHTMLForm(e)?new FormData(e):e),M0.getAdapter=v0.getAdapter,M0.HttpStatusCode=A0,M0.default=M0;const{Axios:N0,AxiosError:P0,CanceledError:F0,isCancel:I0,CancelToken:L0,VERSION:Cte,all:wte,Cancel:R0,isAxiosError:z0,spread:B0,toFormData:V0,AxiosHeaders:H0,HttpStatusCode:U0,formToJSON:Tte,getAdapter:W0,mergeConfig:G0}=M0;let K0=class extends _Q{async postSummaryToPr(){let e=this.summaryService.generateMarkdownSummary();await M0.post(`https://api.bitbucket.org/2.0/repositories/${this.configService.getConfigValue(`gitOrg`)}/${this.configService.getConfigValue(`gitRepo`)}/pullrequests/${this.configService.getConfigValue(`prNumber`)}/comments`,{content:{raw:e}},{headers:{Authorization:`Bearer ${this.configService.getConfigValue(`token`)}`}})}async getPullRequestInfo(){let e=this.configService.getConfigValue(`gitOrg`),t=this.configService.getConfigValue(`gitRepo`),n=this.configService.getConfigValue(`prNumber`),r=`https://api.bitbucket.org/2.0/repositories/${e}/${t}/pullrequests/${n}`,i=`https://api.bitbucket.org/2.0/repositories/${e}/${t}/pullrequests/${n}/diffstat`,a={Authorization:`Bearer ${this.configService.getConfigValue(`token`)}`},[o,s]=await Promise.all([M0.get(r,{headers:a}),M0.get(i,{headers:a})]);return{number:o.data.id,title:o.data.title,url:o.data.links.html.href,changedFiles:s.data.size,baseRef:o.data.destination.branch.name,headRef:o.data.source.branch.name,contributorAvatarUrl:o.data.author?.links?.avatar?.href}}getGitOrigin(){return this.logger.info(`BitbucketHostService: Getting Git origin`),{origin:`origin`}}async getChangedFilesPR(){return(await this.getChangedFilesWithStatus()).map(e=>e.filePath)}async getChangedFilesWithStatus(){return(await M0.get(`https://api.bitbucket.org/2.0/repositories/${this.configService.getConfigValue(`gitOrg`)}/${this.configService.getConfigValue(`gitRepo`)}/pullrequests/${this.configService.getConfigValue(`prNumber`)}/diffstat`,{headers:{Authorization:`Bearer ${this.configService.getConfigValue(`token`)}`}})).data.values.filter(e=>[`commit_file`,`modified`].includes(e.status)).map(e=>({filePath:e.new?.path??e.old?.path??``,status:e.status===`commit_file`?mQ.Added:mQ.Modified})).filter(e=>e.filePath.length>0)}async getContributorAvatarUrl(){let e=this.configService.getConfigValue(`commitHash`),t=this.configService.getConfigValue(`gitOrg`),n=this.configService.getConfigValue(`gitRepo`);if(!(!(0,z.isDefined)(e)||!(0,z.isDefined)(t)||!(0,z.isDefined)(n)))try{let r=`https://api.bitbucket.org/2.0/repositories/${t}/${n}/commit/${e}`;return(await M0.get(r,{headers:{Authorization:`Bearer ${this.configService.getConfigValue(`token`)}`}})).data.author?.user?.links?.avatar?.href}catch(e){this.logger.warn(`BitbucketHostService: Failed to get contributor avatar: ${e instanceof Error?e.message:`Unknown error`}`);return}}getGitCommiterInfo(){return{name:this.configService.getConfigValue(`gitUserName`)??`early-agent[bot]`,email:this.configService.getConfigValue(`gitUserEmail`)??`early-agent[bot]@startearly.ai`}}async setupGit(){let e=this.configService.getConfigValueOrThrow(`token`),t=Buffer.from(`x-token-auth:${e}`).toString(`base64`);try{await bQ(`git remote set-url origin https://x-token-auth@bitbucket.org/${this.configService.getConfigValue(`gitOrg`)}/${this.configService.getConfigValue(`gitRepo`)}.git`),await bQ(`git config --local http.https://bitbucket.org/.extraheader "AUTHORIZATION: basic ${t}"`)}catch{this.logger.error(`Failed to setup Git for Bitbucket`)}}async teardownGit(){try{await bQ(`git config --local --unset http.https://bitbucket.org/.extraheader`)}catch{this.logger.warn(`Failed to tear down Git configuration for Bitbucket`)}}};K0=oQ([tt(),st({extendConstructorArguments:!0,extendProperties:!0})],K0);let q0=class extends _Q{async setupGit(){let e=Buffer.from(`oauth2:${this.configService.getConfigValue(`token`)}`).toString(`base64`);try{await bQ(`git config --local http.https://github.com/.extraheader "AUTHORIZATION: basic ${e}"`)}catch{this.logger.error(`Failed to setup Git`)}try{await bQ(`git fetch --unshallow`)}catch{}}async getPullRequestInfo(){let e=`https://api.github.com/repos/${this.configService.getConfigValue(`gitOrg`)}/${this.configService.getConfigValue(`gitRepo`)}/pulls/${this.configService.getConfigValue(`prNumber`)}`,t=await M0.get(e,{headers:{Authorization:`Bearer ${this.configService.getConfigValue(`token`)}`}});return{title:t.data.title,number:t.data.number,url:t.data.html_url,changedFiles:t.data.changed_files,baseRef:t.data.base.ref,headRef:t.data.head.ref,contributorAvatarUrl:t.data.user?.avatar_url}}async teardownGit(){await bQ(`git config --local --unset http.https://github.com/.extraheader`)}async postSummaryToPr(){let e=this.summaryService.generateMarkdownSummary();await M0.post(`https://api.github.com/repos/${this.configService.getConfigValue(`gitOrg`)}/${this.configService.getConfigValue(`gitRepo`)}/issues/${this.configService.getConfigValue(`prNumber`)}/comments`,{body:e},{headers:{Authorization:`Bearer ${this.configService.getConfigValue(`token`)}`}})}async getChangedFilesPR(){return(await this.getChangedFilesWithStatus()).map(e=>e.filePath)}async getChangedFilesWithStatus(){let e=`https://api.github.com/repos/${this.configService.getConfigValue(`gitOrg`)}/${this.configService.getConfigValue(`gitRepo`)}/pulls/${this.configService.getConfigValue(`prNumber`)}/files`,t=[];for(let n=1;n<=3;n+=1){let r=await M0.get(e,{headers:{Authorization:`Bearer ${this.configService.getConfigValue(`token`)}`},params:{per_page:100,page:n}});if(t.push(...r.data),r.data.length<100)break}return t.filter(e=>[`added`,`modified`].includes(e.status)).map(e=>({filePath:e.filename,status:e.status===`added`?mQ.Added:mQ.Modified})).filter(e=>e.filePath.length>0)}async getContributorAvatarUrl(){let e=this.configService.getConfigValue(`gitOrg`),t=this.configService.getConfigValue(`gitRepo`),n=this.configService.getConfigValue(`commitHash`);if(!(!(0,z.isDefined)(e)||!(0,z.isDefined)(t)||!(0,z.isDefined)(n)))try{let r=`https://api.github.com/repos/${e}/${t}/commits/${n}`;return(await M0.get(r,{headers:{Authorization:`Bearer ${this.configService.getConfigValue(`token`)}`}})).data.author?.avatar_url}catch(e){this.logger.warn(`GithubHostService: Failed to get contributor avatar: ${e instanceof Error?e.message:`Unknown error`}`);return}}getGitOrigin(){return{origin:`origin`}}getGitCommiterInfo(){return{name:this.configService.getConfigValue(`gitUserName`)??`early-agent[bot]`,email:this.configService.getConfigValue(`gitUserEmail`)??`217573370+Early-Agent[bot]@users.noreply.github.com`}}};q0=oQ([tt(),st({extendConstructorArguments:!0,extendProperties:!0})],q0);const J0=new fr({defaultScope:`Singleton`,autobind:!0});J0.bind(cQ).toSelf().inSingletonScope(),J0.bind(lQ).toDynamicValue(e=>new lQ(J0.get(cW.CliOptions),e.get(cQ))).inSingletonScope(),J0.bind(q0).toSelf().inSingletonScope(),J0.bind(K0).toSelf().inSingletonScope(),J0.bind(cW.SCMHostService).toDynamicValue(e=>{let t=e.get(lQ),n=e.get(cQ),r=t.getConfigValue(`SCMProvider`);n.info(`SCMHostService: Selecting provider based on config: ${r}`);let i;switch(r.toLowerCase()){case`github`:i=e.get(q0);break;case`bitbucket`:i=e.get(K0);break;default:n.warn(`Unknown SCM provider: `+r+`, defaulting to github`),i=e.get(q0);break}return i}).inSingletonScope(),J0.bind(cW.TSAgent).toDynamicValue(async e=>{let t=e.get(lQ),n=await e.getAsync(CQ),r=e.get(cW.SCMHostService);await n.hydrateConfig();let i=await n.getGitInfo();await r.setupGit();let a=J0.get(cQ);return(0,sW.createTSAgent)({...t.getConfig(),includeEarlyTests:!0,context:{git:i},progressLogger:a})}).inSingletonScope();var Y0=class extends Error{constructor(e,t){super(t),this.statusCode=e}},X0=class extends Y0{},Z0=class extends Y0{},Ete,Dte,Ote;let Q0=class{constructor(e,t,n,r){this.tsAgent=e,this.gitService=t,this.configService=n,this.logger=r}async calculateCoverage(e){let{resultCommitSha:t,changedSourceFiles:n,successTestFiles:r}=e,i=this.configService.getConfigValue(`refName`);try{this.logger.verbose(`Coverage: checking out pre-commit state...`),await this.gitService.checkout(`${t}^`);let e=this.configService.getConfigValue(`rootPath`),i=r.map(t=>lW.default.isAbsolute(t)?t:lW.default.resolve(e,t)),a=new Set(i.map(e=>lW.default.normalize(e))),o=await this.tsAgent.getTestableFileMap(n),s=this.extractTestPaths(o).filter(e=>!a.has(lW.default.normalize(e)));this.logger.verbose(`Coverage (before): running with ${s.length} existing test files`);for(let e of s)this.logger.debug(` [before] test file: ${e}`);await this.tsAgent.generateCoverage(s);let c=await this.tsAgent.getCoverageForFiles(n),l=await this.tsAgent.getCoverageTree();this.logger.verbose(`Coverage: checking out post-commit state...`),await this.gitService.checkout(t);let u=[...s,...i];this.logger.verbose(`Coverage (after): running with ${u.length} test files`);for(let e of u)this.logger.debug(` [after] test file: ${e}`);await this.tsAgent.generateCoverage(u);let d=await this.tsAgent.getCoverageForFiles(n),f=await this.tsAgent.getCoverageTree();return this.logger.debug(`Coverage complete: before=${c.percentage??`null`}%, after=${d.percentage??`null`}%`),{success:!0,before:{prCoverage:c,coverageTree:l},after:{prCoverage:d,coverageTree:f}}}catch(e){let t=e instanceof Error?e.message:`Unknown error`;return this.logger.warn(`Post-commit coverage failed: `+t),{success:!1,reason:t}}finally{try{(0,z.isDefined)(i)&&await this.gitService.checkout(i)}catch(e){let t=e instanceof Error?e.message:`Unknown error`;this.logger.warn(`Failed to restore HEAD to `+i+`: `+t)}}}extractTestPaths(e){let t=[];for(let n of Object.values(e))for(let e of n)(0,z.isDefined)(e.testPath)&&t.push(e.testPath);return[...new Set(t)]}};Q0=oQ([tt(),aQ(0,Qe(cW.TSAgent)),aQ(1,Qe(CQ)),aQ(2,Qe(lQ)),aQ(3,Qe(cQ)),iQ(`design:paramtypes`,[typeof(Ete=sW.TSAgent!==void 0&&sW.TSAgent)==`function`?Ete:Object,typeof(Dte=CQ!==void 0&&CQ)==`function`?Dte:Object,typeof(Ote=lQ!==void 0&&lQ)==`function`?Ote:Object,Object])],Q0);var $0=u(oH(),1);const e2=`axios-retry`;function t2(e){return e.response||!e.code||[`ERR_CANCELED`,`ECONNABORTED`].includes(e.code)?!1:(0,$0.default)(e)}const n2=[`get`,`head`,`options`],r2=n2.concat([`put`,`delete`]);function i2(e){return e.code!==`ECONNABORTED`&&(!e.response||e.response.status===429||e.response.status>=500&&e.response.status<=599)}function a2(e){return e.config?.method?i2(e)&&n2.indexOf(e.config.method)!==-1:!1}function o2(e){return e.config?.method?i2(e)&&r2.indexOf(e.config.method)!==-1:!1}function kte(e){return t2(e)||o2(e)}function s2(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 c2(e=0,t=void 0){return Math.max(0,s2(t))}function l2(e=0,t=void 0,n=100){let r=2**e*n,i=Math.max(r,s2(t));return i+i*.2*Math.random()}function u2(e=100){return(t=0,n=void 0)=>{let r=t*e;return Math.max(r,s2(n))}}const d2={retries:3,retryCondition:kte,retryDelay:c2,shouldResetTimeout:!1,onRetry:()=>{},onMaxRetryTimesExceeded:()=>{},validateResponse:null};function Ate(e,t){return{...d2,...t,...e[e2]}}function f2(e,t,n=!1){let r=Ate(e,t||{});return r.retryCount=r.retryCount||0,(!r.lastRequestTime||n)&&(r.lastRequestTime=Date.now()),e[e2]=r,r}function p2(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 m2(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 h2(e,t,n,r){t.retryCount+=1;let{retryDelay:i,shouldResetTimeout:a,onRetry:o}=t,s=i(t.retryCount,n);if(p2(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 g2(e,t){e.retryCount>=e.retries&&await e.onMaxRetryTimesExceeded(t,e.retryCount)}const _2=(e,t)=>({requestInterceptorId:e.interceptors.request.use(e=>(f2(e,t,!0),e[e2]?.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 m2(i,n)?h2(e,i,n,r):(await g2(i,n),Promise.reject(n))})});_2.isNetworkError=t2,_2.isSafeRequestError=a2,_2.isIdempotentRequestError=o2,_2.isNetworkOrIdempotentRequestError=kte,_2.exponentialDelay=l2,_2.linearDelay=u2,_2.isRetryableError=i2;const jte=Error(`request for lock canceled`);var v2=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())})},Mte=class{constructor(e,t=jte){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=b2(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return v2(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]=[]),y2(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 y2(e,t){let n=b2(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function b2(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var x2=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())})},S2=class{constructor(e){this._semaphore=new Mte(1,e)}acquire(){return x2(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 C2=new TextDecoder;function w2(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 Nte(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:C2.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=C2.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`).replace(/\s/g,``);try{return w2(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}var T2=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)}},E2=class extends T2{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`};Symbol.asyncIterator;function D2(e){return typeof e==`object`&&!!e}var O2=e=>{if(!D2(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 k2(e){if(typeof e!=`string`)throw new E2(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new E2(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new E2(`Invalid JWT`);if(!t)throw new E2(`JWTs must contain a payload`);let r;try{r=Nte(t)}catch{throw new E2(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(C2.decode(r))}catch{throw new E2(`Failed to parse the decoded payload as JSON`)}if(!O2(i))throw new E2(`Invalid JWT Claims Set`);return i}const A2=e=>{let t=k2(e).exp;return(0,z.isDefined)(t)?t*1e3:null},j2=e=>{if(!(0,z.isDefined)(e))return!0;let t=A2(e);return(0,z.isDefined)(t)?t>Date.now():!0};let M2=class{jwtToken=null;refreshTokenCallback=null;observer=new z.Observer;refreshTokenMutex=new S2;setJWTToken(e){this.jwtToken=e,this.observer.notifyAll(e)}async getJWTToken(){return(0,z.isDefined)(this.jwtToken)?(this.isTokenValid()||await this.refreshTokenMutex.runExclusive(async()=>{if((0,z.isDefined)(this.refreshTokenCallback))return await this.refreshTokenCallback(),this.jwtToken}),this.jwtToken):null}onJWTTokenSave(e){this.observer.addListener(e)}isTokenValid(){return j2(this.jwtToken)}setRefreshTokenCallback(e){this.refreshTokenCallback=e}};M2=oQ([tt(`Singleton`)],M2);var N2,P2;let F2=class{axiosInstance;constructor(e,t,n){this.configService=e,this.authStorage=t,this.logger=n,this.configService=e,this.axiosInstance=M0.create({baseURL:this.configService.getConfigValueOrThrow(`backendURL`),headers:{"Content-Type":`application/json`}}),_2(this.axiosInstance,{retries:3,retryDelay:_2.exponentialDelay,retryCondition:e=>M0.isAxiosError(e)&&_2.isNetworkOrIdempotentRequestError(e)||M0.isAxiosError(e)&&e.response?.status!==void 0&&e.response.status>=500||!1})}async getAuthHeaders(){let e={"x-request-source":sW.RequestSource.CLI},t=await this.authStorage.getJWTToken();return(0,z.isDefined)(t)&&(e.authorization=`Bearer ${t}`),e}async apiCall({url:e,method:t,data:n,config:r}){let i=new H0(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===U0.Conflict){if(t===`workflow_is_cancelled`)throw this.logger.warn(`Agent flow canceled`),new X0(U0.Conflict,t);if(t===`duplicated_by_sha_workflow`)throw this.logger.warn(`Duplicated SHA workflow`),new Z0(U0.Conflict,t)}}handleError(e,t){if(M0.isAxiosError(t))if((0,z.isDefined)(t.response)){let{status:e,statusText:n,data:r}=t.response;throw this.handleCustomErrors(e,r.message),new Y0(e,`API request failed: ${e} ${n} - ${JSON.stringify(r)}`)}else if((0,z.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`)}};F2=oQ([tt(),aQ(0,Qe(lQ)),aQ(1,Qe(M2)),aQ(2,Qe(cQ)),iQ(`design:paramtypes`,[typeof(N2=lQ!==void 0&&lQ)==`function`?N2:Object,typeof(P2=M2!==void 0&&M2)==`function`?P2:Object,Object])],F2);let I2=function(e){return e.PR=`PR`,e.COMMIT=`COMMIT`,e.PROJECT=`PROJECT`,e.COVERAGE=`COVERAGE`,e}({});var L2,Pte;let R2=class{constructor(e,t){this.apiService=e,this.configService=t}mapCommandToType(e){switch(e){case uW.PR:return I2.PR;case uW.COMMIT:return I2.COMMIT;case uW.PROJECT:return I2.PROJECT;case uW.COVERAGE:return I2.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,z.isDefined)(e))return;let t=this.configService.getConfigValue(`reuseCoverageMaxRuns`),n=await this.apiService.post(`api/v1/workflows/${e}/reuse-coverage`,{limit:t});if((0,z.isDefined)(n.coverageBefore))return n.coverageBefore}};R2=oQ([tt(),aQ(0,Qe(F2)),aQ(1,Qe(lQ)),iQ(`design:paramtypes`,[typeof(L2=F2!==void 0&&F2)==`function`?L2:Object,typeof(Pte=lQ!==void 0&&lQ)==`function`?Pte:Object])],R2);var z2,B2,V2,H2,U2;let W2=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,z.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`}`)}}};W2=oQ([tt(),aQ(0,Qe(CQ)),aQ(1,Qe(lQ)),aQ(2,Qe(fQ)),aQ(3,Qe(cW.SCMHostService)),aQ(4,Qe(R2)),aQ(5,Qe(cQ)),iQ(`design:paramtypes`,[typeof(z2=CQ!==void 0&&CQ)==`function`?z2:Object,typeof(B2=lQ!==void 0&&lQ)==`function`?B2:Object,typeof(V2=fQ!==void 0&&fQ)==`function`?V2:Object,typeof(H2=_Q!==void 0&&_Q)==`function`?H2:Object,typeof(U2=R2!==void 0&&R2)==`function`?U2:Object,Object])],W2);let G2=class{constructor(e){this.logger=e}detectChanges(e,t,n,r,i){try{return!(0,z.isDefined)(r)||(0,z.isEmpty)(r)?this.handleNewFile(e,n):this.compareMethodLists(e,t,n,r,i)}catch(t){return this.logger.warn(`Failed to detect changes in file ${e}: ${t instanceof Error?t.message:`Unknown error`}`),[]}}handleNewFile(e,t){return t.map(t=>({name:t.name,type:t.type,parentName:`parentName`in t?t.parentName:void 0,changeType:`added`,filePath:e,canCreateTests:t.canCreateTests}))}compareMethodLists(e,t,n,r,i){let a=[];for(let o of n){let n=this.findMatchingMethod(t,o);(0,z.isDefined)(n)?this.hasMethodChanged(n,o,r,i)&&a.push(this.createChangedMethod(e,o,`modified`)):a.push(this.createChangedMethod(e,o,`added`))}for(let r of t)this.findMatchingMethod(n,r)||a.push(this.createChangedMethod(e,r,`deleted`));return a}findMatchingMethod(e,t){return e.find(e=>{let n=e.name===t.name,r=e.type===t.type,i=(`parentName`in e?e.parentName:void 0)===(`parentName`in t?t.parentName:void 0);return n&&r&&i})}hasMethodChanged(e,t,n,r){let i=this.extractMethodText(e,n),a=this.extractMethodText(t,r);return i.replaceAll(`\r
32409
32412
  `,`
32410
32413
  `)!==a.replaceAll(`\r
32411
32414
  `,`
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}}};G2=oQ([tt(),aQ(0,Qe(cQ)),iQ(`design:paramtypes`,[Object])],G2);var K2,q2,J2;let Y2=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,z.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=lW.default.isAbsolute(e)?e:lW.default.join(n,e),o=lW.default.relative(r,a),s=await this.gitService.getFileAtRevision(o,t),c=await this.getBaseMethodsFromContent(s,a,n);(0,z.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=lW.default.isAbsolute(e)?e:lW.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,z.isDefined)(e)||(0,z.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,z.isDefined)(e))try{await g.unlink(e)}catch{}}};Y2=oQ([tt(),aQ(0,Qe(CQ)),aQ(1,Qe(G2)),aQ(2,Qe(cW.TSAgent)),aQ(3,Qe(cQ)),iQ(`design:paramtypes`,[typeof(K2=CQ!==void 0&&CQ)==`function`?K2:Object,typeof(q2=G2!==void 0&&G2)==`function`?q2:Object,typeof(J2=sW.TSAgent!==void 0&&sW.TSAgent)==`function`?J2:Object,Object])],Y2);var X2;let Z2=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,z.isDefined)(r))return{kept:e};let a=[];for(let t of e){let e=this.findFileCoverage(r,t.filePath);if(!(0,z.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,z.isDefined)(o)?e.parentName===o:!(0,z.isDefined)(e.parentName)));if(!(0,z.isDefined)(s)||!(0,z.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}};Z2=oQ([tt(),aQ(0,Qe(lQ)),iQ(`design:paramtypes`,[typeof(X2=lQ!==void 0&&lQ)==`function`?X2:Object])],Z2);let Q2=class{async execute(e,t,n){let r=[];for(let i of e){let e=i.filePath.toLowerCase(),a=pQ.allowedExtensions.some(t=>e.endsWith(t)),o=lW.default.isAbsolute(i.filePath)?lW.default.relative(t.gitTopLevel,i.filePath):i.filePath;if(!a){n.push({filePath:o,reason:`not-code-file`});continue}if(pQ.excludePatterns.some(t=>e.includes(t.toLowerCase()))){n.push({filePath:o,reason:`excluded-pattern`});continue}r.push(i)}return{kept:r}}};Q2=oQ([tt()],Q2);var $2;let e4=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}}};e4=oQ([tt(),aQ(0,Qe(lQ)),iQ(`design:paramtypes`,[typeof($2=lQ!==void 0&&lQ)==`function`?$2:Object])],e4);var t4=u(Bz());function n4(e,t){let n=lW.default.relative(e,t);return n===``||!n.startsWith(`..`)&&!lW.default.isAbsolute(n)}function r4(e,t,n){let r=lW.default.isAbsolute(e)&&n4(n,e)?e:lW.default.join(n,e),i=(0,t4.default)(t,{cwd:m.default.existsSync(r)&&m.default.statSync(r).isDirectory()?r:lW.default.dirname(r)});return i!==null&&!n4(n,i)?null:i}function i4(e,t){let n=[r4(e,`package.json`,t),r4(e,`project.json`,t)].filter(z.isDefined).filter(e=>n4(t,e));if(n.length===0)return t;let r=n.reduce((e,t)=>e.length>t.length?e:t,n[0]);return lW.default.dirname(r)}const a4=[`pyproject.toml`,`setup.py`,`setup.cfg`,`requirements.txt`],o4=[`package.json`,`tsconfig.json`],s4=[`.py`],c4=[`.ts`,`.tsx`,`.js`,`.jsx`];function l4(e,t){return t.some(t=>e.endsWith(t))}function u4(e){if(l4(e,s4))return`python`;if(l4(e,c4))return`typescript`}function d4(e,t){if(e&&t)return`mixed`;if(e)return`python`;if(t)return`typescript`}function f4(e){let t=m.default.readdirSync(e,{recursive:!0});return d4(t.some(e=>l4(e,s4)),t.some(e=>l4(e,c4)))}function p4(e){return d4(a4.some(t=>m.default.existsSync(lW.default.join(e,t))),o4.some(t=>m.default.existsSync(lW.default.join(e,t))))}function m4(e,t){if(t!==void 0&&t!==``){let n=lW.default.isAbsolute(t)?t:lW.default.join(e,t);return m.default.existsSync(n)&&m.default.statSync(n).isFile()?u4(n):m.default.existsSync(n)&&m.default.statSync(n).isDirectory()?f4(n):u4(t)??p4(e)}return p4(e)}const h4={detectProjectRoot(e,t,n){if(t.length===0)return n.verbose(`No changed files provided, using root path`),e;let r=t[0],i=i4(lW.default.isAbsolute(r)?r:lW.default.join(e,r),e);return i===lW.default.normalize(e)?(n.verbose(`Using workspace root path`),e):(n.info(`Detected nested project root: ${i} (from file: ${r})`),i)}};function g4(e,t){let n=lW.default.relative(e,t);return n!==``&&!n.startsWith(`..`)&&!lW.default.isAbsolute(n)}let _4=class{constructor(e){this.logger=e}async execute(e,t,n){if((0,z.isEmpty)(e))return{kept:[],projectRootPath:t.rootPath};let r=e.map(e=>lW.default.isAbsolute(e.filePath)?e.filePath:lW.default.join(t.rootPath,e.filePath)),i=h4.detectProjectRoot(t.rootPath,r,this.logger),a=[];for(let[t,o]of e.entries()){let e=r[t];if(!g4(i,e)){n.push({filePath:o.filePath,reason:`outside-project`});continue}let s=lW.default.relative(i,e);a.push({filePath:s,status:o.status})}return{kept:a,projectRootPath:i}}};_4=oQ([tt(),aQ(0,Qe(cQ)),iQ(`design:paramtypes`,[Object])],_4);let v4=class{constructor(e){this.tsAgent=e}async execute(e,t,n){let r=e.map(e=>e.filePath);if((0,z.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,z.isDefined)(r)||(0,z.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,z.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,z.isDefined)(t[e]))return t[e];let r=lW.default.resolve(n,e);if((0,z.isDefined)(t[r]))return t[r]}};v4=oQ([tt(),aQ(0,Qe(cW.TSAgent)),iQ(`design:paramtypes`,[Object])],v4);var y4,b4,x4,S4,C4,w4,T4;function E4(e,t){return{async execute(n,r,i){return e(r)?t.execute(n,r,i):{kept:n}}}}let D4=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,E4(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,z.isDefined)(o.projectRootPath)&&!(0,z.isEmpty)(o.projectRootPath)&&(i=o.projectRootPath,this.tsAgent.updateRootPath(i),this.configService.updateConfigValue(`rootPath`,i)),(0,z.isEmpty)(o.kept))return{testables:[],filteredOut:n,projectRootPath:i};r=o.kept}return{testables:r,filteredOut:n,projectRootPath:i}}};D4=oQ([tt(),aQ(0,Qe(lQ)),aQ(1,Qe(cW.TSAgent)),aQ(2,Qe(Q2)),aQ(3,Qe(_4)),aQ(4,Qe(v4)),aQ(5,Qe(Y2)),aQ(6,Qe(Z2)),aQ(7,Qe(e4)),iQ(`design:paramtypes`,[typeof(y4=lQ!==void 0&&lQ)==`function`?y4:Object,Object,typeof(b4=Q2!==void 0&&Q2)==`function`?b4:Object,typeof(x4=_4!==void 0&&_4)==`function`?x4:Object,typeof(S4=v4!==void 0&&v4)==`function`?S4:Object,typeof(C4=Y2!==void 0&&Y2)==`function`?C4:Object,typeof(w4=Z2!==void 0&&Z2)==`function`?w4:Object,typeof(T4=e4!==void 0&&e4)==`function`?T4:Object])],D4);var O4,k4,Fte;let A4=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`)}}};A4=oQ([tt(),aQ(0,Qe(lQ)),aQ(1,Qe(F2)),aQ(2,Qe(M2)),iQ(`design:paramtypes`,[typeof(O4=lQ!==void 0&&lQ)==`function`?O4:Object,typeof(k4=F2!==void 0&&F2)==`function`?k4:Object,typeof(Fte=M2!==void 0&&M2)==`function`?Fte:Object])],A4);var j4;let M4=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,z.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,z.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,z.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,z.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,z.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,z.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,z.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,z.isEmpty)(n)||!(0,z.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,z.isDefined)(t[n.filePath])||(t[n.filePath]=[]),t[n.filePath].push(n);return t}findTestableInCoverage(e,t){return(0,z.isDefined)(e.testables)?e.testables.find(e=>{let n=e.name===t.name,r=`parentName`in e?e.parentName===t.parentName:!(0,z.isDefined)(t.parentName);return n&&r})??null:null}};M4=oQ([tt(),aQ(0,Qe(cW.TSAgent)),aQ(1,Qe(cQ)),iQ(`design:paramtypes`,[typeof(j4=sW.TSAgent!==void 0&&sW.TSAgent)==`function`?j4:Object,Object])],M4);function Ite(e,t){return r4(e,`package.json`,t)??void 0}function N4(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 P4(e,t,n){let r=Ite(e,t),i=(await(0,sW.findLintConfigPath)(t)).path??void 0,a=(0,z.isDefined)(r)?N4(r,n):void 0,o=(0,z.isDefined)(i)?N4(i,n):void 0;return(0,z.isDefined)(r)&&n.info(`Found package.json at: ${r}`),(0,z.isDefined)(i)&&n.info(`Found lint config at: ${i}`),{packageJsonPath:r,packageJsonContent:a,lintConfigPath:i,lintConfigContent:o}}const F4={detectProjectConfigs:P4};var I4,Lte;let L4=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 F4.detectProjectConfigs(t,t,this.logger);if(!(0,z.isDefined)(n.packageJsonContent)&&!(0,z.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`}`)}}};L4=oQ([tt(),aQ(0,Qe(F2)),aQ(1,Qe(lQ)),aQ(2,Qe(cQ)),iQ(`design:paramtypes`,[typeof(I4=F2!==void 0&&F2)==`function`?I4:Object,typeof(Lte=lQ!==void 0&&lQ)==`function`?Lte:Object,Object])],L4);var R4,Rte,zte,Bte,Vte,Hte,Ute,Wte,Gte;let z4=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 Z0||e instanceof X0||this.logger.warn(`Failed to log start operation: ${e instanceof Error?e.message:`Unknown error`}`),e}}catch(e){throw e instanceof Z0||e instanceof X0||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,z.isDefined)(e))return await this.tsAgent.setCoverage(e),this.initialCoverageTree=e,(0,z.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,z.isDefined)(e))throw Error(`Failed to generate initial coverage tree`);return this.initialCoverageTree=e,(0,z.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,z.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,z.isDefined)(this.workflowRunId))throw Error(`Workflow run ID is not set, call logStart() first`);return this.workflowRunId}getInitialCoverageTreeOrThrow(){if(!(0,z.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,z.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)}};z4=oQ([tt(),aQ(0,Qe(lQ)),aQ(1,Qe(A4)),aQ(2,Qe(CQ)),aQ(3,Qe(M4)),aQ(4,Qe(fQ)),aQ(5,Qe(cW.TSAgent)),aQ(6,Qe(R2)),aQ(7,Qe(cW.SCMHostService)),aQ(8,Qe(L4)),aQ(9,Qe(cQ)),iQ(`design:paramtypes`,[typeof(R4=lQ!==void 0&&lQ)==`function`?R4:Object,typeof(Rte=A4!==void 0&&A4)==`function`?Rte:Object,typeof(zte=CQ!==void 0&&CQ)==`function`?zte:Object,typeof(Bte=M4!==void 0&&M4)==`function`?Bte:Object,typeof(Vte=fQ!==void 0&&fQ)==`function`?Vte:Object,typeof(Hte=sW.TSAgent!==void 0&&sW.TSAgent)==`function`?Hte:Object,typeof(Ute=R2!==void 0&&R2)==`function`?Ute:Object,typeof(Wte=_Q!==void 0&&_Q)==`function`?Wte:Object,typeof(Gte=L4!==void 0&&L4)==`function`?Gte:Object,Object])],z4);var Kte,B4,V4;const H4=e=>e instanceof Error&&(e.message===`Operation aborted`||e.name===`AbortError`);let U4=class extends z4{changedFiles=[];prCoverage={before:{percentage:null,totalStatements:0,coveredStatements:0},after:{percentage:null,totalStatements:0,coveredStatements:0}};_successSourceFiles=[];_successTestFiles=[];testableToGenerateService;postGenerationService;postCommitCoverageService;getWorkflowRunId(){return this.workflowRunId}getSuccessSourceFiles(){return this._successSourceFiles}getSuccessTestFiles(){return this._successTestFiles}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,z.isEmpty)(a.testables)){this.logFilteredOutTestables(a.filteredOut),this.handleNoFilteredTestables(),this.configService.getConfigValue(`skipCoverageAfter`)||this.summaryService.setCoverageState(uQ.NoGeneration);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();if(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.setCoverageState(uQ.Skipped);else if((0,z.isDefined)(this.resultCommitSha)){let e=await this.postCommitCoverageService.calculateCoverage({resultCommitSha:this.resultCommitSha,successSourceFiles:this._successSourceFiles,successTestFiles:this._successTestFiles});if(e.success){this.prCoverage={before:e.before.prCoverage,after:e.after.prCoverage};let t=this.getWorkflowRunIdOrThrow();await this.workflowService.saveCoverageToWorkflow(t,`before`,{coverage:e.before.coverageTree??void 0,prCoverage:e.before.prCoverage}),await this.workflowService.saveCoverageToWorkflow(t,`after`,{coverage:e.after.coverageTree??void 0,prCoverage:e.after.prCoverage}),this.summaryService.setCoverageState(uQ.Success)}else{let t=this.getWorkflowRunIdOrThrow();await this.workflowService.saveCoverageToWorkflow(t,`before`,{}),await this.workflowService.saveCoverageToWorkflow(t,`after`,{}),this.summaryService.setCoverageState(uQ.Failed,e.reason)}}}return i}catch(e){if(e instanceof Z0){this.logger.warn(`Duplicate SHA execution detected. Skipping.`);return}if(e instanceof X0){this.logger.warn(`Workflow canceled. Skipping.`),r=!0;return}return H4(e)?(n=`Operation timed out`,this.logger.warn(`Workflow aborted due to timeout`)):(n=e instanceof Error?e.message:`Unknown error`,this.logger.error(`Agent flow failed: `+n)),i}finally{!t&&(0,z.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,z.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,z.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){await this.postGenerationService.cleanupBlankEarlyFiles();let e=this.configService.getConfigValue(`refName`),t=await this.gitService.commitFiles(e);return(0,z.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,z.isDefined)(this.workflowRunId))try{let e=await this.coverageAnalysisService.calculatePRCoverage(this.changedFiles,!0);(0,z.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=[],r=0,i=0,a=0,o=0;try{await this.tsAgent.bulkGenerateTests(e,(s,c,l)=>{o++;let u=lW.default.basename(s.filePath);(0,z.isDefined)(c)&&c.greenTestsCount>0?(t.delete(s),r+=c.greenTestsCount,i+=c.redTestsCount,a+=c.greyTestsCount,this._successSourceFiles.push(s.filePath),(0,z.isDefined)(l)&&l.testFilePath&&this._successTestFiles.push(l.testFilePath),this.logger.info(` [${o}/${e.length}] ✓ ${s.testable.name} (${u}) — ${c.greenTestsCount} passing, ${c.redTestsCount} skipped`)):((0,z.isDefined)(l)&&l.testFilePath&&n.push(l.testFilePath),this.logger.info(` [${o}/${e.length}] ✗ ${s.testable.name} (${u}) — no tests generated`))})}catch(e){if(H4(e))this.logger.warn(`Test generation was partially aborted due to timeout`);else throw e}for(let e of n)try{await g.unlink(e),this.logger.debug(`Removed failed test file: ${e}`)}catch{this.logger.debug(`Could not remove failed test file: ${e}`)}let s=e.length-t.size,c=t.size,l=await this.gitService.getEarlyFiles();return this.logger.info(``),this.logger.info(`✅ Test generation complete for ${s} functions`),c>0&&this.logger.info(`❌ ${c} functions were not generated`),this.logger.info(``),this.logger.info(`================`),this.logger.info(`Overall summary:`),this.logger.info(`================`),this.logger.info(``),this.logger.info(`✅ ${r} tests passing`),this.logger.info(`⚠️ ${i} tests skipped`),this.logger.info(`❌ ${a} tests could not be fixed autonomously (yet)`),this.logger.info(``),{generated:e.length,succeeded:s,failed:c,successMethodsCount:l.length,greenTests:r,redTests:i}}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,z.isDefined)(r))throw Error(`Failed to generate final coverage tree`);let i=r[`/`]?.percentage??0,a=this.getInitialCoverageTreeOrUndefined(),o=a?.[`/`]?.percentage??0;(0,z.isDefined)(a)||this.summaryService.setCoverageBeforeSkipped(),this.summaryService.setCoverageData(o,i);let s=(0,z.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,z.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)}};oQ([Qe(D4),iQ(`design:type`,typeof(Kte=D4!==void 0&&D4)==`function`?Kte:Object)],U4.prototype,`testableToGenerateService`,void 0),oQ([Qe(W2),iQ(`design:type`,typeof(B4=W2!==void 0&&W2)==`function`?B4:Object)],U4.prototype,`postGenerationService`,void 0),oQ([Qe(Q0),iQ(`design:type`,typeof(V4=Q0!==void 0&&Q0)==`function`?V4:Object)],U4.prototype,`postCommitCoverageService`,void 0),U4=oQ([tt(),ct({extendConstructorArguments:!0,extendProperties:!0})],U4);let W4=class extends U4{async getRawChangedFiles(){return this.gitService.getChangedFilesForCommitWithStatus({absolute:!0})}hasDiffContext(){return!0}async getBaseRevision(){let e=this.configService.getConfigValue(`baseRef`);if((0,z.isDefined)(e))return this.gitService.getBaseRevision({baseBranch:e});let t=this.configService.getConfigValue(`commitHash`);if((0,z.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,z.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()}};W4=oQ([tt(),ct({extendConstructorArguments:!0,extendProperties:!0})],W4);function qte(e){let t=e.command(uW.COMMIT).alias(`generate-commit`).description(`Generate tests for the current project in commit context`);return le(t,`--commit-hash <hash>`,`Commit hash`,{envName:`COMMIT_HASH`,isRequired:!0}),le(t,`--ref-name <ref>`,`Head branch name for the commit`,{envName:`REF_NAME`,isRequired:!0}),le(t,`--base-ref <ref>`,`optional base refrence for comparison`,{envName:`BASE_REF`}),le(t,`-s, --test-structure <structure>`,`Test file structure`,{envName:`TEST_STRUCTURE`,def:`siblingFolder`}),le(t,`-f, --test-framework <framework>`,`Test framework to use`,{envName:`TEST_FRAMEWORK`,def:`jest`}),le(t,`--test-suffix <suffix>`,`Test file suffix`,{envName:`TEST_FILE_SUFFIX`,def:`test`}),le(t,`--test-file-naming <naming>`,`Test file naming convention`,{envName:`TEST_FILE_NAMING`,def:`camelCase`}),le(t,`-c, --max-concurrency <number>`,`Number of concurrent workers (1-4)`,{envName:`MAX_CONCURRENCY`,def:`3`}),le(t,`--auto-commit <boolean>`,`Whether to auto-commit files`,{envName:`AUTO_COMMIT`,def:`true`}),le(t,`--auto-commit-skip-ci <boolean>`,`Append [skip ci] to auto-commit message`,{envName:`AUTO_COMMIT_SKIP_CI`,def:`true`}),le(t,`--test-command <command>`,`Custom test command to run`,{envName:`TEST_COMMAND`}),le(t,`--coverage-command <command>`,`Custom coverage command to run`,{envName:`COVERAGE_COMMAND`}),le(t,`--lint-command <command>`,`Custom lint command to run`,{envName:`LINT_COMMAND`}),le(t,`--prettier-command <command>`,`Custom prettier command to run`,{envName:`PRETTIER_COMMAND`}),le(t,`--disable-lint-rules <boolean>`,`Whether to disable failed lint rules in test files`,{envName:`DISABLE_LINT_RULES`,def:`false`}),le(t,`--git-org <org>`,`Git organization name`,{envName:`GIT_ORG`}),le(t,`--git-repo <repo>`,`Git repository name`,{envName:`GIT_REPO`}),le(t,`--git-user-email <email>`,`Git user email for auto commit`,{envName:`GIT_USER_EMAIL`}),le(t,`--git-user-name <name>`,`Git user name for auto commit`,{envName:`GIT_USER_NAME`}),le(t,`--scm-provider <provider>`,`SCM provider (e.g., github, bitbucket)`,{envName:`SCM_PROVIDER`,def:`github`}),le(t,`--keep-error-tests <boolean>`,`Whether to keep error tests`,{envName:`KEEP_ERROR_TESTS`,def:`false`}),le(t,`--keep-failed-tests <boolean>`,`Whether to keep failed tests`,{envName:`KEEP_FAILED_TESTS`,def:`false`}),le(t,`--conditional-keep <boolean>`,`Whether to return the last generated test result even when no green tests were produced`,{envName:`CONDITIONAL_KEEP`,def:`false`}),le(t,`--continue-on-test-errors <boolean>`,`Whether to continue on test errors`,{envName:`CONTINUE_ON_TEST_ERRORS`,def:`false`}),le(t,`--changed-methods-only <boolean>`,`Generate tests only for changed methods, not all methods in changed files`,{envName:`CHANGED_METHODS_ONLY`,def:`true`}),le(t,`--skip-coverage-after <boolean>`,`Skip final coverage generation after test generation`,{envName:`SKIP_COVERAGE_AFTER`,def:`true`}),le(t,`--max-testables <number>`,`Maximum number of testables to generate`,{envName:`MAX_TESTABLES`}),le(t,`--per-function-timeout <number>`,`Per function timeout in milliseconds`,{envName:`PER_FUNCTION_TIMEOUT`}),le(t,`--coverage-threshold <number>`,`Coverage threshold percentage (0-100)`,{envName:`COVERAGE_THRESHOLD`,def:`0`}),le(t,`--reuse-coverage <boolean>`,`Whether to reuse coverage`,{envName:`REUSE_COVERAGE`,def:`false`}),le(t,`--reuse-coverage-max-runs <number>`,`Max number of runs to reuse coverage (1-10)`,{envName:`REUSE_COVERAGE_MAX_RUNS`,def:`10`}),le(t,`--experimental-agent-sdk <boolean>`,`Use experimental Agent SDK for test generation`,{envName:`EXPERIMENTAL_AGENT_SDK`,def:`true`}),t.addHelpText(`after`,`
32415
+ `)}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}}};G2=oQ([tt(),aQ(0,Qe(cQ)),iQ(`design:paramtypes`,[Object])],G2);var K2,q2,J2;let Y2=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,z.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=lW.default.isAbsolute(e)?e:lW.default.join(n,e),o=lW.default.relative(r,a),s=await this.gitService.getFileAtRevision(o,t),c=await this.getBaseMethodsFromContent(s,a,n);(0,z.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=lW.default.isAbsolute(e)?e:lW.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,z.isDefined)(e)||(0,z.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,z.isDefined)(e))try{await g.unlink(e)}catch{}}};Y2=oQ([tt(),aQ(0,Qe(CQ)),aQ(1,Qe(G2)),aQ(2,Qe(cW.TSAgent)),aQ(3,Qe(cQ)),iQ(`design:paramtypes`,[typeof(K2=CQ!==void 0&&CQ)==`function`?K2:Object,typeof(q2=G2!==void 0&&G2)==`function`?q2:Object,typeof(J2=sW.TSAgent!==void 0&&sW.TSAgent)==`function`?J2:Object,Object])],Y2);var X2;let Z2=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,z.isDefined)(r))return{kept:e};let a=[];for(let t of e){let e=this.findFileCoverage(r,t.filePath);if(!(0,z.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,z.isDefined)(o)?e.parentName===o:!(0,z.isDefined)(e.parentName)));if(!(0,z.isDefined)(s)||!(0,z.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}};Z2=oQ([tt(),aQ(0,Qe(lQ)),iQ(`design:paramtypes`,[typeof(X2=lQ!==void 0&&lQ)==`function`?X2:Object])],Z2);let Q2=class{async execute(e,t,n){let r=[];for(let i of e){let e=i.filePath.toLowerCase(),a=pQ.allowedExtensions.some(t=>e.endsWith(t)),o=lW.default.isAbsolute(i.filePath)?lW.default.relative(t.gitTopLevel,i.filePath):i.filePath;if(!a){n.push({filePath:o,reason:`not-code-file`});continue}if(pQ.excludePatterns.some(t=>e.includes(t.toLowerCase()))){n.push({filePath:o,reason:`excluded-pattern`});continue}r.push(i)}return{kept:r}}};Q2=oQ([tt()],Q2);var $2;let e4=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}}};e4=oQ([tt(),aQ(0,Qe(lQ)),iQ(`design:paramtypes`,[typeof($2=lQ!==void 0&&lQ)==`function`?$2:Object])],e4);var t4=u(Bz());function n4(e,t){let n=lW.default.relative(e,t);return n===``||!n.startsWith(`..`)&&!lW.default.isAbsolute(n)}function r4(e,t,n){let r=lW.default.isAbsolute(e)&&n4(n,e)?e:lW.default.join(n,e),i=(0,t4.default)(t,{cwd:m.default.existsSync(r)&&m.default.statSync(r).isDirectory()?r:lW.default.dirname(r)});return i!==null&&!n4(n,i)?null:i}function i4(e,t){let n=[r4(e,`package.json`,t),r4(e,`project.json`,t)].filter(z.isDefined).filter(e=>n4(t,e));if(n.length===0)return t;let r=n.reduce((e,t)=>e.length>t.length?e:t,n[0]);return lW.default.dirname(r)}const a4=[`pyproject.toml`,`setup.py`,`setup.cfg`,`requirements.txt`],o4=[`package.json`,`tsconfig.json`],s4=[`.py`],c4=[`.ts`,`.tsx`,`.js`,`.jsx`];function l4(e,t){return t.some(t=>e.endsWith(t))}function u4(e){if(l4(e,s4))return`python`;if(l4(e,c4))return`typescript`}function d4(e,t){if(e&&t)return`mixed`;if(e)return`python`;if(t)return`typescript`}function f4(e){let t=m.default.readdirSync(e,{recursive:!0});return d4(t.some(e=>l4(e,s4)),t.some(e=>l4(e,c4)))}function p4(e){return d4(a4.some(t=>m.default.existsSync(lW.default.join(e,t))),o4.some(t=>m.default.existsSync(lW.default.join(e,t))))}function m4(e,t){if(t!==void 0&&t!==``){let n=lW.default.isAbsolute(t)?t:lW.default.join(e,t);return m.default.existsSync(n)&&m.default.statSync(n).isFile()?u4(n):m.default.existsSync(n)&&m.default.statSync(n).isDirectory()?f4(n):u4(t)??p4(e)}return p4(e)}const h4={detectProjectRoot(e,t,n){if(t.length===0)return n.verbose(`No changed files provided, using root path`),e;let r=t[0],i=i4(lW.default.isAbsolute(r)?r:lW.default.join(e,r),e);return i===lW.default.normalize(e)?(n.verbose(`Using workspace root path`),e):(n.info(`Detected nested project root: ${i} (from file: ${r})`),i)}};function g4(e,t){let n=lW.default.relative(e,t);return n!==``&&!n.startsWith(`..`)&&!lW.default.isAbsolute(n)}let _4=class{constructor(e){this.logger=e}async execute(e,t,n){if((0,z.isEmpty)(e))return{kept:[],projectRootPath:t.rootPath};let r=e.map(e=>lW.default.isAbsolute(e.filePath)?e.filePath:lW.default.join(t.rootPath,e.filePath)),i=h4.detectProjectRoot(t.rootPath,r,this.logger),a=[];for(let[t,o]of e.entries()){let e=r[t];if(!g4(i,e)){n.push({filePath:o.filePath,reason:`outside-project`});continue}let s=lW.default.relative(i,e);a.push({filePath:s,status:o.status})}return{kept:a,projectRootPath:i}}};_4=oQ([tt(),aQ(0,Qe(cQ)),iQ(`design:paramtypes`,[Object])],_4);let v4=class{constructor(e){this.tsAgent=e}async execute(e,t,n){let r=e.map(e=>e.filePath);if((0,z.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,z.isDefined)(r)||(0,z.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,z.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,z.isDefined)(t[e]))return t[e];let r=lW.default.resolve(n,e);if((0,z.isDefined)(t[r]))return t[r]}};v4=oQ([tt(),aQ(0,Qe(cW.TSAgent)),iQ(`design:paramtypes`,[Object])],v4);var y4,b4,x4,S4,C4,w4,T4;function E4(e,t){return{async execute(n,r,i){return e(r)?t.execute(n,r,i):{kept:n}}}}let D4=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,E4(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,z.isDefined)(o.projectRootPath)&&!(0,z.isEmpty)(o.projectRootPath)&&(i=o.projectRootPath,this.tsAgent.updateRootPath(i),this.configService.updateConfigValue(`rootPath`,i)),(0,z.isEmpty)(o.kept))return{testables:[],filteredOut:n,projectRootPath:i};r=o.kept}return{testables:r,filteredOut:n,projectRootPath:i}}};D4=oQ([tt(),aQ(0,Qe(lQ)),aQ(1,Qe(cW.TSAgent)),aQ(2,Qe(Q2)),aQ(3,Qe(_4)),aQ(4,Qe(v4)),aQ(5,Qe(Y2)),aQ(6,Qe(Z2)),aQ(7,Qe(e4)),iQ(`design:paramtypes`,[typeof(y4=lQ!==void 0&&lQ)==`function`?y4:Object,Object,typeof(b4=Q2!==void 0&&Q2)==`function`?b4:Object,typeof(x4=_4!==void 0&&_4)==`function`?x4:Object,typeof(S4=v4!==void 0&&v4)==`function`?S4:Object,typeof(C4=Y2!==void 0&&Y2)==`function`?C4:Object,typeof(w4=Z2!==void 0&&Z2)==`function`?w4:Object,typeof(T4=e4!==void 0&&e4)==`function`?T4:Object])],D4);var O4,k4,Fte;let A4=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`)}}};A4=oQ([tt(),aQ(0,Qe(lQ)),aQ(1,Qe(F2)),aQ(2,Qe(M2)),iQ(`design:paramtypes`,[typeof(O4=lQ!==void 0&&lQ)==`function`?O4:Object,typeof(k4=F2!==void 0&&F2)==`function`?k4:Object,typeof(Fte=M2!==void 0&&M2)==`function`?Fte:Object])],A4);var j4;let M4=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,z.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,z.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,z.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,z.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,z.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,z.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,z.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,z.isEmpty)(n)||!(0,z.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,z.isDefined)(t[n.filePath])||(t[n.filePath]=[]),t[n.filePath].push(n);return t}findTestableInCoverage(e,t){return(0,z.isDefined)(e.testables)?e.testables.find(e=>{let n=e.name===t.name,r=`parentName`in e?e.parentName===t.parentName:!(0,z.isDefined)(t.parentName);return n&&r})??null:null}};M4=oQ([tt(),aQ(0,Qe(cW.TSAgent)),aQ(1,Qe(cQ)),iQ(`design:paramtypes`,[typeof(j4=sW.TSAgent!==void 0&&sW.TSAgent)==`function`?j4:Object,Object])],M4);function Ite(e,t){return r4(e,`package.json`,t)??void 0}function N4(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 P4(e,t,n){let r=Ite(e,t),i=(await(0,sW.findLintConfigPath)(t)).path??void 0,a=(0,z.isDefined)(r)?N4(r,n):void 0,o=(0,z.isDefined)(i)?N4(i,n):void 0;return(0,z.isDefined)(r)&&n.info(`Found package.json at: ${r}`),(0,z.isDefined)(i)&&n.info(`Found lint config at: ${i}`),{packageJsonPath:r,packageJsonContent:a,lintConfigPath:i,lintConfigContent:o}}const F4={detectProjectConfigs:P4};var I4,Lte;let L4=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 F4.detectProjectConfigs(t,t,this.logger);if(!(0,z.isDefined)(n.packageJsonContent)&&!(0,z.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`}`)}}};L4=oQ([tt(),aQ(0,Qe(F2)),aQ(1,Qe(lQ)),aQ(2,Qe(cQ)),iQ(`design:paramtypes`,[typeof(I4=F2!==void 0&&F2)==`function`?I4:Object,typeof(Lte=lQ!==void 0&&lQ)==`function`?Lte:Object,Object])],L4);var R4,Rte,zte,Bte,Vte,Hte,Ute,Wte,Gte;let z4=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 Z0||e instanceof X0||this.logger.warn(`Failed to log start operation: ${e instanceof Error?e.message:`Unknown error`}`),e}}catch(e){throw e instanceof Z0||e instanceof X0||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,z.isDefined)(e))return await this.tsAgent.setCoverage(e),this.initialCoverageTree=e,(0,z.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,z.isDefined)(e))throw Error(`Failed to generate initial coverage tree`);return this.initialCoverageTree=e,(0,z.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,z.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,z.isDefined)(this.workflowRunId))throw Error(`Workflow run ID is not set, call logStart() first`);return this.workflowRunId}getInitialCoverageTreeOrThrow(){if(!(0,z.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,z.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)}};z4=oQ([tt(),aQ(0,Qe(lQ)),aQ(1,Qe(A4)),aQ(2,Qe(CQ)),aQ(3,Qe(M4)),aQ(4,Qe(fQ)),aQ(5,Qe(cW.TSAgent)),aQ(6,Qe(R2)),aQ(7,Qe(cW.SCMHostService)),aQ(8,Qe(L4)),aQ(9,Qe(cQ)),iQ(`design:paramtypes`,[typeof(R4=lQ!==void 0&&lQ)==`function`?R4:Object,typeof(Rte=A4!==void 0&&A4)==`function`?Rte:Object,typeof(zte=CQ!==void 0&&CQ)==`function`?zte:Object,typeof(Bte=M4!==void 0&&M4)==`function`?Bte:Object,typeof(Vte=fQ!==void 0&&fQ)==`function`?Vte:Object,typeof(Hte=sW.TSAgent!==void 0&&sW.TSAgent)==`function`?Hte:Object,typeof(Ute=R2!==void 0&&R2)==`function`?Ute:Object,typeof(Wte=_Q!==void 0&&_Q)==`function`?Wte:Object,typeof(Gte=L4!==void 0&&L4)==`function`?Gte:Object,Object])],z4);var Kte,B4,V4;const H4=e=>e instanceof Error&&(e.message===`Operation aborted`||e.name===`AbortError`);let U4=class extends z4{changedFiles=[];prCoverage={before:{percentage:null,totalStatements:0,coveredStatements:0},after:{percentage:null,totalStatements:0,coveredStatements:0}};_successSourceFiles=[];_successTestFiles=[];testableToGenerateService;postGenerationService;postCommitCoverageService;getWorkflowRunId(){return this.workflowRunId}getSuccessSourceFiles(){return this._successSourceFiles}getSuccessTestFiles(){return this._successTestFiles}getChangedFiles(){return this.changedFiles}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,z.isEmpty)(a.testables)){this.logFilteredOutTestables(a.filteredOut),this.handleNoFilteredTestables(),this.configService.getConfigValue(`skipCoverageAfter`)||this.summaryService.setCoverageState(uQ.NoGeneration);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();if(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.setCoverageState(uQ.Skipped);else if((0,z.isDefined)(this.resultCommitSha)){let e=await this.postCommitCoverageService.calculateCoverage({resultCommitSha:this.resultCommitSha,changedSourceFiles:[...this.changedFiles],successTestFiles:this._successTestFiles});if(e.success){this.prCoverage={before:e.before.prCoverage,after:e.after.prCoverage};let t=this.getWorkflowRunIdOrThrow();await this.workflowService.saveCoverageToWorkflow(t,`before`,{coverage:e.before.coverageTree??void 0,prCoverage:e.before.prCoverage}),await this.workflowService.saveCoverageToWorkflow(t,`after`,{coverage:e.after.coverageTree??void 0,prCoverage:e.after.prCoverage}),this.summaryService.setCoverageState(uQ.Success)}else{let t=this.getWorkflowRunIdOrThrow();await this.workflowService.saveCoverageToWorkflow(t,`before`,{}),await this.workflowService.saveCoverageToWorkflow(t,`after`,{}),this.summaryService.setCoverageState(uQ.Failed,e.reason)}}else this.summaryService.setCoverageState(uQ.NoGeneration)}return i}catch(e){if(e instanceof Z0){this.logger.warn(`Duplicate SHA execution detected. Skipping.`);return}if(e instanceof X0){this.logger.warn(`Workflow canceled. Skipping.`),r=!0;return}return H4(e)?(n=`Operation timed out`,this.logger.warn(`Workflow aborted due to timeout`)):(n=e instanceof Error?e.message:`Unknown error`,this.logger.error(`Agent flow failed: `+n)),i}finally{!t&&(0,z.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,z.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,z.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){await this.postGenerationService.cleanupBlankEarlyFiles();let e=this.configService.getConfigValue(`refName`),t=await this.gitService.commitFiles(e);return(0,z.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,z.isDefined)(this.workflowRunId))try{let e=await this.coverageAnalysisService.calculatePRCoverage(this.changedFiles,!0);(0,z.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=[],r=0,i=0,a=0,o=0;try{await this.tsAgent.bulkGenerateTests(e,(s,c,l)=>{o++;let u=lW.default.basename(s.filePath);(0,z.isDefined)(c)&&c.greenTestsCount>0?(t.delete(s),r+=c.greenTestsCount,i+=c.redTestsCount,a+=c.greyTestsCount,this._successSourceFiles.push(s.filePath),(0,z.isDefined)(l)&&l.testFilePath&&this._successTestFiles.push(l.testFilePath),this.logger.info(` [${o}/${e.length}] ✓ ${s.testable.name} (${u}) — ${c.greenTestsCount} passing, ${c.redTestsCount} skipped`)):((0,z.isDefined)(l)&&l.testFilePath&&n.push(l.testFilePath),this.logger.info(` [${o}/${e.length}] ✗ ${s.testable.name} (${u}) — no tests generated`))})}catch(e){if(H4(e))this.logger.warn(`Test generation was partially aborted due to timeout`);else throw e}for(let e of n)try{await g.unlink(e),this.logger.debug(`Removed failed test file: ${e}`)}catch{this.logger.debug(`Could not remove failed test file: ${e}`)}let s=e.length-t.size,c=t.size,l=await this.gitService.getEarlyFiles();return this.logger.info(``),this.logger.info(`✅ Test generation complete for ${s} functions`),c>0&&this.logger.info(`❌ ${c} functions were not generated`),this.logger.info(``),this.logger.info(`================`),this.logger.info(`Overall summary:`),this.logger.info(`================`),this.logger.info(``),this.logger.info(`✅ ${r} tests passing`),this.logger.info(`⚠️ ${i} tests skipped`),this.logger.info(`❌ ${a} tests could not be fixed autonomously (yet)`),this.logger.info(``),{generated:e.length,succeeded:s,failed:c,successMethodsCount:l.length,greenTests:r,redTests:i}}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,z.isDefined)(r))throw Error(`Failed to generate final coverage tree`);let i=r[`/`]?.percentage??0,a=this.getInitialCoverageTreeOrUndefined(),o=a?.[`/`]?.percentage??0;(0,z.isDefined)(a)||this.summaryService.setCoverageBeforeSkipped(),this.summaryService.setCoverageData(o,i);let s=(0,z.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,z.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)}};oQ([Qe(D4),iQ(`design:type`,typeof(Kte=D4!==void 0&&D4)==`function`?Kte:Object)],U4.prototype,`testableToGenerateService`,void 0),oQ([Qe(W2),iQ(`design:type`,typeof(B4=W2!==void 0&&W2)==`function`?B4:Object)],U4.prototype,`postGenerationService`,void 0),oQ([Qe(Q0),iQ(`design:type`,typeof(V4=Q0!==void 0&&Q0)==`function`?V4:Object)],U4.prototype,`postCommitCoverageService`,void 0),U4=oQ([tt(),ct({extendConstructorArguments:!0,extendProperties:!0})],U4);let W4=class extends U4{async getRawChangedFiles(){return this.gitService.getChangedFilesForCommitWithStatus({absolute:!0})}hasDiffContext(){return!0}async getBaseRevision(){let e=this.configService.getConfigValue(`baseRef`);if((0,z.isDefined)(e))return this.gitService.getBaseRevision({baseBranch:e});let t=this.configService.getConfigValue(`commitHash`);if((0,z.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,z.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()}};W4=oQ([tt(),ct({extendConstructorArguments:!0,extendProperties:!0})],W4);function qte(e){let t=e.command(uW.COMMIT).alias(`generate-commit`).description(`Generate tests for the current project in commit context`);return le(t,`--commit-hash <hash>`,`Commit hash`,{envName:`COMMIT_HASH`,isRequired:!0}),le(t,`--ref-name <ref>`,`Head branch name for the commit`,{envName:`REF_NAME`,isRequired:!0}),le(t,`--base-ref <ref>`,`optional base refrence for comparison`,{envName:`BASE_REF`}),le(t,`-s, --test-structure <structure>`,`Test file structure`,{envName:`TEST_STRUCTURE`,def:`siblingFolder`}),le(t,`-f, --test-framework <framework>`,`Test framework to use`,{envName:`TEST_FRAMEWORK`,def:`jest`}),le(t,`--test-suffix <suffix>`,`Test file suffix`,{envName:`TEST_FILE_SUFFIX`,def:`test`}),le(t,`--test-file-naming <naming>`,`Test file naming convention`,{envName:`TEST_FILE_NAMING`,def:`camelCase`}),le(t,`-c, --max-concurrency <number>`,`Number of concurrent workers (1-4)`,{envName:`MAX_CONCURRENCY`,def:`3`}),le(t,`--auto-commit <boolean>`,`Whether to auto-commit files`,{envName:`AUTO_COMMIT`,def:`true`}),le(t,`--auto-commit-skip-ci <boolean>`,`Append [skip ci] to auto-commit message`,{envName:`AUTO_COMMIT_SKIP_CI`,def:`true`}),le(t,`--test-command <command>`,`Custom test command to run`,{envName:`TEST_COMMAND`}),le(t,`--coverage-command <command>`,`Custom coverage command to run`,{envName:`COVERAGE_COMMAND`}),le(t,`--lint-command <command>`,`Custom lint command to run`,{envName:`LINT_COMMAND`}),le(t,`--prettier-command <command>`,`Custom prettier command to run`,{envName:`PRETTIER_COMMAND`}),le(t,`--disable-lint-rules <boolean>`,`Whether to disable failed lint rules in test files`,{envName:`DISABLE_LINT_RULES`,def:`false`}),le(t,`--git-org <org>`,`Git organization name`,{envName:`GIT_ORG`}),le(t,`--git-repo <repo>`,`Git repository name`,{envName:`GIT_REPO`}),le(t,`--git-user-email <email>`,`Git user email for auto commit`,{envName:`GIT_USER_EMAIL`}),le(t,`--git-user-name <name>`,`Git user name for auto commit`,{envName:`GIT_USER_NAME`}),le(t,`--scm-provider <provider>`,`SCM provider (e.g., github, bitbucket)`,{envName:`SCM_PROVIDER`,def:`github`}),le(t,`--keep-error-tests <boolean>`,`Whether to keep error tests`,{envName:`KEEP_ERROR_TESTS`,def:`false`}),le(t,`--keep-failed-tests <boolean>`,`Whether to keep failed tests`,{envName:`KEEP_FAILED_TESTS`,def:`false`}),le(t,`--conditional-keep <boolean>`,`Whether to return the last generated test result even when no green tests were produced`,{envName:`CONDITIONAL_KEEP`,def:`false`}),le(t,`--continue-on-test-errors <boolean>`,`Whether to continue on test errors`,{envName:`CONTINUE_ON_TEST_ERRORS`,def:`true`}),le(t,`--changed-methods-only <boolean>`,`Generate tests only for changed methods, not all methods in changed files`,{envName:`CHANGED_METHODS_ONLY`,def:`true`}),le(t,`--skip-coverage-after <boolean>`,`Skip final coverage generation after test generation`,{envName:`SKIP_COVERAGE_AFTER`,def:`false`}),le(t,`--max-testables <number>`,`Maximum number of testables to generate`,{envName:`MAX_TESTABLES`}),le(t,`--per-function-timeout <number>`,`Per function timeout in milliseconds`,{envName:`PER_FUNCTION_TIMEOUT`}),le(t,`--coverage-threshold <number>`,`Coverage threshold percentage (0-100)`,{envName:`COVERAGE_THRESHOLD`,def:`0`}),le(t,`--reuse-coverage <boolean>`,`Whether to reuse coverage`,{envName:`REUSE_COVERAGE`,def:`false`}),le(t,`--reuse-coverage-max-runs <number>`,`Max number of runs to reuse coverage (1-10)`,{envName:`REUSE_COVERAGE_MAX_RUNS`,def:`10`}),le(t,`--experimental-agent-sdk <boolean>`,`Use experimental Agent SDK for test generation`,{envName:`EXPERIMENTAL_AGENT_SDK`,def:`true`}),t.addHelpText(`after`,`
32413
32416
  Examples:
32414
32417
  $ early generate-commit --api-key your-api-key --token your-token --commit-hash abc123 --ref-name feature/new-feature
32415
32418
  $ 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"
@@ -32433,7 +32436,7 @@ Need help? → https://docs.startearly.ai
32433
32436
  pip install earlyai-agent
32434
32437
  # or: uv pip install earlyai-agent`);let e;try{await this.authService.login(),await this.gitService.hydrateConfig();let t=await this.gitService.getGitInfo();try{let e=await this.scmHostService.getPullRequestInfo();this.configService.updateConfigValue(`prName`,e.title),this.configService.updateConfigValue(`prUrl`,e.url),this.configService.updateConfigValue(`prNumber`,String(e.number)),this.configService.updateConfigValue(`prChangedFiles`,e.changedFiles),this.configService.updateConfigValue(`contributorAvatarUrl`,e.contributorAvatarUrl)}catch(e){this.logger.warn(`Failed to fetch PR info: ${e instanceof Error?e.message:`Unknown error`}`)}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,this._coverageTreeBefore=void 0,this._coverageTreeAfter=void 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(`
32435
32438
  `),...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,coverageTreeBefore:this._coverageTreeBefore,coverageTreeAfter:this._coverageTreeAfter,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(`
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;case`coverage_before`:this._handleCoverageBefore(e);break;case`coverage_after`:this._handleCoverageAfter(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`)}_handleCoverageBefore(e){if(e.success===!0&&e.coverage!==void 0){this._coverageTreeBefore=e.coverage;let t=e.coverage[`/`]?.percentage??0;this.logger.info(`Coverage before: ${t.toFixed(1)}% (${e.source_files_count} files, ${e.test_files_count} tests)`)}else this.logger.debug(`Coverage before skipped: ${e.error??`unknown reason`}`)}_handleCoverageAfter(e){if(e.success===!0&&e.coverage!==void 0){this._coverageTreeAfter=e.coverage;let t=e.coverage[`/`]?.percentage??0;this.logger.info(`Coverage after: ${t.toFixed(1)}% (${e.source_files_count} files, ${e.test_files_count} tests)`)}else this.logger.debug(`Coverage after skipped: ${e.error??`unknown reason`}`)}};r3=n3=oQ([tt(),aQ(0,Qe(lQ)),aQ(1,Qe(A4)),aQ(2,Qe(CQ)),aQ(3,Qe(R2)),aQ(4,Qe(cW.SCMHostService)),aQ(5,Qe(cQ)),iQ(`design:paramtypes`,[typeof($4=lQ!==void 0&&lQ)==`function`?$4:Object,typeof(e3=A4!==void 0&&A4)==`function`?e3:Object,typeof(t3=CQ!==void 0&&CQ)==`function`?t3:Object,typeof(Jte=R2!==void 0&&R2)==`function`?Jte:Object,typeof(Yte=_Q!==void 0&&_Q)==`function`?Yte:Object,Object])],r3);async function i3(e,t,n){let r=J0.get(R2),i=J0.get(cQ);for(let[a,o]of[[`before`,t],[`after`,n]])if(o!==void 0)try{let t=o[`/`];await r.saveCoverageToWorkflow(e,a,{prCoverage:{percentage:t?.percentage??null,totalStatements:t?.totalStatements??0,coveredStatements:t?.coveredStatements??0}})}catch(e){i.warn(`Failed to save coverage ${a}: ${e instanceof Error?e.message:`Unknown error`}`)}}function Xte(e){let t=e.command(uW.PR).alias(`generate-pr`).description(`Generate tests for the current project in pr context`);return le(t,`--pr-number <number>`,`PR number`,{envName:`PR_NUMBER`,isRequired:!0}),le(t,`--ref-name <ref>`,`Head reference for the PR`,{envName:`REF_NAME`,isRequired:!0}),le(t,`--base-ref <ref>`,`Base reference for the PR`,{envName:`BASE_REF`}),le(t,`-s, --test-structure <structure>`,`Test file structure`,{envName:`TEST_STRUCTURE`,def:`siblingFolder`}),le(t,`-f, --test-framework <framework>`,`Test framework to use`,{envName:`TEST_FRAMEWORK`,def:`jest`}),le(t,`--test-suffix <suffix>`,`Test file suffix`,{envName:`TEST_FILE_SUFFIX`,def:`test`}),le(t,`--test-file-naming <naming>`,`Test file naming convention`,{envName:`TEST_FILE_NAMING`,def:`camelCase`}),le(t,`-c, --max-concurrency <number>`,`Number of concurrent workers (1-4)`,{envName:`MAX_CONCURRENCY`,def:`3`}),le(t,`--auto-commit <boolean>`,`Whether to auto-commit files`,{envName:`AUTO_COMMIT`,def:`true`}),le(t,`--auto-commit-skip-ci <boolean>`,`Append [skip ci] to auto-commit message`,{envName:`AUTO_COMMIT_SKIP_CI`,def:`true`}),le(t,`--test-command <command>`,`Custom test command to run`,{envName:`TEST_COMMAND`}),le(t,`--coverage-command <command>`,`Custom coverage command to run`,{envName:`COVERAGE_COMMAND`}),le(t,`--lint-command <command>`,`Custom lint command to run`,{envName:`LINT_COMMAND`}),le(t,`--prettier-command <command>`,`Custom prettier command to run`,{envName:`PRETTIER_COMMAND`}),le(t,`--disable-lint-rules <boolean>`,`Whether to disable failed lint rules in test files`,{envName:`DISABLE_LINT_RULES`,def:`false`}),le(t,`--git-org <org>`,`Git organization name`,{envName:`GIT_ORG`}),le(t,`--git-repo <repo>`,`Git repository name`,{envName:`GIT_REPO`}),le(t,`--git-user-email <email>`,`Git user email for auto commit`,{envName:`GIT_USER_EMAIL`}),le(t,`--git-user-name <name>`,`Git user name for auto commit`,{envName:`GIT_USER_NAME`}),le(t,`--scm-provider <provider>`,`SCM provider (e.g., github, bitbucket)`,{envName:`SCM_PROVIDER`,def:`github`}),le(t,`--keep-error-tests <boolean>`,`Whether to keep error tests`,{envName:`KEEP_ERROR_TESTS`,def:`false`}),le(t,`--keep-failed-tests <boolean>`,`Whether to keep failed tests`,{envName:`KEEP_FAILED_TESTS`,def:`false`}),le(t,`--conditional-keep <boolean>`,`Whether to return the last generated test result even when no green tests were produced`,{envName:`CONDITIONAL_KEEP`,def:`false`}),le(t,`--continue-on-test-errors <boolean>`,`Whether to continue on test errors`,{envName:`CONTINUE_ON_TEST_ERRORS`,def:`false`}),le(t,`--changed-methods-only <boolean>`,`Generate tests only for changed methods, not all methods in changed files`,{envName:`CHANGED_METHODS_ONLY`,def:`true`}),le(t,`--skip-coverage-after <boolean>`,`Skip final coverage generation after test generation`,{envName:`SKIP_COVERAGE_AFTER`,def:`true`}),le(t,`--max-testables <number>`,`Maximum number of testables to generate`,{envName:`MAX_TESTABLES`}),le(t,`--per-function-timeout <number>`,`Per function timeout in milliseconds`,{envName:`PER_FUNCTION_TIMEOUT`}),le(t,`--coverage-threshold <number>`,`Coverage threshold percentage (0-100)`,{envName:`COVERAGE_THRESHOLD`,def:`0`}),le(t,`--reuse-coverage <boolean>`,`Whether to reuse coverage`,{envName:`REUSE_COVERAGE`,def:`false`}),le(t,`--reuse-coverage-max-runs <number>`,`Max number of runs to reuse coverage (1-10)`,{envName:`REUSE_COVERAGE_MAX_RUNS`,def:`10`}),le(t,`--experimental-agent-sdk <boolean>`,`Use experimental Agent SDK for test generation`,{envName:`EXPERIMENTAL_AGENT_SDK`,def:`true`}),t.addHelpText(`after`,`
32439
+ `);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;case`coverage_before`:this._handleCoverageBefore(e);break;case`coverage_after`:this._handleCoverageAfter(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`)}_handleCoverageBefore(e){if(e.success===!0&&e.coverage!==void 0){this._coverageTreeBefore=e.coverage;let t=e.coverage[`/`]?.percentage??0;this.logger.info(`Coverage before: ${t.toFixed(1)}% (${e.source_files_count} files, ${e.test_files_count} tests)`)}else this.logger.debug(`Coverage before skipped: ${e.error??`unknown reason`}`)}_handleCoverageAfter(e){if(e.success===!0&&e.coverage!==void 0){this._coverageTreeAfter=e.coverage;let t=e.coverage[`/`]?.percentage??0;this.logger.info(`Coverage after: ${t.toFixed(1)}% (${e.source_files_count} files, ${e.test_files_count} tests)`)}else this.logger.debug(`Coverage after skipped: ${e.error??`unknown reason`}`)}};r3=n3=oQ([tt(),aQ(0,Qe(lQ)),aQ(1,Qe(A4)),aQ(2,Qe(CQ)),aQ(3,Qe(R2)),aQ(4,Qe(cW.SCMHostService)),aQ(5,Qe(cQ)),iQ(`design:paramtypes`,[typeof($4=lQ!==void 0&&lQ)==`function`?$4:Object,typeof(e3=A4!==void 0&&A4)==`function`?e3:Object,typeof(t3=CQ!==void 0&&CQ)==`function`?t3:Object,typeof(Jte=R2!==void 0&&R2)==`function`?Jte:Object,typeof(Yte=_Q!==void 0&&_Q)==`function`?Yte:Object,Object])],r3);async function i3(e,t,n){let r=J0.get(R2),i=J0.get(cQ);for(let[a,o]of[[`before`,t],[`after`,n]])if(o!==void 0)try{let t=o[`/`];await r.saveCoverageToWorkflow(e,a,{prCoverage:{percentage:t?.percentage??null,totalStatements:t?.totalStatements??0,coveredStatements:t?.coveredStatements??0}})}catch(e){i.warn(`Failed to save coverage ${a}: ${e instanceof Error?e.message:`Unknown error`}`)}}function Xte(e){let t=e.command(uW.PR).alias(`generate-pr`).description(`Generate tests for the current project in pr context`);return le(t,`--pr-number <number>`,`PR number`,{envName:`PR_NUMBER`,isRequired:!0}),le(t,`--ref-name <ref>`,`Head reference for the PR`,{envName:`REF_NAME`,isRequired:!0}),le(t,`--base-ref <ref>`,`Base reference for the PR`,{envName:`BASE_REF`}),le(t,`-s, --test-structure <structure>`,`Test file structure`,{envName:`TEST_STRUCTURE`,def:`siblingFolder`}),le(t,`-f, --test-framework <framework>`,`Test framework to use`,{envName:`TEST_FRAMEWORK`,def:`jest`}),le(t,`--test-suffix <suffix>`,`Test file suffix`,{envName:`TEST_FILE_SUFFIX`,def:`test`}),le(t,`--test-file-naming <naming>`,`Test file naming convention`,{envName:`TEST_FILE_NAMING`,def:`camelCase`}),le(t,`-c, --max-concurrency <number>`,`Number of concurrent workers (1-4)`,{envName:`MAX_CONCURRENCY`,def:`3`}),le(t,`--auto-commit <boolean>`,`Whether to auto-commit files`,{envName:`AUTO_COMMIT`,def:`true`}),le(t,`--auto-commit-skip-ci <boolean>`,`Append [skip ci] to auto-commit message`,{envName:`AUTO_COMMIT_SKIP_CI`,def:`true`}),le(t,`--test-command <command>`,`Custom test command to run`,{envName:`TEST_COMMAND`}),le(t,`--coverage-command <command>`,`Custom coverage command to run`,{envName:`COVERAGE_COMMAND`}),le(t,`--lint-command <command>`,`Custom lint command to run`,{envName:`LINT_COMMAND`}),le(t,`--prettier-command <command>`,`Custom prettier command to run`,{envName:`PRETTIER_COMMAND`}),le(t,`--disable-lint-rules <boolean>`,`Whether to disable failed lint rules in test files`,{envName:`DISABLE_LINT_RULES`,def:`false`}),le(t,`--git-org <org>`,`Git organization name`,{envName:`GIT_ORG`}),le(t,`--git-repo <repo>`,`Git repository name`,{envName:`GIT_REPO`}),le(t,`--git-user-email <email>`,`Git user email for auto commit`,{envName:`GIT_USER_EMAIL`}),le(t,`--git-user-name <name>`,`Git user name for auto commit`,{envName:`GIT_USER_NAME`}),le(t,`--scm-provider <provider>`,`SCM provider (e.g., github, bitbucket)`,{envName:`SCM_PROVIDER`,def:`github`}),le(t,`--keep-error-tests <boolean>`,`Whether to keep error tests`,{envName:`KEEP_ERROR_TESTS`,def:`false`}),le(t,`--keep-failed-tests <boolean>`,`Whether to keep failed tests`,{envName:`KEEP_FAILED_TESTS`,def:`false`}),le(t,`--conditional-keep <boolean>`,`Whether to return the last generated test result even when no green tests were produced`,{envName:`CONDITIONAL_KEEP`,def:`false`}),le(t,`--continue-on-test-errors <boolean>`,`Whether to continue on test errors`,{envName:`CONTINUE_ON_TEST_ERRORS`,def:`true`}),le(t,`--changed-methods-only <boolean>`,`Generate tests only for changed methods, not all methods in changed files`,{envName:`CHANGED_METHODS_ONLY`,def:`true`}),le(t,`--skip-coverage-after <boolean>`,`Skip final coverage generation after test generation`,{envName:`SKIP_COVERAGE_AFTER`,def:`false`}),le(t,`--max-testables <number>`,`Maximum number of testables to generate`,{envName:`MAX_TESTABLES`}),le(t,`--per-function-timeout <number>`,`Per function timeout in milliseconds`,{envName:`PER_FUNCTION_TIMEOUT`}),le(t,`--coverage-threshold <number>`,`Coverage threshold percentage (0-100)`,{envName:`COVERAGE_THRESHOLD`,def:`0`}),le(t,`--reuse-coverage <boolean>`,`Whether to reuse coverage`,{envName:`REUSE_COVERAGE`,def:`false`}),le(t,`--reuse-coverage-max-runs <number>`,`Max number of runs to reuse coverage (1-10)`,{envName:`REUSE_COVERAGE_MAX_RUNS`,def:`10`}),le(t,`--experimental-agent-sdk <boolean>`,`Use experimental Agent SDK for test generation`,{envName:`EXPERIMENTAL_AGENT_SDK`,def:`true`}),t.addHelpText(`after`,`
32437
32440
  Examples:
32438
32441
  $ early generate-pr --api-key your-api-key --token your-token --pr-number 123 --ref-name feature/new-feature
32439
32442
  $ 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"
@@ -32444,7 +32447,7 @@ Notes:
32444
32447
  - --test-command must include: $early_filename
32445
32448
 
32446
32449
  Need help? → https://docs.startearly.ai
32447
- `).action(async e=>{try{let t={...e,command:uW.PR};if(J0.bind(cW.CliOptions).toConstantValue(t),m4(process.cwd(),e.targetDirectory??`.`)===`python`){let e=J0.get(r3),t=J0.get(W2),n,r;try{n=await e.runGeneratePr(),n.testResults.succeeded>0&&(await t.cleanupBlankEarlyFiles(),await t.autoCommit()),n.workflowRunId!==void 0&&await i3(n.workflowRunId,n.coverageTreeBefore,n.coverageTreeAfter)}catch(e){throw r=e instanceof Error?e.message:`Unknown error`,e}finally{(n?.workflowRunId!==void 0||n?.testResults!==void 0)&&await t.finalize({testResults:n?.testResults??{generated:0,succeeded:0,failed:0,successMethodsCount:0,greenTests:0,redTests:0},committedFilesCount:0,workflowRunId:n?.workflowRunId,failureReason:r})}}else await(await J0.getAsync(Q4)).runFlow();J0.unbind(cW.CliOptions)}catch(e){J0.get(cQ).error(`Error:`,e instanceof Error?e.message:`Unknown error`),process.exit(1)}})}var Zte=oV();async function Qte(e,t,n){let r=lW.default.join(e,t);try{if((await(0,g.stat)(r)).isFile()){let r=lW.default.normalize(t);return n?.absolute===!0?[lW.default.join(e,r)]:[r]}}catch{}return await(0,Zte.glob)(lW.default.join(t,`**`,`*`),{cwd:e,onlyFiles:!0,ignore:[`**/.*`],absolute:n?.absolute,suppressErrors:!0,dot:!1}).then(e=>e.map(e=>lW.default.normalize(e)))}let a3=class extends U4{async getRawChangedFiles(){let e=this.configService.getConfigValue(`targetDirectory`),t=await this.gitService.getTopLevel();if(!(0,z.isDefined)(e))throw Error(`targetDirectory config is required for project file retrieval`);return(await Qte(t,e)).map(e=>({filePath:lW.default.join(t,e),status:mQ.Modified}))}hasDiffContext(){return!1}async getBaseRevision(){}};a3=oQ([tt(),ct({extendConstructorArguments:!0,extendProperties:!0})],a3);async function o3(e,t,n){if(J0.get(lQ).getConfigValue(`skipCoverageAfter`)){J0.get(fQ).setCoverageState(uQ.Skipped);return}let r=J0.get(Q0),i=J0.get(fQ),a=J0.get(R2),o=await r.calculateCoverage({resultCommitSha:e,successSourceFiles:t.getSuccessSourceFiles(),successTestFiles:t.getSuccessTestFiles()});o.success?(i.setPRCoverageData(o.before.prCoverage,o.after.prCoverage),i.setCoverageState(uQ.Success),n!==void 0&&(await a.saveCoverageToWorkflow(n,`before`,{coverage:o.before.coverageTree??void 0,prCoverage:o.before.prCoverage}),await a.saveCoverageToWorkflow(n,`after`,{coverage:o.after.coverageTree??void 0,prCoverage:o.after.prCoverage}))):(i.setCoverageState(uQ.Failed,o.reason),n!==void 0&&(await a.saveCoverageToWorkflow(n,`before`,{}),await a.saveCoverageToWorkflow(n,`after`,{})))}async function s3(e,t,n){let r=J0.get(R2),i=J0.get(cQ);for(let[a,o]of[[`before`,t],[`after`,n]])if(o!==void 0)try{let t=o[`/`];await r.saveCoverageToWorkflow(e,a,{prCoverage:{percentage:t?.percentage??null,totalStatements:t?.totalStatements??0,coveredStatements:t?.coveredStatements??0}})}catch(e){i.warn(`Failed to save coverage ${a}: ${e instanceof Error?e.message:`Unknown error`}`)}}function c3(e){let t=e.command(uW.PROJECT).alias(`generate-project`).description(`Generate tests for the current project in commit context`);return le(t,`--ref-name <ref>`,`Head branch name for the commit`,{envName:`REF_NAME`,isRequired:!0}),le(t,`--target-directory <directory>`,`path to the target directory of files to generate tests relative to git repository top level`,{envName:`TARGET_DIRECTORY`,isRequired:!0}),le(t,`-s, --test-structure <structure>`,`Test file structure`,{envName:`TEST_STRUCTURE`,def:`siblingFolder`}),le(t,`-f, --test-framework <framework>`,`Test framework to use`,{envName:`TEST_FRAMEWORK`,def:`jest`}),le(t,`--test-suffix <suffix>`,`Test file suffix`,{envName:`TEST_FILE_SUFFIX`,def:`test`}),le(t,`--test-file-naming <naming>`,`Test file naming convention`,{envName:`TEST_FILE_NAMING`,def:`camelCase`}),le(t,`-c, --max-concurrency <number>`,`Number of concurrent workers (1-4)`,{envName:`MAX_CONCURRENCY`,def:`3`}),le(t,`--auto-commit <boolean>`,`Whether to auto-commit files`,{envName:`AUTO_COMMIT`,def:`true`}),le(t,`--auto-commit-skip-ci <boolean>`,`Append [skip ci] to auto-commit message`,{envName:`AUTO_COMMIT_SKIP_CI`,def:`true`}),le(t,`--test-command <command>`,`Custom test command to run`,{envName:`TEST_COMMAND`}),le(t,`--coverage-command <command>`,`Custom coverage command to run`,{envName:`COVERAGE_COMMAND`}),le(t,`--lint-command <command>`,`Custom lint command to run`,{envName:`LINT_COMMAND`}),le(t,`--prettier-command <command>`,`Custom prettier command to run`,{envName:`PRETTIER_COMMAND`}),le(t,`--disable-lint-rules <boolean>`,`Whether to disable failed lint rules in test files`,{envName:`DISABLE_LINT_RULES`,def:`false`}),le(t,`--git-org <org>`,`Git organization name`,{envName:`GIT_ORG`}),le(t,`--git-repo <repo>`,`Git repository name`,{envName:`GIT_REPO`}),le(t,`--git-user-email <email>`,`Git user email for auto commit`,{envName:`GIT_USER_EMAIL`}),le(t,`--git-user-name <name>`,`Git user name for auto commit`,{envName:`GIT_USER_NAME`}),le(t,`--scm-provider <provider>`,`SCM provider (e.g., github, bitbucket)`,{envName:`SCM_PROVIDER`,def:`github`}),le(t,`--keep-error-tests <boolean>`,`Whether to keep error tests`,{envName:`KEEP_ERROR_TESTS`,def:`false`}),le(t,`--keep-failed-tests <boolean>`,`Whether to keep failed tests`,{envName:`KEEP_FAILED_TESTS`,def:`false`}),le(t,`--conditional-keep <boolean>`,`Whether to return the last generated test result even when no green tests were produced`,{envName:`CONDITIONAL_KEEP`,def:`false`}),le(t,`--continue-on-test-errors <boolean>`,`Whether to continue on test errors`,{envName:`CONTINUE_ON_TEST_ERRORS`,def:`false`}),le(t,`--skip-coverage-after <boolean>`,`Skip final coverage generation after test generation`,{envName:`SKIP_COVERAGE_AFTER`,def:`true`}),le(t,`--max-testables <number>`,`Maximum number of testables to generate`,{envName:`MAX_TESTABLES`}),le(t,`--per-function-timeout <number>`,`Per function timeout in milliseconds`,{envName:`PER_FUNCTION_TIMEOUT`}),le(t,`--coverage-threshold <number>`,`Coverage threshold percentage (0-100)`,{envName:`COVERAGE_THRESHOLD`,def:`0`}),le(t,`--reuse-coverage <boolean>`,`Whether to reuse coverage`,{envName:`REUSE_COVERAGE`,def:`false`}),le(t,`--reuse-coverage-max-runs <number>`,`Max number of runs to reuse coverage (1-10)`,{envName:`REUSE_COVERAGE_MAX_RUNS`,def:`10`}),le(t,`--experimental-agent-sdk <boolean>`,`Use experimental Agent SDK for test generation`,{envName:`EXPERIMENTAL_AGENT_SDK`,def:`true`}),t.addHelpText(`after`,`
32450
+ `).action(async e=>{try{let t={...e,command:uW.PR};if(J0.bind(cW.CliOptions).toConstantValue(t),m4(process.cwd(),e.targetDirectory??`.`)===`python`){let e=J0.get(r3),t=J0.get(W2),n,r;try{n=await e.runGeneratePr(),n.testResults.succeeded>0&&(await t.cleanupBlankEarlyFiles(),await t.autoCommit()),n.workflowRunId!==void 0&&await i3(n.workflowRunId,n.coverageTreeBefore,n.coverageTreeAfter)}catch(e){throw r=e instanceof Error?e.message:`Unknown error`,e}finally{(n?.workflowRunId!==void 0||n?.testResults!==void 0)&&await t.finalize({testResults:n?.testResults??{generated:0,succeeded:0,failed:0,successMethodsCount:0,greenTests:0,redTests:0},committedFilesCount:0,workflowRunId:n?.workflowRunId,failureReason:r})}}else await(await J0.getAsync(Q4)).runFlow();J0.unbind(cW.CliOptions)}catch(e){J0.get(cQ).error(`Error:`,e instanceof Error?e.message:`Unknown error`),process.exit(1)}})}var Zte=oV();async function Qte(e,t,n){let r=lW.default.join(e,t);try{if((await(0,g.stat)(r)).isFile()){let r=lW.default.normalize(t);return n?.absolute===!0?[lW.default.join(e,r)]:[r]}}catch{}return await(0,Zte.glob)(lW.default.join(t,`**`,`*`),{cwd:e,onlyFiles:!0,ignore:[`**/.*`],absolute:n?.absolute,suppressErrors:!0,dot:!1}).then(e=>e.map(e=>lW.default.normalize(e)))}let a3=class extends U4{async getRawChangedFiles(){let e=this.configService.getConfigValue(`targetDirectory`),t=await this.gitService.getTopLevel();if(!(0,z.isDefined)(e))throw Error(`targetDirectory config is required for project file retrieval`);return(await Qte(t,e)).map(e=>({filePath:lW.default.join(t,e),status:mQ.Modified}))}hasDiffContext(){return!1}async getBaseRevision(){}};a3=oQ([tt(),ct({extendConstructorArguments:!0,extendProperties:!0})],a3);async function o3(e,t,n){if(J0.get(lQ).getConfigValue(`skipCoverageAfter`)){J0.get(fQ).setCoverageState(uQ.Skipped);return}let r=J0.get(Q0),i=J0.get(fQ),a=J0.get(R2),o=await r.calculateCoverage({resultCommitSha:e,changedSourceFiles:[...t.getChangedFiles()],successTestFiles:t.getSuccessTestFiles()});o.success?(i.setPRCoverageData(o.before.prCoverage,o.after.prCoverage),i.setCoverageState(uQ.Success),n!==void 0&&(await a.saveCoverageToWorkflow(n,`before`,{coverage:o.before.coverageTree??void 0,prCoverage:o.before.prCoverage}),await a.saveCoverageToWorkflow(n,`after`,{coverage:o.after.coverageTree??void 0,prCoverage:o.after.prCoverage}))):(i.setCoverageState(uQ.Failed,o.reason),n!==void 0&&(await a.saveCoverageToWorkflow(n,`before`,{}),await a.saveCoverageToWorkflow(n,`after`,{})))}async function s3(e,t,n){let r=J0.get(R2),i=J0.get(cQ);for(let[a,o]of[[`before`,t],[`after`,n]])if(o!==void 0)try{let t=o[`/`];await r.saveCoverageToWorkflow(e,a,{prCoverage:{percentage:t?.percentage??null,totalStatements:t?.totalStatements??0,coveredStatements:t?.coveredStatements??0}})}catch(e){i.warn(`Failed to save coverage ${a}: ${e instanceof Error?e.message:`Unknown error`}`)}}function c3(e){let t=e.command(uW.PROJECT).alias(`generate-project`).description(`Generate tests for the current project in commit context`);return le(t,`--ref-name <ref>`,`Head branch name for the commit`,{envName:`REF_NAME`,isRequired:!0}),le(t,`--target-directory <directory>`,`path to the target directory of files to generate tests relative to git repository top level`,{envName:`TARGET_DIRECTORY`,isRequired:!0}),le(t,`-s, --test-structure <structure>`,`Test file structure`,{envName:`TEST_STRUCTURE`,def:`siblingFolder`}),le(t,`-f, --test-framework <framework>`,`Test framework to use`,{envName:`TEST_FRAMEWORK`,def:`jest`}),le(t,`--test-suffix <suffix>`,`Test file suffix`,{envName:`TEST_FILE_SUFFIX`,def:`test`}),le(t,`--test-file-naming <naming>`,`Test file naming convention`,{envName:`TEST_FILE_NAMING`,def:`camelCase`}),le(t,`-c, --max-concurrency <number>`,`Number of concurrent workers (1-4)`,{envName:`MAX_CONCURRENCY`,def:`3`}),le(t,`--auto-commit <boolean>`,`Whether to auto-commit files`,{envName:`AUTO_COMMIT`,def:`true`}),le(t,`--auto-commit-skip-ci <boolean>`,`Append [skip ci] to auto-commit message`,{envName:`AUTO_COMMIT_SKIP_CI`,def:`true`}),le(t,`--test-command <command>`,`Custom test command to run`,{envName:`TEST_COMMAND`}),le(t,`--coverage-command <command>`,`Custom coverage command to run`,{envName:`COVERAGE_COMMAND`}),le(t,`--lint-command <command>`,`Custom lint command to run`,{envName:`LINT_COMMAND`}),le(t,`--prettier-command <command>`,`Custom prettier command to run`,{envName:`PRETTIER_COMMAND`}),le(t,`--disable-lint-rules <boolean>`,`Whether to disable failed lint rules in test files`,{envName:`DISABLE_LINT_RULES`,def:`false`}),le(t,`--git-org <org>`,`Git organization name`,{envName:`GIT_ORG`}),le(t,`--git-repo <repo>`,`Git repository name`,{envName:`GIT_REPO`}),le(t,`--git-user-email <email>`,`Git user email for auto commit`,{envName:`GIT_USER_EMAIL`}),le(t,`--git-user-name <name>`,`Git user name for auto commit`,{envName:`GIT_USER_NAME`}),le(t,`--scm-provider <provider>`,`SCM provider (e.g., github, bitbucket)`,{envName:`SCM_PROVIDER`,def:`github`}),le(t,`--keep-error-tests <boolean>`,`Whether to keep error tests`,{envName:`KEEP_ERROR_TESTS`,def:`false`}),le(t,`--keep-failed-tests <boolean>`,`Whether to keep failed tests`,{envName:`KEEP_FAILED_TESTS`,def:`false`}),le(t,`--conditional-keep <boolean>`,`Whether to return the last generated test result even when no green tests were produced`,{envName:`CONDITIONAL_KEEP`,def:`false`}),le(t,`--continue-on-test-errors <boolean>`,`Whether to continue on test errors`,{envName:`CONTINUE_ON_TEST_ERRORS`,def:`true`}),le(t,`--skip-coverage-after <boolean>`,`Skip final coverage generation after test generation`,{envName:`SKIP_COVERAGE_AFTER`,def:`false`}),le(t,`--max-testables <number>`,`Maximum number of testables to generate`,{envName:`MAX_TESTABLES`}),le(t,`--per-function-timeout <number>`,`Per function timeout in milliseconds`,{envName:`PER_FUNCTION_TIMEOUT`}),le(t,`--coverage-threshold <number>`,`Coverage threshold percentage (0-100)`,{envName:`COVERAGE_THRESHOLD`,def:`0`}),le(t,`--reuse-coverage <boolean>`,`Whether to reuse coverage`,{envName:`REUSE_COVERAGE`,def:`false`}),le(t,`--reuse-coverage-max-runs <number>`,`Max number of runs to reuse coverage (1-10)`,{envName:`REUSE_COVERAGE_MAX_RUNS`,def:`10`}),le(t,`--experimental-agent-sdk <boolean>`,`Use experimental Agent SDK for test generation`,{envName:`EXPERIMENTAL_AGENT_SDK`,def:`true`}),t.addHelpText(`after`,`
32448
32451
  Examples:
32449
32452
  $ early generate-project --api-key your-api-key --token your-token --ref-name main --target-directory src/services
32450
32453
  $ early generate-project -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"